diff --git a/.gitignore b/.gitignore index 636867290d6bb1c14a23e5cdbfcfc20b3553834c..0d72066f7bb5117df1e05dd9e5b570131992bfb8 100644 --- a/.gitignore +++ b/.gitignore @@ -12,10 +12,12 @@ target/ .settings .springBeans .sts4-cache +.idea/ ### IntelliJ IDEA ### *.iws *.ipr +*.iml ### NetBeans ### /nbproject/private/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 2631adff7392aad3efb19e737f5c976fabb7d844..62ce099a3564a857b05f155e5ff1e3d9931fbf2f 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -60,6 +60,8 @@ child-lib: variables: COMPONENT: $COMPONENT MODE: $MODE + DISABLE_DEP_CHECK: "true" + DISABLE_SONAR: "true" trigger: include: "services/common/.gitlab-ci-library.yml" strategy: depend diff --git a/CHANGELOG.md b/CHANGELOG.md index dbe3dd08cbee0507db1827e83f95e68d0ffd3c26..cc197aeab8a8dbf6d72593882ea0f00e3ba9cd8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,11 @@ Tous les changements de ce projet seront documentés dans ce document. ## [Non livré] - +- Le paramètre "nomOrganisation" de l'API de chargement des inventaires devient un champ obligatoire -> [Issue2](https://gitlab-forge.din.developpement-durable.gouv.fr/pub/numeco/m4g/numecoeval/-/issues/2) +- Intégrer des nouveaux impacts au référentiel -> [Issue1](https://gitlab-forge.din.developpement-durable.gouv.fr/pub/numeco/m4g/numecoeval/-/issues/1) +- Defect: Mauvaise description de l'API de chargement des données d'entrées +- Defect : Erreur sur le calcul comparant la date de retrait et la date d'achat pour les équipements physiques +- Mise à jour de Java 17 vers 21 et des dépendances - Defect: Libellé erreur erroné quand donnée de référence manquante - Ajout du mode d'utilisation et taux d'utilisation - Ajout d'une API /version pour récupérer la version courante de NumEcoEval dans le composant référentiel diff --git a/assets/docker-compose/docker-compose.yml b/assets/docker-compose/docker-compose.yml index f0eb0f0d8c5cb3132843d0c8c550c7467360a061..5d890da1366ea0e30ae031378665349322110f85 100644 --- a/assets/docker-compose/docker-compose.yml +++ b/assets/docker-compose/docker-compose.yml @@ -19,7 +19,7 @@ services: - "numecoeval_zookeeper_data:/bitnami" environment: ALLOW_ANONYMOUS_LOGIN: "yes" - + # Kafka basé sur la documentation officielle de Bitnami ## https://github.com/bitnami/containers/blob/main/bitnami/kafka/docker-compose.yml ## https://hub.docker.com/r/bitnami/kafka/ @@ -72,7 +72,7 @@ services: LOGGING_LEVEL_ORG_SPRINGFRAMEWORK: $LOGGING_LEVEL_ORG_SPRINGFRAMEWORK api-rest-expositiondonneesentrees: - image: ${REGISTRY_URL}/api-expositiondonneesentrees:${TAG} + image: ${REGISTRY_URL}/api-expositiondonneesentrees:${TAG} depends_on: - postgresdb - api-rest-referentiels @@ -95,6 +95,7 @@ services: NUMECOEVAL_URLS_ALLOWED: "http://localhost,http://api-rest-expositiondonneesentrees" LOGGING_LEVEL_ROOT: $LOGGING_LEVEL_ROOT LOGGING_LEVEL_ORG_SPRINGFRAMEWORK: $LOGGING_LEVEL_ORG_SPRINGFRAMEWORK + NUMECOEVAL_CALCULS_SERVER_URL: "http://api-event-calculs:8080" api-event-donneesentrees: image: ${REGISTRY_URL}/api-event-donneesentrees:${TAG} diff --git a/docs/Indicateurs.plantuml b/docs/Indicateurs.plantuml index b64755f80085c939018d125cb10c397df32ef7a4..bf16d9f5bb0525e7743c050e283fecf943c21cf3 100644 --- a/docs/Indicateurs.plantuml +++ b/docs/Indicateurs.plantuml @@ -41,6 +41,8 @@ String statutEquipementPhysique 'Impact unitaire, le champ est null en cas d'erreur lors du calcul de l'indicateur Double impactUnitaire Double consoElecMoyenne +String modeUtilsation +Double tauxUtilisation } 'Indicateurs d'empreinte environnemtale d'un équipement virtuel diff --git a/docs/MoteurDeCalculG4IT_V1.1.adoc b/docs/MoteurDeCalculG4IT_V1.1.adoc index 629844c141dd340b3ae4d6e242ac31ce34406065..d1e1e3a38c6139745bc4677cf58b644c3732c5b3 100644 --- a/docs/MoteurDeCalculG4IT_V1.1.adoc +++ b/docs/MoteurDeCalculG4IT_V1.1.adoc @@ -8,6 +8,8 @@ |type de changement|date|type de modification |majeur|28/06/2022|Création du document |majeur|Avril 2023|Ouverture en Open Source +|majeur|01/02/2023|Partage des équipements entre les contextes personnels et professionnels (changement règles de calculs avec le tauxUtilisation & modeUtilisation) +|majeur|22/02/2023|Intégrer des nouveaux impact au référentiel(déplacements collaborateurs, bâtiments) -> Création d'une nouvelle API facteurscaracterisation |=== [#_documents_de_reference] @@ -104,9 +106,8 @@ exemple : |ref_Hypothese |Précise les hypothèses nécessaires à certains calculs des indicateurs (par exemple les données par défaut) |ref_TypeEquipement |Précise les types d'équipements autorisés et leur durée de vie par defaut |ref_CorrespondanceRefEqP|Donne la correspondance entre les équipements présents dans les données d'entrées et les équipements de références présents dans la table ref_impactEquipement -|ref_ImpactEquipement |Donne pour chaque type équipement référencé, son impact environnemental selon le critère (<<_criteres_dimpacts_environnementaux>>) et le cycle de vie (<<_analyse_de_cycle_de_vie>>) regardé. -|ref_MixElec|Donne pour chaque pays référencé, l'impact environnemental d'un kWh d'électricité produit, selon les différents critères d'impact. -|ref_ImpactReseau|Donne l'impact lié à l'utilisation du réseau selon les différents critères et l'étapes dans le cycle de vie. +|ref_FacteursCaracterisation|Donne l'impact environnemental de différents items selon le critère (<<_criteres_dimpacts_environnementaux>>) et l'étape du cycle de vie (<<_analyse_de_cycle_de_vie>>). Par exemple, il peut s'agir de l'impact sur le changement climatique d'une certaine configuration de serveur à la fabrication. + |=== **Pour chaque type d'objet, des endpoints de CRUD (Create/Read/Update/Delete) sont disponibles** @@ -116,62 +117,18 @@ le format de ces références est contraint pour garantir la capacité du moteur link:./References.plantuml[Diagramme de classe des référentiels] Toutes ces données sont nécessaires au calcul des règles d'impact. Elles doivent être chargées par un administrateur NumEcoEval avant d'intégrer les données d'entrée. -===== Précisions sur l'import CSV de certains référentiels - -*Référentiels dépendants d'une organisation* : - -Le référentiel est lié à une organisation donnée. L'import se fait avec 2 paramètres : - -* Le nom d'organisation pour laquelle les données sont établies -* Le fichier CSV du référentiel - -Lors de l'import, les données précédentes de l'organisation pour le référentiel sont supprimées. - -_Concerne_: ref_CorrespondanceRefEqP - -*Référentiels généraux* : - -Le référentiel est global à tout le système. L'import se fait uniquement avec le fichier CSV du référentiel. - -Lors de l'import, les données précédentes sont supprimées. - -_Concerne_: ref_Critere, ref_Etape, ref_ImpactEquipement, ref_MixElec, ref_ImpactReseau - -==== Exposition du bloc -Les données de ce bloc sont exposées via les points suivants : -|=== -|Endpoint API REST|Description|Paramètres|Sortie -|[[GET_Etapes]]GET /referentiels/etapes|Renvoie la liste des étapes de ref_EtapeACV|Aucuns| Liste d'objet ref_EtapeACV -|[[GET_Criteres]]GET /referentiels/criteres|Renvoie la liste des Critères de ref_Critere|Aucuns| Liste d'objet ref_Critere -|[[GET_ImpactsReseaux]]GET /referentiels/impactreseaux?etape=+{etape}+&critere=+{critere}+&reseau=+{refReseau}+|Renvoie l'impact d'un équipement sur le réseau selon les paramètres|Le nom du critère, le code de l'étape de cycle de vie et la référence de l'équipement|Un objet ref_ImpactReseau -|[[GET_Hypotheses]]GET /referentiels/hypotheses?cle=+{cle}+|Renvoie l'objet ref_Hypothese correspondant à la clé|La clé unique de l'hypothèse|Un objet ref_Hypothese -|[[GET_typeEquipement]]GET /referentiels/typeEquipement?type=+{type}+|Renvoie l'objet typeEquipement correspondant au type d'équipement|Le type d'équipement|Un objet ref_TypeEquipement -|[[GET_impactMessagerie]]GET /referentiels/impactMessagerie?critere=+{critere}+|Renvoie l'objet ref_ImpactMessagerie correspondant au critère|La référence d'impact messagerie|Un objet ref_ImpactMessagerie -|=== +**Précisions sur l'import CSV de certains référentiels** -**Pour chaque type d'objet, des endpoints de CRUD (Create/Read/Update/Delete) sont disponibles** -_Tableau des endpoints CRUD en attente des retours sur Spring Data REST_ -_TODO Ajouter le tableau une fois les endpoints stabilisés_ - -Pour certains référentiels compatibles, un endpoint d'import par fichier CSV est disponible -pour permettre un chargement en masse. -|=== -|Exemple d'endpoint d'import par CSV|Description|Paramètres|Sortie -|POST /referentiels/<objet_ref>/import/csv|Importer plusieurs références. L'import fonctionne en annule-et-remplace (suppression de toutes les données avant import).|Le fichier CSV avec les données à insérer|Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes). -|=== - -Ce endpoint est actuellement disponible pour les référentiels suivants : -ref_Critere, ref_EtapeACV, ref_Hypothese, ref_TypeEquipement, ref_ImpactEquipement, -ref_MixElec, ref_ImpactReseau, ref_ImpactMessagerie. +Les API permettant d'importer de nouvelles données et d'exporter les références existantes sont décrites https://gitlab-forge.din.developpement-durable.gouv.fr/pub/numeco/m4g/numecoeval/-/blob/develop/services/common/src/main/resources/static/api-referentiels-openapi.yaml?ref_type=heads[ici]. **Points d'attention ** -- Par construction, une suppression sur le référentiel ref_EtapeACV supprime les référentiels référençant cette étape : ref_ImpactEquipement, ref_ImpactReseau et ref_ImpactMessagerie. -- Par construction, un import CSV sur le référentiel ref_EtapeACV supprime les référentiels référençant les étapes : ref_ImpactEquipement, ref_ImpactReseau et ref_ImpactMessagerie. -- Par construction, une suppression sur le référentiel ref_Critere supprime les référentiels référençant le critère : ref_ImpactEquipement, ref_ImpactReseau, ref_ImpactMessagerie et ref_MixElec. -- Par construction, un import CSV sur le référentiel ref_Critere supprime les référentiels référençant les critères : ref_ImpactEquipement, ref_ImpactReseau, ref_ImpactMessagerie et ref_MixElec. +- Par construction, une suppression sur le référentiel ref_EtapeACV supprime les référentiels référençant cette étape : ref_facteursCaracterisation et ref_ImpactMessagerie. +- Par construction, un import CSV sur le référentiel ref_EtapeACV supprime les référentiels référençant les étapes : ref_facteursCaracterisation et ref_ImpactMessagerie. +- Par construction, une suppression sur le référentiel ref_Critere supprime les référentiels référençant le critère : ref_facteursCaracterisation et ref_ImpactMessagerie. +- Par construction, un import CSV sur le référentiel ref_Critere supprime les référentiels référençant les critères : ref_facteursCaracterisation et ref_ImpactMessagerie. ==== Précision sur les hypothèses Les hypothèses de travail se trouvent dans la table "Hypothèses". @@ -628,7 +585,6 @@ refEquipementRetenu = RG_correspondanceRefEquipement(nomOrganisation, equipement FIN SI SINON - EqP.quantité SI EqP.tauxUtilisation est renseigné diff --git a/docs/References.plantuml b/docs/References.plantuml index 3393d834b07b9bb314e1c047b269c9a6bb5fbfb9..7c2296aa23d9a9f9c36ae24065e1b075ee49d5a2 100644 --- a/docs/References.plantuml +++ b/docs/References.plantuml @@ -21,17 +21,19 @@ String source } 'Impact environnementaux de référence -class ref_ImpactEquipement { -'identifiant de l'équipement -* String refEquipement +class ref_FacteurCaracterisation { +* String nom * String etape * String critere -'description de l'équipement +'description du facteur de caractérisation String description -'le type doit correspondre à celui présent dans ref_TypeEquipement -String type +String niveau +String tiers +String categorie Double consoElecMoyenne +String localisation Double valeur +String unite String source } @@ -56,25 +58,6 @@ String libelle String description } -class ref_MixElec { -*String pays -*String critere -String raccourcisAnglais -Double valeur -String unité -String source -} - -'Impact environnementaux du réseau -class ref_ImpactReseau{ -* String refReseau -* String etape -* String critere -Double consoElecMoyenne -Double valeur -String source -} - 'Impact environnemental Messagerie class ref_ImpactMessagerie{ 'L'équation d'impact est une fonction affine de la forme a * x + b @@ -86,12 +69,4 @@ Double constanteOrdonneeOrigine String critere String source } - -ref_EtapeACV "1" --- "0-*" ref_ImpactEquipement : dépend de > -ref_Critere "1" --- "0-*" ref_ImpactEquipement : dépend de > -ref_Critere "1" --- "0-*" ref_MixElec : dépend de > -ref_Critere "1" --- "0-*" ref_ImpactReseau : dépend de > -ref_Critere "1" --- "0-*" ref_ImpactMessagerie : dépend de > -ref_EtapeACV "1" --- "0-*" ref_ImpactReseau : dépend de > - @enduml diff --git a/e2e/1_load_ref.sh b/e2e/1_load_ref.sh index 194009545df531a94edc32e0fd987db7c8531b94..36093c58c4752b8517893b58a491a250b4a8f02e 100644 --- a/e2e/1_load_ref.sh +++ b/e2e/1_load_ref.sh @@ -1,7 +1,9 @@ #!/bin/bash # CONTANTS -REFERENTIELS="criteres etapes hypotheses impactequipements impactreseaux mixelecs typeEquipement correspondanceRefEquipement" +REFERENTIELS="criteres etapes hypotheses typeEquipement correspondanceRefEquipement facteursCaracterisation" + +E2E_LOCAL_PATH=. . ./.env . ./utils.sh @@ -9,6 +11,6 @@ REFERENTIELS="criteres etapes hypotheses impactequipements impactreseaux mixelec log "Send referentiel data" for ref in $REFERENTIELS; do log_n - curl -s -XPOST $REFERENTIEL_URL/referentiel/$ref/csv --form file=@input_ref/$ref.csv + curl -s -XPOST $REFERENTIEL_URL/referentiel/$ref/csv --form file=@${E2E_LOCAL_PATH}/input_ref/$ref.csv echo "" done diff --git a/e2e/5_assert.sh b/e2e/5_assert.sh index f61d80ec85b4847a9c4c35eeb7af0ab3485b7244..86b42ab20104dca5f01850385463a90a8ff13f5c 100644 --- a/e2e/5_assert.sh +++ b/e2e/5_assert.sh @@ -3,6 +3,8 @@ ORGANISATION=${1:-org1} NOM_LOT=${2:-lot1} +E2E_LOCAL_PATH=. + # load INDICATEUR_URL . ./.env @@ -20,11 +22,11 @@ export_table reseau etapeacv,critere,source,statut_indicateur,trace,version_calc ALL_OK=true for file in $(ls actual/); do echo -n "Check file $file : " - res=$(diff -qs actual/$file expected/$file) + res=$(diff -qs actual/$file ${E2E_LOCAL_PATH}/expected/$file) if [ $? -eq 1 ]; then echo "KO" echo "*** REGRESSION : file $file is different from expected, see file: reports/diff_$file" - diff actual/$file expected/$files > reports/diff_$file + diff actual/$file ${E2E_LOCAL_PATH}/expected/$file > reports/diff_$file ALL_OK=false else echo "OK" diff --git a/e2e/e2e.iml b/e2e/e2e.iml index 8021953ed9f8cc6cd6d71c79462bad4cd2b5394c..885ffe64a60205bdd9858b06a69d8c16c57e1497 100644 --- a/e2e/e2e.iml +++ b/e2e/e2e.iml @@ -1,9 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> -<module type="WEB_MODULE" version="4"> - <component name="NewModuleRootManager" inherit-compiler-output="true"> - <exclude-output /> - <content url="file://$MODULE_DIR$" /> - <orderEntry type="inheritedJdk" /> - <orderEntry type="sourceFolder" forTests="false" /> +<module version="4"> + <component name="SonarLintModuleSettings"> + <option name="uniqueId" value="3533810f-e57c-45f5-bdb3-84fc26316012" /> </component> </module> \ No newline at end of file diff --git a/e2e/input_template/EquipementPhysique_hors_serveur.csv b/e2e/input_template/EquipementPhysique_hors_serveur.csv index 09c3d4a9d0bce246d6e05f761f6980c5f90d7b6e..f8963fae13cdaafa4a4d2a48944b3d071820a321 100644 --- a/e2e/input_template/EquipementPhysique_hors_serveur.csv +++ b/e2e/input_template/EquipementPhysique_hors_serveur.csv @@ -5,9 +5,9 @@ physical-eq-003;P2719;4;;2021-03-30;2023-06-16;Monitor;In use;France;;;;MY ENTER physical-eq-004;HUB USB;10;;2023-04-01;2023-06-16;Consumable;Consumed;France;;;;MY ENTERPRISE;;365;;BYOD;0.1 physical-eq-005;P2720DC;2;;2022-11-04;2023-06-16;Monitor;In stock;France;;;;MY ENTERPRISE;;365;;BYOD;12.1 physical-eq-006;PIXEL 6;1;;2022-10-18;2023-06-16;Communication Device;Missing;France;;;;MY ENTERPRISE;;365;;;test -physical-eq-007;UP2516D;1;;2022-07-31;2023-06-16;Monitor;Retired;France;;;;MY ENTERPRISE;;365;;; -physical-eq-008;UP2516D;2;;2022-03-10;2023-06-16;Monitor;In stock;France;;;;MY ENTERPRISE;;365;;; -physical-eq-009;Unknown;3;;2021-08-09;2023-06-16;IP Router;In use;France;;;;MY ENTERPRISE;;365;;; +physical-eq-007;UP2516D;1;;2022-07-31;2023-06-16;Monitor;Retired;France;;;;MY ENTERPRISE;;365;;;0.9 +physical-eq-008;UP2516D;2;;2022-03-10;2023-06-16;Monitor;In stock;France;;;;MY ENTERPRISE;;365;;COPE;0.6 +physical-eq-009;Unknown;3;;2021-08-09;2023-06-16;IP Router;In use;France;;;;MY ENTERPRISE;;365;;COPE;0 physical-eq-010;Unknown;3;;2021-08-09;2023-06-16;IP Router;In use;France;;;;MY ENTERPRISE;;365;;; physical-eq-011;HP 8440p;1;;2021-08-05;2023-06-16;Personal Computer;Missing;France;;;;MY ENTERPRISE;;365;;; physical-eq-012;HP 8440p;1;;2023-04-27;2023-06-16;Personal Computer;Retired;France;;;;MY ENTERPRISE;;365;;; diff --git a/services/.workspace/.idea/compiler.xml b/services/.workspace/.idea/compiler.xml index f846159834d25b6c569ec6503c8ee672b8e3994e..84cc240af38dc7893a3d41b3e62e4c328bf1f58f 100644 --- a/services/.workspace/.idea/compiler.xml +++ b/services/.workspace/.idea/compiler.xml @@ -8,14 +8,14 @@ <sourceTestOutputDir name="target/generated-test-sources/test-annotations" /> <outputRelativeToContentRoot value="true" /> </profile> - <profile name="Annotation profile for api-expositiondonneesentrees" enabled="true"> + <profile name="Annotation profile for common" enabled="true"> <sourceOutputDir name="target/generated-sources/annotations" /> <sourceTestOutputDir name="target/generated-test-sources/test-annotations" /> <outputRelativeToContentRoot value="true" /> <processorPath useClasspath="false"> - <entry name="$MAVEN_REPOSITORY$/org/mapstruct/mapstruct-processor/1.5.3.Final/mapstruct-processor-1.5.3.Final.jar" /> - <entry name="$MAVEN_REPOSITORY$/org/mapstruct/mapstruct/1.5.3.Final/mapstruct-1.5.3.Final.jar" /> - <entry name="$MAVEN_REPOSITORY$/org/projectlombok/lombok/1.18.26/lombok-1.18.26.jar" /> + <entry name="$MAVEN_REPOSITORY$/org/mapstruct/mapstruct-processor/1.5.5.Final/mapstruct-processor-1.5.5.Final.jar" /> + <entry name="$MAVEN_REPOSITORY$/org/mapstruct/mapstruct/1.5.5.Final/mapstruct-1.5.5.Final.jar" /> + <entry name="$MAVEN_REPOSITORY$/org/projectlombok/lombok/1.18.30/lombok-1.18.30.jar" /> <entry name="$MAVEN_REPOSITORY$/org/projectlombok/lombok-mapstruct-binding/0.2.0/lombok-mapstruct-binding-0.2.0.jar" /> <entry name="$MAVEN_REPOSITORY$/com/github/therapi/therapi-runtime-javadoc-scribe/0.15.0/therapi-runtime-javadoc-scribe-0.15.0.jar" /> <entry name="$MAVEN_REPOSITORY$/com/github/therapi/therapi-runtime-javadoc/0.15.0/therapi-runtime-javadoc-0.15.0.jar" /> @@ -30,8 +30,8 @@ <module name="api-rest-caculs" /> <module name="calculs" /> <module name="api-expositiondonneesentrees" /> - <module name="api-event-calculs" /> <module name="api-event-donneesEntrees" /> + <module name="api-event-calculs" /> </profile> </annotationProcessing> <bytecodeTargetLevel> diff --git a/services/.workspace/.idea/jarRepositories.xml b/services/.workspace/.idea/jarRepositories.xml index a6e9089d5710be85f86a10e8dd7857a972a3ed06..1ac99b6fa704cea1755d9c6cc2b2471a4859faba 100644 --- a/services/.workspace/.idea/jarRepositories.xml +++ b/services/.workspace/.idea/jarRepositories.xml @@ -11,6 +11,11 @@ <option name="name" value="gitlab-maven" /> <option name="url" value="https://gitlab-forge.din.developpement-durable.gouv.fr/api/v4/groups/5389/-/packages/maven" /> </remote-repository> + <remote-repository> + <option name="id" value="gitlab-maven" /> + <option name="name" value="gitlab-maven" /> + <option name="url" value="https://gitlab-forge.din.developpement-durable.gouv.fr/api/v4/projects/22954/packages/maven" /> + </remote-repository> <remote-repository> <option name="id" value="central" /> <option name="name" value="Maven Central repository" /> diff --git a/services/.workspace/.idea/misc.xml b/services/.workspace/.idea/misc.xml index 7363f2addc2ae079b7a7bae6dc57cb306cd08ee4..0ab13561ffaa90122bac87600be511be4b057512 100644 --- a/services/.workspace/.idea/misc.xml +++ b/services/.workspace/.idea/misc.xml @@ -15,7 +15,7 @@ </option> <option name="workspaceImportForciblyTurnedOn" value="true" /> </component> - <component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="temurin-17" project-jdk-type="JavaSDK"> + <component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="openjdk-21" project-jdk-type="JavaSDK"> <output url="file://$PROJECT_DIR$/out" /> </component> </project> \ No newline at end of file diff --git a/services/.workspace/.idea/runConfigurations/api_event_calculs__gen_sources_.xml b/services/.workspace/.idea/runConfigurations/api_event_calculs__gen_sources_.xml index af7bfa9f7ac6f008811d8da85534a6f465b76adf..b1f2a817f444a2201a3f550402eba1168a41991c 100644 --- a/services/.workspace/.idea/runConfigurations/api_event_calculs__gen_sources_.xml +++ b/services/.workspace/.idea/runConfigurations/api_event_calculs__gen_sources_.xml @@ -8,7 +8,7 @@ <option name="environmentProperties"> <map /> </option> - <option name="jreName" value="temurin-17" /> + <option name="jreName" value="openjdk-21" /> <option name="mavenProperties"> <map /> </option> diff --git a/services/.workspace/.idea/runConfigurations/api_expositiondonneesentrees__gen_sources_.xml b/services/.workspace/.idea/runConfigurations/api_expositiondonneesentrees__gen_sources_.xml index 89a394ebdd0c2167359695ce572b55d7013e2f4e..07aaa566e4aac35ababe6d361b1142468ea2a48d 100644 --- a/services/.workspace/.idea/runConfigurations/api_expositiondonneesentrees__gen_sources_.xml +++ b/services/.workspace/.idea/runConfigurations/api_expositiondonneesentrees__gen_sources_.xml @@ -8,7 +8,7 @@ <option name="environmentProperties"> <map /> </option> - <option name="jreName" value="temurin-17" /> + <option name="jreName" value="openjdk-21" /> <option name="mavenProperties"> <map /> </option> diff --git a/services/.workspace/.idea/runConfigurations/install_calculs.xml b/services/.workspace/.idea/runConfigurations/install_calculs.xml index d8b53028f2762392a24a01911a7bb5555cd6d5cf..29e0955b302000d0470af31efc9759613d32f046 100644 --- a/services/.workspace/.idea/runConfigurations/install_calculs.xml +++ b/services/.workspace/.idea/runConfigurations/install_calculs.xml @@ -8,7 +8,7 @@ <option name="environmentProperties"> <map /> </option> - <option name="jreName" value="temurin-17" /> + <option name="jreName" value="openjdk-21" /> <option name="mavenProperties"> <map /> </option> diff --git a/services/.workspace/.idea/runConfigurations/install_common.xml b/services/.workspace/.idea/runConfigurations/install_common.xml index 86ce6c8478833e04599599b7cf14b495f23f70ce..01d1be23dcf27f0317306d366e11144598da179f 100644 --- a/services/.workspace/.idea/runConfigurations/install_common.xml +++ b/services/.workspace/.idea/runConfigurations/install_common.xml @@ -8,7 +8,7 @@ <option name="environmentProperties"> <map /> </option> - <option name="jreName" value="temurin-17" /> + <option name="jreName" value="openjdk-21" /> <option name="mavenProperties"> <map /> </option> diff --git a/services/.workspace/.idea/runConfigurations/install_core.xml b/services/.workspace/.idea/runConfigurations/install_core.xml index 104f7ef69e0b2a705a3034cce45e074cd9d0864f..63ea27ee0ba053ae6d247b4097bc2b01a9114dc1 100644 --- a/services/.workspace/.idea/runConfigurations/install_core.xml +++ b/services/.workspace/.idea/runConfigurations/install_core.xml @@ -8,7 +8,7 @@ <option name="environmentProperties"> <map /> </option> - <option name="jreName" value="temurin-17" /> + <option name="jreName" value="openjdk-21" /> <option name="mavenProperties"> <map /> </option> diff --git a/services/api-event-calculs/dependency_check_suppressions.xml b/services/api-event-calculs/dependency_check_suppressions.xml deleted file mode 100644 index 15f53bbc9ca0caa969e8cf94333045ac34dbd899..0000000000000000000000000000000000000000 --- a/services/api-event-calculs/dependency_check_suppressions.xml +++ /dev/null @@ -1,97 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<suppressions xmlns="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.1.xsd"> - - <suppress> - <notes><![CDATA[ - file name: spring-security-crypto-5.7.3.jar - La librairie Spring Security est en version 5.7.3. - Cette CVE est marquée uniquement jusqu'à la version 5.2.4 (exclus) - https://nvd.nist.gov/vuln/detail/CVE-2020-5408 - ]]></notes> - <cve>CVE-2020-5408</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - file name: spring-web-5.3.22.jar - Dans notre contexte, nous ne recevons pas de code Java de l'extérieur et n'effectuons pas de dé-sérialisation de code Java - Côté Spring, le point est déjà remonté comme un faux-positif : https://github.com/spring-projects/spring-framework/issues/24434#issuecomment-744519525 - ]]></notes> - <cve>CVE-2016-1000027</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - file name: snakeyaml-1.33.jar - Faux-positif : la version de Snakeyaml est la 1.33, la CVE existe uniquement sur les versions < 1.32 - https://nvd.nist.gov/vuln/detail/CVE-2022-38752 - ]]></notes> - <cve>CVE-2022-38752</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Faux-positif sur toutes les librairies utils: https://github.com/jeremylong/DependencyCheck/issues/5213 - Concerne : software.amazon.awssdk:utils qui n'est pas utilisé - ]]></notes> - <cve>CVE-2021-4277</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Faux-positif : matchent à tort sur tous les commons : https://github.com/jeremylong/DependencyCheck/issues/5132 - ]]></notes> - <cve>CVE-2021-37533</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2022-1471</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2022-3064</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2021-4235</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : json-smart est une dépendance transitive. - Les json sont limités à la taille des inventaires : la taille des listes n'a pas réellement de limite - et c'est souhaités comme cela (traitement de gros volumes de données). - ]]></notes> - <cve>CVE-2023-1370</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Faux-Positif : Concerne hutool-json et json-java qui ne sont pas utilisés. - Le faux-positif se trouve sur json-path, jackson-core, accessors-smart et json-smart. - cf. https://github.com/jeremylong/DependencyCheck/issues/5502 - ]]></notes> - <cve>CVE-2022-45688</cve> - </suppress> - - - <suppress> - <notes><![CDATA[ - Faux-Positif : Conformément au lien, nous ne sommes pas dans un des cas de vulnérabilité. - cf. cf. https://github.com/jeremylong/DependencyCheck/issues/5502 - ]]></notes> - <cve>CVE-2023-20862</cve> - </suppress> -</suppressions> diff --git a/services/api-event-calculs/pom.xml b/services/api-event-calculs/pom.xml index ab3f9bb160a26111a80d0bc8cf0e1c39cb974a32..c654ab9ced9e1a1f6b77e9854577449e969a36cc 100644 --- a/services/api-event-calculs/pom.xml +++ b/services/api-event-calculs/pom.xml @@ -5,12 +5,12 @@ <parent> <groupId>org.mte.numecoeval</groupId> <artifactId>core</artifactId> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <relativePath/> <!-- lookup parent from repository --> </parent> <artifactId>api-event-calculs</artifactId> <name>api-event-calculs</name> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <description>api-event-calculs</description> <repositories> @@ -42,11 +42,12 @@ <dependency> <groupId>org.mte.numecoeval</groupId> <artifactId>common</artifactId> + <version>${project.version}</version> </dependency> <dependency> <groupId>org.mte.numecoeval</groupId> <artifactId>calculs</artifactId> - <version>1.2.2</version> + <version>${project.version}</version> </dependency> <dependency> @@ -127,6 +128,10 @@ <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> </dependency> + <dependency> + <groupId>io.swagger.core.v3</groupId> + <artifactId>swagger-annotations</artifactId> + </dependency> </dependencies> <build> @@ -229,9 +234,6 @@ <serviceInterface>true</serviceInterface> <serviceImplementation>false</serviceImplementation> <booleanGetterPrefix>is</booleanGetterPrefix> - <additionalModelTypeAnnotations> - @lombok.AllArgsConstructor;@lombok.Builder;@lombok.NoArgsConstructor - </additionalModelTypeAnnotations> </configOptions> </configuration> </execution> @@ -273,9 +275,6 @@ <serviceInterface>true</serviceInterface> <serviceImplementation>false</serviceImplementation> <booleanGetterPrefix>is</booleanGetterPrefix> - <additionalModelTypeAnnotations> - @lombok.AllArgsConstructor;@lombok.Builder;@lombok.NoArgsConstructor - </additionalModelTypeAnnotations> </configOptions> </configuration> </execution> diff --git a/services/api-event-calculs/src/main/java/org/mte/numecoeval/calculs/infrastructure/controller/ExceptionHandler.java b/services/api-event-calculs/src/main/java/org/mte/numecoeval/calculs/infrastructure/controller/ExceptionHandler.java index c9bd236f0749bf3557ae5e533e058d680b86ce9c..f39742a9c5fa0e96cd1d45a493184948be42d114 100644 --- a/services/api-event-calculs/src/main/java/org/mte/numecoeval/calculs/infrastructure/controller/ExceptionHandler.java +++ b/services/api-event-calculs/src/main/java/org/mte/numecoeval/calculs/infrastructure/controller/ExceptionHandler.java @@ -26,11 +26,12 @@ public class ExceptionHandler { * @return l'objet erreur */ private static ErreurRest writeErrorResponse(Exception ex, HttpStatus status) { - return ErreurRest.builder() - .status(status.value()) - .code(status.name()) - .timestamp(LocalDateTime.now()) - .message(ex.getLocalizedMessage()).build(); + var erreurRest = new ErreurRest(); + erreurRest.status(status.value()); + erreurRest.setCode(status.name()); + erreurRest.setTimestamp(LocalDateTime.now()); + erreurRest.setMessage(ex.getLocalizedMessage()); + return erreurRest; } @org.springframework.web.bind.annotation.ExceptionHandler(value = {CalculImpactException.class}) diff --git a/services/api-event-calculs/src/test/java/org/mte/numecoeval/calculs/infrastructure/service/sync/calculs/SyncCalculServiceTest.java b/services/api-event-calculs/src/test/java/org/mte/numecoeval/calculs/infrastructure/service/sync/calculs/SyncCalculServiceTest.java index ee05e985989cad00d2cf384551e943618da73567..a32cfcdff34b00a8fa1e39f917a41b16cbacde38 100644 --- a/services/api-event-calculs/src/test/java/org/mte/numecoeval/calculs/infrastructure/service/sync/calculs/SyncCalculServiceTest.java +++ b/services/api-event-calculs/src/test/java/org/mte/numecoeval/calculs/infrastructure/service/sync/calculs/SyncCalculServiceTest.java @@ -56,11 +56,8 @@ class SyncCalculServiceTest { Mockito.when(mainEquipementPhysiqueService.calcul(any())).thenReturn(calculSizes); - var syncCalculRest = mapper.readValue(""" - { - "equipementPhysiqueIds": [1,2] - } - """, SyncCalculRest.class); + var syncCalculRest = new SyncCalculRest(); + syncCalculRest.setEquipementPhysiqueIds(List.of(1L, 2L)); /* EXECUTE */ var actual = syncCalculService.calcul(syncCalculRest); @@ -85,11 +82,8 @@ class SyncCalculServiceTest { Mockito.when(mainMessagerieService.calcul(any())).thenReturn(calculSizes); - var syncCalculRest = mapper.readValue(""" - { - "messagerieIds": [10,20,30] - } - """, SyncCalculRest.class); + var syncCalculRest = new SyncCalculRest(); + syncCalculRest.setMessagerieIds(List.of(10L, 20L, 30L)); /* EXECUTE */ var actual = syncCalculService.calcul(syncCalculRest); diff --git a/services/api-event-donneesentrees/dependency_check_suppressions.xml b/services/api-event-donneesentrees/dependency_check_suppressions.xml deleted file mode 100644 index 15f53bbc9ca0caa969e8cf94333045ac34dbd899..0000000000000000000000000000000000000000 --- a/services/api-event-donneesentrees/dependency_check_suppressions.xml +++ /dev/null @@ -1,97 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<suppressions xmlns="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.1.xsd"> - - <suppress> - <notes><![CDATA[ - file name: spring-security-crypto-5.7.3.jar - La librairie Spring Security est en version 5.7.3. - Cette CVE est marquée uniquement jusqu'à la version 5.2.4 (exclus) - https://nvd.nist.gov/vuln/detail/CVE-2020-5408 - ]]></notes> - <cve>CVE-2020-5408</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - file name: spring-web-5.3.22.jar - Dans notre contexte, nous ne recevons pas de code Java de l'extérieur et n'effectuons pas de dé-sérialisation de code Java - Côté Spring, le point est déjà remonté comme un faux-positif : https://github.com/spring-projects/spring-framework/issues/24434#issuecomment-744519525 - ]]></notes> - <cve>CVE-2016-1000027</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - file name: snakeyaml-1.33.jar - Faux-positif : la version de Snakeyaml est la 1.33, la CVE existe uniquement sur les versions < 1.32 - https://nvd.nist.gov/vuln/detail/CVE-2022-38752 - ]]></notes> - <cve>CVE-2022-38752</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Faux-positif sur toutes les librairies utils: https://github.com/jeremylong/DependencyCheck/issues/5213 - Concerne : software.amazon.awssdk:utils qui n'est pas utilisé - ]]></notes> - <cve>CVE-2021-4277</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Faux-positif : matchent à tort sur tous les commons : https://github.com/jeremylong/DependencyCheck/issues/5132 - ]]></notes> - <cve>CVE-2021-37533</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2022-1471</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2022-3064</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2021-4235</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : json-smart est une dépendance transitive. - Les json sont limités à la taille des inventaires : la taille des listes n'a pas réellement de limite - et c'est souhaités comme cela (traitement de gros volumes de données). - ]]></notes> - <cve>CVE-2023-1370</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Faux-Positif : Concerne hutool-json et json-java qui ne sont pas utilisés. - Le faux-positif se trouve sur json-path, jackson-core, accessors-smart et json-smart. - cf. https://github.com/jeremylong/DependencyCheck/issues/5502 - ]]></notes> - <cve>CVE-2022-45688</cve> - </suppress> - - - <suppress> - <notes><![CDATA[ - Faux-Positif : Conformément au lien, nous ne sommes pas dans un des cas de vulnérabilité. - cf. cf. https://github.com/jeremylong/DependencyCheck/issues/5502 - ]]></notes> - <cve>CVE-2023-20862</cve> - </suppress> -</suppressions> diff --git a/services/api-event-donneesentrees/pom.xml b/services/api-event-donneesentrees/pom.xml index d423330cf6e10b2d1b4d2d7498ae8c2c44126715..9e0f64f4b8f28040b5173f10560eb2eb2259b41e 100644 --- a/services/api-event-donneesentrees/pom.xml +++ b/services/api-event-donneesentrees/pom.xml @@ -5,12 +5,12 @@ <parent> <groupId>org.mte.numecoeval</groupId> <artifactId>core</artifactId> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <relativePath/> <!-- lookup parent from repository --> </parent> <artifactId>api-event-donneesEntrees</artifactId> <name>api-event-donneesEntrees</name> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <description>api-event-donneesEntrees</description> <repositories> @@ -36,6 +36,7 @@ <dependency> <groupId>org.mte.numecoeval</groupId> <artifactId>common</artifactId> + <version>${project.version}</version> </dependency> <dependency> diff --git a/services/api-expositiondonneesentrees/README.md b/services/api-expositiondonneesentrees/README.md index 628853ac3b5589c2ed8a7d691bbda05c25a89473..ffbe1ffee0604b89eed4a406bc653ad4091a2567 100644 --- a/services/api-expositiondonneesentrees/README.md +++ b/services/api-expositiondonneesentrees/README.md @@ -6,11 +6,11 @@ Le contrat d'interface est disponible au format [OpenAPI 3](src/main/resources/s ## Pré-requis -- JDK 17 - - [Open JDK](https://jdk.java.net/java-se-ri/17) +- JDK 21 + - [Open JDK](https://jdk.java.net/java-se-ri/21) - [Coretto](https://docs.aws.amazon.com/corretto/latest/corretto-17-ug/downloads-list.html) - [Maven 3](https://maven.apache.org/download.cgi) -- Un IDE compatible avec Maven 3 et JDK 17 +- Un IDE compatible avec Maven 3 et JDK 21 ## Build diff --git a/services/api-expositiondonneesentrees/dependency_check_suppressions.xml b/services/api-expositiondonneesentrees/dependency_check_suppressions.xml deleted file mode 100644 index 7937ced36578ad474a7a2d84af4a487d30b95bf1..0000000000000000000000000000000000000000 --- a/services/api-expositiondonneesentrees/dependency_check_suppressions.xml +++ /dev/null @@ -1,99 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<suppressions xmlns="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.1.xsd"> - - <suppress> - <notes><![CDATA[ - file name: spring-security-crypto-5.7.3.jar - La librairie Spring Security est en version 5.7.3. - Cette CVE est marquée uniquement jusqu'à la version 5.2.4 (exclus) - https://nvd.nist.gov/vuln/detail/CVE-2020-5408 - ]]></notes> - <cve>CVE-2020-5408</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - file name: spring-web-5.3.22.jar - Dans notre contexte, nous ne recevons pas de code Java de l'extérieur et n'effectuons pas de dé-sérialisation de code Java - Côté Spring, le point est déjà remonté comme un faux-positif : https://github.com/spring-projects/spring-framework/issues/24434#issuecomment-744519525 - ]]></notes> - <cve>CVE-2016-1000027</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - file name: snakeyaml-1.33.jar - Faux-positif : la version de Snakeyaml est la 1.33, la CVE existe uniquement sur les versions < 1.32 - https://nvd.nist.gov/vuln/detail/CVE-2022-38752 - ]]></notes> - <cve>CVE-2022-38752</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Faux-positif sur toutes les librairies utils: https://github.com/jeremylong/DependencyCheck/issues/5213 - Concerne : software.amazon.awssdk:utils qui n'est pas utilisé - ]]></notes> - <cve>CVE-2021-4277</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Faux-positif : matchent à tort sur tous les commons : https://github.com/jeremylong/DependencyCheck/issues/5132 - ]]></notes> - <cve>CVE-2021-37533</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2022-1471</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2022-3064</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2021-4235</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : json-smart est une dépendance transitive. - Les json sont limités à la taille des inventaires : la taille des listes n'a pas réellement de limite - et c'est souhaités comme cela (traitement de gros volumes de données). - ]]></notes> - <cve>CVE-2023-1370</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Faux-Positif : Concerne hutool-json et json-java qui ne sont pas utilisés. - Le faux-positif se trouve sur json-path, jackson-core, accessors-smart et json-smart. - cf. https://github.com/jeremylong/DependencyCheck/issues/5502 - ]]></notes> - <cve>CVE-2022-45688</cve> - </suppress> - - - <suppress> - <notes><![CDATA[ - Faux-Positif : Conformément au lien, nous ne sommes pas dans un des cas de vulnérabilité. - cf. cf. https://github.com/jeremylong/DependencyCheck/issues/5502 - ]]></notes> - <cve>CVE-2023-20862</cve> - </suppress> - - -</suppressions> diff --git a/services/api-expositiondonneesentrees/pom.xml b/services/api-expositiondonneesentrees/pom.xml index 756f58252907bca4d210a9816dcc710c7d530108..93f48cdcf4efa45456d8697d2966048ef6a7e42a 100644 --- a/services/api-expositiondonneesentrees/pom.xml +++ b/services/api-expositiondonneesentrees/pom.xml @@ -5,11 +5,11 @@ <parent> <groupId>org.mte.numecoeval</groupId> <artifactId>core</artifactId> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <relativePath/> <!-- lookup parent from repository --> </parent> <artifactId>api-expositiondonneesentrees</artifactId> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <name>api-expositiondonneesentrees</name> <description>API Exposition des données d'entrées - Exposition par API pour injecter des données d'entrées </description> @@ -39,6 +39,7 @@ <dependency> <groupId>org.mte.numecoeval</groupId> <artifactId>common</artifactId> + <version>${project.version}</version> </dependency> <!-- REST --> @@ -79,6 +80,10 @@ <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> </dependency> + <dependency> + <groupId>io.swagger.core.v3</groupId> + <artifactId>swagger-annotations</artifactId> + </dependency> <!-- Security --> <dependency> @@ -297,7 +302,7 @@ <serviceImplementation>false</serviceImplementation> <booleanGetterPrefix>is</booleanGetterPrefix> <additionalModelTypeAnnotations> - @lombok.AllArgsConstructor;@lombok.Builder;@lombok.NoArgsConstructor + @lombok.experimental.SuperBuilder </additionalModelTypeAnnotations> </configOptions> </configuration> diff --git a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/domain/ports/input/ImportDonneesEntreePort.java b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/domain/ports/input/ImportDonneesEntreePort.java index 311996e6b49d378f9c4cec73c423fa26d5a95753..60aad67f37ea07507fcf10029e705b2ce1035d92 100644 --- a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/domain/ports/input/ImportDonneesEntreePort.java +++ b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/domain/ports/input/ImportDonneesEntreePort.java @@ -21,9 +21,8 @@ public interface ImportDonneesEntreePort { String MESSAGERIE_CSV_HEADER = "nombreMailEmis;nombreMailEmisXDestinataires;volumeTotalMailEmis;MoisAnnee"; String ENTITE_CSV_HEADER = "nomEntite;nbCollaborateurs;responsableEntite;responsableNumeriqueDurable"; - ResultatImport importCsv(MultipartFile csvDataCenter, MultipartFile csvEquipementPhysique, MultipartFile csvEquipementVirtuel, - MultipartFile csvApplication, MultipartFile csvMessagerie, MultipartFile csvEntite, - String dateLot, String nomOrganisation, String nomLot); + ResultatImport importCsv(String nomOrganisation, String nomLot, String dateLot, MultipartFile csvDataCenter, MultipartFile csvEquipementPhysique, MultipartFile csvEquipementVirtuel, + MultipartFile csvApplication, MultipartFile csvMessagerie, MultipartFile csvEntite); Pair<RapportImport, List<DataCenter>> importDataCenter(String nomLot, LocalDate dateLot, String nomOrganisation, MultipartFile csvDataCenter); diff --git a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/domain/ports/input/impl/ImportDonneesEntreePortImpl.java b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/domain/ports/input/impl/ImportDonneesEntreePortImpl.java index 9a5978c9bf92e023b48f91fe6de2d8ba8eb7523f..2b1557429d22610d08bbe2389ff8ebec0ddb5a4c 100644 --- a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/domain/ports/input/impl/ImportDonneesEntreePortImpl.java +++ b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/domain/ports/input/impl/ImportDonneesEntreePortImpl.java @@ -14,6 +14,7 @@ import org.mte.numecoeval.expositiondonneesentrees.infrastructure.service.ErrorM import org.mte.numecoeval.expositiondonneesentrees.referentiels.generated.api.model.TypeEquipementDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.web.multipart.MultipartFile; import java.io.FileNotFoundException; @@ -52,14 +53,18 @@ public class ImportDonneesEntreePortImpl implements ImportDonneesEntreePort { final Map<String, String> errorMessages; + @Value("#{'${constraints.mode-utilisation}'.split(',')}") + private List<String> modeUtilisationList; + @Override - public ResultatImport importCsv(MultipartFile csvDataCenter, + public ResultatImport importCsv(String nomOrganisation, String nomLot, String dateLot, + MultipartFile csvDataCenter, MultipartFile csvEquipementPhysique, MultipartFile csvEquipementVirtuel, MultipartFile csvApplication, MultipartFile csvMessagerie, - MultipartFile csvEntite, - String dateLot, String nomOrganisation, String nomLot) { + MultipartFile csvEntite + ) { LocalDate dateLotAsDate = dateLot == null || "".equals(dateLot) ? null : LocalDate.parse(dateLot); ResultatImport resultatImport = new ResultatImport(); @@ -201,8 +206,14 @@ public class ImportDonneesEntreePortImpl implements ImportDonneesEntreePort { var goTelechargeStr = CSVHelper.safeString(csvRecord, "goTelecharge"); Float goTelecharge = goTelechargeStr == null ? null : NumberUtils.toFloat(goTelechargeStr); var tauxUtilisationStr = CSVHelper.safeString(csvRecord, "tauxUtilisation"); - Double tauxUtilisation = tauxUtilisationStr == null ? null : NumberUtils.toDouble(tauxUtilisationStr); - + Double tauxUtilisation = NumberUtils.isCreatable(tauxUtilisationStr) ? NumberUtils.toDouble(tauxUtilisationStr) : null; + if (tauxUtilisation != null && (tauxUtilisation < 0 || tauxUtilisation > 1)) { + tauxUtilisation = null; + } + var modeUtilisation = CSVHelper.safeString(csvRecord, "modeUtilisation"); + if (!modeUtilisationList.contains(modeUtilisation)) { + modeUtilisation = null; + } EquipementPhysique equipementToAdd = EquipementPhysique.builder() .statutTraitement(STATUT_TRAITEMENT_EN_ATTENTE) @@ -221,7 +232,7 @@ public class ImportDonneesEntreePortImpl implements ImportDonneesEntreePort { .nbCoeur(CSVHelper.safeString(csvRecord, "nbCoeur")) .nomCourtDatacenter(CSVHelper.safeString(csvRecord, "nomCourtDatacenter", "refDatacenter")) .goTelecharge(goTelecharge) - .modeUtilisation(CSVHelper.safeString(csvRecord, "modeUtilisation")) + .modeUtilisation(modeUtilisation) .tauxUtilisation(tauxUtilisation) .nbJourUtiliseAn(CSVHelper.safeDouble(csvRecord, "nbJourUtiliseAn")) .consoElecAnnuelle(CSVHelper.safeDouble(csvRecord, "consoElecAnnuelle")) diff --git a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/domain/ports/input/impl/StatutPourCalculPortImpl.java b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/domain/ports/input/impl/StatutPourCalculPortImpl.java index 6832764f3900b454f45278a346a71f2a5ba7cc95..39da64041253166f03d96ff6a093bcfd01f3632d 100644 --- a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/domain/ports/input/impl/StatutPourCalculPortImpl.java +++ b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/domain/ports/input/impl/StatutPourCalculPortImpl.java @@ -51,11 +51,11 @@ public class StatutPourCalculPortImpl implements StatutPourCalculPort { var statut = StatutCalculRest.StatutEnum.EN_COURS; if (etat == 100) statut = StatutCalculRest.StatutEnum.TERMINE; - var result = new StatutCalculRest(); - result.setStatut(statut); - result.setEtat(etat + "%"); - result.setEquipementPhysique(volumeMapper.toRest(volumeEqPh)); - result.setMessagerie(volumeMapper.toRest(volumeMessagerie)); - return result; + return StatutCalculRest.builder() + .statut(statut) + .etat(etat + "%") + .equipementPhysique(volumeMapper.toRest(volumeEqPh)) + .messagerie(volumeMapper.toRest(volumeMessagerie)) + .build(); } } diff --git a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/config/ApplicationPortConfig.java b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/config/ApplicationPortConfig.java index ecc79a180445b56b58d736660969c1c9bae6c806..7a62c6b92eb85a818dda843aadf2fcb05f9e3fb7 100644 --- a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/config/ApplicationPortConfig.java +++ b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/config/ApplicationPortConfig.java @@ -9,6 +9,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import java.util.List; + @Configuration @AllArgsConstructor @ComponentScan(basePackages = "org.mte.numecoeval.expositiondonneesentrees.infrastructure.adapters") @@ -18,9 +20,10 @@ public class ApplicationPortConfig { private ErrorManagementService errorManagementService; private MessageProperties messageProperties; + private List<String> modeUtilisationList; @Bean public ImportDonneesEntreePort importDonneesEntreePort() { - return new ImportDonneesEntreePortImpl(referentielServicePort, errorManagementService, messageProperties.getMessages()); + return new ImportDonneesEntreePortImpl(referentielServicePort, errorManagementService, messageProperties.getMessages(), modeUtilisationList); } } diff --git a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/config/MessageProperties.java b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/config/MessageProperties.java index 2b155075ddec16d50ac936ab41858b4f18393588..6675bb9df2ef2255b7f3218d8d22790e6ce28a45 100644 --- a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/config/MessageProperties.java +++ b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/config/MessageProperties.java @@ -6,7 +6,7 @@ import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.stereotype.Component; -import java.util.HashMap; +import java.util.Map; @Component @EnableConfigurationProperties @@ -15,6 +15,6 @@ import java.util.HashMap; @Setter public class MessageProperties { - private HashMap<String, String> messages; + private Map<String, String> messages; } diff --git a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/controller/ImportCSVController.java b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/controller/ImportCSVController.java index f89236569276bdcbd539dbce4b1b15e183824c8e..80a48f93904645008f71660eeeea325f3403da9a 100644 --- a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/controller/ImportCSVController.java +++ b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/controller/ImportCSVController.java @@ -41,14 +41,14 @@ public class ImportCSVController implements ImportsApi { ErrorManagementPostSaveService errorManagementPostSaveService; @Override - public ResponseEntity<List<RapportImportRest>> importCSV(String nomLot, MultipartFile csvDataCenter, MultipartFile csvEquipementPhysique, MultipartFile csvEquipementVirtuel, MultipartFile csvApplication, MultipartFile csvMessagerie, MultipartFile csvEntite, String dateLot, String nomOrganisation) { - return importInterneCSV(nomLot, dateLot, nomOrganisation, csvDataCenter, csvEquipementPhysique, csvEquipementVirtuel, csvApplication, csvMessagerie, csvEntite); + public ResponseEntity<List<RapportImportRest>> importCSV(String nomOrganisation, String nomLot, String dateLot, MultipartFile csvDataCenter, MultipartFile csvEquipementPhysique, MultipartFile csvEquipementVirtuel, MultipartFile csvApplication, MultipartFile csvMessagerie, MultipartFile csvEntite) { + return importInterneCSV(nomOrganisation, nomLot, dateLot, csvDataCenter, csvEquipementPhysique, csvEquipementVirtuel, csvApplication, csvMessagerie, csvEntite); } - public ResponseEntity<List<RapportImportRest>> importInterneCSV(String nomLot, String dateLot, String nomOrganisation, MultipartFile csvDataCenter, MultipartFile csvEquipementPhysique, MultipartFile csvEquipementVirtuel, MultipartFile csvApplication, MultipartFile csvMessagerie, MultipartFile csvEntite) { + public ResponseEntity<List<RapportImportRest>> importInterneCSV(String nomOrganisation, String nomLot, String dateLot, MultipartFile csvDataCenter, MultipartFile csvEquipementPhysique, MultipartFile csvEquipementVirtuel, MultipartFile csvApplication, MultipartFile csvMessagerie, MultipartFile csvEntite) { return ResponseEntity.ok( importDonneesFromCSV( - nomLot, dateLot, nomOrganisation, + nomOrganisation, nomLot, dateLot, csvDataCenter, csvEquipementPhysique, csvEquipementVirtuel, @@ -68,18 +68,18 @@ public class ImportCSVController implements ImportsApi { } public List<RapportImportRest> importDonneesFromCSV( - String nomLot, String dateLot, String nomOrganisation, + String nomOrganisation, String nomLot, String dateLot, MultipartFile csvDataCenter, MultipartFile csvEquipementPhysique, MultipartFile csvEquipementVirtuel, MultipartFile csvApplication, MultipartFile csvMessagerie, MultipartFile csvEntite) throws ValidationException { - LOGGER.info("Reception de fichiers pour imports de données d'entrées : Nom de Lot : {}, Date de lot : {}, Nom Organisation : {}", nomLot, dateLot, nomOrganisation); + LOGGER.info("Reception de fichiers pour imports de données d'entrées :Nom Organisation : {}, Nom de Lot : {}, Date de lot : {}", nomOrganisation, nomLot, dateLot); - validateRequestParametersForImportCSV(nomLot, dateLot, csvDataCenter, csvEquipementPhysique, csvEquipementVirtuel, csvApplication, csvMessagerie, csvEntite); + validateRequestParametersForImportCSV(nomOrganisation, nomLot, dateLot, csvDataCenter, csvEquipementPhysique, csvEquipementVirtuel, csvApplication, csvMessagerie, csvEntite); - return importAllCsv(csvDataCenter, csvEquipementPhysique, csvEquipementVirtuel, csvApplication, csvMessagerie, csvEntite, dateLot, nomOrganisation, nomLot); + return importAllCsv(nomOrganisation, nomLot, dateLot, csvDataCenter, csvEquipementPhysique, csvEquipementVirtuel, csvApplication, csvMessagerie, csvEntite); } /** @@ -95,7 +95,7 @@ public class ImportCSVController implements ImportsApi { * @param csvEntite Fichier CSV des entités * @throws ResponseStatusException avec le statut 400 lorsque les entrées ne sont pas cohérentes. */ - private void validateRequestParametersForImportCSV(String nomLot, String dateLot, MultipartFile csvDataCenter, MultipartFile csvEquipementPhysique, MultipartFile csvEquipementVirtuel, MultipartFile csvApplication, MultipartFile csvMessagerie, MultipartFile csvEntite) { + private void validateRequestParametersForImportCSV(String nomOrganisation, String nomLot, String dateLot, MultipartFile csvDataCenter, MultipartFile csvEquipementPhysique, MultipartFile csvEquipementVirtuel, MultipartFile csvApplication, MultipartFile csvMessagerie, MultipartFile csvEntite) { if (CSVHelper.fileIsNullOrEmpty(csvDataCenter) && CSVHelper.fileIsNullOrEmpty(csvEquipementPhysique) && CSVHelper.fileIsNullOrEmpty(csvEquipementVirtuel) @@ -111,6 +111,10 @@ public class ImportCSVController implements ImportsApi { LOGGER.error("Import: Erreur contrôle : Le nom du Lot ne peut être pas vide"); throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Le nom du Lot ne peut être pas vide"); } + if (StringUtils.isBlank(nomOrganisation)) { + LOGGER.error("Import: Erreur contrôle : Le nom de l'organisation ne peut être pas vide"); + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, " Le nom de l'organisation ne peut être pas vide"); + } if (dateLot != null && !"".equals(dateLot)) { try { @@ -138,9 +142,9 @@ public class ImportCSVController implements ImportsApi { * @return {@link List} des {@link RapportImportRest} correspondant à l'import * @throws ValidationException en cas d'absence de donner à pousser dans le système. */ - private List<RapportImportRest> importAllCsv(MultipartFile csvDataCenter, MultipartFile csvEquipementPhysique, MultipartFile csvEquipementVirtuel, MultipartFile csvApplication, MultipartFile csvMessagerie, MultipartFile csvEntite, String dateLot, String nomOrganisation, String nomLot) throws ValidationException { + private List<RapportImportRest> importAllCsv(String nomOrganisation, String nomLot, String dateLot, MultipartFile csvDataCenter, MultipartFile csvEquipementPhysique, MultipartFile csvEquipementVirtuel, MultipartFile csvApplication, MultipartFile csvMessagerie, MultipartFile csvEntite) throws ValidationException { // Lecture & conversion - var resultatImport = importDonneesEntreePort.importCsv(csvDataCenter, csvEquipementPhysique, csvEquipementVirtuel, csvApplication, csvMessagerie, csvEntite, dateLot, nomOrganisation, nomLot); + var resultatImport = importDonneesEntreePort.importCsv(nomOrganisation, nomLot, dateLot, csvDataCenter, csvEquipementPhysique, csvEquipementVirtuel, csvApplication, csvMessagerie, csvEntite); saveDonneesEntreePort.save(resultatImport.getDonneesEntree()); diff --git a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/service/ErrorManagementService.java b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/service/ErrorManagementService.java index 952379b7acbcdeaf9a01a8488019dd731bf7dd52..473a1a4e1fed90602ece904dcfee3464a3919c43 100644 --- a/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/service/ErrorManagementService.java +++ b/services/api-expositiondonneesentrees/src/main/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/service/ErrorManagementService.java @@ -92,7 +92,7 @@ public class ErrorManagementService { // CA 3.1 // L'ajout d'un équipement dont le date de retrait (equipementPhysique.DateRetrait) précède la date d'achat (equipementPhysique.DateAchat) if (equipementPhysique.getDateAchat() != null && equipementPhysique.getDateRetrait() != null && - equipementPhysique.getDateAchat().isBefore(equipementPhysique.getDateRetrait())) { + equipementPhysique.getDateAchat().isAfter(equipementPhysique.getDateRetrait())) { erreurs.add(messageProperties.getMessages().get("EQUIPEMENT_DATE_INCOHERENTE").formatted(equipementPhysique.getNomEquipementPhysique())); } diff --git a/services/api-expositiondonneesentrees/src/main/resources/static/openapi.yaml b/services/api-expositiondonneesentrees/src/main/resources/static/openapi.yaml index 9cd38d0d6829013d3d9ef083404f41e5f8c46e93..821abfa69dc5d0dfdf300e14f99f09649aae2c83 100644 --- a/services/api-expositiondonneesentrees/src/main/resources/static/openapi.yaml +++ b/services/api-expositiondonneesentrees/src/main/resources/static/openapi.yaml @@ -168,15 +168,25 @@ paths: - Imports summary: Soumission de données d'entrées au format CSV pour calcul d'indicateurs description: | - Endpoint de soumission des données d'entrées au format CSV pour le calcul d'indicateurs. \ - La taille totale de tous les fichiers ne doit pas dépasser 10 Mo. \ - Le séparateur des fichiers CSV est le point-virgule (;). \ - Le Header du CSV des data centers est : nomCourtDatacenter;nomLongDatacenter;pue;localisation;nomSourceDonnee \ - Le Header du CSV des équipements physiques est : modele;quantite;nomEquipementPhysique;type;statut;paysDUtilisation;utilisateur;dateAchat;dateRetrait;nbCoeur;nomCourtDatacenter;goTelecharge;modeUtilisation;tauxUtilisation;nbJourUtiliseAn;consoElecAnnuelle;nomSourceDonnee \ - Le Header du CSV des équipements virtuels est : nomEquipementVirtuel;nomEquipementPhysique;vCPU;cluster;nomSourceDonnee;nomSourceEquipementPhysique;consoElecAnnuelle;typeEqv;capaciteStockage;cleRepartition \ - Le Header du CSV des application est : nomApplication;typeEnvironnement;nomEquipementVirtuel;nomEquipementPhysique;domaine;sousDomaine;nomSourceDonnee;typeEqv;nomSourceEquipementVirtuel;capaciteStockage;cleRepartition \ - Le Header du CSV de la messagerie est : nombreMailEmis;nombreMailEmisXDestinataires;volumeTotalMailEmis;MoisAnnee;nomSourceDonnee \ - Le Header du CSV des entités est : nomEntite;nbCollaborateurs;responsableEntite;responsableNumeriqueResponsable;nomSourceDonnee + Endpoint de soumission des données d'entrées au format CSV pour le calcul d'indicateurs. + + La taille totale de tous les fichiers ne doit pas dépasser 10 Mo. <br/> + + Le séparateur des fichiers CSV est le point-virgule (;). <br/> + + Les colonnes facultatives sont notées entre parenthèses, toutes les autres sont obligatoires ! <br/> + + Le Header du CSV des data centers est : nomCourtDatacenter;nomLongDatacenter;pue;localisation;(nomEntite). <br/> + + Le Header du CSV des équipements physiques est : nomEquipementPhysique,modele;quantite;nomCourtDatacenter;dateAchat;dateRetrait;type;statut;paysDUtilisation;consoElecAnnuelle;utilisateur;(nomSourceDonnee);(nomEntite);nbCoeur;nbJourUtiliseAn;goTelecharge;(modeUtilisation);(tauxUtilisation). <br/> + + Le Header du CSV des équipements virtuels est : nomEquipementVirtuel;nomEquipementPhysique;(nomSourceDonneeEquipementPhysique);(cleRepartition);vCPU;cluster;(consoElecAnnuelle);(typeEqv);(capaciteStockage);(nomEntite). <br/> + + Le Header du CSV des application est : nomApplication;typeEnvironnement;(nomEquipementVirtuel);(nomSourceEquipementVirtuel);domaine;sousDomaine;(nomEntite);nomEquipementPhysique;(nomSourceDonnee). <br/> + + Le Header du CSV de la messagerie est : nombreMailEmis;nombreMailEmisXDestinataires;volumeTotalMailEmis;MoisAnnee;(nomEntite). <br/> + + Le Header du CSV des entités est : nomEntite;nbCollaborateurs;responsableEntite;responsableNumeriqueResponsable. operationId: importCSV requestBody: @@ -186,7 +196,14 @@ paths: type: object required: - nomLot + - nomOrganisation properties: + nomOrganisation: + type: string + nomLot: + type: string + dateLot: + type: string csvDataCenter: type: string format: binary @@ -205,12 +222,7 @@ paths: csvEntite: type: string format: binary - dateLot: - type: string - nomOrganisation: - type: string - nomLot: - type: string + responses: "500": description: Erreur interne du service diff --git a/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/domain/port/input/ImportDonneesEntreePortImplTest.java b/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/domain/port/input/ImportDonneesEntreePortImplTest.java index 0bdb213e5c574fc002de9fc6f57da89459227be6..a92ad7fc80a14c33aa6e99fc16bb9a3482731263 100644 --- a/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/domain/port/input/ImportDonneesEntreePortImplTest.java +++ b/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/domain/port/input/ImportDonneesEntreePortImplTest.java @@ -31,11 +31,12 @@ class ImportDonneesEntreePortImplTest { ImportDonneesEntreePortImpl importDonneesEntreePort; ErrorManagementService errorManagementService; + private List<String> modeUtilisationList; @BeforeEach public void init() { MockitoAnnotations.openMocks(this); - importDonneesEntreePort = new ImportDonneesEntreePortImpl(referentielServicePort, errorManagementService, errorMessages); + importDonneesEntreePort = new ImportDonneesEntreePortImpl(referentielServicePort, errorManagementService, errorMessages, modeUtilisationList); } @Test diff --git a/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/domain/port/input/StatutPourCalculPortImplTest.java b/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/domain/port/input/StatutPourCalculPortImplTest.java index e5162cec935f1e158d5a0b112e9465a8205e7589..759780e146182eda45ed3fccfc9c797dc81d13f7 100644 --- a/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/domain/port/input/StatutPourCalculPortImplTest.java +++ b/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/domain/port/input/StatutPourCalculPortImplTest.java @@ -11,6 +11,7 @@ import org.mte.numecoeval.expositiondonneesentrees.domain.exception.NotFoundExce import org.mte.numecoeval.expositiondonneesentrees.domain.model.Volume; import org.mte.numecoeval.expositiondonneesentrees.domain.ports.input.impl.StatutPourCalculPortImpl; import org.mte.numecoeval.expositiondonneesentrees.generated.api.model.StatutCalculRest; +import org.mte.numecoeval.expositiondonneesentrees.generated.api.model.VolumeRest; import org.mte.numecoeval.expositiondonneesentrees.infrastructure.mapper.VolumeMapper; import org.springframework.test.util.ReflectionTestUtils; import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper; @@ -47,20 +48,18 @@ class StatutPourCalculPortImplTest { /* EXECUTE : params does not matter in the test */ var actual = statutPourCalculPort.statutCalculs(volumeEqPhysique, volumeMessagerie); - var expected = mapper.readValue(""" - { - "statut" : "EN_COURS", - "etat" : "98%", - "equipementPhysique" : { - "nbEnCours" : 10, - "nbTraite" : 100 - }, - "messagerie" : { - "nbEnCours" : 50, - "nbTraite" : 5000 - } - } - """, StatutCalculRest.class); + var expected = StatutCalculRest.builder() + .statut(StatutCalculRest.StatutEnum.EN_COURS) + .etat("98%") + .equipementPhysique(VolumeRest.builder() + .nbEnCours(10) + .nbTraite(100) + .build()) + .messagerie(VolumeRest.builder() + .nbEnCours(50) + .nbTraite(5000) + .build()) + .build(); /* ASSERT */ assertEquals(mapper.writeValueAsString(expected), mapper.writeValueAsString(actual)); @@ -77,20 +76,18 @@ class StatutPourCalculPortImplTest { /* EXECUTE : params does not matter in the test */ var actual = statutPourCalculPort.statutCalculs(volumeEqPhysique, volumeMessagerie); - var expected = mapper.readValue(""" - { - "statut" : "TERMINE", - "etat" : "100%", - "equipementPhysique" : { - "nbEnCours" : 0, - "nbTraite" : 100 - }, - "messagerie" : { - "nbEnCours" : 0, - "nbTraite" : 5000 - } - } - """, StatutCalculRest.class); + var expected = StatutCalculRest.builder() + .statut(StatutCalculRest.StatutEnum.TERMINE) + .etat("100%") + .equipementPhysique(VolumeRest.builder() + .nbEnCours(0) + .nbTraite(100) + .build()) + .messagerie(VolumeRest.builder() + .nbEnCours(0) + .nbTraite(5000) + .build()) + .build(); /* ASSERT */ assertEquals(mapper.writeValueAsString(expected), mapper.writeValueAsString(actual)); diff --git a/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/controller/ImportCSVControllerTest.java b/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/controller/ImportCSVControllerTest.java index e8ca5bc9d0df40d9a919021536b090502444c096..a38ae6109bbf325cdd1341d3d9851d02db9489c5 100644 --- a/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/controller/ImportCSVControllerTest.java +++ b/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/controller/ImportCSVControllerTest.java @@ -91,7 +91,7 @@ class ImportCSVControllerTest { MockMultipartFile csvMessagerie = null; MockMultipartFile csvEntite = null; - var exception = assertThrows(ResponseStatusException.class, () -> importCSVController.importInterneCSV(nomLot, "2023-01-01", "TEST", csvDataCenters, csvEquipements, csvEquipementsVirtuels, csvApplications, csvMessagerie, csvEntite)); + var exception = assertThrows(ResponseStatusException.class, () -> importCSVController.importInterneCSV("TEST", nomLot, "2023-01-01", csvDataCenters, csvEquipements, csvEquipementsVirtuels, csvApplications, csvMessagerie, csvEntite)); assertEquals(HttpStatus.BAD_REQUEST, exception.getStatusCode()); assertEquals("Le nom du Lot ne peut être pas vide", exception.getReason()); diff --git a/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/service/ErrorManagementServiceTest.java b/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/service/ErrorManagementServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0e4adc46067632e80213c44e6c6ee6bb155b6e2b --- /dev/null +++ b/services/api-expositiondonneesentrees/src/test/java/org/mte/numecoeval/expositiondonneesentrees/infrastructure/service/ErrorManagementServiceTest.java @@ -0,0 +1,89 @@ +package org.mte.numecoeval.expositiondonneesentrees.infrastructure.service; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mte.numecoeval.expositiondonneesentrees.domain.model.EquipementPhysique; +import org.mte.numecoeval.expositiondonneesentrees.domain.ports.output.ReferentielServicePort; +import org.mte.numecoeval.expositiondonneesentrees.infrastructure.config.MessageProperties; + +import java.io.IOException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +@ExtendWith(MockitoExtension.class) +public class ErrorManagementServiceTest { + @Mock + MessageProperties messageProperties; + @InjectMocks + ErrorManagementService errorManagementService; + @Mock + ReferentielServicePort referentielServicePort; + + private Map<String, String> messages = new HashMap<>(); + + @BeforeEach + public void init() { + List<String> modeUtilisationList = new ArrayList<>(); + errorManagementService = new ErrorManagementService(messageProperties, referentielServicePort, modeUtilisationList); + messages.put("LIGNE_INCONSISTENTE", "Fichier %s , La ligne n°%d n'est pas consistente avec les headers du fichier"); + messages.put("LIGNE_INCORRECTE", "Fichier %s , La ligne n°%d est incorrecte pour l'objet %s requise"); + messages.put("TYPE_EQUIPEMENT_INCONNU", "Le type d'équipement %s correspondant à l'équipement %s n'existe pas dans la table des références ref_TypeEquipement"); + messages.put("EQUIPEMENT_MIX_ELEC_LOCALISATION_INCONNUE", "Le pays %s correspondant à l'équipement physique %s n'existe pas dans la table des mix électriques ref_MixElec.pays"); + messages.put("DATACENTER_MIX_ELEC_LOCALISATION_INCONNUE", "La localisation %s du centre de données %s n'existe pas dans la table des mix électriques ref_MixElec.pays"); + messages.put("EQUIPEMENT_CORRESPONDANCE_INCONNUE", "L'équipement %s de type %s ne possède pas de référence d'équipement par défaut dans la table ref_typeEquipement et pas de correspondance dans la table ref_CorrespondanceRefEqP"); + messages.put("EQUIPEMENT_IMPACT_INCONNU", "L'impact de l'équipement de référence %s pour l'étape %s et le critère %s ne pourra pas être calculé en raison de l'absence de facteur d'impact sur l'équipement"); + messages.put("EQUIPEMENT_DATE_INCOHERENTE", "L'âge de l'équipement %s ne peut être calculé car sa date de retrait précède sa date d'achat"); + messages.put("EQUIPEMENT_MODE_UTILISATION_INCONNU", "Le mode d'utilisation renseigné '%s' est inconnu du référentiel"); + messages.put("EQUIPEMENT_TAUX_UTILISATION_INVALIDE", "Le taux d'utilisation renseigné '%s' n'est pas valide, il doit être compris entre 0 et 1, le taux par défaut sera appliqué."); + messages.put("EQUIPEMENT_DATACENTER_INCONNU", "L'équipement %s n'est lié à aucun datacenter"); + messages.put("EQUIPEMENT_VIRTUEL_INCONNU", "L'équipement virtuel %s n'est supporté par aucun équipement physique"); + messages.put("APPLICATION_AVEC_EQUIPEMENT_PHYSIQUE_INCONNU", "L'application %s n'est supporté par aucun équipement physique"); + messages.put("APPLICATION_AVEC_EQUIPEMENT_VIRTUEL_INCONNU", "L'application %s n'est supporté par aucun équipement virtuel"); + Mockito.lenient().when(messageProperties.getMessages()).thenReturn(messages); + } + + @Test + void importEqPhysique_with_DateEntreeAfterDateRetrait_shouldReturnReportWith1Error() throws IOException { + EquipementPhysique eq1 = EquipementPhysique.builder() + .nomEquipementPhysique("physical-eq-001") + .modele("P2719") + .quantite(1.0) + .dateAchat(LocalDate.of(2023, 3, 30)) + .dateRetrait(LocalDate.of(2023, 1, 17)) + .type("Monitor") + .statut("In use") + .paysDUtilisation("France") + .modeUtilisation("COPE").build(); + + var actual = errorManagementService.checkEquipementPhysique(eq1, ""); + assertTrue(actual.getKey().stream().anyMatch(ds -> "L'âge de l'équipement physical-eq-001 ne peut être calculé car sa date de retrait précède sa date d'achat".equals(ds))); + } + + @Test + void importEqPhysique_with_DateEntreeAfterDateRetrait_shouldNotReturnReportWith1Error() throws IOException { + EquipementPhysique eq1 = EquipementPhysique.builder() + .nomEquipementPhysique("physical-eq-001") + .modele("P2719") + .quantite(1.0) + .dateAchat(LocalDate.of(2021, 3, 30)) + .dateRetrait(LocalDate.of(2023, 1, 17)) + .type("Monitor") + .statut("In use") + .paysDUtilisation("France") + .modeUtilisation("COPE").build(); + + var actual = errorManagementService.checkEquipementPhysique(eq1, ""); + assertFalse(actual.getKey().stream().anyMatch(ds -> "L'âge de l'équipement physical-eq-001 ne peut être calculé car sa date de retrait précède sa date d'achat".equals(ds))); + } +} diff --git a/services/api-expositiondonneesentrees/src/test/resources/equipementPhysique.csv b/services/api-expositiondonneesentrees/src/test/resources/equipementPhysique.csv index dec2cbe1fa34fe8d08aa4031b70da63b6399cc3f..76afcce70ff76ee90f90d4d15968a22d2d206f0f 100644 --- a/services/api-expositiondonneesentrees/src/test/resources/equipementPhysique.csv +++ b/services/api-expositiondonneesentrees/src/test/resources/equipementPhysique.csv @@ -1,2 +1,2 @@ test -test +test \ No newline at end of file diff --git a/services/api-referentiel/api-referentiel.iml b/services/api-referentiel/api-referentiel.iml new file mode 100644 index 0000000000000000000000000000000000000000..d5bc377d18926496c6e4b7e2aaac604f19d46655 --- /dev/null +++ b/services/api-referentiel/api-referentiel.iml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<module version="4"> + <component name="SonarLintModuleSettings"> + <option name="uniqueId" value="f6788965-8e1c-4fa4-b11f-37fed51ad998" /> + </component> +</module> \ No newline at end of file diff --git a/services/api-referentiel/dependency_check_suppressions.xml b/services/api-referentiel/dependency_check_suppressions.xml deleted file mode 100644 index 15f53bbc9ca0caa969e8cf94333045ac34dbd899..0000000000000000000000000000000000000000 --- a/services/api-referentiel/dependency_check_suppressions.xml +++ /dev/null @@ -1,97 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<suppressions xmlns="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.1.xsd"> - - <suppress> - <notes><![CDATA[ - file name: spring-security-crypto-5.7.3.jar - La librairie Spring Security est en version 5.7.3. - Cette CVE est marquée uniquement jusqu'à la version 5.2.4 (exclus) - https://nvd.nist.gov/vuln/detail/CVE-2020-5408 - ]]></notes> - <cve>CVE-2020-5408</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - file name: spring-web-5.3.22.jar - Dans notre contexte, nous ne recevons pas de code Java de l'extérieur et n'effectuons pas de dé-sérialisation de code Java - Côté Spring, le point est déjà remonté comme un faux-positif : https://github.com/spring-projects/spring-framework/issues/24434#issuecomment-744519525 - ]]></notes> - <cve>CVE-2016-1000027</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - file name: snakeyaml-1.33.jar - Faux-positif : la version de Snakeyaml est la 1.33, la CVE existe uniquement sur les versions < 1.32 - https://nvd.nist.gov/vuln/detail/CVE-2022-38752 - ]]></notes> - <cve>CVE-2022-38752</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Faux-positif sur toutes les librairies utils: https://github.com/jeremylong/DependencyCheck/issues/5213 - Concerne : software.amazon.awssdk:utils qui n'est pas utilisé - ]]></notes> - <cve>CVE-2021-4277</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Faux-positif : matchent à tort sur tous les commons : https://github.com/jeremylong/DependencyCheck/issues/5132 - ]]></notes> - <cve>CVE-2021-37533</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2022-1471</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2022-3064</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2021-4235</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : json-smart est une dépendance transitive. - Les json sont limités à la taille des inventaires : la taille des listes n'a pas réellement de limite - et c'est souhaités comme cela (traitement de gros volumes de données). - ]]></notes> - <cve>CVE-2023-1370</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Faux-Positif : Concerne hutool-json et json-java qui ne sont pas utilisés. - Le faux-positif se trouve sur json-path, jackson-core, accessors-smart et json-smart. - cf. https://github.com/jeremylong/DependencyCheck/issues/5502 - ]]></notes> - <cve>CVE-2022-45688</cve> - </suppress> - - - <suppress> - <notes><![CDATA[ - Faux-Positif : Conformément au lien, nous ne sommes pas dans un des cas de vulnérabilité. - cf. cf. https://github.com/jeremylong/DependencyCheck/issues/5502 - ]]></notes> - <cve>CVE-2023-20862</cve> - </suppress> -</suppressions> diff --git a/services/api-referentiel/pom.xml b/services/api-referentiel/pom.xml index 9f954208236118f50502eccbaa271da03577a406..c030145604d07ede80dfe653e31a6738d8c170f8 100644 --- a/services/api-referentiel/pom.xml +++ b/services/api-referentiel/pom.xml @@ -5,12 +5,12 @@ <parent> <groupId>org.mte.numecoeval</groupId> <artifactId>core</artifactId> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <relativePath/> <!-- lookup parent from repository --> </parent> <artifactId>api-referentiel</artifactId> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <name>api-referentiel</name> <description>API Referentiel - Lecture, chargement et exposition par API</description> @@ -39,6 +39,7 @@ <dependency> <groupId>org.mte.numecoeval</groupId> <artifactId>common</artifactId> + <version>${project.version}</version> </dependency> <!-- open api docs provisoire --> @@ -46,12 +47,21 @@ <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> </dependency> + <dependency> + <groupId>io.swagger.core.v3</groupId> + <artifactId>swagger-annotations</artifactId> + </dependency> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-common</artifactId> </dependency> + <dependency> + <groupId>io.swagger.core.v3</groupId> + <artifactId>swagger-annotations</artifactId> + </dependency> + <!-- Security --> <dependency> <groupId>org.springframework.boot</groupId> @@ -147,42 +157,6 @@ <scope>test</scope> </dependency> - <!-- Tests fonctionnels --> - <dependency> - <groupId>io.cucumber</groupId> - <artifactId>cucumber-core</artifactId> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>io.cucumber</groupId> - <artifactId>cucumber-java</artifactId> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>io.cucumber</groupId> - <artifactId>cucumber-spring</artifactId> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>io.cucumber</groupId> - <artifactId>cucumber-junit-platform-engine</artifactId> - <scope>test</scope> - </dependency> - - <!-- Tests d'API REST --> - <dependency> - <groupId>io.rest-assured</groupId> - <artifactId>rest-assured</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>io.rest-assured</groupId> - <artifactId>rest-assured-all</artifactId> - <scope>test</scope> - </dependency> </dependencies> diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/FacteurCaracterisation.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/FacteurCaracterisation.java new file mode 100644 index 0000000000000000000000000000000000000000..d88b97a46ecdd86dafc9ee6ffb61ecfdf53cf006 --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/FacteurCaracterisation.java @@ -0,0 +1,26 @@ +package org.mte.numecoeval.referentiel.domain.model; + +import lombok.*; +import lombok.experimental.Accessors; +import lombok.experimental.FieldDefaults; + +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@Accessors(chain = true) +@FieldDefaults(level = AccessLevel.PRIVATE) +@NoArgsConstructor +public class FacteurCaracterisation implements AbstractReferentiel { + String nom; + String etape; + String critere; + String description; + String niveau; + String tiers; + String categorie; + Double consoElecMoyenne; + String localisation; + Double valeur; + String unite; + String source; +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/id/FacteurCaracterisationId.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/id/FacteurCaracterisationId.java new file mode 100644 index 0000000000000000000000000000000000000000..499191de89ce7ad7b7c945d43acc60b6996875ad --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/id/FacteurCaracterisationId.java @@ -0,0 +1,17 @@ +package org.mte.numecoeval.referentiel.domain.model.id; + +import lombok.*; +import lombok.experimental.Accessors; +import lombok.experimental.FieldDefaults; + +@Getter +@Setter +@EqualsAndHashCode(callSuper = false) +@Accessors(chain = true) +@FieldDefaults(level = AccessLevel.PRIVATE) +@NoArgsConstructor +public class FacteurCaracterisationId { + String nom; + String etape; + String critere; +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/id/ImpactEquipementId.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/id/ImpactEquipementId.java index 1bb9cb754096ea8323c6b137e7a394c5c5435058..ab0992d9ea652839379591c20aab9a8b12b3bfd3 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/id/ImpactEquipementId.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/id/ImpactEquipementId.java @@ -1,10 +1,6 @@ package org.mte.numecoeval.referentiel.domain.model.id; -import lombok.AccessLevel; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; +import lombok.*; import lombok.experimental.Accessors; import lombok.experimental.FieldDefaults; @@ -16,6 +12,7 @@ import java.io.Serializable; @Accessors(chain = true) @FieldDefaults(level = AccessLevel.PRIVATE) @NoArgsConstructor +@ToString public class ImpactEquipementId implements Serializable { String refEquipement; String etape; diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/id/ImpactReseauId.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/id/ImpactReseauId.java index 22a3511d4f40f47e8fcca45b1999a608968e44e9..135c83425d1d2f1cfa95dfe5933a98c7feec3284 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/id/ImpactReseauId.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/model/id/ImpactReseauId.java @@ -1,11 +1,6 @@ package org.mte.numecoeval.referentiel.domain.model.id; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; +import lombok.*; import lombok.experimental.Accessors; import lombok.experimental.FieldDefaults; @@ -18,6 +13,8 @@ import java.io.Serializable; @FieldDefaults(level = AccessLevel.PRIVATE) @NoArgsConstructor @AllArgsConstructor +@ToString + public class ImpactReseauId implements Serializable { String refReseau; diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/ports/input/impl/ImportFacteurCaracterisationPortImpl.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/ports/input/impl/ImportFacteurCaracterisationPortImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..0209c96a3a90dd44508fc5abe5624a25d296d06c --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/domain/ports/input/impl/ImportFacteurCaracterisationPortImpl.java @@ -0,0 +1,103 @@ +package org.mte.numecoeval.referentiel.domain.ports.input.impl; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVRecord; +import org.mte.numecoeval.referentiel.domain.data.ResultatImport; +import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.domain.ports.input.ImportCSVReferentielPort; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.FacteurCaracterisationDTO; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +@Slf4j + +public class ImportFacteurCaracterisationPortImpl implements ImportCSVReferentielPort<FacteurCaracterisationDTO> { + private static final String HEADER_NOM = "nom"; + private static final String HEADER_ETAPEACV = "etapeacv"; + private static final String HEADER_CRITERE = "critere"; + private static final String HEADER_DESCRIPTION = "description"; + private static final String HEADER_NIVEAU = "niveau"; + private static final String HEADER_TIERS = "tiers"; + private static final String HEADER_CATEGORIE = "categorie"; + private static final String HEADER_CONSO_ELEC_MOYENNE = "consoElecMoyenne"; + private static final String HEADER_LOCALISATION = "localisation"; + private static final String HEADER_VALEUR = "valeur"; + private static final String HEADER_UNITE = "unite"; + private static final String HEADER_SOURCE = "source"; + private static final String[] HEADERS = new String[]{HEADER_NOM, HEADER_ETAPEACV, HEADER_CRITERE, + HEADER_DESCRIPTION, HEADER_NIVEAU, HEADER_TIERS, HEADER_CATEGORIE, HEADER_CONSO_ELEC_MOYENNE, HEADER_LOCALISATION, HEADER_VALEUR, + HEADER_UNITE, HEADER_SOURCE}; + private static final String[] MANDATORY_HEADERS = new String[]{HEADER_NOM, HEADER_ETAPEACV, HEADER_CRITERE + , HEADER_NIVEAU, HEADER_TIERS, HEADER_CATEGORIE, HEADER_CONSO_ELEC_MOYENNE, HEADER_LOCALISATION, HEADER_VALEUR, + HEADER_UNITE, HEADER_SOURCE}; + + + public static String[] getHeaders() { + return HEADERS; + } + + public void checkCSVRecord(CSVRecord csvRecord) throws ReferentielException { + checkAllHeadersAreMapped(csvRecord, MANDATORY_HEADERS); + checkFieldIsMappedAndNotBlankInCSVRecord(csvRecord, HEADER_NOM); + checkFieldIsMappedAndNotBlankInCSVRecord(csvRecord, HEADER_ETAPEACV); + checkFieldIsMappedAndNotBlankInCSVRecord(csvRecord, HEADER_CRITERE); + } + + @Override + public ResultatImport<FacteurCaracterisationDTO> importCSV(InputStream csvInputStream) { + ResultatImport<FacteurCaracterisationDTO> resultatImport = new ResultatImport<>(); + List<FacteurCaracterisationDTO> dtos = new ArrayList<>(); + + try (Reader reader = new InputStreamReader(csvInputStream)) { + Iterable<CSVRecord> records = CSVFormat.DEFAULT.builder() + .setHeader() + .setDelimiter(CSV_SEPARATOR) + .setTrim(true) + .setAllowMissingColumnNames(true) + .setSkipHeaderRecord(true) + .build().parse(reader); + records.forEach(csvRecord -> { + try { + checkCSVRecord(csvRecord); + dtos.add(FacteurCaracterisationDTO.builder() + .nom(csvRecord.get(HEADER_NOM).trim()) + .etape(csvRecord.get(HEADER_ETAPEACV).trim()) + .critere(csvRecord.get(HEADER_CRITERE).trim()) + .description(getStringValueFromRecord(csvRecord, "description")) + .niveau(getStringValueFromRecord(csvRecord, "niveau")) + .tiers(getStringValueFromRecord(csvRecord, "tiers")) + .categorie(getStringValueFromRecord(csvRecord, "categorie")) + .consoElecMoyenne(getDoubleValueFromRecord(csvRecord, HEADER_CONSO_ELEC_MOYENNE, null)) + .localisation(getStringValueFromRecord(csvRecord, "localisation")) + .valeur(getDoubleValueFromRecord(csvRecord, HEADER_VALEUR, null)) + .unite(getStringValueFromRecord(csvRecord, "unite")) + .source(getStringValueFromRecord(csvRecord, "source")) + .build()); + } catch (Exception e) { + log.error("Erreur prévue lors de la lecture de la ligne {} : {}", csvRecord.getRecordNumber() + 1, e.getMessage()); + resultatImport.getErreurs().add(e.getMessage()); + } + }); + + } catch (Exception e) { + log.error("Erreur de traitement du fichier", e); + + resultatImport.setErreurs(Collections.singletonList("Le fichier CSV n'a pas pu être lu.")); + resultatImport.setNbrLignesImportees(0); + resultatImport.setObjects(null); + return resultatImport; + } + + resultatImport.setObjects(dtos); + resultatImport.setNbrLignesImportees(dtos.size()); + + return resultatImport; + } + +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/FacteurCaracterisationCsvExportService.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/FacteurCaracterisationCsvExportService.java new file mode 100644 index 0000000000000000000000000000000000000000..df6bea8d1b8a040544d27c3e4e14c54c6c396f7d --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/FacteurCaracterisationCsvExportService.java @@ -0,0 +1,47 @@ +package org.mte.numecoeval.referentiel.infrastructure.adapter.export; + +import org.apache.commons.csv.CSVPrinter; +import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportFacteurCaracterisationPortImpl; +import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielCsvExportService; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.util.List; + +@Service +public class FacteurCaracterisationCsvExportService extends ReferentielCsvExportService<FacteurCaracterisationEntity> { + private final FacteurCaracterisationRepository repository; + + public FacteurCaracterisationCsvExportService(FacteurCaracterisationRepository repository) { + super(FacteurCaracterisationEntity.class); + this.repository = repository; + } + + @Override + public String[] getHeaders() { + return ImportFacteurCaracterisationPortImpl.getHeaders(); + } + + @Override + public List<FacteurCaracterisationEntity> getObjectsToWrite() { + return repository.findAll(); + } + + @Override + protected String getObjectId(FacteurCaracterisationEntity object) { + return String.join("-", object.getNom(), object.getEtape(), object.getCritere()); + } + + @Override + public void printRecord(CSVPrinter csvPrinter, FacteurCaracterisationEntity objectToWrite) throws IOException { + csvPrinter.printRecord(objectToWrite.getNom(), + objectToWrite.getEtape(), objectToWrite.getCritere(), objectToWrite.getDescription(), + objectToWrite.getNiveau(), objectToWrite.getTiers(), objectToWrite.getCategorie(), + formatDouble(objectToWrite.getConsoElecMoyenne()), objectToWrite.getLocalisation(), + formatDouble(objectToWrite.getValeur()), objectToWrite.getUnite(), + objectToWrite.getSource() + ); + } +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactEquipementCsvExportService.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactEquipementCsvExportService.java index ea7030a8826430df874d89cee1a7238807abc449..83d3a2136de3a04317a6db904d70f56240cdf108 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactEquipementCsvExportService.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactEquipementCsvExportService.java @@ -1,23 +1,30 @@ package org.mte.numecoeval.referentiel.infrastructure.adapter.export; import org.apache.commons.csv.CSVPrinter; +import org.mte.numecoeval.referentiel.domain.model.ImpactEquipement; import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportImpactEquipementPortImpl; import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielCsvExportService; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactEquipementEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactEquipementRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactEquipementMapper; +import org.mte.numecoeval.referentiel.utils.Constants; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.List; @Service -public class ImpactEquipementCsvExportService extends ReferentielCsvExportService<ImpactEquipementEntity> { +public class ImpactEquipementCsvExportService extends ReferentielCsvExportService<ImpactEquipement> { - private final ImpactEquipementRepository repository; + private final FacteurCaracterisationRepository repository; + private final FacteurCaracterisationMapper facteurCaracterisationMapper; + private final ImpactEquipementMapper equipementMapper; - public ImpactEquipementCsvExportService(ImpactEquipementRepository repository) { - super(ImpactEquipementEntity.class); + public ImpactEquipementCsvExportService(FacteurCaracterisationRepository repository, FacteurCaracterisationMapper facteurCaracterisationMapper, ImpactEquipementMapper equipementMapper) { + super(ImpactEquipement.class); this.repository = repository; + this.facteurCaracterisationMapper = facteurCaracterisationMapper; + this.equipementMapper = equipementMapper; } @Override @@ -26,22 +33,23 @@ public class ImpactEquipementCsvExportService extends ReferentielCsvExportServic } @Override - public List<ImpactEquipementEntity> getObjectsToWrite() { - return repository.findAll(); + public List<ImpactEquipement> getObjectsToWrite() { + var facteurCaracterisationList = facteurCaracterisationMapper.toDomains(repository.findByNiveau(Constants.EQUIPEMENT_NIVEAU)); + return equipementMapper.toImpactEquipements(facteurCaracterisationList); } @Override - protected String getObjectId(ImpactEquipementEntity object) { - return String.join("-", object.getRefEquipement(),object.getEtape(),object.getCritere()); + protected String getObjectId(ImpactEquipement object) { + return String.join("-", object.getRefEquipement(), object.getEtape(), object.getCritere()); } @Override - public void printRecord(CSVPrinter csvPrinter, ImpactEquipementEntity objectToWrite) throws IOException { + public void printRecord(CSVPrinter csvPrinter, ImpactEquipement objectToWrite) throws IOException { csvPrinter.printRecord(objectToWrite.getRefEquipement(), - objectToWrite.getEtape(),objectToWrite.getCritere(), - formatDouble(objectToWrite.getConsoElecMoyenne()),formatDouble(objectToWrite.getValeur()), + objectToWrite.getEtape(), objectToWrite.getCritere(), + formatDouble(objectToWrite.getConsoElecMoyenne()), formatDouble(objectToWrite.getValeur()), objectToWrite.getSource(), objectToWrite.getType() - ); + ); } } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactReseauCsvExportService.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactReseauCsvExportService.java index fcc0937fd4249cfc0b7cffa82b42e4defcc0a295..fe8aabea598e966d7b3377906e1770733f075821 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactReseauCsvExportService.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactReseauCsvExportService.java @@ -1,23 +1,30 @@ package org.mte.numecoeval.referentiel.infrastructure.adapter.export; import org.apache.commons.csv.CSVPrinter; +import org.mte.numecoeval.referentiel.domain.model.ImpactReseau; import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportImpactReseauPortImpl; import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielCsvExportService; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactReseauEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactReseauRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactReseauMapper; +import org.mte.numecoeval.referentiel.utils.Constants; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.List; @Service -public class ImpactReseauCsvExportService extends ReferentielCsvExportService<ImpactReseauEntity> { +public class ImpactReseauCsvExportService extends ReferentielCsvExportService<ImpactReseau> { + private final FacteurCaracterisationRepository repository; + private final FacteurCaracterisationMapper facteurCaracterisationMapper; + private final ImpactReseauMapper reseauMapper; - private final ImpactReseauRepository repository; - - public ImpactReseauCsvExportService(ImpactReseauRepository repository) { - super(ImpactReseauEntity.class); + public ImpactReseauCsvExportService(FacteurCaracterisationRepository repository, FacteurCaracterisationMapper facteurCaracterisationMapper, ImpactReseauMapper reseauMapper) { + super(ImpactReseau.class); this.repository = repository; + this.facteurCaracterisationMapper = facteurCaracterisationMapper; + this.reseauMapper = reseauMapper; + } @Override @@ -26,23 +33,26 @@ public class ImpactReseauCsvExportService extends ReferentielCsvExportService<Im } @Override - public List<ImpactReseauEntity> getObjectsToWrite() { - return repository.findAll(); + public List<ImpactReseau> getObjectsToWrite() { + var facteurCaracterisationList = facteurCaracterisationMapper.toDomains(repository.findByNiveauAndTiers(Constants.RESEAU_NIVEAU, Constants.RESEAU_TIERS)); + return reseauMapper.toImpactReseaux(facteurCaracterisationList); } @Override - protected String getObjectId(ImpactReseauEntity object) { - return String.join("-", object.getRefReseau(),object.getEtape(),object.getCritere()); + protected String getObjectId(ImpactReseau object) { + return String.join("-", object.getRefReseau(), object.getEtape(), object.getCritere()); } @Override - public void printRecord(CSVPrinter csvPrinter, ImpactReseauEntity objectToWrite) throws IOException { - csvPrinter.printRecord(objectToWrite.getRefReseau(), - objectToWrite.getEtape(),objectToWrite.getCritere(), + public void printRecord(CSVPrinter csvPrinter, ImpactReseau objectToWrite) throws IOException { + csvPrinter.printRecord( + objectToWrite.getRefReseau(), + objectToWrite.getEtape(), + objectToWrite.getCritere(), formatDouble(objectToWrite.getValeur()), formatDouble(objectToWrite.getConsoElecMoyenne()), objectToWrite.getSource() - ); + ); } } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/MixElectriqueCsvExportService.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/MixElectriqueCsvExportService.java index af99d634c27a8717191ecd89a031d430ea8d426d..e40c261ba14f1062489307623d48b41235dc61aa 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/MixElectriqueCsvExportService.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/MixElectriqueCsvExportService.java @@ -1,23 +1,30 @@ package org.mte.numecoeval.referentiel.infrastructure.adapter.export; import org.apache.commons.csv.CSVPrinter; +import org.mte.numecoeval.referentiel.domain.model.MixElectrique; import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportMixElectriquePortImpl; import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielCsvExportService; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.MixElectriqueEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.MixElectriqueRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.MixElectriqueMapper; +import org.mte.numecoeval.referentiel.utils.Constants; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.List; @Service -public class MixElectriqueCsvExportService extends ReferentielCsvExportService<MixElectriqueEntity> { +public class MixElectriqueCsvExportService extends ReferentielCsvExportService<MixElectrique> { - private final MixElectriqueRepository repository; + private final FacteurCaracterisationRepository repository; + private final FacteurCaracterisationMapper facteurCaracterisationMapper; + private final MixElectriqueMapper mixElectriqueMapper; - public MixElectriqueCsvExportService(MixElectriqueRepository repository) { - super(MixElectriqueEntity.class); + public MixElectriqueCsvExportService(FacteurCaracterisationRepository repository, FacteurCaracterisationMapper facteurCaracterisationMapper, MixElectriqueMapper mixElectriqueMapper) { + super(MixElectrique.class); this.repository = repository; + this.facteurCaracterisationMapper = facteurCaracterisationMapper; + this.mixElectriqueMapper = mixElectriqueMapper; } @Override @@ -26,24 +33,25 @@ public class MixElectriqueCsvExportService extends ReferentielCsvExportService<M } @Override - public List<MixElectriqueEntity> getObjectsToWrite() { - return repository.findAll(); + public List<MixElectrique> getObjectsToWrite() { + var facteurCaracterisationList = facteurCaracterisationMapper.toDomains(repository.findByNiveauAndCategorie(Constants.MIXELEC_NIVEAU, Constants.MIXELEC_CATEGORIE)); + return mixElectriqueMapper.toMixElectriques(facteurCaracterisationList); } @Override - protected String getObjectId(MixElectriqueEntity object) { + protected String getObjectId(MixElectrique object) { return String.join("-", object.getPays(), object.getCritere()); } @Override - public void printRecord(CSVPrinter csvPrinter, MixElectriqueEntity objectToWrite) throws IOException { + public void printRecord(CSVPrinter csvPrinter, MixElectrique objectToWrite) throws IOException { csvPrinter.printRecord( objectToWrite.getPays(), objectToWrite.getRaccourcisAnglais(), objectToWrite.getCritere(), formatDouble(objectToWrite.getValeur()), objectToWrite.getSource() - ); + ); } } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/init/FusionFacteurCaracterisationService.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/init/FusionFacteurCaracterisationService.java new file mode 100644 index 0000000000000000000000000000000000000000..986138c7ce93608e4a4ec2af88c8a9bfcf9a225d --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/init/FusionFacteurCaracterisationService.java @@ -0,0 +1,58 @@ +package org.mte.numecoeval.referentiel.infrastructure.init; + +import jakarta.annotation.PostConstruct; +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.infrastructure.jpa.adapter.ImpactEquipementJpaAdapter; +import org.mte.numecoeval.referentiel.infrastructure.jpa.adapter.ImpactReseauJpaAdapter; +import org.mte.numecoeval.referentiel.infrastructure.jpa.adapter.MixElectriqueJpaAdapter; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactEquipementRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactReseauRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.MixElectriqueRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactEquipementMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactReseauMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.MixElectriqueMapper; +import org.springframework.stereotype.Service; + +@Service +@Slf4j +@AllArgsConstructor +public class FusionFacteurCaracterisationService { + private MixElectriqueJpaAdapter mixElectriqueJpaAdapter; + private MixElectriqueRepository mixElectriqueRepository; + private MixElectriqueMapper mixElectriqueMapper; + private ImpactReseauJpaAdapter impactReseauJpaAdapter; + private ImpactReseauRepository impactReseauRepository; + private ImpactReseauMapper impactReseauMapper; + private ImpactEquipementJpaAdapter impactEquipementJpaAdapter; + private ImpactEquipementRepository impactEquipementRepository; + private ImpactEquipementMapper impactEquipementMapper; + + @PostConstruct + public void init() throws ReferentielException { + log.info("démarrage de la fusion des tables vers ref_facteurcaracterisation"); + + var mixelecs = mixElectriqueRepository.findAll(); + if (!mixelecs.isEmpty()) { + log.info("migration des mix électriques vers la nouvelle table"); + mixElectriqueJpaAdapter.saveAll(mixElectriqueMapper.toDomains(mixelecs)); + mixElectriqueRepository.deleteAll(); + log.info("fin de la migration des mix électriques vers la nouvelle table"); + } + var impactReseaux = impactReseauRepository.findAll(); + if (!impactReseaux.isEmpty()) { + log.info("migration des impact réseaux vers la nouvelle table"); + impactReseauJpaAdapter.saveAll(impactReseauMapper.toDomains(impactReseaux)); + impactReseauRepository.deleteAll(); + log.info("fin de la migration des impact réseaux vers la nouvelle table"); + } + var impactEquipements = impactEquipementRepository.findAll(); + if (!impactEquipements.isEmpty()) { + log.info("migration des impacts équipements vers la nouvelle table"); + impactEquipementJpaAdapter.saveAll(impactEquipementMapper.toDomains(impactEquipements)); + impactEquipementRepository.deleteAll(); + log.info("fin de la migration des impacts équipements vers la nouvelle table"); + } + } +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/FacteurCaracterisationJpaAdapter.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/FacteurCaracterisationJpaAdapter.java new file mode 100644 index 0000000000000000000000000000000000000000..a01d01daab7ca1dcdcf67e8fbaa58b8c62ce6d99 --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/FacteurCaracterisationJpaAdapter.java @@ -0,0 +1,66 @@ +package org.mte.numecoeval.referentiel.infrastructure.jpa.adapter; + +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.ListUtils; +import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.domain.model.FacteurCaracterisation; +import org.mte.numecoeval.referentiel.domain.model.id.FacteurCaracterisationId; +import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.FacteurCaracterisationIdEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; +import org.springframework.stereotype.Service; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +@Service +@Slf4j +@AllArgsConstructor +public class FacteurCaracterisationJpaAdapter implements ReferentielPersistencePort<FacteurCaracterisation, FacteurCaracterisationId> { + private FacteurCaracterisationRepository repository; + + private FacteurCaracterisationMapper mapper; + + + @Override + public FacteurCaracterisation save(FacteurCaracterisation referentiel) throws ReferentielException { + var entityToSave = mapper.toEntity(referentiel); + if (entityToSave != null) { + var entitySaved = repository.save(entityToSave); + return mapper.toDomain(entitySaved); + } + return null; + } + + @Override + public void saveAll(Collection<FacteurCaracterisation> referentiel) throws ReferentielException { + repository.saveAll(mapper.toEntities(referentiel)); + } + + @Override + public FacteurCaracterisation get(FacteurCaracterisationId id) throws ReferentielException { + if (id != null) { + FacteurCaracterisationIdEntity ieIdEntity = mapper.toEntityId(id); + Optional<FacteurCaracterisationEntity> optionalEntity = repository.findById(ieIdEntity); + return mapper.toDomain( + optionalEntity + .orElseThrow(() -> new ReferentielException("Facteur Caractérisation non trouvé")) + ); + } + throw new ReferentielException("Facteur Caractérisation non trouvé"); + } + + @Override + public void purge() { + repository.deleteAll(); + } + + @Override + public List<FacteurCaracterisation> getAll() { + return ListUtils.emptyIfNull(mapper.toDomains(repository.findAll())); + } +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/ImpactEquipementJpaAdapter.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/ImpactEquipementJpaAdapter.java index 59da314f3d6ca1edd1a0cbb9f3bd4f532d0c869b..d5fad8a40213fc6ddaf221888dd70b2e58c3681e 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/ImpactEquipementJpaAdapter.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/ImpactEquipementJpaAdapter.java @@ -2,15 +2,16 @@ package org.mte.numecoeval.referentiel.infrastructure.jpa.adapter; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.ListUtils; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.domain.model.FacteurCaracterisation; import org.mte.numecoeval.referentiel.domain.model.ImpactEquipement; import org.mte.numecoeval.referentiel.domain.model.id.ImpactEquipementId; import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactEquipementEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.ImpactEquipementIdEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactEquipementRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactEquipementMapper; +import org.mte.numecoeval.referentiel.utils.Constants; import org.springframework.stereotype.Service; import java.util.Collection; @@ -23,47 +24,50 @@ import java.util.Optional; @AllArgsConstructor public class ImpactEquipementJpaAdapter implements ReferentielPersistencePort<ImpactEquipement, ImpactEquipementId> { - private ImpactEquipementRepository repository; - + private FacteurCaracterisationRepository facteurCaracterisationRepository; private ImpactEquipementMapper mapper; + private FacteurCaracterisationMapper facteurCaracterisationMapper; @Override public ImpactEquipement save(ImpactEquipement referentiel) throws ReferentielException { - var entityToSave = mapper.toEntity(referentiel); - if(entityToSave != null) { - var entitySaved = repository.save(entityToSave); - return mapper.toDomain(entitySaved); + var facteurCaracterisation = mapper.toFacteurCaracterisation(referentiel); + var entityToSave = facteurCaracterisationMapper.toEntity(facteurCaracterisation); + if (entityToSave != null) { + facteurCaracterisationRepository.save(entityToSave); + return referentiel; } return null; } @Override - public void saveAll(Collection<ImpactEquipement> referentiel) throws ReferentielException { + public void saveAll(Collection<ImpactEquipement> referentiels) throws ReferentielException { purge(); - repository.saveAll(mapper.toEntities(referentiel)); + List<FacteurCaracterisation> facteurCaracterisationList = mapper.toFacteurCaracterisations(referentiels.stream().toList()); + facteurCaracterisationRepository.saveAll(facteurCaracterisationMapper.toEntities(facteurCaracterisationList)); } @Override public ImpactEquipement get(ImpactEquipementId id) throws ReferentielException { - if(id != null) { - ImpactEquipementIdEntity ieIdEntity = mapper.toEntityId(id); - Optional<ImpactEquipementEntity> optionalEntity = repository.findById(ieIdEntity); - return mapper.toDomain( - optionalEntity - .orElseThrow(() -> new ReferentielException("Impact Equipement non trouvé")) - ); + if (id != null) { + Optional<FacteurCaracterisationEntity> facteurCaracterisationEntities = facteurCaracterisationRepository.findByNomAndEtapeAndCritere(id.getRefEquipement(), id.getEtape(), id.getCritere()); + if (facteurCaracterisationEntities.isPresent()) { + return mapper.toImpactEquipement(facteurCaracterisationMapper.toDomain(facteurCaracterisationEntities.get())); + } else { + throw new ReferentielException("Impact équipement non trouvé pour l'id " + id); + } } - throw new ReferentielException("Impact Equipement non trouvé"); + throw new ReferentielException("Impact équipement non trouvé pour l'id null"); } @Override public void purge() { - repository.deleteAll(); + + facteurCaracterisationRepository.deleteByNiveau(Constants.EQUIPEMENT_NIVEAU); } @Override public List<ImpactEquipement> getAll() { - return ListUtils.emptyIfNull(mapper.toDomains(repository.findAll())); + return mapper.toImpactEquipements(facteurCaracterisationMapper.toDomains(facteurCaracterisationRepository.findByNiveau(Constants.EQUIPEMENT_NIVEAU))); } } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/ImpactReseauJpaAdapter.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/ImpactReseauJpaAdapter.java index f7019303191b263e84c41b2da9a373e1e15953d5..8dad1e2d952e1e19b5a7689c3cb1f67412875f00 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/ImpactReseauJpaAdapter.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/ImpactReseauJpaAdapter.java @@ -2,15 +2,16 @@ package org.mte.numecoeval.referentiel.infrastructure.jpa.adapter; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.ListUtils; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.domain.model.FacteurCaracterisation; import org.mte.numecoeval.referentiel.domain.model.ImpactReseau; import org.mte.numecoeval.referentiel.domain.model.id.ImpactReseauId; import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactReseauEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.ImpactReseauIdEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactReseauRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactReseauMapper; +import org.mte.numecoeval.referentiel.utils.Constants; import org.springframework.stereotype.Service; import java.util.Collection; @@ -21,42 +22,51 @@ import java.util.Optional; @Service @Slf4j @AllArgsConstructor -public class ImpactReseauJpaAdapter implements ReferentielPersistencePort<ImpactReseau, ImpactReseauId> { - ImpactReseauRepository reseauRepository; +public class ImpactReseauJpaAdapter implements ReferentielPersistencePort<ImpactReseau, ImpactReseauId> { + FacteurCaracterisationRepository facteurCaracterisationRepository; ImpactReseauMapper reseauMapper; + FacteurCaracterisationMapper facteurCaracterisationMapper; @Override public ImpactReseau save(ImpactReseau facteurImpact) throws ReferentielException { - ImpactReseauEntity impactReseauEntity = reseauMapper.toEntity(facteurImpact); - ImpactReseauEntity save = reseauRepository.save(impactReseauEntity); - return reseauMapper.toDomain(save); + var facteurCaracterisation = reseauMapper.toFacteurCaracterisation(facteurImpact); + var entityToSave = facteurCaracterisationMapper.toEntity(facteurCaracterisation); + if (entityToSave != null) { + facteurCaracterisationRepository.save(entityToSave); + return facteurImpact; + } + return null; } @Override public void saveAll(Collection<ImpactReseau> facteursImpacts) throws ReferentielException { - List<ImpactReseauEntity> impactReseauEntities = reseauMapper.toEntity(facteursImpacts); - reseauRepository.saveAll(impactReseauEntities); + List<FacteurCaracterisation> facteurCaracterisationList = reseauMapper.toFacteurCaracterisations(facteursImpacts.stream().toList()); + facteurCaracterisationRepository.saveAll(facteurCaracterisationMapper.toEntities(facteurCaracterisationList)); } @Override public ImpactReseau get(ImpactReseauId id) throws ReferentielException { - ImpactReseauIdEntity reseauId = reseauMapper.toEntityId(id); - Optional<ImpactReseauEntity> reseauEntityOptional = reseauRepository.findById(reseauId); - return reseauMapper.toDomain( - reseauEntityOptional.orElseThrow(() -> new ReferentielException("Impact Réseau non trouvé")) - ); + if (id != null) { + Optional<FacteurCaracterisationEntity> facteurCaracterisationEntities = facteurCaracterisationRepository.findByNomAndEtapeAndCritere(id.getRefReseau(), id.getEtape(), id.getCritere()); + if (facteurCaracterisationEntities.isPresent()) { + return reseauMapper.toImpactReseau(facteurCaracterisationMapper.toDomain(facteurCaracterisationEntities.get())); + } else { + throw new ReferentielException("Référence réseau non trouvée pour l'id " + id); + } + } + throw new ReferentielException("Référence réseau non trouvée pour l'id null"); } @Override public void purge() { - reseauRepository.deleteAll(); + facteurCaracterisationRepository.deleteByNiveauAndTiers(Constants.RESEAU_NIVEAU, Constants.RESEAU_TIERS); } @Override public List<ImpactReseau> getAll() { - return ListUtils.emptyIfNull(reseauMapper.toDomains(reseauRepository.findAll())); + return reseauMapper.toImpactReseaux(facteurCaracterisationMapper.toDomains(facteurCaracterisationRepository.findByNiveauAndTiers(Constants.RESEAU_NIVEAU, Constants.RESEAU_TIERS))); } } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/MixElectriqueJpaAdapter.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/MixElectriqueJpaAdapter.java index 48337d782a49867ae8186f98355c4f31e61b08e3..f1131a65b1bb1bace3fc2739ea948103d4d1e0ef 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/MixElectriqueJpaAdapter.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/adapter/MixElectriqueJpaAdapter.java @@ -2,15 +2,16 @@ package org.mte.numecoeval.referentiel.infrastructure.jpa.adapter; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.ListUtils; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.domain.model.FacteurCaracterisation; import org.mte.numecoeval.referentiel.domain.model.MixElectrique; import org.mte.numecoeval.referentiel.domain.model.id.MixElectriqueId; import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.MixElectriqueEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.MixElectriqueIdEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.MixElectriqueRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; import org.mte.numecoeval.referentiel.infrastructure.mapper.MixElectriqueMapper; +import org.mte.numecoeval.referentiel.utils.Constants; import org.springframework.stereotype.Service; import java.util.Collection; @@ -22,48 +23,52 @@ import java.util.Optional; @Slf4j @AllArgsConstructor public class MixElectriqueJpaAdapter implements ReferentielPersistencePort<MixElectrique, MixElectriqueId> { - MixElectriqueRepository mixElectriqueRepository; + FacteurCaracterisationRepository facteurCaracterisationRepository; MixElectriqueMapper mixElectriqueMapper; + FacteurCaracterisationMapper facteurCaracterisationMapper; @Override public MixElectrique save(MixElectrique referentiel) throws ReferentielException { - var entityToSave = mixElectriqueMapper.toEntity(referentiel); + var facteurCaracterisation = mixElectriqueMapper.toFacteurCaracterisation(referentiel); + + var entityToSave = facteurCaracterisationMapper.toEntity(facteurCaracterisation); if (entityToSave != null) { - var entitySaved = mixElectriqueRepository.save(entityToSave); - return mixElectriqueMapper.toDomain(entitySaved); + facteurCaracterisationRepository.save(entityToSave); + return referentiel; } return null; } @Override public void saveAll(Collection<MixElectrique> mixElecs) throws ReferentielException { - List<MixElectriqueEntity> mixElecsEntities = mixElectriqueMapper.toEntities(mixElecs); - mixElectriqueRepository.saveAll(mixElecsEntities); + List<FacteurCaracterisation> facteurCaracterisationList = mixElectriqueMapper.toFacteurCaracterisations(mixElecs.stream().toList()); + facteurCaracterisationRepository.saveAll(facteurCaracterisationMapper.toEntities(facteurCaracterisationList)); } @Override public MixElectrique get(MixElectriqueId id) throws ReferentielException { if (id != null) { - MixElectriqueIdEntity meIdEntity = mixElectriqueMapper.toEntityId(id); - Optional<MixElectriqueEntity> reseauEntityOptional = mixElectriqueRepository.findById(meIdEntity); - return mixElectriqueMapper.toDomain( - reseauEntityOptional - .orElseThrow(() -> new ReferentielException("Mix Electrique non trouvé pour l'id " + id)) - ); + + Optional<FacteurCaracterisationEntity> facteurCaracterisationEntities = facteurCaracterisationRepository.findByNiveauAndCategorieAndLocalisationAndCritere(Constants.MIXELEC_NIVEAU, Constants.MIXELEC_CATEGORIE, id.getPays(), id.getCritere()); + if (facteurCaracterisationEntities.isPresent()) { + return mixElectriqueMapper.toMixElectrique(facteurCaracterisationMapper.toDomain(facteurCaracterisationEntities.get())); + } else { + throw new ReferentielException("Mix Electrique non trouvé pour l'id " + id); + } } throw new ReferentielException("Mix Electrique non trouvé pour l'id null"); } @Override public void purge() { - mixElectriqueRepository.deleteAll(); + facteurCaracterisationRepository.deleteByNiveauAndCategorie(Constants.MIXELEC_NIVEAU, Constants.MIXELEC_CATEGORIE); } @Override public List<MixElectrique> getAll() { - return ListUtils.emptyIfNull(mixElectriqueMapper.toDomains(mixElectriqueRepository.findAll())); + return mixElectriqueMapper.toMixElectriques(facteurCaracterisationMapper.toDomains(facteurCaracterisationRepository.findByNiveauAndCategorie(Constants.MIXELEC_NIVEAU, Constants.MIXELEC_CATEGORIE))); } } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/FacteurCaracterisationEntity.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/FacteurCaracterisationEntity.java new file mode 100644 index 0000000000000000000000000000000000000000..1f805bc5ab9a072b5fea46cfd617a69a7502190e --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/FacteurCaracterisationEntity.java @@ -0,0 +1,42 @@ +package org.mte.numecoeval.referentiel.infrastructure.jpa.entity; + +import jakarta.persistence.*; +import lombok.AccessLevel; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import lombok.experimental.Accessors; +import lombok.experimental.FieldDefaults; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.FacteurCaracterisationIdEntity; + +@Getter +@Setter +@Accessors(chain = true) +@FieldDefaults(level = AccessLevel.PRIVATE) +@Entity +@IdClass(FacteurCaracterisationIdEntity.class) +@Table(name = "REF_FACTEURCARACTERISATION") +@EqualsAndHashCode +public class FacteurCaracterisationEntity implements AbstractReferentielEntity { + @Id + String nom; + @Id + @Column(name = "ETAPEACV") + String etape; + @Id + @Column(name = "NOMCRITERE") + String critere; + + String localisation; + + String description; + String niveau; + String tiers; + String categorie; + Double consoElecMoyenne; + + Double valeur; + String unite; + String source; + +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/ImpactEquipementEntity.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/ImpactEquipementEntity.java index 2f90d6a89b57c90304e76927270b36641ecd78f5..d878dc03a39a91d8a35ddd876e89641f87e7d70a 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/ImpactEquipementEntity.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/ImpactEquipementEntity.java @@ -1,17 +1,12 @@ package org.mte.numecoeval.referentiel.infrastructure.jpa.entity; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.IdClass; -import jakarta.persistence.Table; +import jakarta.persistence.*; import lombok.AccessLevel; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import lombok.experimental.FieldDefaults; -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.ImpactEquipementIdEntity; @Getter @@ -21,6 +16,7 @@ import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.ImpactEquipem @Entity @IdClass(ImpactEquipementIdEntity.class) @Table(name = "REF_IMPACTEQUIPEMENT") +@EqualsAndHashCode public class ImpactEquipementEntity implements AbstractReferentielEntity { @Id @Column(name = "REFEQUIPEMENT") @@ -35,40 +31,5 @@ public class ImpactEquipementEntity implements AbstractReferentielEntity { String type; Double valeur; Double consoElecMoyenne; - String description; - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - ImpactEquipementEntity that = (ImpactEquipementEntity) o; - - return new EqualsBuilder() - .append(refEquipement, that.refEquipement) - .append(etape, that.etape) - .append(critere, that.critere) - .append(source, that.source) - .append(type, that.type) - .append(valeur, that.valeur) - .append(consoElecMoyenne, that.consoElecMoyenne) - .append(description, that.description) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(refEquipement) - .append(etape) - .append(critere) - .append(source) - .append(type) - .append(valeur) - .append(consoElecMoyenne) - .append(description) - .toHashCode(); - } } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/ImpactReseauEntity.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/ImpactReseauEntity.java index 2b202ed39cad4a4285abbb64638108c3c858a8ff..de8f5b5f4dd010912ae6b0c53617b2f6d67b9e9f 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/ImpactReseauEntity.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/ImpactReseauEntity.java @@ -1,17 +1,12 @@ package org.mte.numecoeval.referentiel.infrastructure.jpa.entity; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.IdClass; -import jakarta.persistence.Table; +import jakarta.persistence.*; import lombok.AccessLevel; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import lombok.experimental.FieldDefaults; -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.ImpactReseauIdEntity; @Getter @@ -21,6 +16,7 @@ import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.ImpactReseauI @Entity @IdClass(ImpactReseauIdEntity.class) @Table(name = "REF_IMPACTRESEAU") +@EqualsAndHashCode public class ImpactReseauEntity implements AbstractReferentielEntity { @Id @Column(name = "REFRESEAU", nullable = false) @@ -35,20 +31,4 @@ public class ImpactReseauEntity implements AbstractReferentielEntity { Double valeur; @Column(name = "CONSOELECMOYENNE") Double consoElecMoyenne; - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - ImpactReseauEntity that = (ImpactReseauEntity) o; - - return new EqualsBuilder().append(refReseau, that.refReseau).append(etape, that.etape).append(critere, that.critere).append(source, that.source).append(valeur, that.valeur).append(consoElecMoyenne, that.consoElecMoyenne).isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37).append(refReseau).append(etape).append(critere).append(source).append(valeur).append(consoElecMoyenne).toHashCode(); - } } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/MixElectriqueEntity.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/MixElectriqueEntity.java index c42caef280ddd7e9d58ba18f0fd6e1ffa2d2a2fd..f73d533403dc570340ce815259518e7de0f19cbd 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/MixElectriqueEntity.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/MixElectriqueEntity.java @@ -1,17 +1,12 @@ package org.mte.numecoeval.referentiel.infrastructure.jpa.entity; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.Id; -import jakarta.persistence.IdClass; -import jakarta.persistence.Table; +import jakarta.persistence.*; import lombok.AccessLevel; +import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import lombok.experimental.FieldDefaults; -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.MixElectriqueIdEntity; @Getter @@ -21,8 +16,8 @@ import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.MixElectrique @Entity @IdClass(MixElectriqueIdEntity.class) @Table(name = "REF_MIXELEC") +@EqualsAndHashCode public class MixElectriqueEntity implements AbstractReferentielEntity { - @Id String pays; @Id @@ -32,20 +27,4 @@ public class MixElectriqueEntity implements AbstractReferentielEntity { String raccourcisAnglais; String source; Double valeur; - - @Override - public boolean equals(Object o) { - if (this == o) return true; - - if (o == null || getClass() != o.getClass()) return false; - - MixElectriqueEntity that = (MixElectriqueEntity) o; - - return new EqualsBuilder().append(pays, that.pays).append(critere, that.critere).append(raccourcisAnglais, that.raccourcisAnglais).append(source, that.source).append(valeur, that.valeur).isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37).append(pays).append(critere).append(raccourcisAnglais).append(source).append(valeur).toHashCode(); - } } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/id/FacteurCaracterisationIdEntity.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/id/FacteurCaracterisationIdEntity.java new file mode 100644 index 0000000000000000000000000000000000000000..448f4b349d13d23cad37b1b5c3d36cd610e3cacc --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/entity/id/FacteurCaracterisationIdEntity.java @@ -0,0 +1,37 @@ +package org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.Accessors; +import lombok.experimental.FieldDefaults; +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; + +@Getter +@Setter +@Accessors(chain = true) +@FieldDefaults(level = AccessLevel.PRIVATE) +@NoArgsConstructor +public class FacteurCaracterisationIdEntity implements AbstractReferentieIdEntity { + String nom; + String etape; + String critere; + + @Override + public boolean equals(Object o) { + if (this == o) return true; + + if (o == null || getClass() != o.getClass()) return false; + + FacteurCaracterisationIdEntity that = (FacteurCaracterisationIdEntity) o; + + return new EqualsBuilder().append(nom, that.nom).append(etape, that.etape).append(critere, that.critere).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(17, 37).append(nom).append(etape).append(critere).toHashCode(); + } +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/repository/FacteurCaracterisationRepository.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/repository/FacteurCaracterisationRepository.java new file mode 100644 index 0000000000000000000000000000000000000000..bd6cb54385e58bf83a00474ea462766cb8a10ab0 --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/jpa/repository/FacteurCaracterisationRepository.java @@ -0,0 +1,39 @@ +package org.mte.numecoeval.referentiel.infrastructure.jpa.repository; + +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.transaction.Transactional; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.FacteurCaracterisationIdEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; + +import java.util.List; +import java.util.Optional; + +@RepositoryRestResource(path = "FacteurCaracterisation", itemResourceRel = "FacteursCaracterisation") +@Tag(name = "FacteurCaracterisation - CRUD/Spring Data REST") +public interface FacteurCaracterisationRepository extends JpaRepository<FacteurCaracterisationEntity, FacteurCaracterisationIdEntity> { + + @Transactional + @Modifying + void deleteByNiveauAndCategorie(String niveau, String categorie); + + @Transactional + @Modifying + void deleteByNiveau(String niveau); + + @Transactional + @Modifying + void deleteByNiveauAndTiers(String niveau, String tiers); + + Optional<FacteurCaracterisationEntity> findByNiveauAndCategorieAndLocalisationAndCritere(String niveau, String categorie, String localisation, String critere); + + Optional<FacteurCaracterisationEntity> findByNomAndEtapeAndCritere(String nom, String etape, String critere); + + List<FacteurCaracterisationEntity> findByNiveauAndCategorie(String niveau, String categorie); + + List<FacteurCaracterisationEntity> findByNiveauAndTiers(String niveau, String tiers); + + List<FacteurCaracterisationEntity> findByNiveau(String niveau); +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/FacteurCaracterisationMapper.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/FacteurCaracterisationMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..57baea0f12f5bd1e88a50d633f8bebca0afe2339 --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/FacteurCaracterisationMapper.java @@ -0,0 +1,33 @@ +package org.mte.numecoeval.referentiel.infrastructure.mapper; + +import org.mapstruct.Mapper; +import org.mte.numecoeval.referentiel.domain.model.FacteurCaracterisation; +import org.mte.numecoeval.referentiel.domain.model.id.FacteurCaracterisationId; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.FacteurCaracterisationIdEntity; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.FacteurCaracterisationDTO; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.FacteurCaracterisationIdDTO; + +import java.util.Collection; +import java.util.List; + +@Mapper(componentModel = "spring") +public interface FacteurCaracterisationMapper { + FacteurCaracterisationId toDomainId(FacteurCaracterisationIdDTO id); + + FacteurCaracterisationEntity toEntity(FacteurCaracterisation referentiel); + + List<FacteurCaracterisationEntity> toEntities(Collection<FacteurCaracterisation> referentiel); + + FacteurCaracterisationIdEntity toEntityId(FacteurCaracterisationId id); + + FacteurCaracterisation toDomain(FacteurCaracterisationEntity entity); + + List<FacteurCaracterisation> toDomains(List<FacteurCaracterisationEntity> entities); + + FacteurCaracterisation toDomain(FacteurCaracterisationDTO dto); + + List<FacteurCaracterisation> toDomainsFromDTO(List<FacteurCaracterisationDTO> iesDTO); + + FacteurCaracterisationDTO toDTO(FacteurCaracterisation facteurCaracterisation); +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/ImpactEquipementMapper.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/ImpactEquipementMapper.java index d129f74be694fcf660c67443f85f2d7fe4020448..50743926e6a843acf62cf901b627bc1f4108124d 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/ImpactEquipementMapper.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/ImpactEquipementMapper.java @@ -1,11 +1,13 @@ package org.mte.numecoeval.referentiel.infrastructure.mapper; import org.mapstruct.Mapper; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactEquipementDTO; +import org.mapstruct.Mapping; +import org.mte.numecoeval.referentiel.domain.model.FacteurCaracterisation; import org.mte.numecoeval.referentiel.domain.model.ImpactEquipement; import org.mte.numecoeval.referentiel.domain.model.id.ImpactEquipementId; import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactEquipementEntity; import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.ImpactEquipementIdEntity; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactEquipementDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.ImpactEquipementIdDTO; import java.util.Collection; @@ -30,4 +32,16 @@ public interface ImpactEquipementMapper { List<ImpactEquipement> toDomainsFromDTO(List<ImpactEquipementDTO> iesDTO); ImpactEquipementDTO toDTO(ImpactEquipement impactEquipement); + + @Mapping(target = "nom", source = "refEquipement") + @Mapping(target = "niveau", expression = "java(org.mte.numecoeval.referentiel.utils.Constants.EQUIPEMENT_NIVEAU)") + FacteurCaracterisation toFacteurCaracterisation(ImpactEquipement impactEquipement); + + List<FacteurCaracterisation> toFacteurCaracterisations(List<ImpactEquipement> impactEquipements); + + @Mapping(target = "refEquipement", source = "nom") + ImpactEquipement toImpactEquipement(FacteurCaracterisation facteurCaracterisation); + + List<ImpactEquipement> toImpactEquipements(List<FacteurCaracterisation> facteurCaracterisations); + } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/ImpactReseauMapper.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/ImpactReseauMapper.java index 3411ffc6babc1b1e406f6a9ad144b15c47ccafc2..4bc31228316513146020b5470b7b82d481a354de 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/ImpactReseauMapper.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/ImpactReseauMapper.java @@ -2,11 +2,12 @@ package org.mte.numecoeval.referentiel.infrastructure.mapper; import org.mapstruct.Mapper; import org.mapstruct.Mapping; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactReseauDTO; +import org.mte.numecoeval.referentiel.domain.model.FacteurCaracterisation; import org.mte.numecoeval.referentiel.domain.model.ImpactReseau; import org.mte.numecoeval.referentiel.domain.model.id.ImpactReseauId; import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactReseauEntity; import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.ImpactReseauIdEntity; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactReseauDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.ImpactReseauIdDTO; import java.util.Collection; @@ -36,4 +37,16 @@ public interface ImpactReseauMapper { List<ImpactReseau> toDomains(List<ImpactReseauEntity> entities); List<ImpactReseau> toDomainsFromDTO(List<ImpactReseauDTO> dtos); + + @Mapping(target = "nom", source = "refReseau") + @Mapping(target = "niveau", expression = "java(org.mte.numecoeval.referentiel.utils.Constants.RESEAU_NIVEAU)") + @Mapping(target = "tiers", expression = "java(org.mte.numecoeval.referentiel.utils.Constants.RESEAU_TIERS)") + FacteurCaracterisation toFacteurCaracterisation(ImpactReseau impactReseau); + + List<FacteurCaracterisation> toFacteurCaracterisations(List<ImpactReseau> impactReseaux); + + @Mapping(target = "refReseau", source = "nom") + ImpactReseau toImpactReseau(FacteurCaracterisation facteurCaracterisation); + + List<ImpactReseau> toImpactReseaux(List<FacteurCaracterisation> facteurCaracterisations); } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/MixElectriqueMapper.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/MixElectriqueMapper.java index c204d9f4306df29c599cbb2e0f14531f64383951..bbafcff07fb6487f139c1a6cd78474fbb82770ad 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/MixElectriqueMapper.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/mapper/MixElectriqueMapper.java @@ -1,11 +1,13 @@ package org.mte.numecoeval.referentiel.infrastructure.mapper; import org.mapstruct.Mapper; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.MixElectriqueDTO; +import org.mapstruct.Mapping; +import org.mte.numecoeval.referentiel.domain.model.FacteurCaracterisation; import org.mte.numecoeval.referentiel.domain.model.MixElectrique; import org.mte.numecoeval.referentiel.domain.model.id.MixElectriqueId; import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.MixElectriqueEntity; import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.MixElectriqueIdEntity; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.MixElectriqueDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.MixElectriqueIdDTO; import java.util.Collection; @@ -29,4 +31,18 @@ public interface MixElectriqueMapper { List<MixElectrique> toDomainsFromDTO(List<MixElectriqueDTO> mixElecs); MixElectriqueDTO toDTO(MixElectrique mixElectrique); -} + + @Mapping(target = "localisation", source = "pays") + @Mapping(target = "nom", expression = "java(org.mte.numecoeval.referentiel.utils.Constants.MIXELEC_NOM_LOW_VOLTAGE + mixElectrique.getRaccourcisAnglais())") + @Mapping(target = "etape", expression = "java(org.mte.numecoeval.referentiel.utils.Constants.MIXELEC_ETAPEACV)") + @Mapping(target = "niveau", expression = "java(org.mte.numecoeval.referentiel.utils.Constants.MIXELEC_NIVEAU)") + @Mapping(target = "categorie", expression = "java(org.mte.numecoeval.referentiel.utils.Constants.MIXELEC_CATEGORIE)") + FacteurCaracterisation toFacteurCaracterisation(MixElectrique mixElectrique); + + List<FacteurCaracterisation> toFacteurCaracterisations(List<MixElectrique> mixElectriques); + + @Mapping(target = "pays", source = "localisation") + MixElectrique toMixElectrique(FacteurCaracterisation facteurCaracterisation); + + List<MixElectrique> toMixElectriques(List<FacteurCaracterisation> facteurCaracterisations); +} \ No newline at end of file diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/correspondance/ReferentielAdministrationCorrespondanceRefEquipementRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/correspondance/ReferentielAdministrationCorrespondanceRefEquipementRestApi.java index 6db611f89300265941ea66305831157ae02ff9c0..8934b03eb58f1cf65ce4e063cdde8e69844bc7f0 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/correspondance/ReferentielAdministrationCorrespondanceRefEquipementRestApi.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/correspondance/ReferentielAdministrationCorrespondanceRefEquipementRestApi.java @@ -6,8 +6,8 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.servlet.http.HttpServletResponse; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; @@ -21,6 +21,14 @@ public interface ReferentielAdministrationCorrespondanceRefEquipementRestApi { @Operation( summary = "Alimentation du référentiel des correspondances de RefEquipement par csv : annule et remplace.", + description = """ + Le référentiel est lié à une organisation donnée. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le nom d’organisation pour laquelle les données sont établies et le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> + """, tags = {"Import Référentiels"}, operationId = "importCorrespondanceRefEquipementCSV" ) @@ -35,6 +43,12 @@ public interface ReferentielAdministrationCorrespondanceRefEquipementRestApi { @Operation( summary = "Exporter les correspondances de RefEquipement sous format csv", + description = """ + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_CorrespondanceRefEquipement </li> + </ul> + """, tags = {"Export Référentiels"}, operationId = "exportCorrespondanceRefEquipementCSV" ) diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/correspondance/ReferentielCorrespondanceRefEquipementRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/correspondance/ReferentielCorrespondanceRefEquipementRestApi.java index 2255fe5ddf85a6b58a7f7df6f5bee2190a05e0ad..8952046333c6da220ed4c1fbd8f8f6b6d1d4969b 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/correspondance/ReferentielCorrespondanceRefEquipementRestApi.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/correspondance/ReferentielCorrespondanceRefEquipementRestApi.java @@ -15,10 +15,6 @@ public interface ReferentielCorrespondanceRefEquipementRestApi { @Operation( summary = "Endpoint interne à NumEcoEval - Récupération d'une correspondance de refEquipement à partir d'un modèle d'équipement.", - description = """ - Endpoint interne utilisé dans l'import de données d'entrées dans NumEcoEval - pour déterminer la référence d'équipement à utiliser dans les référentiels'. - """, tags = "Interne NumEcoEval", operationId = "getCorrespondanceRefEquipement" ) diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/critere/ReferentielAdministrationCritereRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/critere/ReferentielAdministrationCritereRestApi.java index 8e1b8382851c0f928fd8e40b584cd41401a46b12..063ef0a7b15ab54a181d872d8ebc7d8bbf2b8207 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/critere/ReferentielAdministrationCritereRestApi.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/critere/ReferentielAdministrationCritereRestApi.java @@ -6,8 +6,8 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.servlet.http.HttpServletResponse; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; @@ -20,8 +20,15 @@ import java.io.IOException; public interface ReferentielAdministrationCritereRestApi { @Operation( - summary = "Alimentation des Criteres par csv (annule et remplace).", - description = "Alimentation des Criteres par csv (annule et remplace).", + summary = "Alimentation des Criteres par csv : annule et remplace.", + description = """ + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> + """, tags = {"Import Référentiels"}, operationId = "importCriteresCSV" ) @@ -35,6 +42,12 @@ public interface ReferentielAdministrationCritereRestApi { @Operation( summary = "Exporter les criteres sous format csv", + description = """ + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des Critères de ref_Critere </li> + </ul> + """, tags = {"Export Référentiels"}, operationId = "exportCriteresCSV" ) diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/critere/ReferentielCritereRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/critere/ReferentielCritereRestApi.java index f1c5ab8e5f545db51c656c434af61419ff2e6d6c..5252f4cede833412608eb66e9ea6d7ed82879414 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/critere/ReferentielCritereRestApi.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/critere/ReferentielCritereRestApi.java @@ -18,7 +18,7 @@ public interface ReferentielCritereRestApi { @Operation( summary = "Endpoint interne à NumEcoEval - Récupération de tous les critères d'impacts écologiques", description = """ - Endpoint interne utilisé dans la génération des indicateurs par le module api-calcul de NumEcoEval. + Renvoie l'intégralité des types des critères d'impacts écologiques utilisés dans NumEcoEval. """, tags = "Interne NumEcoEval", operationId = "getAllCriteres" diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/etape/ReferentielAdministrationEtapeRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/etape/ReferentielAdministrationEtapeRestApi.java index dd10619b03f95ae99e9e3f3aebf152a8ce0f86f2..ebaf5527b5694da66bc44cade9de852c208c20aa 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/etape/ReferentielAdministrationEtapeRestApi.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/etape/ReferentielAdministrationEtapeRestApi.java @@ -6,8 +6,8 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.servlet.http.HttpServletResponse; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; @@ -21,7 +21,14 @@ public interface ReferentielAdministrationEtapeRestApi { @Operation( summary = "Alimentation Etape ACV par csv : annule et remplace.", - description = "Alimentation Etape ACV par csv : annule et remplace.", + description = """ + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> + """, tags = {"Import Référentiels"}, operationId = "importEtapesCSV" ) @@ -34,6 +41,12 @@ public interface ReferentielAdministrationEtapeRestApi { @Operation( summary = "Exporter les etapes sous format csv", + description = """ + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_EtapeACV </li> + </ul> + """, tags = {"Export Référentiels"}, operationId = "exportEtapesCSV" ) diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/facteurcaracterisation/ReferentielAdministrationFacteurCaracterisationRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/facteurcaracterisation/ReferentielAdministrationFacteurCaracterisationRestApi.java new file mode 100644 index 0000000000000000000000000000000000000000..1e184353ac958d1eee9c30e88e8e5208a4f57333 --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/facteurcaracterisation/ReferentielAdministrationFacteurCaracterisationRestApi.java @@ -0,0 +1,62 @@ +package org.mte.numecoeval.referentiel.infrastructure.restapi.controller.facteurcaracterisation; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.servlet.http.HttpServletResponse; +import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; + +public interface ReferentielAdministrationFacteurCaracterisationRestApi { + + @Operation( + summary = "Alimentation du référentiel FacteurCaracterisation par csv : annule et remplace.", + description = """ + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, on peut choisir le mode pour supprimer les données déjà présentes dans la base ou pas. Par défaut, les anciennes données sont conservées. + <ul> + <li>Entrée : Le mode d'import 'FULL' ou 'DELTA' et le fichier CSV avec les données à insérer</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> + """, + tags = {"Import Référentiels"}, + operationId = "importFacteurCaracterisationCSV" + ) + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Rapport d'import du fichier CSV"), + @ApiResponse(responseCode = "400", description = "Invalid request", content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = ErrorResponseDTO.class))})}) + @PostMapping(path = "/referentiel/facteursCaracterisation/csv", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + RapportImportDTO importCSV( + @RequestPart("file") MultipartFile file, + @RequestParam(value = "mode", defaultValue = "DELTA") + @Schema(description = "Choix du mode d'insertion FULL (purge puis insertion des nouvelles données) ou " + + "DELTA (upsert : maj de la base de données existante)", defaultValue = "DELTA") String mode + ) throws IOException, ReferentielException; + + + @Operation( + summary = "Exporter les facteurs de caractérisation sous format csv", + description = """ + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_FacteurCaracterisation </li> + </ul> + """, + tags = {"Export Référentiels"}, + operationId = "exportFacteurCaracterisationCSV" + ) + @GetMapping("/referentiel/facteursCaracterisation/csv") + void exportCSV(HttpServletResponse servletResponse) throws IOException; +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/facteurcaracterisation/ReferentielFacteurCaracterisationRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/facteurcaracterisation/ReferentielFacteurCaracterisationRestApi.java new file mode 100644 index 0000000000000000000000000000000000000000..056cd35dcb397e3d4a76b3d8b267ca8219c773e3 --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/facteurcaracterisation/ReferentielFacteurCaracterisationRestApi.java @@ -0,0 +1,46 @@ +package org.mte.numecoeval.referentiel.infrastructure.restapi.controller.facteurcaracterisation; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.FacteurCaracterisationDTO; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; + +public interface ReferentielFacteurCaracterisationRestApi { + + @Operation(summary = "Endpoint interne à NumEcoEval - Récupération d'un Facteur de Caractérisation", + description = """ + Endpoint interne utilisé dans la génération des indicateurs par le module api-calcul de NumEcoEval. + Récupération d'un impact équipement en fonction de 3 paramètres: + <ul> + <li>Le nom du facteur de caractérisation: nom</li> + <li>L'étape ACV: etape</li> + <li>Le critère d'impact: critere</li> + </ul> + . + """, + tags = "Interne NumEcoEval", + operationId = "getFacteurCaracterisation") + @ApiResponses(value = { + @ApiResponse(responseCode = "200", description = "Facteur Caractérisation trouvé", + content = {@Content(mediaType = "application/json", schema = @Schema(implementation = FacteurCaracterisationDTO.class))}), + @ApiResponse(responseCode = "400", description = "Invalid request", content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = ErrorResponseDTO.class))}), + @ApiResponse(responseCode = "404", description = "Facteur Caractérisation non trouvé", content = {@Content(mediaType = "application/json", + schema = @Schema(implementation = ErrorResponseDTO.class))})}) + @GetMapping(path = "/referentiel/facteursCaracterisation", produces = MediaType.APPLICATION_JSON_VALUE) + FacteurCaracterisationDTO get( + @RequestParam + @Schema(description = "Nom du facteur de caractérisation recherché") final String nom, + @RequestParam + @Schema(description = "Nom du critère d'impact écologique") final String critere, + @RequestParam + @Schema(description = "Code de l'étape ACV") final String etapeacv + ); + +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/facteurcaracterisation/ReferentielFacteurCaracterisationRestApiImpl.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/facteurcaracterisation/ReferentielFacteurCaracterisationRestApiImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..c71b396f0fc4c3075f29dca64b267e439e84e223 --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/facteurcaracterisation/ReferentielFacteurCaracterisationRestApiImpl.java @@ -0,0 +1,71 @@ +package org.mte.numecoeval.referentiel.infrastructure.restapi.controller.facteurcaracterisation; + +import jakarta.servlet.http.HttpServletResponse; +import lombok.AllArgsConstructor; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportFacteurCaracterisationPortImpl; +import org.mte.numecoeval.referentiel.infrastructure.adapter.export.FacteurCaracterisationCsvExportService; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.BaseExportReferentiel; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.FacteurCaracterisationDTO; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.FacteurCaracterisationIdDTO; +import org.mte.numecoeval.referentiel.infrastructure.restapi.facade.FacteurCaracterisationFacade; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.server.ResponseStatusException; + +import java.io.IOException; + +@RestController +@Slf4j +@AllArgsConstructor +public class ReferentielFacteurCaracterisationRestApiImpl implements BaseExportReferentiel<FacteurCaracterisationEntity>, ReferentielFacteurCaracterisationRestApi, ReferentielAdministrationFacteurCaracterisationRestApi { + private FacteurCaracterisationFacade referentielFacade; + + private FacteurCaracterisationCsvExportService csvExportService; + + @SneakyThrows + @Override + public FacteurCaracterisationDTO get(String nom, String critere, String etapeacv) { + + FacteurCaracterisationIdDTO id = FacteurCaracterisationIdDTO.builder() + .nom(StringUtils.trim(nom)) + .critere(critere) + .etape(etapeacv) + .build(); + + return referentielFacade.get(id); + } + + @Override + public RapportImportDTO importCSV(MultipartFile fichier, String mode) throws IOException, ReferentielException { + if (fichier == null || fichier.isEmpty()) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Le fichier n'existe pas ou alors il est vide"); + } + var rapportImport = new ImportFacteurCaracterisationPortImpl().importCSV(fichier.getInputStream()); + if ("FULL".equals(mode)) { + referentielFacade.purgeAndAddAll(rapportImport.getObjects()); + } else if ("DELTA".equals(mode)) { + referentielFacade.upsert(rapportImport.getObjects()); + } else { + throw new ReferentielException("Le mode d'import indiqué n'est pas valide"); + } + + return new RapportImportDTO( + fichier.getOriginalFilename(), + rapportImport.getErreurs(), + rapportImport.getNbrLignesImportees() + ); + + } + + @Override + public void exportCSV(HttpServletResponse servletResponse) throws IOException { + exportCSV(servletResponse, csvExportService, "facteurCaracterisation"); + } +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/hypothese/ReferentielAdministrationHypotheseRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/hypothese/ReferentielAdministrationHypotheseRestApi.java index 34bb5683957fed156254b3be6d7428acd6d60750..c3d123dcc20f3e040cf16d71c862213287a03530 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/hypothese/ReferentielAdministrationHypotheseRestApi.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/hypothese/ReferentielAdministrationHypotheseRestApi.java @@ -6,8 +6,8 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.servlet.http.HttpServletResponse; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; @@ -21,7 +21,14 @@ public interface ReferentielAdministrationHypotheseRestApi { @Operation( summary = "Alimentation des Hypothèses par csv : annule et remplace.", - description = "Alimentation des Hypothèses par csv : annule et remplace.", + description = """ + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> + """, tags = {"Import Référentiels"}, operationId = "importHypothesesCSV" ) @@ -35,6 +42,12 @@ public interface ReferentielAdministrationHypotheseRestApi { @Operation( summary = "Exporter les hypothèses sous format csv", + description = """ + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_Hypotheses </li> + </ul> + """, tags = {"Export Référentiels"}, operationId = "exportHypothesesCSV" ) diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactequipement/ReferentielAdministrationImpactEquipementRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactequipement/ReferentielAdministrationImpactEquipementRestApi.java index acef1066978903d2f13a5cae4c82703efecdb1c5..adfa3bf58d221ec84ee7d292b6b3221dfdbadb9a 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactequipement/ReferentielAdministrationImpactEquipementRestApi.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactequipement/ReferentielAdministrationImpactEquipementRestApi.java @@ -6,8 +6,8 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.servlet.http.HttpServletResponse; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; @@ -21,7 +21,14 @@ public interface ReferentielAdministrationImpactEquipementRestApi { @Operation( summary = "Alimentation du référentiel ImpactEquipement par csv : annule et remplace.", - description = "Alimentation du référentiel ImpactEquipement par csv : annule et remplace.", + description = """ + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> + """, tags = {"Import Référentiels"}, operationId = "importImpactEquipementCSV" ) @@ -35,6 +42,12 @@ public interface ReferentielAdministrationImpactEquipementRestApi { @Operation( summary = "Exporter les impacts d'équipements sous format csv", + description = """ + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_ImpactEquipement </li> + </ul> + """, tags = {"Export Référentiels"}, operationId = "exportImpactEquipementCSV" ) diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactequipement/ReferentielImpactEquipementRestApiImpl.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactequipement/ReferentielImpactEquipementRestApiImpl.java index 27e9300d43b819aaebaa41c385fc7c589feaedfb..1cbce12b878f7eec6c804d01308784c17a7229f7 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactequipement/ReferentielImpactEquipementRestApiImpl.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactequipement/ReferentielImpactEquipementRestApiImpl.java @@ -6,9 +6,9 @@ import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.domain.model.ImpactEquipement; import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportImpactEquipementPortImpl; import org.mte.numecoeval.referentiel.infrastructure.adapter.export.ImpactEquipementCsvExportService; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactEquipementEntity; import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.BaseExportReferentiel; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactEquipementDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; @@ -24,7 +24,7 @@ import java.io.IOException; @RestController @Slf4j @AllArgsConstructor -public class ReferentielImpactEquipementRestApiImpl implements BaseExportReferentiel<ImpactEquipementEntity>, ReferentielImpactEquipementRestApi, ReferentielAdministrationImpactEquipementRestApi { +public class ReferentielImpactEquipementRestApiImpl implements BaseExportReferentiel<ImpactEquipement>, ReferentielImpactEquipementRestApi, ReferentielAdministrationImpactEquipementRestApi { private ImpactEquipementFacade referentielFacade; private ImpactEquipementCsvExportService csvExportService; @@ -38,7 +38,7 @@ public class ReferentielImpactEquipementRestApiImpl implements BaseExportReferen .critere(critere) .etape(etapeacv) .build(); - + return referentielFacade.get(id); } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactmessagerie/ReferentielInterneImpactMessagerieRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactmessagerie/ReferentielInterneImpactMessagerieRestApi.java index 6272030fe67c6092388e18322cf6d56395a36cd0..7d4c587ae0e45adb09c9ce812528b7681856a89d 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactmessagerie/ReferentielInterneImpactMessagerieRestApi.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactmessagerie/ReferentielInterneImpactMessagerieRestApi.java @@ -6,8 +6,8 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.servlet.http.HttpServletResponse; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; @@ -21,7 +21,14 @@ public interface ReferentielInterneImpactMessagerieRestApi { @Operation( summary = "Alimentation du référentiel Impact Messagerie par csv : annule et remplace.", - description = "Alimentation du référentiel Impact Messagerie par csv : annule et remplace.", + description = """ + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> + """, tags = {"Import Référentiels"}, operationId = "importImpactMessagerieCSV" ) @@ -29,13 +36,19 @@ public interface ReferentielInterneImpactMessagerieRestApi { @ApiResponse(responseCode = "200", description = "Rapport d'import du fichier CSV"), @ApiResponse(responseCode = "400", description = "Invalid request", content = {@Content(mediaType = "application/json", - schema = @Schema(implementation = ErrorResponseDTO.class))})}) + schema = @Schema(implementation = ErrorResponseDTO.class))})}) @PostMapping(path = "/referentiel/impactMessagerie/csv", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) RapportImportDTO importCSV(@RequestPart("file") MultipartFile file) throws IOException, ReferentielException; @Operation( summary = "Exporter les impacts de messagerie sous format csv", + description = """ + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_ImpactMessagerie </li> + </ul> + """, tags = {"Export Référentiels"}, operationId = "exportImpactMessagerieCSV" ) diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactreseau/ReferentielAdministrationImpactReseauRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactreseau/ReferentielAdministrationImpactReseauRestApi.java index 0d2340e1940a3734b7e83ad7fd6fb9d399638659..202daa59420b83dab5d7e120d3e6fb66bc37d9f0 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactreseau/ReferentielAdministrationImpactReseauRestApi.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactreseau/ReferentielAdministrationImpactReseauRestApi.java @@ -6,17 +6,13 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.servlet.http.HttpServletResponse; +import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactReseauDTO; -import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @@ -24,10 +20,17 @@ import java.io.IOException; public interface ReferentielAdministrationImpactReseauRestApi { @Operation( - summary = "Exposition ressource ajout d' un Impact Reseau", + summary = "Alimentation du référentiel ImpactReseau par csv : annule et remplace.", + description = """ + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> + """, tags = {"Administration détaillée"}, - hidden = true, - description = "Exposition ressource ajout d' un Impact Reseau" + hidden = true ) @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "impact reseau trouvé", @@ -41,7 +44,7 @@ public interface ReferentielAdministrationImpactReseauRestApi { @Operation( summary = "Exposition ressource update Impact Reseau ", - tags = {"Administration détaillée"},hidden = true + tags = {"Administration détaillée"}, hidden = true ) @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Modication d'un impact reseau : les champs refReseau, critere & etapeACV ne peuvent pas être modifié", @@ -56,6 +59,14 @@ public interface ReferentielAdministrationImpactReseauRestApi { @Operation( summary = "Alimentation du référentiel ImpactReseau par csv : annule et remplace.", + description = """ + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> + """, tags = {"Import Référentiels"}, operationId = "importImpactReseauxCSV" ) @@ -69,6 +80,12 @@ public interface ReferentielAdministrationImpactReseauRestApi { @Operation( summary = "Exporter les impacts réseaux sous format csv", + description = """ + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_ImpactReseau </li> + </ul> + """, tags = {"Export Référentiels"}, operationId = "exportImpactReseauxCSV" ) diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactreseau/ReferentielImpactReseauRestApiImpl.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactreseau/ReferentielImpactReseauRestApiImpl.java index bdd40ff1b8de1cd5ff3f4420b3a8f16b6fd65b94..ec44f8a61f4f25589bd5be72973b554c5a6e302d 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactreseau/ReferentielImpactReseauRestApiImpl.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/impactreseau/ReferentielImpactReseauRestApiImpl.java @@ -6,9 +6,9 @@ import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.domain.model.ImpactReseau; import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportImpactReseauPortImpl; import org.mte.numecoeval.referentiel.infrastructure.adapter.export.ImpactReseauCsvExportService; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactReseauEntity; import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.BaseExportReferentiel; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactReseauDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; @@ -29,7 +29,7 @@ import java.util.Objects; @RestController @Slf4j @AllArgsConstructor -public class ReferentielImpactReseauRestApiImpl implements BaseExportReferentiel<ImpactReseauEntity>, ReferentielImpactReseauRestApi, ReferentielAdministrationImpactReseauRestApi { +public class ReferentielImpactReseauRestApiImpl implements BaseExportReferentiel<ImpactReseau>, ReferentielImpactReseauRestApi, ReferentielAdministrationImpactReseauRestApi { private ImpactReseauFacade referentielFacade; private ImpactReseauCsvExportService csvExportService; diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/mixelectrique/ReferentielAdministrationMixElectriqueRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/mixelectrique/ReferentielAdministrationMixElectriqueRestApi.java index a983084502654e264d83e7d8500d1be18bfe1952..7ce920c8deb6ba4343763e28ff626cce6332a574 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/mixelectrique/ReferentielAdministrationMixElectriqueRestApi.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/mixelectrique/ReferentielAdministrationMixElectriqueRestApi.java @@ -6,8 +6,8 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.servlet.http.HttpServletResponse; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; @@ -22,6 +22,14 @@ public interface ReferentielAdministrationMixElectriqueRestApi { @Operation( summary = "Alimentation du référentiel ImpactEquipement par csv : annule et remplace.", + description = """ + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> + """, tags = {"Import Référentiels"}, operationId = "importImpactEquipementCSV" ) @@ -35,6 +43,12 @@ public interface ReferentielAdministrationMixElectriqueRestApi { @Operation( summary = "Exporter les impacts des mix électrique sous format csv", + description = """ + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_MexElectriques </li> + </ul> + """, tags = {"Export Référentiels"}, operationId = "exportImpactEquipementCSV" ) diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/mixelectrique/ReferentielMixElecRestApiImpl.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/mixelectrique/ReferentielMixElecRestApiImpl.java index 770a4e6031689a219f81b3de2f923e3f440ef60d..3ab25de01439ec4be9c6a24fab9bfd0252ba87e7 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/mixelectrique/ReferentielMixElecRestApiImpl.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/mixelectrique/ReferentielMixElecRestApiImpl.java @@ -5,9 +5,9 @@ import lombok.AllArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.domain.model.MixElectrique; import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportMixElectriquePortImpl; import org.mte.numecoeval.referentiel.infrastructure.adapter.export.MixElectriqueCsvExportService; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.MixElectriqueEntity; import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.BaseExportReferentiel; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.MixElectriqueDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; @@ -24,7 +24,7 @@ import java.util.List; @RestController @Slf4j @AllArgsConstructor -public class ReferentielMixElecRestApiImpl implements BaseExportReferentiel<MixElectriqueEntity>, ReferentielMixElectriqueRestApi, ReferentielAdministrationMixElectriqueRestApi { +public class ReferentielMixElecRestApiImpl implements BaseExportReferentiel<MixElectrique>, ReferentielMixElectriqueRestApi, ReferentielAdministrationMixElectriqueRestApi { private MixElectriqueFacade referentielFacade; private MixElectriqueCsvExportService csvExportService; @@ -63,7 +63,7 @@ public class ReferentielMixElecRestApiImpl implements BaseExportReferentiel<MixE .pays(pays) .critere(critere) .build(); - + return referentielFacade.get(id); } diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/typeequipement/ReferentielAdministrationTypeEquipementRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/typeequipement/ReferentielAdministrationTypeEquipementRestApi.java index b0daa761c15e81958f01a687bc00dc81025c33f5..458241aa40b9a3adbb92c8733358baa8f049a74c 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/typeequipement/ReferentielAdministrationTypeEquipementRestApi.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/typeequipement/ReferentielAdministrationTypeEquipementRestApi.java @@ -6,8 +6,8 @@ import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import jakarta.servlet.http.HttpServletResponse; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.RapportImportDTO; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; @@ -21,6 +21,14 @@ public interface ReferentielAdministrationTypeEquipementRestApi { @Operation( summary = "Alimentation du référentiel Type Equipement par csv : annule et remplace.", + description = """ + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> + """, tags = {"Import Référentiels"}, operationId = "importTypeEquipementCSV" ) @@ -28,13 +36,19 @@ public interface ReferentielAdministrationTypeEquipementRestApi { @ApiResponse(responseCode = "200", description = "Rapport d'import du fichier CSV"), @ApiResponse(responseCode = "400", description = "Invalid request", content = {@Content(mediaType = "application/json", - schema = @Schema(implementation = ErrorResponseDTO.class))})}) + schema = @Schema(implementation = ErrorResponseDTO.class))})}) @PostMapping(path = "/referentiel/typeEquipement/csv", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) RapportImportDTO importCSV(@RequestPart("file") MultipartFile file) throws IOException, ReferentielException; @Operation( summary = "Exporter les impacts des types d'équipements sous format csv", + description = """ + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_TypeEquipement </li> + </ul> + """, tags = {"Export Référentiels"}, operationId = "exportTypeEquipementCSV" ) diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/typeequipement/ReferentielTypeEquipementRestApi.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/typeequipement/ReferentielTypeEquipementRestApi.java index 0bbc6c19f09fd10c1ab0b7b9ce4fa82bcc99a171..07a9ebec051523a9fc841c121442801f1a09d7d7 100644 --- a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/typeequipement/ReferentielTypeEquipementRestApi.java +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/typeequipement/ReferentielTypeEquipementRestApi.java @@ -6,9 +6,9 @@ import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.TypeEquipementDTO; -import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -22,7 +22,7 @@ public interface ReferentielTypeEquipementRestApi { description = """ Endpoint interne utilisé à la réception de données d'entrées par le module api-expositiondonneesentrees de NumEcoEval. Renvoie l'intégralité des types d'équipements utilisables par NumEcoEval. - + Les types d'équipement servent notamment à alimenter la durée de vie par défaut des équipements reçues. """, @@ -35,7 +35,7 @@ public interface ReferentielTypeEquipementRestApi { array = @ArraySchema(schema = @Schema(implementation = TypeEquipementDTO.class)))}), @ApiResponse(responseCode = "400", description = "Invalid request", content = {@Content(mediaType = "application/json", - schema = @Schema(implementation = ErrorResponseDTO.class))}), + schema = @Schema(implementation = ErrorResponseDTO.class))}), @ApiResponse(responseCode = "404", description = "Types Equipement non trouvé", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class))})}) @GetMapping(path = "/referentiel/typesEquipement", produces = MediaType.APPLICATION_JSON_VALUE) @@ -44,7 +44,7 @@ public interface ReferentielTypeEquipementRestApi { @Operation( summary = "Endpoint interne à NumEcoEval - Récupération d'un type d'équipement via son type", description = """ - V2 - Endpoint interne utilisé à l'enrichissement données pour un équipement physique. + Endpoint interne utilisé à la réception de données d'entrées par le module api-expositiondonneesentrees de NumEcoEval. Renvoie l'intégralité des types d'équipements d'un certain type. """, tags = "Interne NumEcoEval", operationId = "getTypeEquipement" @@ -55,7 +55,7 @@ public interface ReferentielTypeEquipementRestApi { schema = @Schema(implementation = TypeEquipementDTO.class))}), @ApiResponse(responseCode = "400", description = "Invalid request", content = {@Content(mediaType = "application/json", - schema = @Schema(implementation = ErrorResponseDTO.class))}), + schema = @Schema(implementation = ErrorResponseDTO.class))}), @ApiResponse(responseCode = "404", description = "Types Equipement non trouvé", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponseDTO.class))})}) @GetMapping(path = "/referentiel/typesEquipement/{type}", produces = MediaType.APPLICATION_JSON_VALUE) diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/dto/FacteurCaracterisationDTO.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/dto/FacteurCaracterisationDTO.java new file mode 100644 index 0000000000000000000000000000000000000000..e1beb39ed41b429f121624ae460fc20466d3d00d --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/dto/FacteurCaracterisationDTO.java @@ -0,0 +1,66 @@ +package org.mte.numecoeval.referentiel.infrastructure.restapi.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.*; +import lombok.experimental.FieldDefaults; + +@Setter +@Getter +@AllArgsConstructor +@NoArgsConstructor +@Builder +@FieldDefaults(level = AccessLevel.PRIVATE) +@EqualsAndHashCode +@Schema( + description = "Référentiel de l'impact écologique d'un facteur de caractérisation. La clé est composé des champs nom, etape et critere." +) +public class FacteurCaracterisationDTO { + @Schema( + description = "Nom du facteur de caractérisation, fait partie de la clé dans le référentiel" + ) + String nom; + @Schema( + description = "Étape ACV concernée, fait partie de la clé dans le référentiel" + ) + String etape; + @Schema( + description = "Critère d'impact écologique concerné, fait partie de la clé dans le référentiel" + ) + String critere; + @Schema( + description = "Description de l'entrée dans le référentiel" + ) + String description; + @Schema( + description = "Niveau du facteur de caractérisation concerné" + ) + String niveau; + @Schema( + description = "Tiers du facteur de caractérisation concerné" + ) + String tiers; + @Schema( + description = "Catégorie du facteur de caractérisation concerné" + ) + String categorie; + @Schema( + description = "Consommation électrique moyenne" + ) + Double consoElecMoyenne; + @Schema( + description = "Localisation du facteur de caractérisation concerné" + ) + String localisation; + @Schema( + description = "Valeur de l'impact écologique" + ) + Double valeur; + @Schema( + description = "Unité du critère d'impact écologique" + ) + String unite; + @Schema( + description = "Source de l'impact écologique pour ce facteur de caractérisation" + ) + String source; +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/dto/id/FacteurCaracterisationIdDTO.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/dto/id/FacteurCaracterisationIdDTO.java new file mode 100644 index 0000000000000000000000000000000000000000..1e17f24668cebc99da08369c7ec9b88508615b27 --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/dto/id/FacteurCaracterisationIdDTO.java @@ -0,0 +1,17 @@ +package org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id; + +import lombok.*; +import lombok.experimental.FieldDefaults; + +@Setter +@Getter +@AllArgsConstructor +@NoArgsConstructor +@Builder +@FieldDefaults(level = AccessLevel.PRIVATE) +@EqualsAndHashCode +public class FacteurCaracterisationIdDTO { + String nom; + String etape; + String critere; +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/facade/FacteurCaracterisationFacade.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/facade/FacteurCaracterisationFacade.java new file mode 100644 index 0000000000000000000000000000000000000000..f959e8c849da1dd0712d46da8cb0f8ce5effe2ba --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/infrastructure/restapi/facade/FacteurCaracterisationFacade.java @@ -0,0 +1,41 @@ +package org.mte.numecoeval.referentiel.infrastructure.restapi.facade; + +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.domain.model.FacteurCaracterisation; +import org.mte.numecoeval.referentiel.domain.model.id.FacteurCaracterisationId; +import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.FacteurCaracterisationDTO; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.FacteurCaracterisationIdDTO; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +@Slf4j +@AllArgsConstructor +public class FacteurCaracterisationFacade { + + private ReferentielPersistencePort<FacteurCaracterisation, FacteurCaracterisationId> persistencePort; + + + private FacteurCaracterisationMapper mapper; + + + public FacteurCaracterisationDTO get(FacteurCaracterisationIdDTO id) throws ReferentielException { + FacteurCaracterisationId facteurCaracterisationId = mapper.toDomainId(id); + FacteurCaracterisation facteurCaracterisation = persistencePort.get(facteurCaracterisationId); + return mapper.toDTO(facteurCaracterisation); + } + + public void purgeAndAddAll(List<FacteurCaracterisationDTO> fcsDTO) throws ReferentielException { + persistencePort.purge(); + persistencePort.saveAll(mapper.toDomainsFromDTO(fcsDTO)); + } + + public void upsert(List<FacteurCaracterisationDTO> fcsDTO) throws ReferentielException { + persistencePort.saveAll(mapper.toDomainsFromDTO(fcsDTO)); + } +} diff --git a/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/utils/Constants.java b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/utils/Constants.java new file mode 100644 index 0000000000000000000000000000000000000000..27b7430f4e7a134e442d0c8d784d914db06572d7 --- /dev/null +++ b/services/api-referentiel/src/main/java/org/mte/numecoeval/referentiel/utils/Constants.java @@ -0,0 +1,13 @@ +package org.mte.numecoeval.referentiel.utils; + +public class Constants { + + public static final String EQUIPEMENT_NIVEAU = "2-Equipement"; + public static final String MIXELEC_NIVEAU = "0-Base data"; + public static final String MIXELEC_CATEGORIE = "electricity-mix"; + public static final String MIXELEC_ETAPEACV = "FABRICATION"; + public static final String MIXELEC_NOM_LOW_VOLTAGE = "Electricity Mix/ Production mix/ Low voltage/ "; + public static final String RESEAU_NIVEAU = "3-System"; + public static final String RESEAU_TIERS = "Network"; + +} diff --git a/services/api-referentiel/src/main/resources/schema.sql b/services/api-referentiel/src/main/resources/schema.sql index e394926020efd12d149a435ee516dd18317c341a..e52a333a27706cac1ca02a000762765e8a1b25f2 100644 --- a/services/api-referentiel/src/main/resources/schema.sql +++ b/services/api-referentiel/src/main/resources/schema.sql @@ -81,11 +81,26 @@ CREATE TABLE IF NOT EXISTS ref_mixelec nomcritere varchar(255) NOT NULL, CONSTRAINT ref_mixelec_pkey PRIMARY KEY (nomcritere, pays) ); - + CREATE TABLE IF NOT EXISTS ref_facteurcaracterisation +( + nom varchar(255) NOT NULL, + etapeacv varchar(255) NOT NULL, + nomcritere varchar(255) NOT NULL, + description varchar(255) NULL, + niveau varchar(255) NULL, + tiers varchar(255) NULL, + categorie varchar(255) NULL, + conso_elec_moyenne float8 NULL, + localisation varchar(255) NULL, + valeur float8 NULL, + unite varchar(255) NULL, + source varchar(255) NULL, + CONSTRAINT ref_facteurcaracterisation_pkey PRIMARY KEY (nom, etapeacv, nomcritere) +); -- suppression des contraintes de clés étrangères ALTER TABLE ref_impactequipement DROP CONSTRAINT IF EXISTS fk5iuiwnk7rymtob1fku71uuj52; ALTER TABLE ref_impactequipement DROP CONSTRAINT IF EXISTS fksfjum8kagn7q6vsv5uqn6kimx; ALTER TABLE ref_impactreseau DROP CONSTRAINT IF EXISTS fk31ykp7xtj41win3ptqlr3us9s; ALTER TABLE ref_impactreseau DROP CONSTRAINT IF EXISTS fkb8tkreu8c8s8pqqnft6vr4pnf; ALTER TABLE ref_mixelec DROP CONSTRAINT IF EXISTS fkdncd4m2je6fbno7pkn850u1fs; -ALTER TABLE ref_impact_messagerie DROP CONSTRAINT IF EXISTS fkohnlpwfp0ebk7dswmfbe5l3k0; \ No newline at end of file +ALTER TABLE ref_impact_messagerie DROP CONSTRAINT IF EXISTS fkohnlpwfp0ebk7dswmfbe5l3k0; diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/CucumberIntegrationTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/CucumberIntegrationTest.java deleted file mode 100644 index 6a41ee15a04dc4a606e70369bceab12796980cf9..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/CucumberIntegrationTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.mte.numecoeval.referentiel; - -import io.cucumber.spring.CucumberContextConfiguration; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.platform.suite.api.ConfigurationParameter; -import org.junit.platform.suite.api.IncludeEngines; -import org.junit.platform.suite.api.SelectClasspathResource; -import org.junit.platform.suite.api.Suite; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; - -import static io.cucumber.junit.platform.engine.Constants.GLUE_PROPERTY_NAME; -import static io.cucumber.junit.platform.engine.Constants.PLUGIN_PROPERTY_NAME; - -@CucumberContextConfiguration -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@ActiveProfiles(profiles = {"test"}) -@Suite -@IncludeEngines("cucumber") -@SelectClasspathResource("org/mte/numecoeval/referentiel") -@ConfigurationParameter(key = PLUGIN_PROPERTY_NAME, value = "pretty,html:target/cucumber-reports.html") -@ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "org.mte.numecoeval.referentiel") -class CucumberIntegrationTest { - - @Test - void loadCucumber() { - Assertions.assertNotNull(CucumberIntegrationTest.class); - } -} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/ReferentielApplicationTests.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/ReferentielApplicationTests.java index 5d1c0da87d2007f08862bdc4b22e20efa5a97a2f..e2b40087be5772bbd5127a36979b975db96e9834 100644 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/ReferentielApplicationTests.java +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/ReferentielApplicationTests.java @@ -1,68 +1,17 @@ package org.mte.numecoeval.referentiel; -import io.restassured.RestAssured; -import io.restassured.http.ContentType; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.hypothese.ReferentielHypotheseRestApi; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.core.env.Environment; import org.springframework.test.context.ActiveProfiles; -import org.springframework.web.bind.annotation.GetMapping; - -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.Objects; - -import static io.restassured.RestAssured.given; -import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) @ActiveProfiles(profiles = {"test"}) class ReferentielApplicationTests { - - @Autowired - Environment environment; - - @BeforeEach - public void setupRestAssured() { - RestAssured.baseURI = "http://localhost"; - RestAssured.port = Integer.parseInt(Objects.requireNonNull(environment.getProperty("server.port"))); - } @Test void contextLoads() { Assertions.assertNotNull(ReferentielApplication.class); } - @Test - void getHypothese_whenNoData_shouldReturn404() throws NoSuchMethodException { - String requestPath = Arrays.stream(ReferentielHypotheseRestApi.class.getMethod("get", String.class) - .getAnnotation(GetMapping.class).path()).findFirst().orElse(null); - var response = given() - .contentType(ContentType.JSON) - .param("cle", "NonExistant") - .get(requestPath) - .thenReturn(); - - assertEquals(404, response.getStatusCode()); - var errorResponseDTO = response.as(ErrorResponseDTO.class); - assertEquals(404, errorResponseDTO.getCode()); - assertEquals("Hypothèse non trouvé", errorResponseDTO.getMessage()); - } - - @Test - void unknownEndpoint_shouldReturn400() throws NoSuchMethodException { - var response = given() - .contentType(ContentType.JSON) - .get("/this/is/not/an/existing/endpoint?true=yes") - .thenReturn(); - - assertEquals(404, response.getStatusCode()); - var errorResponseDTO = response.as(LinkedHashMap.class); - assertEquals("/this/is/not/an/existing/endpoint", errorResponseDTO.get("path")); - } } diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/domain/port/input/ImportFacteurCaracterisationPortTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/domain/port/input/ImportFacteurCaracterisationPortTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3054d4c1cd8722e7d0b58478070a155890260bb8 --- /dev/null +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/domain/port/input/ImportFacteurCaracterisationPortTest.java @@ -0,0 +1,136 @@ +package org.mte.numecoeval.referentiel.domain.port.input; + +import org.junit.jupiter.api.Test; +import org.mte.numecoeval.referentiel.domain.ports.input.ImportCSVReferentielPort; +import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportFacteurCaracterisationPortImpl; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.FacteurCaracterisationDTO; +import org.mte.numecoeval.referentiel.utils.Constants; +import org.springframework.util.ResourceUtils; + +import java.io.*; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + +public class ImportFacteurCaracterisationPortTest { + ImportCSVReferentielPort<FacteurCaracterisationDTO> importPortToTest = new ImportFacteurCaracterisationPortImpl(); + + @Test + void importCSV_shouldImportAllDatas() throws Exception { + File file = ResourceUtils.getFile("classpath:csv/unit/facteurCaracterisation.csv"); + var resultatImport = importPortToTest.importCSV(new FileInputStream(file)); + + assertEquals(4, resultatImport.getNbrLignesImportees()); + assertEquals(0, resultatImport.getErreurs().size()); + assertEquals(4, resultatImport.getObjects().size()); + String name = Constants.MIXELEC_NOM_LOW_VOLTAGE + "FR"; + assertTrue(resultatImport.getObjects().stream().anyMatch(dto -> + name.equals(dto.getNom()) + && Constants.MIXELEC_ETAPEACV.equals(dto.getEtape()) + && "Changement climatique".equals(dto.getCritere()) + && Constants.MIXELEC_NIVEAU.equals(dto.getNiveau()) + && Constants.MIXELEC_CATEGORIE.equals(dto.getCategorie()) + && "France".equals(dto.getLocalisation()) + && Double.valueOf(0.0813225).equals(dto.getValeur()) + && "kWh".equals(dto.getUnite()) + && "BaseImpact".equals(dto.getSource()) + + ) + ); + + assertTrue(resultatImport.getObjects().stream().anyMatch(dto -> + "Laptop".equals(dto.getNom()) + && "DISTRIBUTION".equals(dto.getEtape()) + && "Ressources use, minerals and metals".equals(dto.getCritere()) + && "HP".equals(dto.getDescription()) + && Constants.EQUIPEMENT_NIVEAU.equals(dto.getNiveau()) + && "End-user/Terminals".equals(dto.getTiers()) + && "Consultation".equals(dto.getCategorie()) + && "Allemagne".equals(dto.getLocalisation()) + && Double.valueOf(0.000882).equals(dto.getValeur()) + && "Item".equals(dto.getUnite()) + && "NegaOctet".equals(dto.getSource()) + ) + ); + + assertTrue(resultatImport.getObjects().stream().anyMatch(dto -> + "Mobile network".equals(dto.getNom()) + && "FABRICATION".equals(dto.getEtape()) + && "Climate change".equals(dto.getCritere()) + && Constants.RESEAU_NIVEAU.equals(dto.getNiveau()) + && Constants.RESEAU_TIERS.equals(dto.getTiers()) + && Double.valueOf(0.8).equals(dto.getConsoElecMoyenne()) + && Double.valueOf(0.00000159).equals(dto.getValeur()) + && "GB".equals(dto.getUnite()) + && "NegaOctet".equals(dto.getSource()) + ) + ); + + + } + + @Test + void importCSV_whenErrorInMiddleOfFile_shouldImportDatasWithErrors() throws Exception { + File file = ResourceUtils.getFile("classpath:csv/unit/facteurCaracterisation_errorInMiddle.csv"); + var resultatImport = importPortToTest.importCSV(new FileInputStream(file)); + + assertEquals(4, resultatImport.getNbrLignesImportees()); + assertEquals(3, resultatImport.getErreurs().size()); + assertTrue(resultatImport.getErreurs().stream().anyMatch("La ligne n°4 est invalide : La colonne nom ne peut être vide"::equals)); + assertTrue(resultatImport.getErreurs().stream().anyMatch("La ligne n°5 est invalide : La colonne etapeacv ne peut être vide"::equals)); + assertTrue(resultatImport.getErreurs().stream().anyMatch("La ligne n°6 est invalide : La colonne critere ne peut être vide"::equals)); + assertEquals(4, resultatImport.getObjects().size()); + String name = Constants.MIXELEC_NOM_LOW_VOLTAGE + "FR"; + assertTrue(resultatImport.getObjects().stream().anyMatch(dto -> + name.equals(dto.getNom()) + && Constants.MIXELEC_ETAPEACV.equals(dto.getEtape()) + && "Changement climatique".equals(dto.getCritere()) + && Constants.MIXELEC_NIVEAU.equals(dto.getNiveau()) + && Constants.MIXELEC_CATEGORIE.equals(dto.getCategorie()) + && "France".equals(dto.getLocalisation()) + && Double.valueOf(0.0813225).equals(dto.getValeur()) + && "kWh".equals(dto.getUnite()) + && "BaseImpact".equals(dto.getSource()) + + ) + ); + } + + @Test + void importCSV_whenWrongFile_shouldReturnOnlyErrors() throws Exception { + File file = ResourceUtils.getFile("classpath:csv/unit/wrongCSVFile.csv"); + var resultatImport = importPortToTest.importCSV(new FileInputStream(file)); + + assertEquals(0, resultatImport.getNbrLignesImportees()); + assertEquals(1, resultatImport.getErreurs().size()); + assertTrue(resultatImport.getErreurs().stream().anyMatch("La ligne n°2 est invalide : Entêtes incohérentes"::equals)); + } + + @Test + void importCSV_whenStreamAlreadyClosedShouldReturnReportWithOneError() throws IOException { + DataInputStream dataInputStream = mock(DataInputStream.class); + doNothing().when(dataInputStream).close(); + + var resultatImport = importPortToTest.importCSV(dataInputStream); + + verify(dataInputStream).close(); + assertEquals(0, resultatImport.getNbrLignesImportees()); + assertEquals(1, resultatImport.getErreurs().size()); + assertEquals("Le fichier CSV n'a pas pu être lu.", resultatImport.getErreurs().get(0)); + } + + @Test + void importCSV_whenFileNotFoundShouldReturnReportWithOneError() throws IOException { + DataInputStream dataInputStream = mock(DataInputStream.class); + doThrow(new FileNotFoundException("start Read csv etape")).when(dataInputStream).close(); + + var resultatImport = importPortToTest.importCSV(dataInputStream); + + verify(dataInputStream).close(); + assertEquals(0, resultatImport.getNbrLignesImportees()); + assertEquals(1, resultatImport.getErreurs().size()); + assertEquals("Le fichier CSV n'a pas pu être lu.", resultatImport.getErreurs().get(0)); + } + +} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/factory/TestDataFactory.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/factory/TestDataFactory.java index 50a7ff9a5aece407a6adb64023e7f9c5bdb861fb..53bc5801502b2dd52f92a827d92b0d8863318d12 100644 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/factory/TestDataFactory.java +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/factory/TestDataFactory.java @@ -1,49 +1,11 @@ package org.mte.numecoeval.referentiel.factory; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.CorrespondanceRefEquipementDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.CritereDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.EtapeDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.HypotheseDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactEquipementDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactMessagerieDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactReseauDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.MixElectriqueDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.TypeEquipementDTO; -import org.mte.numecoeval.referentiel.domain.model.CorrespondanceRefEquipement; -import org.mte.numecoeval.referentiel.domain.model.Critere; -import org.mte.numecoeval.referentiel.domain.model.Etape; -import org.mte.numecoeval.referentiel.domain.model.Hypothese; -import org.mte.numecoeval.referentiel.domain.model.ImpactEquipement; -import org.mte.numecoeval.referentiel.domain.model.ImpactMessagerie; -import org.mte.numecoeval.referentiel.domain.model.ImpactReseau; -import org.mte.numecoeval.referentiel.domain.model.MixElectrique; -import org.mte.numecoeval.referentiel.domain.model.TypeEquipement; -import org.mte.numecoeval.referentiel.domain.model.id.CritereId; -import org.mte.numecoeval.referentiel.domain.model.id.EtapeId; -import org.mte.numecoeval.referentiel.domain.model.id.HypotheseId; -import org.mte.numecoeval.referentiel.domain.model.id.ImpactEquipementId; -import org.mte.numecoeval.referentiel.domain.model.id.ImpactReseauId; -import org.mte.numecoeval.referentiel.domain.model.id.MixElectriqueId; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.CorrespondanceRefEquipementEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.CritereEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.EtapeEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.HypotheseEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactEquipementEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactMessagerieEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactReseauEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.MixElectriqueEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.TypeEquipementEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.CritereIdEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.EtapeIdEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.HypotheseIdEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.ImpactReseauIdEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.MixElectriqueIdEntity; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.CritereIdDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.EtapeIdDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.HypotheseIdDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.ImpactEquipementIdDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.ImpactReseauIdDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.MixElectriqueIdDTO; +import org.mte.numecoeval.referentiel.domain.model.*; +import org.mte.numecoeval.referentiel.domain.model.id.*; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.*; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.*; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.*; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.*; public class TestDataFactory { @@ -178,10 +140,11 @@ public class TestDataFactory { } public static TypeEquipementEntity entity(String type, boolean estUnServeur, Double dureeVieDefaut, String commentaire, String source, String refEquipementParDefaut) { - return new TypeEquipementEntity(type,estUnServeur,commentaire,dureeVieDefaut,source, refEquipementParDefaut); + return new TypeEquipementEntity(type, estUnServeur, commentaire, dureeVieDefaut, source, refEquipementParDefaut); } } + public static class MixElectriqueFactory { public static MixElectriqueDTO dto(CritereDTO critere, String pays, String raccourcisAnglais, Double valeur, String source) { @@ -288,6 +251,76 @@ public class TestDataFactory { } + public static class FacteurCaracterisationFactory { + + public static FacteurCaracterisationDTO dto(String nom, String etape, String critere, String description, String niveau, String tiers, String categorie, Double consoElecMoyenne, String localisation, Double valeur, String unite, String source) { + return new FacteurCaracterisationDTO( + nom, + etape, + critere, + description, + niveau, + tiers, + categorie, + consoElecMoyenne, + localisation, + valeur, + unite, + source + ); + } + + public static FacteurCaracterisation domain(String nom, Etape etape, Critere critere, String description, String niveau, String tiers, String categorie, Double consoElecMoyenne, String localisation, Double valeur, String unite, String source) { + return new FacteurCaracterisation() + .setNom(nom) + .setEtape(etape.getCode()) + .setCritere(critere.getNomCritere()) + .setDescription(description) + .setNiveau(niveau) + .setTiers(tiers) + .setCategorie(categorie) + .setConsoElecMoyenne(consoElecMoyenne) + .setLocalisation(localisation) + .setValeur(valeur) + .setUnite(unite) + .setSource(source); + } + + public static FacteurCaracterisationEntity entity(String nom, EtapeEntity etape, CritereEntity critere, String description, String niveau, String tiers, String categorie, Double consoElecMoyenne, String localisation, Double valeur, String unite, String source) { + return new FacteurCaracterisationEntity() + .setNom(nom) + .setEtape(etape.getCode()) + .setCritere(critere.getNomCritere()) + .setDescription(description) + .setNiveau(niveau) + .setTiers(tiers) + .setCategorie(categorie) + .setConsoElecMoyenne(consoElecMoyenne) + .setLocalisation(localisation) + .setValeur(valeur) + .setUnite(unite) + .setSource(source); + } + + public static FacteurCaracterisationIdDTO idDTO(String nom, String etapeIdDTO, String critereId) { + return FacteurCaracterisationIdDTO + .builder() + .nom(nom) + .etape(etapeIdDTO) + .critere(critereId) + .build(); + } + + public static FacteurCaracterisationId idDomain(String nom, String etapeId, String critereId) { + return new FacteurCaracterisationId() + .setNom(nom) + .setEtape(etapeId) + .setCritere(critereId); + } + + + } + public static class ImpactReseauFactory { public static ImpactReseauDTO dto(EtapeDTO etape, CritereDTO critere, String refReseau, String source, Double valeur, Double consoElecMoyenne) { diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/FacteurCaracterisationCsvExportServiceTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/FacteurCaracterisationCsvExportServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..cdc55bbdc8d15f737d8b2734a6846d7fba4ef0dc --- /dev/null +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/FacteurCaracterisationCsvExportServiceTest.java @@ -0,0 +1,137 @@ +package org.mte.numecoeval.referentiel.infrastructure.adapter.export; + +import org.apache.commons.csv.CSVPrinter; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportFacteurCaracterisationPortImpl; +import org.mte.numecoeval.referentiel.factory.TestDataFactory; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.utils.Constants; + +import java.io.IOException; +import java.io.StringWriter; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.List; +import java.util.Locale; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.when; + +public class FacteurCaracterisationCsvExportServiceTest { + @InjectMocks + FacteurCaracterisationCsvExportService exportService; + + @Mock + FacteurCaracterisationRepository repository; + + @Mock + CSVPrinter csvPrinter; + + @BeforeEach + void setup() { + MockitoAnnotations.openMocks(this); + } + + @Test + void getHeadersShouldReturnSameHeadersAsImport() { + assertEquals(ImportFacteurCaracterisationPortImpl.getHeaders(), exportService.getHeaders()); + } + + @Test + void getObjectsToWriteShouldReturnRepositoryFindAll() { + + var entities = List.of( + TestDataFactory.FacteurCaracterisationFactory.entity( + "Ecran 27 pouces", + TestDataFactory.EtapeFactory.entity("UTILISATION", ""), + TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), + "description", Constants.EQUIPEMENT_NIVEAU, "tiers", "Monitor", 0.01, "France", 0.02, "kgCO2e", + "NegaOctet"), + TestDataFactory.FacteurCaracterisationFactory.entity( + "Ecran 27 pouces", + TestDataFactory.EtapeFactory.entity("DISTRIBUTION", ""), + TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), + "description", Constants.EQUIPEMENT_NIVEAU, "tiers", "Monitor", 0.01, "France", 0.02, "kgCO2e", + "NegaOctet") + ); + when(repository.findAll()).thenReturn(entities); + + assertEquals(entities, exportService.getObjectsToWrite()); + } + + @Test + void printRecordShouldUseEntityAttributes() throws IOException { + var entity = TestDataFactory.FacteurCaracterisationFactory.entity( + "Ecran 27 pouces", + TestDataFactory.EtapeFactory.entity("DISTRIBUTION", ""), + TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), + "description", Constants.EQUIPEMENT_NIVEAU, "tiers", "Monitor", 0.01, "France", 0.02, "kgCO2e", + "NegaOctet"); + DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); + df.setMaximumFractionDigits(340); + + assertDoesNotThrow(() -> exportService.printRecord(csvPrinter, entity)); + + Mockito.verify(csvPrinter, times(1)).printRecord(entity.getNom(), + entity.getEtape(), entity.getCritere(), entity.getDescription(), entity.getNiveau(), entity.getTiers(), entity.getCategorie(), + df.format(entity.getConsoElecMoyenne()), entity.getLocalisation(), df.format(entity.getValeur()), + entity.getUnite(), entity.getSource()); + } + + @Test + void logRecordErrorShouldLogSpecificErrorForRecord() { + var entity = TestDataFactory.FacteurCaracterisationFactory.entity( + "Ecran 27 pouces", + TestDataFactory.EtapeFactory.entity("DISTRIBUTION", ""), + TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), + "description", Constants.EQUIPEMENT_NIVEAU, "tiers", "Monitor", 0.01, "France", 0.02, "kgCO2e", + "NegaOctet"); + + assertDoesNotThrow(() -> exportService.logRecordError(entity, new Exception("Test"))); + } + + @Test + void logRecordErrorShouldLogGenericErrorForRecord() { + assertDoesNotThrow(() -> exportService.logRecordError(null, new Exception("Test"))); + } + + @Test + void logRecordErrorShouldLogGenericErrorForFile() { + assertDoesNotThrow(() -> exportService.logWriterError(new Exception("Test"))); + } + + @Test + void writeToCsvShouldReturnCSV() { + // given + var entities = List.of( + TestDataFactory.FacteurCaracterisationFactory.entity( + "Ecran 27 pouces", + TestDataFactory.EtapeFactory.entity("DISTRIBUTION", ""), + TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), + "description", Constants.EQUIPEMENT_NIVEAU, "tiers", "Monitor", 0.01, "France", 0.02, "kgCO2e", + "NegaOctet") + ); + when(repository.findAll()).thenReturn(entities); + StringWriter stringWriter = new StringWriter(); + + // when + exportService.writeToCsv(stringWriter); + + // Then + String result = stringWriter.toString(); + assertEquals( + "nom;etapeacv;critere;description;niveau;tiers;categorie;consoElecMoyenne;localisation;valeur;unite;source\r\n" + + "Ecran 27 pouces;DISTRIBUTION;Changement climatique;description;2-Equipement;tiers;Monitor;0.01;France;0.02;kgCO2e;NegaOctet\r\n", + result + ); + } + + +} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactEquipementCsvExportServiceTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactEquipementCsvExportServiceTest.java index d33419aa6bb26209f5742ca3fff7308405217e63..dc7029687ef5f3f608ea6c95c43f459574bc3d34 100644 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactEquipementCsvExportServiceTest.java +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactEquipementCsvExportServiceTest.java @@ -7,9 +7,17 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.mte.numecoeval.referentiel.domain.model.ImpactEquipement; import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportImpactEquipementPortImpl; import org.mte.numecoeval.referentiel.factory.TestDataFactory; -import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactEquipementRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapperImpl; +import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactEquipementMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactEquipementMapperImpl; +import org.mte.numecoeval.referentiel.utils.Constants; +import org.springframework.test.util.ReflectionTestUtils; import java.io.IOException; import java.io.StringWriter; @@ -17,6 +25,7 @@ import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.Locale; +import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -29,7 +38,9 @@ class ImpactEquipementCsvExportServiceTest { ImpactEquipementCsvExportService exportService; @Mock - ImpactEquipementRepository repository; + FacteurCaracterisationRepository repository; + FacteurCaracterisationMapper facteurCaracterisationMapper = new FacteurCaracterisationMapperImpl(); + ImpactEquipementMapper equipementMapper = new ImpactEquipementMapperImpl(); @Mock CSVPrinter csvPrinter; @@ -37,30 +48,39 @@ class ImpactEquipementCsvExportServiceTest { @BeforeEach void setup() { MockitoAnnotations.openMocks(this); - } + ReflectionTestUtils.setField(exportService, "facteurCaracterisationMapper", facteurCaracterisationMapper); + ReflectionTestUtils.setField(exportService, "equipementMapper", equipementMapper); - @Test - void getHeadersShouldReturnSameHeadersAsImport() { - assertEquals(ImportImpactEquipementPortImpl.getHeaders(), exportService.getHeaders()); } - @Test - void getObjectsToWriteShouldReturnRepositoryFindAll() { - var entities = List.of( - TestDataFactory.ImpactEquipementFactory.entity( + private List<FacteurCaracterisationEntity> facteurCaracterisationEntities() { + return List.of( + TestDataFactory.FacteurCaracterisationFactory.entity("Laptop", TestDataFactory.EtapeFactory.entity("UTILISATION", ""), TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), - "Ref-Ecran", "RefTest", "Ecran", 0.1, 0.2 + "", Constants.EQUIPEMENT_NIVEAU, "", "Ecran", 0.1, "", 0.2, "", "NegaOctet" ), - TestDataFactory.ImpactEquipementFactory.entity( + TestDataFactory.FacteurCaracterisationFactory.entity("Ecran", TestDataFactory.EtapeFactory.entity("DISTRIBUTION", ""), TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), - "Ref-Ecran", "RefTest", "Ecran", 0.01, 0.002 + "", Constants.EQUIPEMENT_NIVEAU, "", "Ecran", 0.01, "", 0.002, "", "" ) ); - when(repository.findAll()).thenReturn(entities); + } + + @Test + void getHeadersShouldReturnSameHeadersAsImport() { + assertEquals(ImportImpactEquipementPortImpl.getHeaders(), exportService.getHeaders()); + } + + @Test + void getObjectsToWriteShouldReturnRepositoryFindAll() { + var entities = facteurCaracterisationEntities(); - assertEquals(entities, exportService.getObjectsToWrite()); + when(repository.findByNiveau(Constants.EQUIPEMENT_NIVEAU)).thenReturn(entities); + var actual = exportService.getObjectsToWrite(); + assertEquals(2, actual.size()); + assertEquals("DISTRIBUTION,UTILISATION", actual.stream().map(ImpactEquipement::getEtape).sorted().collect(Collectors.joining(","))); } @Test @@ -73,12 +93,14 @@ class ImpactEquipementCsvExportServiceTest { DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); df.setMaximumFractionDigits(340); - assertDoesNotThrow(() -> exportService.printRecord(csvPrinter, entity)); + assertDoesNotThrow(() -> exportService.printRecord(csvPrinter, equipementMapper.toDomain(entity))); Mockito.verify(csvPrinter, times(1)).printRecord(entity.getRefEquipement(), entity.getEtape(), entity.getCritere(), df.format(entity.getConsoElecMoyenne()), df.format(entity.getValeur()), entity.getSource(), entity.getType()); + + } @Test @@ -89,7 +111,7 @@ class ImpactEquipementCsvExportServiceTest { "Ref-Ecran", "RefTest", "Ecran", 0.1, 0.2 ); - assertDoesNotThrow(() -> exportService.logRecordError(entity, new Exception("Test"))); + assertDoesNotThrow(() -> exportService.logRecordError(equipementMapper.toDomain(entity), new Exception("Test"))); } @Test @@ -105,14 +127,9 @@ class ImpactEquipementCsvExportServiceTest { @Test void writeToCsvShouldReturnCSV() { // given - var entities = List.of( - TestDataFactory.ImpactEquipementFactory.entity( - TestDataFactory.EtapeFactory.entity("UTILISATION", ""), - TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), - "Ref-Ecran", "RefTest", "Ecran", 0.1, 0.2 - ) - ); - when(repository.findAll()).thenReturn(entities); + var entities = facteurCaracterisationEntities(); + + when(repository.findByNiveau(Constants.EQUIPEMENT_NIVEAU)).thenReturn(entities); StringWriter stringWriter = new StringWriter(); // when @@ -121,7 +138,9 @@ class ImpactEquipementCsvExportServiceTest { // Then String result = stringWriter.toString(); assertEquals( - "refEquipement;etapeacv;critere;consoElecMoyenne;valeur;source;type\r\nRef-Ecran;UTILISATION;Changement climatique;0.2;0.1;RefTest;Ecran\r\n", + "refEquipement;etapeacv;critere;consoElecMoyenne;valeur;source;type\r\n" + + "Laptop;UTILISATION;Changement climatique;0.1;0.2;NegaOctet;\r\n" + + "Ecran;DISTRIBUTION;Changement climatique;0.01;0.002;;\r\n", result ); } diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactMixElectriqueCsvExportServiceTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactMixElectriqueCsvExportServiceTest.java index 212d0da355dff7bd6e2170283ff1f577d1fdb344..f079cedeebc1378c6fdb59121a7c7b5d3967be4b 100644 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactMixElectriqueCsvExportServiceTest.java +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactMixElectriqueCsvExportServiceTest.java @@ -8,9 +8,18 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.mte.numecoeval.referentiel.domain.model.MixElectrique; import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportMixElectriquePortImpl; import org.mte.numecoeval.referentiel.factory.TestDataFactory; -import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.MixElectriqueRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.MixElectriqueEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapperImpl; +import org.mte.numecoeval.referentiel.infrastructure.mapper.MixElectriqueMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.MixElectriqueMapperImpl; +import org.mte.numecoeval.referentiel.utils.Constants; +import org.springframework.test.util.ReflectionTestUtils; import java.io.IOException; import java.io.StringWriter; @@ -18,6 +27,7 @@ import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.Locale; +import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -30,14 +40,39 @@ class ImpactMixElectriqueCsvExportServiceTest { MixElectriqueCsvExportService exportService; @Mock - MixElectriqueRepository repository; - + FacteurCaracterisationRepository repository; + FacteurCaracterisationMapper facteurCaracterisationMapper = new FacteurCaracterisationMapperImpl(); + MixElectriqueMapper mixElectriqueMapper = new MixElectriqueMapperImpl(); @Mock CSVPrinter csvPrinter; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); + ReflectionTestUtils.setField(exportService, "facteurCaracterisationMapper", facteurCaracterisationMapper); + ReflectionTestUtils.setField(exportService, "mixElectriqueMapper", mixElectriqueMapper); + } + + private List<FacteurCaracterisationEntity> facteurCaracterisationEntities() { + return List.of( + TestDataFactory.FacteurCaracterisationFactory.entity("Electricity mix FR", + TestDataFactory.EtapeFactory.entity("FABRICATION", ""), + TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), + "", Constants.MIXELEC_NIVEAU, "", Constants.MIXELEC_CATEGORIE, 0.0, "France", 0.2, "", "NegaOctet" + ), + TestDataFactory.FacteurCaracterisationFactory.entity("Electricity mix ES", + TestDataFactory.EtapeFactory.entity("FABRICATION", ""), + TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), + "", Constants.MIXELEC_NIVEAU, "", Constants.MIXELEC_CATEGORIE, 0.0, "Espagne", 0.1, "", "" + ) + ); + } + + private MixElectriqueEntity mixElectriqueEntity() { + return TestDataFactory.MixElectriqueFactory.entity( + TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), + "France", "FR", 0.2, "Test" + ); } @Test @@ -47,31 +82,21 @@ class ImpactMixElectriqueCsvExportServiceTest { @Test void getObjectsToWriteShouldReturnRepositoryFindAll() { - var entities = List.of( - TestDataFactory.MixElectriqueFactory.entity( - TestDataFactory.CritereFactory.entity("Changement climatique", "",""), - "France", "FR",0.2, "Test" - ), - TestDataFactory.MixElectriqueFactory.entity( - TestDataFactory.CritereFactory.entity("Acidification", "",""), - "Angleterre", "EN",0.1, "Test" - ) - ); - when(repository.findAll()).thenReturn(entities); + var entities = facteurCaracterisationEntities(); - assertEquals(entities, exportService.getObjectsToWrite()); + when(repository.findByNiveauAndCategorie(Constants.MIXELEC_NIVEAU, Constants.MIXELEC_CATEGORIE)).thenReturn(entities); + var actual = exportService.getObjectsToWrite(); + assertEquals(2, actual.size()); + assertEquals("Espagne,France", actual.stream().map(MixElectrique::getPays).sorted().collect(Collectors.joining(","))); } @Test void printRecordShouldUseEntityAttributes() throws IOException { - var entity = TestDataFactory.MixElectriqueFactory.entity( - TestDataFactory.CritereFactory.entity("Changement climatique", "",""), - "France", "FR",0.2, "Test" - ); + var entity = mixElectriqueEntity(); DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); df.setMaximumFractionDigits(340); - assertDoesNotThrow(() -> exportService.printRecord(csvPrinter, entity)); + assertDoesNotThrow(() -> exportService.printRecord(csvPrinter, mixElectriqueMapper.toDomain(entity))); Mockito.verify(csvPrinter, times(1)).printRecord( entity.getPays(), @@ -82,35 +107,27 @@ class ImpactMixElectriqueCsvExportServiceTest { } @Test - void logRecordErrorShouldLogSpecificErrorForRecord(){ - var entity = TestDataFactory.MixElectriqueFactory.entity( - TestDataFactory.CritereFactory.entity("Changement climatique", "",""), - "France", "FR",0.2, "Test" - ); + void logRecordErrorShouldLogSpecificErrorForRecord() { + var entity = mixElectriqueEntity(); - assertDoesNotThrow(() -> exportService.logRecordError(entity, new Exception("Test"))); + assertDoesNotThrow(() -> exportService.logRecordError(mixElectriqueMapper.toDomain(entity), new Exception("Test"))); } @Test - void logRecordErrorShouldLogGenericErrorForRecord(){ + void logRecordErrorShouldLogGenericErrorForRecord() { assertDoesNotThrow(() -> exportService.logRecordError(null, new Exception("Test"))); } @Test - void logRecordErrorShouldLogGenericErrorForFile(){ + void logRecordErrorShouldLogGenericErrorForFile() { assertDoesNotThrow(() -> exportService.logWriterError(new Exception("Test"))); } @Test void writeToCsvShouldReturnCSV() { // given - var entities = List.of( - TestDataFactory.MixElectriqueFactory.entity( - TestDataFactory.CritereFactory.entity("Changement climatique", "",""), - "France", "FR",0.2, "Test" - ) - ); - when(repository.findAll()).thenReturn(entities); + var entities = facteurCaracterisationEntities(); + when(repository.findByNiveauAndCategorie(Constants.MIXELEC_NIVEAU, Constants.MIXELEC_CATEGORIE)).thenReturn(entities); StringWriter stringWriter = new StringWriter(); // when @@ -119,7 +136,9 @@ class ImpactMixElectriqueCsvExportServiceTest { // Then String result = stringWriter.toString(); assertEquals( - "pays;raccourcisAnglais;critere;valeur;source\r\nFrance;FR;Changement climatique;0.2;Test\r\n", + "pays;raccourcisAnglais;critere;valeur;source\r\n" + + "France;;Changement climatique;0.2;NegaOctet\r\n" + + "Espagne;;Changement climatique;0.1;\r\n", result ); } diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactReseauCsvExportServiceTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactReseauCsvExportServiceTest.java index 3eeee78506deeadd1d44ddebfa08218cb08d4cdd..c398b1ec8ae31c2c3283cb413c5391cd5ba430dc 100644 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactReseauCsvExportServiceTest.java +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/adapter/export/ImpactReseauCsvExportServiceTest.java @@ -7,9 +7,17 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.mte.numecoeval.referentiel.domain.model.ImpactReseau; import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportImpactReseauPortImpl; import org.mte.numecoeval.referentiel.factory.TestDataFactory; -import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactReseauRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapperImpl; +import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactReseauMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactReseauMapperImpl; +import org.mte.numecoeval.referentiel.utils.Constants; +import org.springframework.test.util.ReflectionTestUtils; import java.io.IOException; import java.io.StringWriter; @@ -17,6 +25,7 @@ import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.List; import java.util.Locale; +import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -29,38 +38,48 @@ class ImpactReseauCsvExportServiceTest { ImpactReseauCsvExportService exportService; @Mock - ImpactReseauRepository repository; - + FacteurCaracterisationRepository repository; + FacteurCaracterisationMapper facteurCaracterisationMapper = new FacteurCaracterisationMapperImpl(); + ImpactReseauMapper reseauMapper = new ImpactReseauMapperImpl(); @Mock CSVPrinter csvPrinter; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); + ReflectionTestUtils.setField(exportService, "facteurCaracterisationMapper", facteurCaracterisationMapper); + ReflectionTestUtils.setField(exportService, "reseauMapper", reseauMapper); } - @Test - void getHeadersShouldReturnSameHeadersAsImport() { - assertEquals(ImportImpactReseauPortImpl.getHeaders(), exportService.getHeaders()); - } - - @Test - void getObjectsToWriteShouldReturnRepositoryFindAll() { - var entities = List.of( - TestDataFactory.ImpactReseauFactory.entity( + private List<FacteurCaracterisationEntity> facteurCaracterisationEntities() { + return List.of( + TestDataFactory.FacteurCaracterisationFactory.entity("Fixed-line network", TestDataFactory.EtapeFactory.entity("UTILISATION", ""), TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), - "Ref-Ecran", "RefTest", 0.1, 0.2 + "", Constants.RESEAU_NIVEAU, Constants.RESEAU_TIERS, "Ecran", 0.1, "", 0.2, "", "NegaOctet" ), - TestDataFactory.ImpactReseauFactory.entity( + TestDataFactory.FacteurCaracterisationFactory.entity("Mobile network", TestDataFactory.EtapeFactory.entity("DISTRIBUTION", ""), TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), - "Ref-Ecran", "RefTest", 0.01, 0.002 + "", Constants.RESEAU_NIVEAU, Constants.RESEAU_TIERS, "Ecran", 0.01, "", 0.002, "", "" ) ); - when(repository.findAll()).thenReturn(entities); + } + - assertEquals(entities, exportService.getObjectsToWrite()); + @Test + void getHeadersShouldReturnSameHeadersAsImport() { + assertEquals(ImportImpactReseauPortImpl.getHeaders(), exportService.getHeaders()); + } + + @Test + void getObjectsToWriteShouldReturnRepositoryFindAll() { + var entities = facteurCaracterisationEntities(); + when(repository.findByNiveauAndTiers(Constants.RESEAU_NIVEAU, Constants.RESEAU_TIERS)).thenReturn(entities); + + var actual = exportService.getObjectsToWrite(); + assertEquals(2, actual.size()); + assertEquals("DISTRIBUTION,UTILISATION", actual.stream().map(ImpactReseau::getEtape).sorted().collect(Collectors.joining(","))); } @Test @@ -70,10 +89,11 @@ class ImpactReseauCsvExportServiceTest { TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), "Ref-Ecran", "RefTest", 0.1, 0.2 ); + DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); df.setMaximumFractionDigits(340); - assertDoesNotThrow(() -> exportService.printRecord(csvPrinter, entity)); + assertDoesNotThrow(() -> exportService.printRecord(csvPrinter, reseauMapper.toDomain(entity))); Mockito.verify(csvPrinter, times(1)).printRecord(entity.getRefReseau(), entity.getEtape(), entity.getCritere(), @@ -89,7 +109,7 @@ class ImpactReseauCsvExportServiceTest { "Ref-Ecran", "RefTest", 0.1, 0.2 ); - assertDoesNotThrow(() -> exportService.logRecordError(entity, new Exception("Test"))); + assertDoesNotThrow(() -> exportService.logRecordError(reseauMapper.toDomain(entity), new Exception("Test"))); } @Test @@ -105,14 +125,8 @@ class ImpactReseauCsvExportServiceTest { @Test void writeToCsvShouldReturnCSV() { // given - var entities = List.of( - TestDataFactory.ImpactReseauFactory.entity( - TestDataFactory.EtapeFactory.entity("UTILISATION", ""), - TestDataFactory.CritereFactory.entity("Changement climatique", "", ""), - "Ref-Ecran", "RefTest", 0.1, 0.2 - ) - ); - when(repository.findAll()).thenReturn(entities); + var entities = facteurCaracterisationEntities(); + when(repository.findByNiveauAndTiers(Constants.RESEAU_NIVEAU, Constants.RESEAU_TIERS)).thenReturn(entities); StringWriter stringWriter = new StringWriter(); // when @@ -121,8 +135,12 @@ class ImpactReseauCsvExportServiceTest { // Then String result = stringWriter.toString(); assertEquals( - "refReseau;etapeACV;critere;valeur;consoElecMoyenne;source\r\nRef-Ecran;UTILISATION;Changement climatique;0.1;0.2;RefTest\r\n", + "refReseau;etapeACV;critere;valeur;consoElecMoyenne;source\r\n" + + "Fixed-line network;UTILISATION;Changement climatique;0.2;0.1;NegaOctet\r\n" + + "Mobile network;DISTRIBUTION;Changement climatique;0.002;0.01;\r\n", result ); } + + } diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/FacteurCaracterisationJpaAdaptaterTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/FacteurCaracterisationJpaAdaptaterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..2c2bd92eec6935e59875645913280b91f64c157d --- /dev/null +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/FacteurCaracterisationJpaAdaptaterTest.java @@ -0,0 +1,4 @@ +package org.mte.numecoeval.referentiel.infrastructure.jpa; + +public class FacteurCaracterisationJpaAdaptaterTest { +} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/ImpactEquipementJpaAdapterTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/ImpactEquipementJpaAdapterTest.java index d5485aa72111439e385475b60e7f8d24846011e3..97b140c9f6504b78b337879956450a560ad00233 100644 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/ImpactEquipementJpaAdapterTest.java +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/ImpactEquipementJpaAdapterTest.java @@ -1,5 +1,6 @@ package org.mte.numecoeval.referentiel.infrastructure.jpa; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -12,16 +13,20 @@ import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; import org.mte.numecoeval.referentiel.domain.model.ImpactEquipement; import org.mte.numecoeval.referentiel.domain.model.id.ImpactEquipementId; import org.mte.numecoeval.referentiel.infrastructure.jpa.adapter.ImpactEquipementJpaAdapter; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactEquipementEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactEquipementRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapperImpl; import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactEquipementMapper; import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactEquipementMapperImpl; +import org.mte.numecoeval.referentiel.utils.Constants; import org.springframework.test.util.ReflectionTestUtils; import java.util.Collections; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; class ImpactEquipementJpaAdapterTest { @@ -29,131 +34,130 @@ class ImpactEquipementJpaAdapterTest { private ImpactEquipementJpaAdapter jpaAdapter; @Mock - ImpactEquipementRepository repository; + FacteurCaracterisationRepository repository; + FacteurCaracterisationMapper facteurCaracterisationMapper = new FacteurCaracterisationMapperImpl(); ImpactEquipementMapper mapper = new ImpactEquipementMapperImpl(); + private static final String CRITERE = "Changement climatique"; + private static final String ETAPE = "UTILISATION"; + private static final String NOM = "Ecran 27 pouces"; + + @BeforeEach void setup() { MockitoAnnotations.openMocks(this); ReflectionTestUtils.setField(jpaAdapter, "mapper", mapper); + ReflectionTestUtils.setField(jpaAdapter, "facteurCaracterisationMapper", facteurCaracterisationMapper); + } - @Test - void get_shouldReturnDomain() { - var expectedEntity = new ImpactEquipementEntity() - .setEtape("UTILISATION") - .setCritere("Changement climatique") - .setRefEquipement("Ecran 27 pouces") - .setType("Monitor") + private FacteurCaracterisationEntity facteurCaracterisationEntity() { + return new FacteurCaracterisationEntity() + .setNom(NOM) + .setEtape(ETAPE) + .setCritere(CRITERE) + .setNiveau(Constants.EQUIPEMENT_NIVEAU) .setSource("Test") .setConsoElecMoyenne(0.020) .setValeur(0.120); + } + + private ImpactEquipement impactEquipement() { + return new ImpactEquipement() + .setRefEquipement(NOM) + .setEtape(ETAPE) + .setCritere(CRITERE) + .setSource("Test") + .setConsoElecMoyenne(0.020) + .setValeur(0.120); + } + + + @Test + void get_shouldReturnDomain() { + var expectedEntity = facteurCaracterisationEntity(); var wantedId = new ImpactEquipementId() - .setEtape("UTILISATION") - .setCritere("Changement climatique") - .setRefEquipement(expectedEntity.getRefEquipement()); - var wantedEntityId = mapper.toEntityId(wantedId); - Mockito.when(repository.findById(wantedEntityId)).thenReturn(Optional.of(expectedEntity)); - - var expectedDomain = assertDoesNotThrow( () -> jpaAdapter.get(wantedId) ); - - assertNotNull(expectedDomain.getEtape()); - assertEquals(expectedEntity.getEtape(), expectedDomain.getEtape()); - assertNotNull(expectedDomain.getCritere()); - assertEquals(expectedEntity.getCritere(), expectedDomain.getCritere()); - assertEquals(expectedEntity.getRefEquipement(), expectedDomain.getRefEquipement()); - assertEquals(expectedEntity.getType(), expectedDomain.getType()); - assertEquals(expectedEntity.getConsoElecMoyenne(), expectedDomain.getConsoElecMoyenne()); - assertEquals(expectedEntity.getValeur(), expectedDomain.getValeur()); - assertEquals(expectedEntity.getSource(), expectedDomain.getSource()); + .setRefEquipement(NOM) + .setEtape(ETAPE) + .setCritere(CRITERE); + + Mockito.when(repository.findByNomAndEtapeAndCritere(wantedId.getRefEquipement(), wantedId.getEtape(), wantedId.getCritere())).thenReturn(Optional.of(expectedEntity)); + + var actualDomain = assertDoesNotThrow(() -> jpaAdapter.get(wantedId)); + + assertNotNull(actualDomain.getEtape()); + assertEquals(expectedEntity.getEtape(), actualDomain.getEtape()); + assertNotNull(actualDomain.getCritere()); + assertEquals(expectedEntity.getCritere(), actualDomain.getCritere()); + assertEquals(expectedEntity.getNom(), actualDomain.getRefEquipement()); + assertEquals(expectedEntity.getConsoElecMoyenne(), actualDomain.getConsoElecMoyenne()); + assertEquals(expectedEntity.getValeur(), actualDomain.getValeur()); + assertEquals(expectedEntity.getSource(), actualDomain.getSource()); } + @Test void get_shouldThrowException() { var wantedId = new ImpactEquipementId() + .setRefEquipement("NonExistant") .setEtape("Absent") - .setCritere("Inexistant") - .setRefEquipement("NonExistant"); - var wantedEntityId = mapper.toEntityId(wantedId); - Mockito.when(repository.findById(wantedEntityId)).thenReturn(Optional.empty()); - - ReferentielException expectedException = assertThrows(ReferentielException.class, () -> jpaAdapter.get(wantedId) ); + .setCritere("Inexistant"); - assertEquals("Impact Equipement non trouvé",expectedException.getMessage()); + Mockito.when(repository.findByNomAndEtapeAndCritere(wantedId.getRefEquipement(), wantedId.getEtape(), wantedId.getCritere())).thenReturn(Optional.empty()); + ReferentielException expectedException = assertThrows(ReferentielException.class, () -> jpaAdapter.get(wantedId)); + assertEquals("Impact équipement non trouvé pour l'id ImpactEquipementId(refEquipement=NonExistant, etape=Absent, critere=Inexistant)", expectedException.getMessage()); } + @Test void get_whenNull_shouldThrowException() { - ReferentielException expectedException = assertThrows(ReferentielException.class, () -> jpaAdapter.get(null) ); - - assertEquals("Impact Equipement non trouvé",expectedException.getMessage()); + ReferentielException expectedException = assertThrows(ReferentielException.class, () -> jpaAdapter.get(null)); + assertEquals("Impact équipement non trouvé pour l'id null", expectedException.getMessage()); } @Test void purge_shouldCallDeleteAll() { jpaAdapter.purge(); - - Mockito.verify(repository, Mockito.times(1)).deleteAll(); + Mockito.verify(repository, Mockito.times(1)).deleteByNiveau(Constants.EQUIPEMENT_NIVEAU); } @Test void getAll_shouldCallfindAll() { jpaAdapter.getAll(); - - Mockito.verify(repository, Mockito.times(1)).findAll(); + Mockito.verify(repository, Mockito.times(1)).findByNiveau(any()); } @Test void saveAll_shouldCallsaveAll() { - var domainToSave = new ImpactEquipement() - .setEtape("UTILISATION") - .setCritere("Changement climatique") - .setRefEquipement("Ecran 27 pouces") - .setType("Monitor") - .setSource("Test") - .setConsoElecMoyenne(0.020) - .setValeur(0.120); - var entityToSave = mapper.toEntity(domainToSave); + var domainToSave = impactEquipement(); + var entitiesToSave = facteurCaracterisationMapper.toEntities(mapper.toFacteurCaracterisations(Collections.singletonList(domainToSave))); assertDoesNotThrow(() -> jpaAdapter.saveAll(Collections.singletonList(domainToSave))); - - Mockito.verify(repository, Mockito.times(1)).saveAll(Collections.singletonList(entityToSave)); + Mockito.verify(repository).saveAll(entitiesToSave); + Mockito.verify(repository, Mockito.times(1)).saveAll(entitiesToSave); } @Test void save_shouldSaveAndReturnDomain() { - var wantedDomain = new ImpactEquipement() - .setEtape("UTILISATION") - .setCritere("Changement climatique") - .setRefEquipement("Ecran 27 pouces") - .setType("Monitor") - .setSource("Test") - .setConsoElecMoyenne(0.020) - .setValeur(0.120); - var expectedEntity = mapper.toEntities(Collections.singletonList(wantedDomain)).get(0); + var domain = impactEquipement(); + var actualEntity = facteurCaracterisationMapper.toEntity(mapper.toFacteurCaracterisation(domain)); + var expectedEntity = facteurCaracterisationEntity(); - Mockito.when(repository.save(expectedEntity)).thenReturn(expectedEntity); + assertEquals(expectedEntity.getNom(), actualEntity.getNom()); + assertEquals(expectedEntity.getNiveau(), actualEntity.getNiveau()); - var expectedDomain = assertDoesNotThrow( () -> jpaAdapter.save(wantedDomain) ); + Mockito.when(repository.save(actualEntity)).thenReturn(actualEntity); - assertNotNull(expectedDomain.getEtape()); - assertEquals(expectedEntity.getEtape(), expectedDomain.getEtape()); - assertNotNull(expectedDomain.getCritere()); - assertEquals(expectedEntity.getCritere(), expectedDomain.getCritere()); - assertEquals(expectedEntity.getRefEquipement(), expectedDomain.getRefEquipement()); - assertEquals(expectedEntity.getType(), expectedDomain.getType()); - assertEquals(expectedEntity.getConsoElecMoyenne(), expectedDomain.getConsoElecMoyenne()); - assertEquals(expectedEntity.getValeur(), expectedDomain.getValeur()); - assertEquals(expectedEntity.getSource(), expectedDomain.getSource()); + assertDoesNotThrow(() -> jpaAdapter.save(domain)); + Mockito.verify(repository).save(actualEntity); } @ParameterizedTest @NullSource void save_shouldSaveAndReturnNull(ImpactEquipement nullValue) { - var expectedDomain = assertDoesNotThrow( () -> jpaAdapter.save(nullValue) ); - - assertNull(expectedDomain); + var expectedDomain = assertDoesNotThrow(() -> jpaAdapter.save(nullValue)); + Assertions.assertNull(expectedDomain); } } diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/ImpactReseauJpaAdapterTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/ImpactReseauJpaAdapterTest.java index 258f988fa6bd331fd6f263044f03a421398231b1..3989ea4d167eee296eaf59ca87000040f0afb181 100644 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/ImpactReseauJpaAdapterTest.java +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/ImpactReseauJpaAdapterTest.java @@ -1,197 +1,164 @@ package org.mte.numecoeval.referentiel.infrastructure.jpa; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.NullSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; import org.mte.numecoeval.referentiel.domain.model.ImpactReseau; import org.mte.numecoeval.referentiel.domain.model.id.ImpactReseauId; import org.mte.numecoeval.referentiel.infrastructure.jpa.adapter.ImpactReseauJpaAdapter; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.ImpactReseauEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.id.ImpactReseauIdEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.ImpactReseauRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapperImpl; import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactReseauMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.mte.numecoeval.referentiel.infrastructure.mapper.ImpactReseauMapperImpl; +import org.mte.numecoeval.referentiel.utils.Constants; +import org.springframework.test.util.ReflectionTestUtils; -import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.any; -@ContextConfiguration(classes = {ImpactReseauJpaAdapter.class}) -@ExtendWith(SpringExtension.class) class ImpactReseauJpaAdapterTest { - @Autowired - private ImpactReseauJpaAdapter impactReseauJpaAdapter; - @MockBean - private ImpactReseauMapper impactReseauMapper; + @InjectMocks + private ImpactReseauJpaAdapter jpaAdapter; + + @Mock + FacteurCaracterisationRepository repository; + FacteurCaracterisationMapper facteurCaracterisationMapper = new FacteurCaracterisationMapperImpl(); + ImpactReseauMapper mapper = new ImpactReseauMapperImpl(); + + private static final String CRITERE = "Changement climatique"; + private static final String ETAPE = "UTILISATION"; + private static final String NOM = "Mobile network"; + + + @BeforeEach + void setup() { + MockitoAnnotations.openMocks(this); + ReflectionTestUtils.setField(jpaAdapter, "reseauMapper", mapper); + ReflectionTestUtils.setField(jpaAdapter, "facteurCaracterisationMapper", facteurCaracterisationMapper); + } + + private FacteurCaracterisationEntity facteurCaracterisationEntity() { + return new FacteurCaracterisationEntity() + .setNom(NOM) + .setEtape(ETAPE) + .setCritere(CRITERE) + .setNiveau(Constants.RESEAU_NIVEAU) + .setTiers(Constants.RESEAU_TIERS) + .setSource("Test") + .setConsoElecMoyenne(0.020) + .setValeur(0.120); + } + + private ImpactReseau impactReseau() { + return new ImpactReseau() + .setRefReseau(NOM) + .setEtape(ETAPE) + .setCritere(CRITERE) + .setSource("Test") + .setConsoElecMoyenne(0.020) + .setValeur(0.120); + } + + @Test + void get_shouldReturnDomain() { + var expectedEntity = facteurCaracterisationEntity(); + + var wantedId = new ImpactReseauId() + .setRefReseau(NOM) + .setEtape(ETAPE) + .setCritere(CRITERE); + + Mockito.when(repository.findByNomAndEtapeAndCritere(wantedId.getRefReseau(), wantedId.getEtape(), wantedId.getCritere())).thenReturn(Optional.of(expectedEntity)); + + var actualDomain = assertDoesNotThrow(() -> jpaAdapter.get(wantedId)); + + assertNotNull(actualDomain.getEtape()); + assertEquals(expectedEntity.getEtape(), actualDomain.getEtape()); + assertNotNull(actualDomain.getCritere()); + assertEquals(expectedEntity.getCritere(), actualDomain.getCritere()); + assertEquals(expectedEntity.getNom(), actualDomain.getRefReseau()); + assertEquals(expectedEntity.getConsoElecMoyenne(), actualDomain.getConsoElecMoyenne()); + assertEquals(expectedEntity.getValeur(), actualDomain.getValeur()); + assertEquals(expectedEntity.getSource(), actualDomain.getSource()); + } - @MockBean - private ImpactReseauRepository impactReseauRepository; - /** - * Method under test: {@link ImpactReseauJpaAdapter#save(ImpactReseau)} - */ @Test - void testSave() throws ReferentielException { - String expectedCritere = "Nom Critere"; - String expectedEtape = "Code"; - ImpactReseau impactReseau = new ImpactReseau(); - impactReseau.setConsoElecMoyenne(10.0d); - impactReseau.setCritere(expectedCritere); - impactReseau.setEtape(expectedEtape); - impactReseau.setRefReseau("Ref Reseau"); - impactReseau.setSource("Source"); - impactReseau.setValeur(10.0d); - - ImpactReseauEntity impactReseauEntity = new ImpactReseauEntity(); - impactReseauEntity.setConsoElecMoyenne(10.0d); - impactReseauEntity.setCritere(expectedCritere); - - impactReseauEntity.setEtape(expectedEtape); - impactReseauEntity.setRefReseau("Ref Reseau"); - impactReseauEntity.setSource("Source"); - impactReseauEntity.setValeur(10.0d); - when(impactReseauMapper.toDomain((ImpactReseauEntity) any())).thenReturn(impactReseau); - when(impactReseauMapper.toEntity((ImpactReseau) any())).thenReturn(impactReseauEntity); - - ImpactReseauEntity impactReseauEntity1 = new ImpactReseauEntity(); - impactReseauEntity1.setConsoElecMoyenne(10.0d); - impactReseauEntity1.setCritere(expectedCritere); - impactReseauEntity1.setEtape(expectedEtape); - impactReseauEntity1.setRefReseau("Ref Reseau"); - impactReseauEntity1.setSource("Source"); - impactReseauEntity1.setValeur(10.0d); - when(impactReseauRepository.save((ImpactReseauEntity) any())).thenReturn(impactReseauEntity1); - - ImpactReseau impactReseau1 = new ImpactReseau(); - impactReseau1.setConsoElecMoyenne(10.0d); - impactReseau1.setCritere(expectedCritere); - impactReseau1.setEtape(expectedEtape); - impactReseau1.setRefReseau("Ref Reseau"); - impactReseau1.setSource("Source"); - impactReseau1.setValeur(10.0d); - assertSame(impactReseau, impactReseauJpaAdapter.save(impactReseau1)); - verify(impactReseauMapper).toDomain((ImpactReseauEntity) any()); - verify(impactReseauMapper).toEntity((ImpactReseau) any()); - verify(impactReseauRepository).save((ImpactReseauEntity) any()); + void get_shouldThrowException() { + var wantedId = new ImpactReseauId() + .setRefReseau("NonExistant") + .setEtape("Absent") + .setCritere("Inexistant"); + + Mockito.when(repository.findByNomAndEtapeAndCritere(wantedId.getRefReseau(), wantedId.getEtape(), wantedId.getCritere())).thenReturn(Optional.empty()); + ReferentielException expectedException = assertThrows(ReferentielException.class, () -> jpaAdapter.get(wantedId)); + assertEquals("Référence réseau non trouvée pour l'id ImpactReseauId(refReseau=NonExistant, etape=Absent, critere=Inexistant)", expectedException.getMessage()); } - /** - * Method under test: {@link ImpactReseauJpaAdapter#saveAll(Collection)} - */ + @Test - void testSaveAll() throws ReferentielException { - when(impactReseauMapper.toEntity((Collection<ImpactReseau>) any())).thenReturn(new ArrayList<>()); - when(impactReseauRepository.saveAll((Iterable<ImpactReseauEntity>) any())).thenReturn(new ArrayList<>()); - impactReseauJpaAdapter.saveAll(new ArrayList<>()); - verify(impactReseauMapper).toEntity((Collection<ImpactReseau>) any()); - verify(impactReseauRepository).saveAll((Iterable<ImpactReseauEntity>) any()); + void get_whenNull_shouldThrowException() { + ReferentielException expectedException = assertThrows(ReferentielException.class, () -> jpaAdapter.get(null)); + assertEquals("Référence réseau non trouvée pour l'id null", expectedException.getMessage()); } - /** - * Method under test: {@link ImpactReseauJpaAdapter#get(ImpactReseauId)} - */ @Test - void testGet() throws ReferentielException { - String expectedCritere = "Nom Critere"; - String expectedEtape = "Code"; - ImpactReseauIdEntity impactReseauIdEntity = new ImpactReseauIdEntity(); - impactReseauIdEntity.setCritere(expectedCritere); - impactReseauIdEntity.setEtape(expectedEtape); - impactReseauIdEntity.setRefReseau("Ref Reseau"); - - ImpactReseau impactReseau = new ImpactReseau(); - impactReseau.setConsoElecMoyenne(10.0d); - impactReseau.setCritere(expectedCritere); - impactReseau.setEtape(expectedEtape); - impactReseau.setRefReseau("Ref Reseau"); - impactReseau.setSource("Source"); - impactReseau.setValeur(10.0d); - when(impactReseauMapper.toDomain((ImpactReseauEntity) any())).thenReturn(impactReseau); - when(impactReseauMapper.toEntityId((ImpactReseauId) any())).thenReturn(impactReseauIdEntity); - - ImpactReseauEntity impactReseauEntity = new ImpactReseauEntity(); - impactReseauEntity.setConsoElecMoyenne(10.0d); - impactReseauEntity.setCritere(expectedCritere); - impactReseauEntity.setEtape(expectedEtape); - impactReseauEntity.setRefReseau("Ref Reseau"); - impactReseauEntity.setSource("Source"); - impactReseauEntity.setValeur(10.0d); - Optional<ImpactReseauEntity> ofResult = Optional.of(impactReseauEntity); - when(impactReseauRepository.findById((ImpactReseauIdEntity) any())).thenReturn(ofResult); - - ImpactReseauId impactReseauId = new ImpactReseauId(); - impactReseauId.setCritere(expectedCritere); - impactReseauId.setEtape(expectedEtape); - impactReseauId.setRefReseau("Ref Reseau"); - assertSame(impactReseau, impactReseauJpaAdapter.get(impactReseauId)); - verify(impactReseauMapper).toDomain((ImpactReseauEntity) any()); - verify(impactReseauMapper).toEntityId(any()); - verify(impactReseauRepository).findById(any()); + void purge_shouldCallDeleteAll() { + jpaAdapter.purge(); + Mockito.verify(repository, Mockito.times(1)).deleteByNiveauAndTiers(Constants.RESEAU_NIVEAU, Constants.RESEAU_TIERS); } - /** - * Method under test: {@link ImpactReseauJpaAdapter#get(ImpactReseauId)} - */ @Test - void testGet2() throws ReferentielException { - String expectedCritere = "Nom Critere"; - String expectedEtape = "Code"; - ImpactReseauIdEntity impactReseauIdEntity = new ImpactReseauIdEntity(); - impactReseauIdEntity.setCritere(expectedCritere); - impactReseauIdEntity.setEtape(expectedEtape); - impactReseauIdEntity.setRefReseau("Ref Reseau"); - - ImpactReseau impactReseau = new ImpactReseau(); - impactReseau.setConsoElecMoyenne(10.0d); - impactReseau.setCritere(expectedCritere); - impactReseau.setEtape(expectedEtape); - impactReseau.setRefReseau("Ref Reseau"); - impactReseau.setSource("Source"); - impactReseau.setValeur(10.0d); - when(impactReseauMapper.toDomain((ImpactReseauEntity) any())).thenReturn(impactReseau); - when(impactReseauMapper.toEntityId(any())).thenReturn(impactReseauIdEntity); - when(impactReseauRepository.findById(any())).thenReturn(Optional.empty()); - - ImpactReseauId impactReseauId = new ImpactReseauId(); - impactReseauId.setCritere(expectedCritere); - impactReseauId.setEtape(expectedEtape); - impactReseauId.setRefReseau("Ref Reseau"); - assertThrows(ReferentielException.class, () -> impactReseauJpaAdapter.get(impactReseauId)); - verify(impactReseauMapper).toEntityId((ImpactReseauId) any()); - verify(impactReseauRepository).findById((ImpactReseauIdEntity) any()); + void getAll_shouldCallfindAll() { + jpaAdapter.getAll(); + Mockito.verify(repository, Mockito.times(1)).findByNiveauAndTiers(any(), any()); } - /** - * Method under test: {@link ImpactReseauJpaAdapter#purge()} - */ @Test - void testPurge() { - doNothing().when(impactReseauRepository).deleteAll(); - impactReseauJpaAdapter.purge(); - verify(impactReseauRepository).deleteAll(); + void saveAll_shouldCallsaveAll() { + var domainToSave = impactReseau(); + var entitiesToSave = facteurCaracterisationMapper.toEntities(mapper.toFacteurCaracterisations(Collections.singletonList(domainToSave))); + + assertDoesNotThrow(() -> jpaAdapter.saveAll(Collections.singletonList(domainToSave))); + Mockito.verify(repository).saveAll(entitiesToSave); + Mockito.verify(repository, Mockito.times(1)).saveAll(entitiesToSave); } - /** - * Methods under test: - * - * <ul> - * <li>default or parameterless constructor of {@link ImpactReseauJpaAdapter} - * <li>{@link ImpactReseauJpaAdapter#getAll()} - * </ul> - */ @Test - void testConstructor() { - Mockito.when(impactReseauRepository.findAll()).thenReturn(Collections.emptyList()); - assertTrue((impactReseauJpaAdapter.getAll().isEmpty())); + void save_shouldSaveAndReturnDomain() { + var domain = impactReseau(); + var actualEntity = facteurCaracterisationMapper.toEntity(mapper.toFacteurCaracterisation(domain)); + var expectedEntity = facteurCaracterisationEntity(); + + assertEquals(expectedEntity.getNom(), actualEntity.getNom()); + assertEquals(expectedEntity.getNiveau(), actualEntity.getNiveau()); + assertEquals(expectedEntity.getTiers(), actualEntity.getTiers()); + + Mockito.when(repository.save(actualEntity)).thenReturn(actualEntity); + + assertDoesNotThrow(() -> jpaAdapter.save(domain)); + Mockito.verify(repository).save(actualEntity); + } + + @ParameterizedTest + @NullSource + void save_shouldSaveAndReturnNull(ImpactReseau nullValue) { + var expectedDomain = assertDoesNotThrow(() -> jpaAdapter.save(nullValue)); + Assertions.assertNull(expectedDomain); } -} + +} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/MixElectriqueJpaAdapterTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/MixElectriqueJpaAdapterTest.java index 6de658438f8a7d6d26866b5cace366464cd26f31..f06a4f596029bee7ae713c317a51124b5ecd20ad 100644 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/MixElectriqueJpaAdapterTest.java +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/jpa/MixElectriqueJpaAdapterTest.java @@ -13,57 +13,75 @@ import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; import org.mte.numecoeval.referentiel.domain.model.MixElectrique; import org.mte.numecoeval.referentiel.domain.model.id.MixElectriqueId; import org.mte.numecoeval.referentiel.infrastructure.jpa.adapter.MixElectriqueJpaAdapter; -import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.MixElectriqueEntity; -import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.MixElectriqueRepository; +import org.mte.numecoeval.referentiel.infrastructure.jpa.entity.FacteurCaracterisationEntity; +import org.mte.numecoeval.referentiel.infrastructure.jpa.repository.FacteurCaracterisationRepository; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapperImpl; import org.mte.numecoeval.referentiel.infrastructure.mapper.MixElectriqueMapper; import org.mte.numecoeval.referentiel.infrastructure.mapper.MixElectriqueMapperImpl; +import org.mte.numecoeval.referentiel.utils.Constants; import org.springframework.test.util.ReflectionTestUtils; import java.util.Collections; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; class MixElectriqueJpaAdapterTest { @InjectMocks private MixElectriqueJpaAdapter jpaAdapter; - @Mock - MixElectriqueRepository repository; - + FacteurCaracterisationRepository repository; + FacteurCaracterisationMapper facteurCaracterisationMapper = new FacteurCaracterisationMapperImpl(); MixElectriqueMapper mapper = new MixElectriqueMapperImpl(); + private static final String PAYS = "France"; + private static final String CRITERE = "Changement climatique"; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); ReflectionTestUtils.setField(jpaAdapter, "mixElectriqueMapper", mapper); + ReflectionTestUtils.setField(jpaAdapter, "facteurCaracterisationMapper", facteurCaracterisationMapper); } - @Test - void get_shouldReturnDomain() { - var expectedCritere = "Changement climatique"; - var expectedEntity = new MixElectriqueEntity() - .setCritere(expectedCritere) - .setPays("France") + private FacteurCaracterisationEntity facteurCaracterisationEntity() { + return new FacteurCaracterisationEntity() + .setNom(Constants.MIXELEC_NOM_LOW_VOLTAGE + "FR") + .setNiveau(Constants.MIXELEC_NIVEAU) + .setEtape(Constants.MIXELEC_ETAPEACV) + .setCategorie(Constants.MIXELEC_CATEGORIE) + .setCritere(CRITERE) + .setLocalisation(PAYS) + .setSource("Test") + .setValeur(0.120); + } + + private MixElectrique mixelectrique() { + return new MixElectrique() + .setCritere(CRITERE) + .setPays(PAYS) .setSource("Test") .setRaccourcisAnglais("FR") .setValeur(0.120); + } + @Test + void get_shouldReturnDomain() { + var expectedEntity = facteurCaracterisationEntity(); var wantedId = new MixElectriqueId() - .setPays(expectedEntity.getPays()) - .setCritere(expectedCritere); - var wantedEntityId = mapper.toEntityId(wantedId); - Mockito.when(repository.findById(wantedEntityId)).thenReturn(Optional.of(expectedEntity)); - - var expectedDomain = assertDoesNotThrow(() -> jpaAdapter.get(wantedId)); - - assertNotNull(expectedDomain.getCritere()); - Assertions.assertEquals(expectedEntity.getCritere(), expectedDomain.getCritere()); - Assertions.assertEquals(expectedEntity.getPays(), expectedDomain.getPays()); - Assertions.assertEquals(expectedEntity.getRaccourcisAnglais(), expectedDomain.getRaccourcisAnglais()); - Assertions.assertEquals(expectedEntity.getValeur(), expectedDomain.getValeur()); - Assertions.assertEquals(expectedEntity.getSource(), expectedDomain.getSource()); + .setPays(PAYS) + .setCritere(CRITERE); + + Mockito.when(repository.findByNiveauAndCategorieAndLocalisationAndCritere(Constants.MIXELEC_NIVEAU, Constants.MIXELEC_CATEGORIE, wantedId.getPays(), wantedId.getCritere())).thenReturn(Optional.of(expectedEntity)); + + var actualDomain = assertDoesNotThrow(() -> jpaAdapter.get(wantedId)); + + assertNotNull(actualDomain.getCritere()); + Assertions.assertEquals(expectedEntity.getCritere(), actualDomain.getCritere()); + Assertions.assertEquals(PAYS, actualDomain.getPays()); + Assertions.assertNull(actualDomain.getRaccourcisAnglais()); } @Test @@ -71,8 +89,7 @@ class MixElectriqueJpaAdapterTest { var wantedId = new MixElectriqueId() .setPays("NonExistant") .setCritere("Inexistant"); - var wantedEntityId = mapper.toEntityId(wantedId); - Mockito.when(repository.findById(wantedEntityId)).thenReturn(Optional.empty()); + Mockito.when(repository.findByNiveauAndCategorieAndLocalisationAndCritere(Constants.MIXELEC_NIVEAU, Constants.MIXELEC_CATEGORIE, wantedId.getPays(), wantedId.getCritere())).thenReturn(Optional.empty()); ReferentielException expectedException = assertThrows(ReferentielException.class, () -> jpaAdapter.get(wantedId)); @@ -90,80 +107,60 @@ class MixElectriqueJpaAdapterTest { void purge_shouldCallDeleteAll() { jpaAdapter.purge(); - Mockito.verify(repository, Mockito.times(1)).deleteAll(); + Mockito.verify(repository, Mockito.times(1)).deleteByNiveauAndCategorie(any(), any()); } @Test void getAll_shouldCallfindAll() { - var expectedCritere = "Changement climatique"; - var expectedEntity = new MixElectriqueEntity() - .setCritere(expectedCritere) - .setPays("France") - .setSource("Test") - .setRaccourcisAnglais("FR") - .setValeur(0.120); - Mockito.when(repository.findAll()).thenReturn(Collections.singletonList(expectedEntity)); + var expectedEntity = facteurCaracterisationEntity(); + Mockito.when(repository.findByNiveauAndCategorie(any(), any())).thenReturn(Collections.singletonList(expectedEntity)); var result = jpaAdapter.getAll(); - Mockito.verify(repository, Mockito.times(1)).findAll(); + Mockito.verify(repository, Mockito.times(1)).findByNiveauAndCategorie(any(), any()); assertNotNull(result); assertEquals(1, result.size()); - var expectedDomain = result.get(0); - assertNotNull(expectedDomain.getCritere()); - Assertions.assertEquals(expectedEntity.getCritere(), expectedDomain.getCritere()); - Assertions.assertEquals(expectedEntity.getPays(), expectedDomain.getPays()); - Assertions.assertEquals(expectedEntity.getRaccourcisAnglais(), expectedDomain.getRaccourcisAnglais()); - Assertions.assertEquals(expectedEntity.getValeur(), expectedDomain.getValeur()); - Assertions.assertEquals(expectedEntity.getSource(), expectedDomain.getSource()); + var actualDomain = result.get(0); + assertNotNull(actualDomain.getCritere()); + assertNull(actualDomain.getRaccourcisAnglais()); + assertEquals(PAYS, actualDomain.getPays()); } + @Test void saveAll_shouldCallsaveAll() { - var wantedCritere = "Changement climatique"; - var domainToSave = new MixElectrique() - .setCritere(wantedCritere) - .setPays("France") - .setSource("Test") - .setRaccourcisAnglais("FR") - .setValeur(0.120); - - var entityToSave = mapper.toEntity(domainToSave); + var domainToSave = mixelectrique(); + var entitiesToSave = facteurCaracterisationMapper.toEntities(mapper.toFacteurCaracterisations(Collections.singletonList(domainToSave))); assertDoesNotThrow(() -> jpaAdapter.saveAll(Collections.singletonList(domainToSave))); - - Mockito.verify(repository, Mockito.times(1)).saveAll(Collections.singletonList(entityToSave)); + Mockito.verify(repository).saveAll(entitiesToSave); + Mockito.verify(repository, Mockito.times(1)).saveAll(entitiesToSave); } @Test void save_shouldSaveAndReturnDomain() { - var wantedCritere = "Changement climatique"; - var wantedDomain = new MixElectrique() - .setCritere(wantedCritere) - .setPays("France") - .setSource("Test") - .setRaccourcisAnglais("FR") - .setValeur(0.120); - var expectedEntity = mapper.toEntities(Collections.singletonList(wantedDomain)).get(0); + var domain = mixelectrique(); + var actualEntity = facteurCaracterisationMapper.toEntity(mapper.toFacteurCaracterisation(domain)); + var expectedEntity = facteurCaracterisationEntity(); - Mockito.when(repository.save(expectedEntity)).thenReturn(expectedEntity); + assertEquals(expectedEntity.getNom(), actualEntity.getNom()); + assertEquals(expectedEntity.getLocalisation(), actualEntity.getLocalisation()); + assertEquals(expectedEntity.getEtape(), actualEntity.getEtape()); + assertEquals(expectedEntity.getNiveau(), actualEntity.getNiveau()); + assertEquals(expectedEntity.getCategorie(), actualEntity.getCategorie()); - var expectedDomain = assertDoesNotThrow(() -> jpaAdapter.save(wantedDomain)); + Mockito.when(repository.save(actualEntity)).thenReturn(actualEntity); - assertNotNull(expectedDomain.getCritere()); - Assertions.assertEquals(wantedDomain.getCritere(), expectedDomain.getCritere()); - Assertions.assertEquals(wantedDomain.getPays(), expectedDomain.getPays()); - Assertions.assertEquals(wantedDomain.getRaccourcisAnglais(), expectedDomain.getRaccourcisAnglais()); - Assertions.assertEquals(wantedDomain.getValeur(), expectedDomain.getValeur()); - Assertions.assertEquals(wantedDomain.getSource(), expectedDomain.getSource()); + assertDoesNotThrow(() -> jpaAdapter.save(domain)); + Mockito.verify(repository).save(actualEntity); } @ParameterizedTest @NullSource void save_shouldSaveAndReturnNull(MixElectrique nullValue) { var expectedDomain = assertDoesNotThrow(() -> jpaAdapter.save(nullValue)); - assertNull(expectedDomain); } + } diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/facteurcaracterisation/ReferentielFacteurCaracterisationRestApiImplTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/facteurcaracterisation/ReferentielFacteurCaracterisationRestApiImplTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3a1fd17532c770010e4f10a5b9732abcb43041ff --- /dev/null +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/restapi/controller/facteurcaracterisation/ReferentielFacteurCaracterisationRestApiImplTest.java @@ -0,0 +1,129 @@ +package org.mte.numecoeval.referentiel.infrastructure.restapi.controller.facteurcaracterisation; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.infrastructure.adapter.export.FacteurCaracterisationCsvExportService; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.FacteurCaracterisationDTO; +import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.id.FacteurCaracterisationIdDTO; +import org.mte.numecoeval.referentiel.infrastructure.restapi.facade.FacteurCaracterisationFacade; +import org.mte.numecoeval.referentiel.utils.Constants; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.web.server.ResponseStatusException; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + + +@ContextConfiguration(classes = {ReferentielFacteurCaracterisationRestApiImpl.class}) +@ExtendWith(SpringExtension.class) + +public class ReferentielFacteurCaracterisationRestApiImplTest { + @Autowired + private ReferentielFacteurCaracterisationRestApiImpl referentielRestApi; + + @MockBean + private FacteurCaracterisationFacade referentielFacade; + + @MockBean + private FacteurCaracterisationCsvExportService csvExportService; + + @Test + void get_shouldCallFacadeGetAndReturnMatchingDTO() throws ReferentielException { + String nom = "Ordinateur Portable"; + String nomCritere = "Changement Climatique"; + String codeEtapeACV = "UTILISATION"; + var idDTO = new FacteurCaracterisationIdDTO(nom, + codeEtapeACV, + nomCritere + ); + var expectedDTO = FacteurCaracterisationDTO.builder() + .nom(nom) + .etape(codeEtapeACV) + .critere(nomCritere) + .niveau(Constants.EQUIPEMENT_NIVEAU) + .valeur(1.0).build(); + + when(referentielFacade.get(idDTO)).thenReturn(expectedDTO); + + var receivedDTO = referentielRestApi.get(nom, nomCritere, codeEtapeACV); + assertSame(receivedDTO, receivedDTO); + verify(referentielFacade).get(idDTO); + } + + @Test + void get_whenNotFound_thenShouldThrowReferentielException() throws ReferentielException { + String refEquipement = "Ordinateur Portable"; + String nomCritere = "Changement Climatique"; + String codeEtapeACV = "UTILISATION"; + var idDTO = new FacteurCaracterisationIdDTO(refEquipement, + codeEtapeACV, + nomCritere + ); + + when(referentielFacade.get(idDTO)).thenThrow(new ReferentielException("Impact Equipement non trouvé")); + var exception = assertThrows(ReferentielException.class, () -> referentielRestApi.get(refEquipement, nomCritere, codeEtapeACV)); + assertEquals("Impact Equipement non trouvé", exception.getMessage()); + } + + @Test + void importCSV_shouldCallPurgeAndAddAll() throws IOException, ReferentielException { + doNothing().when(referentielFacade).purgeAndAddAll(any()); + referentielRestApi.importCSV(new MockMultipartFile("Name", "AAAAAAAA".getBytes(StandardCharsets.UTF_8)), "FULL"); + verify(referentielFacade).purgeAndAddAll(any()); + } + + @Test + void importCSV_shouldCallUpsert() throws IOException, ReferentielException { + referentielRestApi.importCSV(new MockMultipartFile("Name", "AAAAAAAA".getBytes(StandardCharsets.UTF_8)), "DELTA"); + verify(referentielFacade).upsert(any()); + } + + @Test + void importCSV_withWrongModeShouldThrowException() throws IOException, ReferentielException { + var exception = assertThrows(ReferentielException.class, () -> referentielRestApi.importCSV(new MockMultipartFile("Name", "AAAAAAAA".getBytes(StandardCharsets.UTF_8)), "WRONG")); + assertEquals("Le mode d'import indiqué n'est pas valide", exception.getMessage()); + + } + + @Test + void importCSV_whenEmptyFileThenShouldThrowException() throws ReferentielException { + doNothing().when(referentielFacade).purgeAndAddAll(any()); + MockMultipartFile file = new MockMultipartFile("Name", (byte[]) null); + ResponseStatusException responseStatusException = assertThrows(ResponseStatusException.class, () -> referentielRestApi.importCSV(file, "FULL")); + assertEquals(HttpStatus.BAD_REQUEST, responseStatusException.getStatusCode()); + assertEquals("Le fichier n'existe pas ou alors il est vide", responseStatusException.getReason()); + } + + @Test + void importCSV_whenNullFileThenShouldThrowException() throws ReferentielException { + doNothing().when(referentielFacade).purgeAndAddAll(any()); + ResponseStatusException responseStatusException = assertThrows(ResponseStatusException.class, () -> referentielRestApi.importCSV(null, "FULL")); + assertEquals(HttpStatus.BAD_REQUEST, responseStatusException.getStatusCode()); + assertEquals("Le fichier n'existe pas ou alors il est vide", responseStatusException.getReason()); + } + + @Test + void exportCSV_shouldReturnCSVFile() throws UnsupportedEncodingException { + var servletResponse = new MockHttpServletResponse(); + + assertDoesNotThrow(() -> referentielRestApi.exportCSV(servletResponse)); + + assertEquals("text/csv;charset=UTF-8", servletResponse.getContentType()); + String headerContentDisposition = servletResponse.getHeader("Content-Disposition"); + assertNotNull(headerContentDisposition); + assertTrue(headerContentDisposition.contains("attachment; filename=facteurCaracterisation-")); + assertEquals(200, servletResponse.getStatus()); + + } +} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/restapi/facade/FacteurCaracterisationFacadeTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/restapi/facade/FacteurCaracterisationFacadeTest.java new file mode 100644 index 0000000000000000000000000000000000000000..84ca5ec83bf97335b63feba5afd24d70fbe18984 --- /dev/null +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/restapi/facade/FacteurCaracterisationFacadeTest.java @@ -0,0 +1,110 @@ +package org.mte.numecoeval.referentiel.infrastructure.restapi.facade; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.*; +import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; +import org.mte.numecoeval.referentiel.domain.model.FacteurCaracterisation; +import org.mte.numecoeval.referentiel.domain.model.id.FacteurCaracterisationId; +import org.mte.numecoeval.referentiel.domain.ports.output.ReferentielPersistencePort; +import org.mte.numecoeval.referentiel.factory.TestDataFactory; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapper; +import org.mte.numecoeval.referentiel.infrastructure.mapper.FacteurCaracterisationMapperImpl; +import org.mte.numecoeval.referentiel.utils.Constants; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.Arrays; +import java.util.Collection; + +import static org.junit.jupiter.api.Assertions.*; + +public class FacteurCaracterisationFacadeTest { + @InjectMocks + FacteurCaracterisationFacade facadeToTest; + + @Mock + private ReferentielPersistencePort<FacteurCaracterisation, FacteurCaracterisationId> persistencePort; + + private FacteurCaracterisationMapper mapper = new FacteurCaracterisationMapperImpl(); + + @BeforeEach + void setup() { + MockitoAnnotations.openMocks(this); + ReflectionTestUtils.setField(facadeToTest, "mapper", mapper); + } + + @Test + void get_shouldReturnMatchingDTO() throws ReferentielException { + var wantedDTOId = TestDataFactory.FacteurCaracterisationFactory.idDTO( + "Ecran 27 pouces", + TestDataFactory.DEFAULT_ETAPE, + TestDataFactory.DEFAULT_CRITERE + + ); + var expectedDomainID = TestDataFactory.FacteurCaracterisationFactory.idDomain( + "Ecran 27 pouces", + TestDataFactory.DEFAULT_ETAPE, + TestDataFactory.DEFAULT_CRITERE + + ); + var expectedDomain = TestDataFactory.FacteurCaracterisationFactory.domain("Ecran 27 pouces", + TestDataFactory.EtapeFactory.domain(TestDataFactory.DEFAULT_ETAPE, "Test"), + TestDataFactory.CritereFactory.domain(TestDataFactory.DEFAULT_CRITERE, TestDataFactory.DEFAULT_UNITE, TestDataFactory.DEFAULT_CRITERE), + "", Constants.EQUIPEMENT_NIVEAU, "", "", 0.01, "France", 0.02, "", "NegaOctet" + ); + Mockito.when(persistencePort.get(expectedDomainID)).thenReturn(expectedDomain); + + var dto = assertDoesNotThrow(() -> facadeToTest.get(wantedDTOId)); + assertEquals(expectedDomain.getNom(), dto.getNom()); + assertEquals(expectedDomain.getEtape(), dto.getEtape()); + assertEquals(expectedDomain.getCritere(), dto.getCritere()); + assertEquals(expectedDomain.getNiveau(), dto.getNiveau()); + assertEquals(expectedDomain.getValeur(), dto.getValeur()); + } + + @Test + void purgeAndAddAll_ShouldCallPurgeThenSaveAll() throws ReferentielException { + var dtosToSave = Arrays.asList( + TestDataFactory.FacteurCaracterisationFactory.dto( + "Ecran 27 pouces", + TestDataFactory.DEFAULT_ETAPE, + TestDataFactory.DEFAULT_CRITERE, + "", Constants.EQUIPEMENT_NIVEAU, "", "", 0.01, "France", 0.02, "", + "NegaOctet"), + TestDataFactory.FacteurCaracterisationFactory.dto( + "Ecran 27 pouces", + "FIN_DE_VIE", + "Acidification", + "", Constants.EQUIPEMENT_NIVEAU, "", "", 0.01, "France", 0.02, "", + "NegaOctet") + ); + + ArgumentCaptor<Collection<FacteurCaracterisation>> valueCapture = ArgumentCaptor.forClass(Collection.class); + + assertDoesNotThrow(() -> facadeToTest.purgeAndAddAll(dtosToSave)); + + Mockito.verify(persistencePort, Mockito.times(1)).purge(); + Mockito.verify(persistencePort, Mockito.times(1)).saveAll(valueCapture.capture()); + + var expectedDomains = valueCapture.getValue(); + assertNotNull(expectedDomains); + assertEquals(dtosToSave.size(), expectedDomains.size()); + dtosToSave.forEach(dto -> { + var matchingDomain = expectedDomains.stream() + .filter(domain -> + dto.getEtape().equals(domain.getEtape()) + && dto.getCritere().equals(domain.getCritere()) + && dto.getNom().equals(domain.getNom())) + .findAny(); + assertTrue(matchingDomain.isPresent()); + var domain = matchingDomain.get(); + assertEquals(dto.getNom(), domain.getNom()); + assertEquals(dto.getEtape(), domain.getEtape()); + assertEquals(dto.getCritere(), domain.getCritere()); + assertEquals(dto.getNiveau(), domain.getNiveau()); + assertEquals(dto.getSource(), domain.getSource()); + assertEquals(dto.getValeur(), domain.getValeur()); + assertEquals(dto.getConsoElecMoyenne(), domain.getConsoElecMoyenne()); + }); + } +} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/restapi/facade/MixElectriqueFacadeTest.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/restapi/facade/MixElectriqueFacadeTest.java index e88502887af3c1789617ae8604d13f13c743a820..87ab4d6cef30fa76166315167fcdc40ab2c2810c 100644 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/restapi/facade/MixElectriqueFacadeTest.java +++ b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/infrastructure/restapi/facade/MixElectriqueFacadeTest.java @@ -3,11 +3,7 @@ package org.mte.numecoeval.referentiel.infrastructure.restapi.facade; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; +import org.mockito.*; import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; import org.mte.numecoeval.referentiel.domain.model.MixElectrique; import org.mte.numecoeval.referentiel.domain.model.id.MixElectriqueId; diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/AbstractStepDefinitions.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/AbstractStepDefinitions.java deleted file mode 100644 index 71c6e4c77baf437fe5ce54549a218756b045dd3f..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/AbstractStepDefinitions.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.mte.numecoeval.referentiel.steps; - -import io.restassured.RestAssured; -import io.restassured.response.Response; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.critere.ReferentielAdministrationCritereRestApi; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.etape.ReferentielAdministrationEtapeRestApi; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.ResourceUtils; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.Arrays; -import java.util.Objects; - -import static io.restassured.RestAssured.given; -import static org.junit.jupiter.api.Assertions.assertEquals; - -@Transactional -public abstract class AbstractStepDefinitions { - - @Autowired - protected Environment environment; - - protected Response response; - - /** - * Configuration par défaut pour les clients d'API - */ - protected void setupRestAssured() { - RestAssured.baseURI = "http://localhost"; - RestAssured.port = Integer.parseInt(Objects.requireNonNull(environment.getProperty("server.port"))); - } - - /** - * Initialisation des référentiels étapes et critères avec des valeurs par défaut. - * @throws FileNotFoundException - * @throws NoSuchMethodException - */ - protected void initAlimentationEtapeEtCritere() throws FileNotFoundException, NoSuchMethodException { - RestAssured.baseURI = "http://localhost"; - RestAssured.port = Integer.parseInt(Objects.requireNonNull(environment.getProperty("server.port"))); - File fileCritere = ResourceUtils.getFile("classpath:" + "csv/ref_Critere.csv"); - File fileEtape = ResourceUtils.getFile("classpath:" + "csv/ref_etapeACV.csv"); - //chargement Etape - String path = Arrays.stream(ReferentielAdministrationCritereRestApi.class.getMethod("importCSV", MultipartFile.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - Response response = given() - .multiPart("file", fileCritere) - .post(path) - .thenReturn(); - assertEquals(200, response.getStatusCode()); - - path = Arrays.stream(ReferentielAdministrationEtapeRestApi.class.getMethod("importCSV", MultipartFile.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - response = given() - .multiPart("file", fileEtape) - .post(path) - .thenReturn(); - assertEquals(200, response.getStatusCode()); - } -} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/CorrespondanceRefEquipementStepDefinitions.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/CorrespondanceRefEquipementStepDefinitions.java deleted file mode 100644 index 6a5f7896dbd0d354d173f0d98f3f29fea280b287..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/CorrespondanceRefEquipementStepDefinitions.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.mte.numecoeval.referentiel.steps; - -import io.cucumber.java.DataTableType; -import io.cucumber.java.fr.Alors; -import io.cucumber.java.fr.Et; -import io.cucumber.java.fr.Quand; -import org.mte.numecoeval.referentiel.domain.model.CorrespondanceRefEquipement; -import org.mte.numecoeval.referentiel.infrastructure.jpa.adapter.CorrespondanceRefEquipementJpaAdapter; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.correspondance.ReferentielAdministrationCorrespondanceRefEquipementRestApi; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.ResourceUtils; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import static io.restassured.RestAssured.given; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -public class CorrespondanceRefEquipementStepDefinitions extends AbstractStepDefinitions { - - @Autowired - CorrespondanceRefEquipementJpaAdapter jpaAdapter; - - @DataTableType - public CorrespondanceRefEquipement correspondanceRefEquipement(Map<String, String> entry) { - return CorrespondanceRefEquipement.builder() - .modeleEquipementSource(entry.get("modeleEquipementSource")) - .refEquipementCible(entry.get("refEquipementCible")) - .build(); - } - - @Quand("le fichier CSV des correspondances d'équipements {string} est importé par API et la réponse est {int}") - public void importReferentielCorrespondanceRefEquipements(String nomFichier, int codeReponseHttpAttendu) throws FileNotFoundException, NoSuchMethodException { - setupRestAssured(); - initAlimentationEtapeEtCritere(); - File file = ResourceUtils.getFile("classpath:" + nomFichier); - String requestPath = Arrays.stream(ReferentielAdministrationCorrespondanceRefEquipementRestApi.class.getMethod("importCSV", MultipartFile.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - response = given() - .multiPart("file", file) - .post(requestPath) - .thenReturn(); - assertEquals(codeReponseHttpAttendu, response.getStatusCode()); - } - - @Et("La récupération de tous les correspondances d'équipements renvoie {int} lignes") - public void getAllCorrespondanceRefEquipement(int nombreLignesAttendues) throws NoSuchMethodException { - List<CorrespondanceRefEquipement> domains = jpaAdapter.getAll(); - - assertEquals(nombreLignesAttendues, domains.size()); - } - - @Alors("Vérifications des correspondances d'équipements disponibles") - public void checkImpactEquipements(List<CorrespondanceRefEquipement> dataTable) { - List<CorrespondanceRefEquipement> datasInDatabase = jpaAdapter.getAll(); - - assertEquals(dataTable.size(), datasInDatabase.size()); - dataTable.forEach(expected -> { - var dataInDatabase = datasInDatabase.stream().filter(data -> data.getModeleEquipementSource().equals(expected.getModeleEquipementSource())).findFirst().orElse(null); - assertNotNull(dataInDatabase, "Il existe une correspondance d'équipement avec le modèle %s".formatted(expected.getModeleEquipementSource())); - - assertEquals(expected.getRefEquipementCible(), dataInDatabase.getRefEquipementCible(), "CorrespondanceRefEquipement %s : la référence cible ne matche pas".formatted(expected.getRefEquipementCible())); - }); - } -} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/CritereStepdefs.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/CritereStepdefs.java deleted file mode 100644 index 4c51f11023d4717822db39e14608b3d0505a5f46..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/CritereStepdefs.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.mte.numecoeval.referentiel.steps; - -import io.cucumber.java.fr.Alors; -import io.cucumber.java.fr.Et; -import io.cucumber.java.fr.Quand; -import io.restassured.http.ContentType; -import io.restassured.response.Response; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.CritereDTO; -import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportCriterePortImpl; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.critere.ReferentielAdministrationCritereRestApi; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.critere.ReferentielCritereRestApi; -import org.springframework.util.ResourceUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -import static io.restassured.RestAssured.given; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class CritereStepdefs extends AbstractStepDefinitions { - - private List<CritereDTO> critereDTOS; - - private List<CritereDTO> critereCSV; - - @Quand("le fichier CSV {string} est inject") - public void leFichierCSVEstInject(String nomFichier) throws FileNotFoundException, NoSuchMethodException { - setupRestAssured(); - File file = ResourceUtils.getFile("classpath:" + nomFichier); - - // Chargement des données - critereCSV = new ImportCriterePortImpl().importCSV(new FileInputStream(file)).getObjects(); - - String requestPath = Arrays.stream(ReferentielAdministrationCritereRestApi.class.getMethod("importCSV", MultipartFile.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - Response response = given() - .multiPart("file", file) - .post(requestPath) - .thenReturn(); - //check que le status est OK - assertEquals(200, response.getStatusCode()); - } - - @Alors("Il existe {int} elements dans le referentiel critere") - public void ilExisteElementsDansLeReferentielCritere(int nombreElements) throws NoSuchMethodException { - String requestPath = Arrays.stream(ReferentielCritereRestApi.class.getMethod("getAll") - .getAnnotation(GetMapping.class).path()).findFirst().orElse(null); - Response response = given() - .contentType(ContentType.JSON) - .get(requestPath) - .thenReturn(); - critereDTOS = Arrays.asList(response.as(CritereDTO[].class)); - assertEquals(nombreElements, response.as(List.class).size()); - - } - - @Et("chacun des elements du referential ajouté est identique au element du fichier csv") - public void chacunDesElementsDuReferentialAjouteEstIdentiqueAuElementDuFichierCsv() { - List<CritereDTO> resultEgalite = critereCSV.stream().filter(critereEntity -> - critereDTOS.stream().anyMatch(api -> - Optional.of(critereEntity.getDescription()).equals(Optional.of(api.getDescription())) - && critereEntity.getNomCritere().equals(api.getNomCritere()) - && critereEntity.getUnite().equals(api.getUnite()) - )).toList(); - assertEquals(critereCSV.size(), resultEgalite.size()); - } -} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/EtapeStepdefs.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/EtapeStepdefs.java deleted file mode 100644 index 67807c3ca177d13fc4d8120919fbce52b6bb18de..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/EtapeStepdefs.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.mte.numecoeval.referentiel.steps; - -import io.cucumber.java.fr.Alors; -import io.cucumber.java.fr.Et; -import io.cucumber.java.fr.Quand; -import io.restassured.http.ContentType; -import io.restassured.response.Response; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.EtapeDTO; -import org.mte.numecoeval.referentiel.domain.data.ResultatImport; -import org.mte.numecoeval.referentiel.domain.ports.input.impl.ImportEtapePortImpl; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.etape.ReferentielAdministrationEtapeRestApi; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.etape.ReferentielEtapeRestApi; -import org.springframework.util.ResourceUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static io.restassured.RestAssured.given; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class EtapeStepdefs extends AbstractStepDefinitions { - private List<EtapeDTO> etapeCVS; - private EtapeDTO[] etapesAPI; - - @Quand("le fichier CSV {string} est injecte") - public void leFichierCSVEstInjecte(String nomFichier) throws FileNotFoundException, NoSuchMethodException { - setupRestAssured(); - File file = ResourceUtils.getFile("classpath:" + nomFichier); - //stockage des dtos etapes pour verifications avec la ressource rest api apres alimentation - ResultatImport<EtapeDTO> resultatImport = new ImportEtapePortImpl().importCSV(new FileInputStream(file)); - etapeCVS = resultatImport.getObjects(); - String requestPath = Arrays.stream(ReferentielAdministrationEtapeRestApi.class.getMethod("importCSV", MultipartFile.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - Response response = given() - .multiPart("file", file) - .post(requestPath) - .thenReturn(); - //check que le status est OK - assertEquals(200, response.getStatusCode()); - } - - @Alors("Il existe {int} elements dans le referentiel Etape ACV") - public void ilExisteElementsDansLeReferentielEtapeACV(int taille) throws NoSuchMethodException { - String requestPath = Arrays.stream(ReferentielEtapeRestApi.class.getMethod("getAll") - .getAnnotation(GetMapping.class).path()).findFirst().orElse(null); - Response response = given() - .contentType(ContentType.JSON) - .get(requestPath) - .thenReturn(); - etapesAPI = response.as(EtapeDTO[].class); - assertEquals(taille, response.as(List.class).size()); - - - } - - - @Et("chacun des elements du referentiel ajouté est identique au element du fichier csv") - public void chacunDesElementsDuReferentielAjoutéEstIdentiqueAuElementDuFichierCsv() { - - List<EtapeDTO> resultEgalite = etapeCVS.stream().filter(csv -> - Arrays.stream(etapesAPI).collect(Collectors.toList()).stream().anyMatch(api -> - csv.getLibelle().equals(api.getLibelle()) - && csv.getCode().equals(api.getCode()) - )) - .collect(Collectors.toList()); - - assertEquals(etapeCVS.size(), resultEgalite.size()); - } -} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/HypotheseStepdefs.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/HypotheseStepdefs.java deleted file mode 100644 index 0eb99ad11bcbdb35f0537de5a256cc41583753ff..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/HypotheseStepdefs.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.mte.numecoeval.referentiel.steps; - -import io.cucumber.java.fr.Alors; -import io.cucumber.java.fr.Quand; -import io.restassured.http.ContentType; -import io.restassured.path.json.JsonPath; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.hypothese.ReferentielAdministrationHypotheseRestApi; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.hypothese.ReferentielHypotheseRestApi; -import org.springframework.util.ResourceUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.Arrays; - -import static io.restassured.RestAssured.given; -import static org.junit.jupiter.api.Assertions.assertEquals; - -public class HypotheseStepdefs extends AbstractStepDefinitions { - - @Quand("le fichier CSV REF HYPOTHESE{string} est inject") - public void leFichierCSVREFHYPOTHESEEstInject(String nomFichier) throws FileNotFoundException, NoSuchMethodException { - - setupRestAssured(); - File file = ResourceUtils.getFile("classpath:" + nomFichier); - String requestPath = Arrays.stream(ReferentielAdministrationHypotheseRestApi.class.getMethod("importCSV", MultipartFile.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - response = given() - .multiPart("file", file) - .post(requestPath) - .thenReturn(); - - } - - @Alors("le statut http est {int}") - public void checkReponseApi(int codeHttpAttendu) { - assertEquals(codeHttpAttendu, response.getStatusCode()); - } - - @Quand("lors de la recherche de hypothese avec la cle {string}") - public void lorsDeLaRechercheDeHypotheseAvecLaCle(String cle) throws NoSuchMethodException { - setupRestAssured(); - String requestPath = Arrays.stream(ReferentielHypotheseRestApi.class.getMethod("get", String.class) - .getAnnotation(GetMapping.class).path()).findFirst().orElse(null); - response = given() - .contentType(ContentType.JSON) - .param("cle", cle) - .get(requestPath) - .thenReturn(); - assertEquals(200, response.getStatusCode()); - - } - - @Alors("Le resultat est : cle = {string} valeur={string} et source={string}") - public void leResultatEstCleValeurEtSource(String cle, String valeur, String source) { - JsonPath jsonPath = response.jsonPath(); - assertEquals(cle, jsonPath.get("code")); - assertEquals(source, jsonPath.get("source")); - assertEquals(valeur, jsonPath.get("valeur")); - - - } -} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/ImpactImpactEquipementStepDefinitions.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/ImpactImpactEquipementStepDefinitions.java deleted file mode 100644 index 959e3e91e06f85ab0996a4a79f5fe3bdbb2f40d9..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/ImpactImpactEquipementStepDefinitions.java +++ /dev/null @@ -1,82 +0,0 @@ -package org.mte.numecoeval.referentiel.steps; - -import io.cucumber.java.DataTableType; -import io.cucumber.java.fr.Alors; -import io.cucumber.java.fr.Et; -import io.cucumber.java.fr.Quand; -import org.apache.commons.lang3.math.NumberUtils; -import org.mte.numecoeval.referentiel.domain.model.ImpactEquipement; -import org.mte.numecoeval.referentiel.infrastructure.jpa.adapter.ImpactEquipementJpaAdapter; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.impactequipement.ReferentielAdministrationImpactEquipementRestApi; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.ResourceUtils; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import static io.restassured.RestAssured.given; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class ImpactImpactEquipementStepDefinitions extends AbstractStepDefinitions { - - @Autowired - ImpactEquipementJpaAdapter jpaAdapter; - - @DataTableType - public ImpactEquipement impactEquipement(Map<String, String> entry) { - var impact = new ImpactEquipement(); - impact.setEtape(entry.get("etape")); - impact.setCritere(entry.get("critere")); - impact.setRefEquipement(entry.get("refEquipement")); - impact.setValeur(NumberUtils.createDouble(entry.get("valeur"))); - impact.setConsoElecMoyenne(NumberUtils.createDouble(entry.get("consoElecMoyenne"))); - impact.setSource(entry.get("source")); - impact.setType(entry.get("type")); - impact.setDescription(entry.get("description")); - return impact; - } - - @Quand("le fichier CSV des impacts d'équipements {string} est importé par API et la réponse est {int}") - public void importReferentielImpactEquipements(String nomFichier, int codeReponseHttpAttendu) throws FileNotFoundException, NoSuchMethodException { - setupRestAssured(); - initAlimentationEtapeEtCritere(); - File file = ResourceUtils.getFile("classpath:" + nomFichier); - String requestPath = Arrays.stream(ReferentielAdministrationImpactEquipementRestApi.class.getMethod("importCSV", MultipartFile.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - response = given() - .multiPart("file", file) - .post(requestPath) - .thenReturn(); - assertEquals(codeReponseHttpAttendu, response.getStatusCode()); - } - - @Et("La récupération de tous les impacts d'équipements renvoie {int} lignes") - public void getAllImpactEquipements(int nombreLignesAttendues) throws NoSuchMethodException { - List<ImpactEquipement> impactEquipements = jpaAdapter.getAll(); - - assertEquals(nombreLignesAttendues, impactEquipements.size()); - } - - @Alors("Vérifications des impacts équipements disponibles") - public void checkImpactEquipements(List<ImpactEquipement> dataTable) { - List<ImpactEquipement> impactEquipements = jpaAdapter.getAll(); - - assertEquals(dataTable.size(), impactEquipements.size()); - dataTable.forEach( expected -> - assertTrue( - impactEquipements.stream().anyMatch(impactEquipement1 -> impactEquipement1.equals(expected)), - "L'équipement étape: %s, critere: %s, refEquipement: %s n'est pas disponible".formatted( - expected.getEtape(), - expected.getCritere(), - expected.getRefEquipement() - ) - ) - ); - } -} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/ImpactMessagerieStepDefinitions.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/ImpactMessagerieStepDefinitions.java deleted file mode 100644 index 4f546f6e4501a6c411098999e2241167a76cccb3..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/ImpactMessagerieStepDefinitions.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.mte.numecoeval.referentiel.steps; - -import io.cucumber.java.fr.Alors; -import io.cucumber.java.fr.Et; -import io.cucumber.java.fr.Quand; -import org.apache.commons.lang3.StringUtils; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactMessagerieDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.impactmessagerie.ReferentielImpactMessagerieRestApi; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.impactmessagerie.ReferentielInterneImpactMessagerieRestApi; -import org.springframework.util.ResourceUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.Arrays; -import java.util.List; - -import static io.restassured.RestAssured.given; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class ImpactMessagerieStepDefinitions extends AbstractStepDefinitions { - - List<ImpactMessagerieDTO> impactsMessageriesDisponibles; - - @Quand("le fichier CSV des impacts messageries {string} est importé par API et la réponse est {int}") - public void importReferentielImpactMessagerie(String nomFichier, int codeReponseHttpAttendu) throws FileNotFoundException, NoSuchMethodException { - setupRestAssured(); - File file = ResourceUtils.getFile("classpath:" + nomFichier); - String requestPath = Arrays.stream(ReferentielInterneImpactMessagerieRestApi.class.getMethod("importCSV", MultipartFile.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - response = given() - .multiPart("file", file) - .post(requestPath) - .thenReturn(); - assertEquals(codeReponseHttpAttendu, response.getStatusCode()); - } - - @Et("La récupération de tous les impacts de messagerie renvoie {int} lignes") - public void getAllImpactMessagerie(int nombreLignesAttendues) throws NoSuchMethodException { - String requestPath = Arrays.stream(ReferentielImpactMessagerieRestApi.class.getMethod("getAllImpactMessagerie") - .getAnnotation(GetMapping.class).path()).findFirst().orElse(null); - response = given() - .get(requestPath) - .thenReturn(); - - assertEquals(200, response.getStatusCode()); - impactsMessageriesDisponibles = Arrays.asList(response.as(ImpactMessagerieDTO[].class)); - assertEquals(nombreLignesAttendues, impactsMessageriesDisponibles.size()); - } - - @Alors("un impact messagerie pour le critère {string} a une fonction y = {string}x + {string} et de source {string}") - public void checkImpactMessagerieDisponible(String critere, String constanteCoefficientDirecteur, String constanteOrdonneeOrigine, String source) { - - assertTrue( - impactsMessageriesDisponibles.stream().anyMatch(impactMessagerieDTO -> - StringUtils.equals(critere, impactMessagerieDTO.getCritere()) - && Double.valueOf(constanteCoefficientDirecteur).equals(impactMessagerieDTO.getConstanteCoefficientDirecteur()) - && Double.valueOf(constanteOrdonneeOrigine).equals(impactMessagerieDTO.getConstanteOrdonneeOrigine()) - && StringUtils.equals(source, impactMessagerieDTO.getSource()) - ) - ); - - } -} diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/ImpactReseauStepDefinitions.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/ImpactReseauStepDefinitions.java deleted file mode 100644 index f0edc8e5bdfa511483818ff9a7eb0968be48e7a0..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/ImpactReseauStepDefinitions.java +++ /dev/null @@ -1,258 +0,0 @@ -package org.mte.numecoeval.referentiel.steps; - -import io.cucumber.java.fr.Alors; -import io.cucumber.java.fr.Quand; -import io.restassured.http.ContentType; -import io.restassured.response.Response; -import lombok.extern.slf4j.Slf4j; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ErrorResponseDTO; -import org.mte.numecoeval.referentiel.infrastructure.restapi.dto.ImpactReseauDTO; -import org.mte.numecoeval.referentiel.domain.exception.ReferentielException; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.impactreseau.ReferentielAdministrationImpactReseauRestApi; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.impactreseau.ReferentielImpactReseauRestApi; -import org.springframework.http.HttpStatus; -import org.springframework.util.ResourceUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Arrays; - -import static io.restassured.RestAssured.given; -import static org.junit.jupiter.api.Assertions.*; - -@Slf4j -public class ImpactReseauStepDefinitions extends AbstractStepDefinitions { - - @Quand("on ajoute un facteur impact reseau dont la refReseau est {string}, etapeACV est {string} , critere est {string} la source est {string} la valeur est {string} et l'unité est {string}") - public void onAjouteUnFacteurImpactReseauDontLaRefReseauEstEtapeACVEstCritereEstLa(String refReseau, String etapeACV, String critere, String source, String valeur, String unite) throws ReferentielException, NoSuchMethodException, FileNotFoundException { - log.debug("Debut creation d'un impact reseau dans table ref_impactReseau"); - initAlimentationEtapeEtCritere(); - String requestPath = Arrays.stream(ReferentielAdministrationImpactReseauRestApi.class.getMethod("add", ImpactReseauDTO.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - ImpactReseauDTO impactReseau = new ImpactReseauDTO(); - impactReseau.setRefReseau(refReseau); - impactReseau.setEtapeACV(etapeACV); - impactReseau.setCritere(critere); - impactReseau.setSource(source); - impactReseau.setValeur(Double.valueOf(valeur)); - Response response = given() - .contentType(ContentType.JSON) - .body(impactReseau) - .post(requestPath) - .thenReturn(); - assertEquals(200, response.getStatusCode()); - ImpactReseauDTO impactReseauResultat = response.as(ImpactReseauDTO.class); - //verification de la sortie - assertEquals(refReseau, impactReseauResultat.getRefReseau()); - assertEquals(refReseau, impactReseauResultat.getRefReseau()); - assertEquals(source, impactReseauResultat.getSource()); - assertEquals(critere, impactReseauResultat.getCritere()); - assertEquals(etapeACV, impactReseauResultat.getEtapeACV()); - assertEquals(Double.valueOf(valeur), impactReseauResultat.getValeur()); - log.debug("Debut creation d'un impact reseau dans table ref_impactReseau"); - } - - @Alors("impact reseau est persister dans la table ref_impactReseau avec les elements suivants: la refReseau est {string}, etapeACV est {string} , critere est {string} la source est {string} la valeur est {string} et l'unité est {string}") - public void impactReseauEstPersisterDansLaTableRef_impactReseau(String refReseau, String etapeACV, String critere, String source, String valeur, String unite) throws ReferentielException, NoSuchMethodException { - log.debug("Debut recuperation depuis table ref_impactReseau pour verification de la CAF1"); - //check avec la ressource get - //invocation de la ressource restapi ajout impact reseau - String requestPath = Arrays.stream(ReferentielImpactReseauRestApi.class.getMethod("get", String.class, String.class, String.class) - .getAnnotation(GetMapping.class).path()).findFirst().orElse(null); - Response response = given() - .contentType(ContentType.JSON) - .queryParam("refReseau", refReseau) - .queryParam("etapeacv", etapeACV) - .queryParam("critere", critere) - .get(requestPath) - .thenReturn(); - assertEquals(200, response.getStatusCode()); - ImpactReseauDTO impactReseauResultat = response.as(ImpactReseauDTO.class); - //verification de la sortie - assertEquals(refReseau, impactReseauResultat.getRefReseau()); - assertEquals(refReseau, impactReseauResultat.getRefReseau()); - assertEquals(source, impactReseauResultat.getSource()); - assertEquals(critere, impactReseauResultat.getCritere()); - assertEquals(etapeACV, impactReseauResultat.getEtapeACV()); - assertEquals(Double.valueOf(valeur), impactReseauResultat.getValeur()); - log.debug("END recuperation depuis table ref_impactReseau pour verification de la CAF1"); - } - - @Quand("on persiste un facteur impact reseau dont la refReseau est {string}, etapeACV est {string} , critere est {string} la source est {string}") - public void onPersisteUnFacteurImpactReseauDontLaRefReseauEstEtapeACVEstCritereEstLaSourceEst(String refReseau, String etapeACV, String critere, String source) throws NoSuchMethodException, FileNotFoundException { - log.debug("Debut creation à vide dans table ref_impactReseau"); - //invoquation de la ressource restapi ajout impact reseau - setupRestAssured(); - String requestPath = Arrays.stream(ReferentielAdministrationImpactReseauRestApi.class.getMethod("add", ImpactReseauDTO.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - ImpactReseauDTO impactReseau = new ImpactReseauDTO(); - impactReseau.setRefReseau(refReseau); - impactReseau.setEtapeACV(etapeACV); - impactReseau.setCritere(critere); - impactReseau.setSource(source); - Response response = given() - .contentType(ContentType.JSON) - .body(impactReseau) - .post(requestPath) - .thenReturn(); - assertEquals(200, response.getStatusCode()); - ImpactReseauDTO impactReseauResultat = response.as(ImpactReseauDTO.class); - //verification de la sortie - assertEquals(refReseau, impactReseauResultat.getRefReseau()); - assertEquals(refReseau, impactReseauResultat.getRefReseau()); - assertEquals(source, impactReseauResultat.getSource()); - assertEquals(critere, impactReseauResultat.getCritere()); - assertEquals(etapeACV, impactReseauResultat.getEtapeACV()); - log.debug("Fin creation à vide dans table ref_impactReseau"); - } - - - @Alors("il est possible de modifier impact Reseau avec les élements suivants: le refReseau est {string}, etapeACV est {string} , critere est {string} la source est {string}, valeur est {string} et l'unité est {string}") - public void ilEstPossibleDeModifierImpactReseau(String refReseau, String etapeACV, String critere, String source, String valeur, String unite) throws ReferentielException, NoSuchMethodException { - log.debug("Debut modification impact reseau depuis table ref_impactReseau"); - //check avec REST API GeT - String requestPathGet = Arrays.stream(ReferentielImpactReseauRestApi.class.getMethod("get", String.class, String.class, String.class) - .getAnnotation(GetMapping.class).path()).findFirst().orElse(null); - Response responseGet = given() - .contentType(ContentType.JSON) - .queryParam("refReseau", refReseau) - .queryParam("etapeacv", etapeACV) - .queryParam("critere", critere) - .get(requestPathGet) - .thenReturn(); - assertEquals(200, responseGet.getStatusCode()); - ImpactReseauDTO impactReseauResultatGet = responseGet.as(ImpactReseauDTO.class); - //verification de la sortie - assertEquals(etapeACV, impactReseauResultatGet.getEtapeACV()); - assertEquals(refReseau, impactReseauResultatGet.getRefReseau()); - assertEquals(critere, impactReseauResultatGet.getCritere()); - assertEquals(source, impactReseauResultatGet.getSource()); - assertNull(impactReseauResultatGet.getConsoElecMoyenne()); - //upadate avec rest api update - //modification de l'impact vide - //setupRestAssured(); - String requestPathUpdate = Arrays.stream(ReferentielAdministrationImpactReseauRestApi.class.getMethod("update", ImpactReseauDTO.class) - .getAnnotation(PutMapping.class).path()).findFirst().orElse(null); - ImpactReseauDTO impactReseau = new ImpactReseauDTO(); - impactReseau.setRefReseau(refReseau); - impactReseau.setEtapeACV(etapeACV); - impactReseau.setCritere(critere); - impactReseau.setSource(source); - impactReseau.setValeur(Double.valueOf(valeur)); - Response response = given() - .contentType(ContentType.JSON) - .body(impactReseau) - .post(requestPathUpdate) - .thenReturn(); - assertEquals(200, response.getStatusCode()); - ImpactReseauDTO impactReseauResultatUpdate = response.as(ImpactReseauDTO.class); - //verification de la sortie - assertEquals(refReseau, impactReseauResultatUpdate.getRefReseau()); - assertEquals(refReseau, impactReseauResultatUpdate.getRefReseau()); - assertEquals(source, impactReseauResultatUpdate.getSource()); - assertEquals(critere, impactReseauResultatUpdate.getCritere()); - assertEquals(etapeACV, impactReseauResultatUpdate.getEtapeACV()); - assertEquals(Double.valueOf(valeur), impactReseauResultatUpdate.getValeur()); - log.debug("Fin modification impact reseau depuis table ref_impactReseau"); - } - - @Quand("on ajoute un facteur impact reseau dont la refReseau est {string}, etapeACV est {string} , critere est {string} la valeur est {string} et l'unité est {string}") - public void onAjouteUnFacteurImpactReseauDontLaRefReseau(String refReseau, String etapeACV, String critere, String valeur, String unite) throws NoSuchMethodException, FileNotFoundException { - log.debug("Debut creation impact reseau sans source dans table ref_impactReseau"); - //invoquation de la ressource restapi ajout impact reseau - setupRestAssured(); - String requestPath = Arrays.stream(ReferentielAdministrationImpactReseauRestApi.class.getMethod("add", ImpactReseauDTO.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - ImpactReseauDTO impactReseau = new ImpactReseauDTO(); - impactReseau.setRefReseau(refReseau); - impactReseau.setEtapeACV(etapeACV); - impactReseau.setCritere(critere); - impactReseau.setValeur(Double.valueOf(valeur)); - response = given() - .contentType(ContentType.JSON) - .body(impactReseau) - .post(requestPath) - .thenReturn(); - log.error("Fin creation impact reseau sans source dans table ref_impactReseau"); - } - - - @Alors("Impossible d ajouter l'impact réseau dans la table ref_impactreseau") - public void impossibleDAjouterLImpactReseauDansLaTableRef_impactreseau() { - assertEquals(500, response.getStatusCode()); - ErrorResponseDTO impactReseauResultat = response.as(ErrorResponseDTO.class); - //assertEquals("La source est obligatoire", impactReseauResultat.getMessage()); - assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, impactReseauResultat.getStatus()); - assertEquals(500, impactReseauResultat.getCode()); - assertNotNull(impactReseauResultat.getTimestamp()); - } - - @Quand("le fichier CSV {string} est envoyé") - public void leFichierCSVEstEnvoye(String fichier) throws IOException, NoSuchMethodException { - File file = ResourceUtils.getFile("classpath:" + fichier); - setupRestAssured(); - String requestPath = Arrays.stream(ReferentielAdministrationImpactReseauRestApi.class.getMethod("importCSV", MultipartFile.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - Response response = given() - .multiPart("file", file) - .post(requestPath) - .thenReturn(); - //check que le status est OK - assertEquals(200, response.getStatusCode()); - } - - @Alors("l impact reseau refReseal est {string}, etapeACV est {string} , critere est {string} la source est {string} la valeur est {string} et l'unité est {string} existe") - public void lImpactReseauRefResealEstE(String refReseau, String etapeACV, String critere, String source, String valeur, String unite) throws NoSuchMethodException { - //recuperataion d'un resultat ajouter - String requestPath = Arrays.stream(ReferentielImpactReseauRestApi.class.getMethod("get", String.class, String.class, String.class) - .getAnnotation(GetMapping.class).path()).findFirst().orElse(null); - Response response = given() - .contentType(ContentType.JSON) - .queryParam("refReseau", refReseau) - .queryParam("etapeacv", etapeACV) - .queryParam("critere", critere) - .get(requestPath) - .thenReturn(); - ImpactReseauDTO impactReseauDTO = response.as(ImpactReseauDTO.class); - assertEquals(200, response.getStatusCode()); - ImpactReseauDTO impactReseauResultat = response.as(ImpactReseauDTO.class); - //verification de la sortie aleatoire - assertEquals(refReseau, impactReseauResultat.getRefReseau()); - assertEquals(refReseau, impactReseauResultat.getRefReseau()); - assertEquals(source, impactReseauResultat.getSource()); - assertEquals(critere, impactReseauResultat.getCritere()); - assertEquals(etapeACV, impactReseauResultat.getEtapeACV()); - assertEquals(Double.valueOf(valeur), impactReseauResultat.getValeur()); - } - - - @Quand("on cherche l impact reseau dont la refReseau est {string}, etapeACV est {string} , critere est {string}") - public void onChercheLImpactReseauquinexistePAs(String refReseau, String etapeACV, String critere) throws NoSuchMethodException, FileNotFoundException { - setupRestAssured(); - String requestPath = Arrays.stream(ReferentielImpactReseauRestApi.class.getMethod("get", String.class, String.class, String.class) - .getAnnotation(GetMapping.class).path()).findFirst().orElse(null); - response = given() - .contentType(ContentType.JSON) - .queryParam("refReseau", refReseau) - .queryParam("etapeacv", etapeACV) - .queryParam("critere", critere) - .get(requestPath) - .thenReturn(); - } - - @Alors("lecture reponse impact resau n existe pas") - public void lectureReponseImpactResauNExistePas() { - assertEquals(404, response.getStatusCode()); - ErrorResponseDTO impactReseauResultat = response.as(ErrorResponseDTO.class); - assertEquals("Impact Réseau non trouvé", impactReseauResultat.getMessage()); - assertEquals(HttpStatus.NOT_FOUND, impactReseauResultat.getStatus()); - assertEquals(404, impactReseauResultat.getCode()); - assertNotNull(impactReseauResultat.getTimestamp()); - } - -} \ No newline at end of file diff --git a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/TypeEquipementStepDefinitions.java b/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/TypeEquipementStepDefinitions.java deleted file mode 100644 index a4f2ce2e4501796f68f0e7fd90d78598753d4bb4..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/java/org/mte/numecoeval/referentiel/steps/TypeEquipementStepDefinitions.java +++ /dev/null @@ -1,95 +0,0 @@ -package org.mte.numecoeval.referentiel.steps; - -import io.cucumber.java.DataTableType; -import io.cucumber.java.fr.Alors; -import io.cucumber.java.fr.Et; -import io.cucumber.java.fr.Quand; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; -import org.mte.numecoeval.referentiel.domain.model.TypeEquipement; -import org.mte.numecoeval.referentiel.infrastructure.jpa.adapter.TypeEquipementJpaAdapter; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.typeequipement.ReferentielAdministrationTypeEquipementRestApi; -import org.mte.numecoeval.referentiel.infrastructure.restapi.controller.typeequipement.ReferentielTypeEquipementRestApi; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.ResourceUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import static io.restassured.RestAssured.given; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -public class TypeEquipementStepDefinitions extends AbstractStepDefinitions { - - @Autowired - TypeEquipementJpaAdapter jpaAdapter; - - @DataTableType - public TypeEquipement typeEquipement(Map<String, String> entry) { - return TypeEquipement.builder() - .type(entry.get("type")) - .source(StringUtils.defaultString(entry.get("source"))) - .commentaire(StringUtils.defaultString(entry.get("commentaire"))) - .serveur(Boolean.parseBoolean(entry.get("serveur"))) - .refEquipementParDefaut(StringUtils.defaultString(entry.get("refEquipementParDefaut"))) - .dureeVieDefaut(NumberUtils.createDouble(entry.get("dureeVieDefaut"))) - .build(); - } - - @Quand("le fichier CSV des types d'équipements {string} est importé par API et la réponse est {int}") - public void importReferentielTypeEquipements(String nomFichier, int codeReponseHttpAttendu) throws FileNotFoundException, NoSuchMethodException { - setupRestAssured(); - initAlimentationEtapeEtCritere(); - File file = ResourceUtils.getFile("classpath:" + nomFichier); - String requestPath = Arrays.stream(ReferentielAdministrationTypeEquipementRestApi.class.getMethod("importCSV", MultipartFile.class) - .getAnnotation(PostMapping.class).path()).findFirst().orElse(null); - response = given() - .multiPart("file", file) - .post(requestPath) - .thenReturn(); - assertEquals(codeReponseHttpAttendu, response.getStatusCode()); - } - - @Et("La récupération de tous les types d'équipements renvoie {int} lignes") - public void getAllTypeEquipement(int nombreLignesAttendues) throws NoSuchMethodException { - List<TypeEquipement> typeEquipements = jpaAdapter.getAll(); - - assertEquals(nombreLignesAttendues, typeEquipements.size()); - } - - @Alors("Vérifications des types d'équipements disponibles") - public void checkImpactEquipements(List<TypeEquipement> dataTable) { - List<TypeEquipement> datasInDatabase = jpaAdapter.getAll(); - - assertEquals(dataTable.size(), datasInDatabase.size()); - dataTable.forEach(expected -> { - var dataInDatabase = datasInDatabase.stream().filter(data -> data.getType().equals(expected.getType())).findFirst().orElse(null); - assertNotNull(dataInDatabase, "Il existe un type d'équipement avec le type %s".formatted(expected.getType())); - - assertEquals(expected.getCommentaire(), dataInDatabase.getCommentaire(), "TypeEquipement %s : le commentaire ne matche pas".formatted(expected.getType())); - assertEquals(expected.getSource(), dataInDatabase.getSource(), "TypeEquipement %s : la source ne matche pas".formatted(expected.getType())); - assertEquals(expected.getDureeVieDefaut(), dataInDatabase.getDureeVieDefaut(), "TypeEquipement %s : la durée de vie par défaut ne matche pas".formatted(expected.getType())); - assertEquals(expected.getRefEquipementParDefaut(), dataInDatabase.getRefEquipementParDefaut(), "TypeEquipement %s : la référence d'équipement par défaut ne matche pas".formatted(expected.getType())); - assertEquals(expected.isServeur(), dataInDatabase.isServeur(), "TypeEquipement %s : le flag serveur ne matche pas".formatted(expected.getType())); - }); - } - - @Et("La récupération unitaire d\'un type équipement {string} répond {int}") - public void getTypeEquipementAndCheckHttpStatus(String type, int codeReponseHttpAttendu) throws NoSuchMethodException { - - String requestPath = Arrays.stream(ReferentielTypeEquipementRestApi.class.getMethod("getTypeEquipement", String.class) - .getAnnotation(GetMapping.class).path()).findFirst().orElse(null); - response = given() - .pathParam("type", type) - .get(requestPath) - .thenReturn(); - assertEquals(codeReponseHttpAttendu, response.getStatusCode()); - } -} diff --git a/services/api-referentiel/src/test/resources/csv/ref_Critere.csv b/services/api-referentiel/src/test/resources/csv/ref_Critere.csv deleted file mode 100644 index f275ab0ba74c6e521de749ae6d5d5df05cc18bf1..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/csv/ref_Critere.csv +++ /dev/null @@ -1,6 +0,0 @@ -nomCritere;description;unite -Changement climatique;;kg CO_{2} eq -Émissions de particules fines;;Diseaseincidence -Radiations ionisantes;;kBq U-235 eq -Acidification;;mol H^{+} eq -Épuisement des ressources naturelles (minérales et métaux);;kg Sb eq diff --git a/services/api-referentiel/src/test/resources/csv/ref_Hypothese.csv b/services/api-referentiel/src/test/resources/csv/ref_Hypothese.csv deleted file mode 100644 index a1a6b28614a66c174a8d3e58047a24c3dfa46a90..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/csv/ref_Hypothese.csv +++ /dev/null @@ -1,3 +0,0 @@ -cle;valeur;source -PUEPardDfault;1.6;expertise IJO -DureeVieServeurParDefaut;3;US 46 diff --git a/services/api-referentiel/src/test/resources/csv/ref_ImpactMessagerie.csv b/services/api-referentiel/src/test/resources/csv/ref_ImpactMessagerie.csv deleted file mode 100644 index 49e5fa58a87ab9acf3f85c96e16abd90794f6ccb..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/csv/ref_ImpactMessagerie.csv +++ /dev/null @@ -1,2 +0,0 @@ -critere;constanteCoefficientDirecteur;constanteOrdonneeOrigine;source -Changement climatique;0.0112;5.9606;"US #66" diff --git a/services/api-referentiel/src/test/resources/csv/ref_MixElectrique.csv b/services/api-referentiel/src/test/resources/csv/ref_MixElectrique.csv deleted file mode 100644 index 64eae19eeeb817b63528cc615b57e89323daf9d9..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/csv/ref_MixElectrique.csv +++ /dev/null @@ -1,21 +0,0 @@ -pays ;raccourcisAnglais;critere ;valeur ;source -France;FR ;Acidification ;0.913 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Changement climatique ;149 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Radiations ionisantes ;69.1 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Épuisement des ressources naturelles (minérales et métaux);0.00913 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Émissions de particules fines ;0.00000523 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Acidification ;0.05573787269904 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Changement climatique ;11.0082325332 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Radiations ionisantes ;0.02997901628064 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Épuisement des ressources naturelles (minérales et métaux);0.00000043143695751072003;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Émissions de particules fines ;0.0000003353284653936 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Acidification ;0.01120932 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Changement climatique ;1.9485359999999998 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Radiations ionisantes ;0.38956 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Épuisement des ressources naturelles (minérales et métaux);0.0009197928000000001 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Émissions de particules fines ;0.00043580159999999995 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Acidification ;0.0219 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Changement climatique ;1.46 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Radiations ionisantes ;0.166 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Épuisement des ressources naturelles (minérales et métaux);0.00000388 ;Ref_Base_donnee_reference_20480728.xlsx -France;FR ;Émissions de particules fines ;0.0000000775 ;Ref_Base_donnee_reference_20480728.xlsx diff --git a/services/api-referentiel/src/test/resources/csv/ref_etapeACV.csv b/services/api-referentiel/src/test/resources/csv/ref_etapeACV.csv deleted file mode 100644 index d9a41e0350f80cde95d53d8e4baf1e9c25c5f484..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/csv/ref_etapeACV.csv +++ /dev/null @@ -1,5 +0,0 @@ -code;libelle -FABRICATION;Fabrication -DISTRIBUTION;Distribution -UTILISATION;Utilisation -FIN_DE_VIE;Fin de vie \ No newline at end of file diff --git a/services/api-referentiel/src/test/resources/csv/ref_impactEquipement.csv b/services/api-referentiel/src/test/resources/csv/ref_impactEquipement.csv deleted file mode 100644 index 8d5c0e533d400fb63823ed266173e5955d0b1b23..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/csv/ref_impactEquipement.csv +++ /dev/null @@ -1,109 +0,0 @@ -refEquipement;etapeacv;critere;consoElecMoyenne;valeur;source;type -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";FABRICATION;Acidification;29.1;0.913;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";FABRICATION;Changement climatique;29.1;149;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";FABRICATION;Radiations ionisantes;29.1;69.1;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";FABRICATION;Épuisement des ressources naturelles (minérales et métaux);29.1;0.00913;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";FABRICATION;Émissions de particules fines;29.1;0.00000523;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";DISTRIBUTION;Acidification;29.1;0.05573787269904;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";DISTRIBUTION;Changement climatique;29.1;11.0082325332;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";DISTRIBUTION;Radiations ionisantes;29.1;0.02997901628064;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";DISTRIBUTION;Épuisement des ressources naturelles (minérales et métaux);29.1;0.00000043143695751072003;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";DISTRIBUTION;Émissions de particules fines;29.1;0.0000003353284653936;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";UTILISATION;Acidification;29.1;0.01120932;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";UTILISATION;Changement climatique;29.1;1.9485359999999998;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";UTILISATION;Radiations ionisantes;29.1;50.38956;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";UTILISATION;Épuisement des ressources naturelles (minérales et métaux);29.1;0.0000009197928000000001;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";UTILISATION;Émissions de particules fines;29.1;0.00000043580159999999995;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";FIN_DE_VIE;Acidification;29.1;0.0219;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";FIN_DE_VIE;Changement climatique;29.1;1.46;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";FIN_DE_VIE;Radiations ionisantes;29.1;0.166;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";FIN_DE_VIE;Épuisement des ressources naturelles (minérales et métaux);29.1;0.00000388;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 14.5 8 Go RAM 564 Go SSD";FIN_DE_VIE;Émissions de particules fines;29.1;0.0000000775;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";FABRICATION;Acidification;29.1;1.78;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";FABRICATION;Changement climatique;29.1;308;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";FABRICATION;Radiations ionisantes;29.1;98.1;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";FABRICATION;Épuisement des ressources naturelles (minérales et métaux);29.1;0.012;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";FABRICATION;Émissions de particules fines;29.1;0.0000101;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";DISTRIBUTION;Acidification;29.1;0.09322822755018001;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";DISTRIBUTION;Changement climatique;29.1;18.41257941565;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";DISTRIBUTION;Radiations ionisantes;29.1;0.050143473659880006;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";DISTRIBUTION;Épuisement des ressources naturelles (minérales et métaux);29.1;0.00000072162967297924;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";DISTRIBUTION;Émissions de particules fines;29.1;0.0000005608767784262;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";UTILISATION;Acidification;29.1;0.01120932;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";UTILISATION;Changement climatique;29.1;1.9485359999999998;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";UTILISATION;Radiations ionisantes;29.1;50.38956;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";UTILISATION;Épuisement des ressources naturelles (minérales et métaux);29.1;0.0000009197928000000001;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";UTILISATION;Émissions de particules fines;29.1;0.00000043580159999999995;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";FIN_DE_VIE;Acidification;29.1;0.0222;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";FIN_DE_VIE;Changement climatique;29.1;1.48;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";FIN_DE_VIE;Radiations ionisantes;29.1;0.187;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";FIN_DE_VIE;Épuisement des ressources naturelles (minérales et métaux);29.1;0.00000383;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur portable 15.6 16 Go RAM 512 Go SSD carte graphique";FIN_DE_VIE;Émissions de particules fines;29.1;0.0000000774;Ref_Base_donnee_reference_20220728.xlsx; -"Tablette 11.1 6 Go RAM 512 Go SSD";DISTRIBUTION;Épuisement des ressources naturelles (minérales et métaux);18.6;0.00000016364437964909999;Ref_Base_donnee_reference_20220728.xlsx; -"Tablette 11.1 6 Go RAM 512 Go SSD";DISTRIBUTION;Émissions de particules fines;18.6;0.00000013479328674935998;Ref_Base_donnee_reference_20220728.xlsx; -"Tablette 11.1 6 Go RAM 512 Go SSD";UTILISATION;Acidification;18.6;0.00716472;Ref_Base_donnee_reference_20220728.xlsx; -"Tablette 11.1 6 Go RAM 512 Go SSD";UTILISATION;Changement climatique;18.6;1.245456;Ref_Base_donnee_reference_20220728.xlsx; -"Tablette 11.1 6 Go RAM 512 Go SSD";UTILISATION;Radiations ionisantes;18.6;32.20776;Ref_Base_donnee_reference_20220728.xlsx; -"Tablette 11.1 6 Go RAM 512 Go SSD";UTILISATION;Épuisement des ressources naturelles (minérales et métaux);18.6;0.0000005879088000000001;Ref_Base_donnee_reference_20220728.xlsx; -"Tablette 11.1 6 Go RAM 512 Go SSD";UTILISATION;Émissions de particules fines;18.6;0.0000002785536;Ref_Base_donnee_reference_20220728.xlsx; -"Tablette 11.1 6 Go RAM 512 Go SSD";FIN_DE_VIE;Acidification;18.6;0.00498;Ref_Base_donnee_reference_20220728.xlsx; -"Tablette 11.1 6 Go RAM 512 Go SSD";FIN_DE_VIE;Changement climatique;18.6;0.404;Ref_Base_donnee_reference_20220728.xlsx; -"Tablette 11.1 6 Go RAM 512 Go SSD";FIN_DE_VIE;Radiations ionisantes;18.6;0.0736;Ref_Base_donnee_reference_20220728.xlsx; -"Tablette 11.1 6 Go RAM 512 Go SSD";FIN_DE_VIE;Épuisement des ressources naturelles (minérales et métaux);18.6;0.00000019;Ref_Base_donnee_reference_20220728.xlsx; -"Tablette 11.1 6 Go RAM 512 Go SSD";FIN_DE_VIE;Émissions de particules fines;18.6;0.0000000176;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";FABRICATION;Acidification;3.9;0.268;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";FABRICATION;Changement climatique;3.9;44.1;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";FABRICATION;Radiations ionisantes;3.9;12.2;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";FABRICATION;Épuisement des ressources naturelles (minérales et métaux);3.9;0.00263;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";FABRICATION;Émissions de particules fines;3.9;0.00000151;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";DISTRIBUTION;Acidification;3.9;0.008213194002682;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";DISTRIBUTION;Changement climatique;3.9;1.5308100265771998;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";DISTRIBUTION;Radiations ionisantes;3.9;0.010082124523881202;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";DISTRIBUTION;Épuisement des ressources naturelles (minérales et métaux);3.9;0.000000059421842323899996;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";DISTRIBUTION;Émissions de particules fines;3.9;0.00000004894555773144;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";UTILISATION;Acidification;3.9;0.00150228;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";UTILISATION;Changement climatique;3.9;0.261144;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";UTILISATION;Radiations ionisantes;3.9;6.75324;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";UTILISATION;Épuisement des ressources naturelles (minérales et métaux);3.9;0.0000001232712;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";UTILISATION;Émissions de particules fines;3.9;0.00000005840639999999999;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";FIN_DE_VIE;Acidification;3.9;0.00428;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";FIN_DE_VIE;Changement climatique;3.9;0.244;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";FIN_DE_VIE;Radiations ionisantes;3.9;0.039;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";FIN_DE_VIE;Épuisement des ressources naturelles (minérales et métaux);3.9;0.000000123;Ref_Base_donnee_reference_20220728.xlsx; -"Smartphone 6.72 OLED 11 Go RAM 341 Go SSD";FIN_DE_VIE;Émissions de particules fines;3.9;0.0000000118;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";FABRICATION;Acidification;100;1.87;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";FABRICATION;Changement climatique;100;289;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";FABRICATION;Radiations ionisantes;100;1330;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";FABRICATION;Épuisement des ressources naturelles (minérales et métaux);100;0.0279;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";FABRICATION;Émissions de particules fines;100;0.0000108;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";DISTRIBUTION;Acidification;100;0.11085933300800001;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";DISTRIBUTION;Changement climatique;100;3.1848028296;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";DISTRIBUTION;Radiations ionisantes;100;0.0065306696856;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";DISTRIBUTION;Épuisement des ressources naturelles (minérales et métaux);100;0.00000011291803934400001;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";DISTRIBUTION;Émissions de particules fines;100;0.0000005823743571200001;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";UTILISATION;Acidification;100;0.03852;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";UTILISATION;Changement climatique;100;6.695999999999999;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";UTILISATION;Radiations ionisantes;100;173.16;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";UTILISATION;Épuisement des ressources naturelles (minérales et métaux);100;0.0000031608000000000003;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";UTILISATION;Émissions de particules fines;100;0.0000014975999999999999;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";FIN_DE_VIE;Acidification;100;0.0966;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";FIN_DE_VIE;Changement climatique;100;6.61;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";FIN_DE_VIE;Radiations ionisantes;100;0.625;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";FIN_DE_VIE;Épuisement des ressources naturelles (minérales et métaux);100;0.0000135;Ref_Base_donnee_reference_20220728.xlsx; -"Ordinateur fixe (sans écran) 8 Go RAM 250 Go SSD 1 000 Go HDD carte graphique";FIN_DE_VIE;Émissions de particules fines;100;0.000000363;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";FABRICATION;Acidification;70;0.394;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";FABRICATION;Changement climatique;70;59;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";FABRICATION;Radiations ionisantes;70;143;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";FABRICATION;Épuisement des ressources naturelles (minérales et métaux);70;0.0117;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";FABRICATION;Émissions de particules fines;70;0.00000247;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";DISTRIBUTION;Acidification;70;0.044321516904000005;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";DISTRIBUTION;Changement climatique;70;1.2732828948000001;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";DISTRIBUTION;Radiations ionisantes;70;0.0026109591228;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";DISTRIBUTION;Épuisement des ressources naturelles (minérales et métaux);70;0.000000045144586872;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";DISTRIBUTION;Émissions de particules fines;70;0.00000023283303456000003;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";UTILISATION;Acidification;70;0.026964;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";UTILISATION;Changement climatique;70;4.6872;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";UTILISATION;Radiations ionisantes;70;121.212;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";UTILISATION;Épuisement des ressources naturelles (minérales et métaux);70;0.00000221256;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";FIN_DE_VIE;Épuisement des ressources naturelles (minérales et métaux);70;0.000012;Ref_Base_donnee_reference_20220728.xlsx; -"Ecran d'ordinateur LCD 24";FIN_DE_VIE;Émissions de particules fines;70;0.000000149;Ref_Base_donnee_reference_20220728.xlsx; diff --git a/services/api-referentiel/src/test/resources/csv/ref_impactreseau.csv b/services/api-referentiel/src/test/resources/csv/ref_impactreseau.csv deleted file mode 100644 index e8e363c6c311fc900ebfbe7b94e32b9c00dc470a..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/csv/ref_impactreseau.csv +++ /dev/null @@ -1,101 +0,0 @@ -refReseau;etapeACV;critere;valeur;unite;consoElecMoyenne;source -impactReseauMobileMoyen;DISTRIBUTION;Acidification;138.28;;;RefTest V1.00 -impactReseauMobileMoyen;FABRICATION;Acidification;148.28;;;RefTest V1.00 -impactReseauMobileMoyen;FIN_DE_VIE;Acidification;1.28;;;RefTest V1.00 -impactReseauMobileMoyen;UTILISATION;Acidification;18.8;;;RefTest V1.00 -impactReseauMobileMoyen;DISTRIBUTION;Changement climatique;1.428;;;RefTest V1.00 -impactReseauMobileMoyen;FABRICATION;Changement climatique;518.28;;;RefTest V1.00 -impactReseauMobileMoyen;FIN_DE_VIE;Changement climatique;64.28;;;RefTest V1.00 -impactReseauMobileMoyen;UTILISATION;Changement climatique;76.28;;;RefTest V1.00 -impactReseauMobileMoyen;DISTRIBUTION;Épuisement des ressources naturelles (minérales et métaux);78.28;;;RefTest V1.00 -impactReseauMobileMoyen;FABRICATION;Épuisement des ressources naturelles (minérales et métaux);87.28;;;RefTest V1.00 -impactReseauMobileMoyen;FIN_DE_VIE;Épuisement des ressources naturelles (minérales et métaux);54.28;;;RefTest V1.00 -impactReseauMobileMoyen;UTILISATION;Épuisement des ressources naturelles (minérales et métaux);34.76;;;RefTest V1.00 -impactReseauMobileMoyen;DISTRIBUTION;Radiations ionisantes;138.28;;;RefTest V1.00 -impactReseauMobileMoyen;FABRICATION;Radiations ionisantes;148.28;;;RefTest V1.00 -impactReseauMobileMoyen;FIN_DE_VIE;Radiations ionisantes;1.28;;;RefTest V1.00 -impactReseauMobileMoyen;UTILISATION;Radiations ionisantes;18.8;;;RefTest V1.00 -impactReseauMobileMoyen;DISTRIBUTION;Émissions de particules fines;138.28;;;RefTest V1.00 -impactReseauMobileMoyen;FABRICATION;Émissions de particules fines;148.28;;;RefTest V1.00 -impactReseauMobileMoyen;FIN_DE_VIE;Émissions de particules fines;1.28;;;RefTest V1.00 -impactReseauMobileMoyen;UTILISATION;Émissions de particules fines;18.8;;;RefTest V1.00 -impactReseauMobileFRANCE;DISTRIBUTION;Acidification;138.28;;;RefTest V1.00 -impactReseauMobileFRANCE;FABRICATION;Acidification;148.28;;;RefTest V1.00 -impactReseauMobileFRANCE;FIN_DE_VIE;Acidification;1.28;;;RefTest V1.00 -impactReseauMobileFRANCE;UTILISATION;Acidification;18.8;;;RefTest V1.00 -impactReseauMobileFRANCE;DISTRIBUTION;Changement climatique;1.428;;;RefTest V1.00 -impactReseauMobileFRANCE;FABRICATION;Changement climatique;518.28;;;RefTest V1.00 -impactReseauMobileFRANCE;FIN_DE_VIE;Changement climatique;64.28;;;RefTest V1.00 -impactReseauMobileFRANCE;UTILISATION;Changement climatique;76.28;;;RefTest V1.00 -impactReseauMobileFRANCE;DISTRIBUTION;Épuisement des ressources naturelles (minérales et métaux);78.28;;;RefTest V1.00 -impactReseauMobileFRANCE;FABRICATION;Épuisement des ressources naturelles (minérales et métaux);87.28;;;RefTest V1.00 -impactReseauMobileFRANCE;FIN_DE_VIE;Épuisement des ressources naturelles (minérales et métaux);54.28;;;RefTest V1.00 -impactReseauMobileFRANCE;UTILISATION;Épuisement des ressources naturelles (minérales et métaux);34.76;;;RefTest V1.00 -impactReseauMobileFRANCE;DISTRIBUTION;Radiations ionisantes;138.28;;;RefTest V1.00 -impactReseauMobileFRANCE;FABRICATION;Radiations ionisantes;148.28;;;RefTest V1.00 -impactReseauMobileFRANCE;FIN_DE_VIE;Radiations ionisantes;1.28;;;RefTest V1.00 -impactReseauMobileFRANCE;UTILISATION;Radiations ionisantes;18.8;;;RefTest V1.00 -impactReseauMobileFRANCE;DISTRIBUTION;Émissions de particules fines;138.28;;;RefTest V1.00 -impactReseauMobileFRANCE;FABRICATION;Émissions de particules fines;148.28;;;RefTest V1.00 -impactReseauMobileFRANCE;FIN_DE_VIE;Émissions de particules fines;1.28;;;RefTest V1.00 -impactReseauMobileFRANCE;UTILISATION;Émissions de particules fines;18.8;;;RefTest V1.00 -impactReseauMobile4G;DISTRIBUTION;Acidification;138.28;;;RefTest V1.00 -impactReseauMobile4G;FABRICATION;Acidification;148.28;;;RefTest V1.00 -impactReseauMobile4G;FIN_DE_VIE;Acidification;1.28;;;RefTest V1.00 -impactReseauMobile4G;UTILISATION;Acidification;18.8;;;RefTest V1.00 -impactReseauMobile4G;DISTRIBUTION;Changement climatique;1.428;;;RefTest V1.00 -impactReseauMobile4G;FABRICATION;Changement climatique;518.28;;;RefTest V1.00 -impactReseauMobile4G;FIN_DE_VIE;Changement climatique;64.28;;;RefTest V1.00 -impactReseauMobile4G;UTILISATION;Changement climatique;76.28;;;RefTest V1.00 -impactReseauMobile4G;DISTRIBUTION;Épuisement des ressources naturelles (minérales et métaux);78.28;;;RefTest V1.00 -impactReseauMobile4G;FABRICATION;Épuisement des ressources naturelles (minérales et métaux);87.28;;;RefTest V1.00 -impactReseauMobile4G;FIN_DE_VIE;Épuisement des ressources naturelles (minérales et métaux);54.28;;;RefTest V1.00 -impactReseauMobile4G;UTILISATION;Épuisement des ressources naturelles (minérales et métaux);34.76;;;RefTest V1.00 -impactReseauMobile4G;DISTRIBUTION;Radiations ionisantes;138.28;;;RefTest V1.00 -impactReseauMobile4G;FABRICATION;Radiations ionisantes;148.28;;;RefTest V1.00 -impactReseauMobile4G;FIN_DE_VIE;Radiations ionisantes;1.28;;;RefTest V1.00 -impactReseauMobile4G;UTILISATION;Radiations ionisantes;18.8;;;RefTest V1.00 -impactReseauMobile4G;DISTRIBUTION;Émissions de particules fines;138.28;;;RefTest V1.00 -impactReseauMobile4G;FABRICATION;Émissions de particules fines;148.28;;;RefTest V1.00 -impactReseauMobile4G;FIN_DE_VIE;Émissions de particules fines;1.28;;;RefTest V1.00 -impactReseauMobile4G;UTILISATION;Émissions de particules fines;18.8;;;RefTest V1.00 -impactReseauMobile5G;DISTRIBUTION;Acidification;138.28;;;RefTest V1.00 -impactReseauMobile5G;FABRICATION;Acidification;148.28;;;RefTest V1.00 -impactReseauMobile5G;FIN_DE_VIE;Acidification;1.28;;;RefTest V1.00 -impactReseauMobile5G;UTILISATION;Acidification;18.8;;;RefTest V1.00 -impactReseauMobile5G;DISTRIBUTION;Changement climatique;1.428;;;RefTest V1.00 -impactReseauMobile5G;FABRICATION;Changement climatique;518.28;;;RefTest V1.00 -impactReseauMobile5G;FIN_DE_VIE;Changement climatique;64.28;;;RefTest V1.00 -impactReseauMobile5G;UTILISATION;Changement climatique;76.28;;;RefTest V1.00 -impactReseauMobile5G;DISTRIBUTION;Épuisement des ressources naturelles (minérales et métaux);78.28;;;RefTest V1.00 -impactReseauMobile5G;FABRICATION;Épuisement des ressources naturelles (minérales et métaux);87.28;;;RefTest V1.00 -impactReseauMobile5G;FIN_DE_VIE;Épuisement des ressources naturelles (minérales et métaux);54.28;;;RefTest V1.00 -impactReseauMobile5G;UTILISATION;Épuisement des ressources naturelles (minérales et métaux);34.76;;;RefTest V1.00 -impactReseauMobile5G;DISTRIBUTION;Radiations ionisantes;138.28;;;RefTest V1.00 -impactReseauMobile5G;FABRICATION;Radiations ionisantes;148.28;;;RefTest V1.00 -impactReseauMobile5G;FIN_DE_VIE;Radiations ionisantes;1.28;;;RefTest V1.00 -impactReseauMobile5G;UTILISATION;Radiations ionisantes;18.8;;;RefTest V1.00 -impactReseauMobile5G;DISTRIBUTION;Émissions de particules fines;138.28;;;RefTest V1.00 -impactReseauMobile5G;FABRICATION;Émissions de particules fines;148.28;;;RefTest V1.00 -impactReseauMobile5G;FIN_DE_VIE;Émissions de particules fines;1.28;;;RefTest V1.00 -impactReseauMobile5G;UTILISATION;Émissions de particules fines;18.8;;;RefTest V1.00 -impactReseauMobile2G;DISTRIBUTION;Acidification;138.28;;;RefTest V1.00 -impactReseauMobile2G;FABRICATION;Acidification;148.28;;;RefTest V1.00 -impactReseauMobile2G;FIN_DE_VIE;Acidification;1.28;;;RefTest V1.00 -impactReseauMobile2G;UTILISATION;Acidification;18.8;;;RefTest V1.00 -impactReseauMobile2G;DISTRIBUTION;Changement climatique;1.428;;;RefTest V1.00 -impactReseauMobile2G;FABRICATION;Changement climatique;518.28;;;RefTest V1.00 -impactReseauMobile2G;FIN_DE_VIE;Changement climatique;64.28;;;RefTest V1.00 -impactReseauMobile2G;UTILISATION;Changement climatique;76.28;;;RefTest V1.00 -impactReseauMobile2G;DISTRIBUTION;Épuisement des ressources naturelles (minérales et métaux);78.28;;;RefTest V1.00 -impactReseauMobile2G;FABRICATION;Épuisement des ressources naturelles (minérales et métaux);87.28;;;RefTest V1.00 -impactReseauMobile2G;FIN_DE_VIE;Épuisement des ressources naturelles (minérales et métaux);54.28;;;RefTest V1.00 -impactReseauMobile2G;UTILISATION;Épuisement des ressources naturelles (minérales et métaux);34.76;;;RefTest V1.00 -impactReseauMobile2G;DISTRIBUTION;Radiations ionisantes;138.28;;;RefTest V1.00 -impactReseauMobile2G;FABRICATION;Radiations ionisantes;148.28;;;RefTest V1.00 -impactReseauMobile2G;FIN_DE_VIE;Radiations ionisantes;1.28;;;RefTest V1.00 -impactReseauMobile2G;UTILISATION;Radiations ionisantes;18.8;;;RefTest V1.00 -impactReseauMobile2G;DISTRIBUTION;Émissions de particules fines;138.28;;;RefTest V1.00 -impactReseauMobile2G;FABRICATION;Émissions de particules fines;148.28;;;RefTest V1.00 -impactReseauMobile2G;FIN_DE_VIE;Émissions de particules fines;1.28;;;RefTest V1.00 - diff --git a/services/api-referentiel/src/test/resources/csv/sprint10/ref_CorrespondanceRefEquipement.csv b/services/api-referentiel/src/test/resources/csv/sprint10/ref_CorrespondanceRefEquipement.csv deleted file mode 100644 index c16f1e6f5ddc30a51faf623d85ba40f489e72abb..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/csv/sprint10/ref_CorrespondanceRefEquipement.csv +++ /dev/null @@ -1,4 +0,0 @@ -modeleEquipementSource;refEquipementCible -Fairphone V1;smartphone01 -Fairphone V2;smartphone01 -Ecran 27 pouces;ecran01 \ No newline at end of file diff --git a/services/api-referentiel/src/test/resources/csv/sprint10/ref_ImpactEquipement.csv b/services/api-referentiel/src/test/resources/csv/sprint10/ref_ImpactEquipement.csv deleted file mode 100644 index 13f505c0712f68a675b8f1a00255cc516b0619d4..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/csv/sprint10/ref_ImpactEquipement.csv +++ /dev/null @@ -1,7 +0,0 @@ -refEquipement;etapeacv;critere;consoElecMoyenne;valeur;source;type;description -"computer monitor-01-23";FIN_DE_VIE;Acidification;35.81692801813716;0.020296259210277726;reftest_20221013;computer monitor;Description Impact Equipement computer monitor -"digital price tag - power unit-01";FABRICATION;Radiations ionisantes;;5.89E+01;reftest_20221013;digital price tag - power unit;Description Impact Equipement digital price tag - power unit -"docking station-01";FABRICATION;Radiations ionisantes;1.28;3.50E+01;reftest_20221013;docking station;Description Impact Equipement docking station -"empty 42u bay-01";FABRICATION;Radiations ionisantes;;5.87E+01;reftest_20221013;empty 42u bay;Description Impact Equipement empty 42u bay -"feature phone-01";FABRICATION;Radiations ionisantes;0.09;5.11E+00;reftest_20221013;feature phone;Description Impact Equipement feature phone -"firewall-01";FABRICATION;Radiations ionisantes;876;2.65E+02;reftest_20221013;firewall;Description Impact Equipement firewall diff --git a/services/api-referentiel/src/test/resources/csv/sprint10/ref_TypeEquipement.csv b/services/api-referentiel/src/test/resources/csv/sprint10/ref_TypeEquipement.csv deleted file mode 100644 index f5d8fc3e97e0a5a9736915d8026507766bee8c67..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/csv/sprint10/ref_TypeEquipement.csv +++ /dev/null @@ -1,18 +0,0 @@ -type;serveur;commentaire;dureeVieDefaut;refEquipementParDefaut;source -ServeurCalcul;true;commentaires;6;serveur_par_defaut;Test -ServeurStockage;true;;6;serveur_par_defaut;Test -Armoire;false;;7;armoir_par_defaut;Test -NAS;false;;6;baie_stockage_par_defaut;Test -Switch;false;;6;switch_par_defaut;Test -OrdinateurPortable;false;;4;laptop_par_defaut;Test -OrdinateurDeBureau;false;;5;desktop_par_defaut;Test -Tablette;false;;2.5;tablette_par_defaut;Test -TelephoneMobile;false;commentaires;2.5;smartphone_par_defaut;Test -TelephoneFixe;false;;10;telephone_fixe_par_defaut;Test -EquipementReseau;false;commentaires;5;switch_par_defaut;Test -BorneWifi;false;;4;borneWifi_par_defaut;Test -Imprimante;false;;5;imprimante_par_defaut;Test -Ecran;false;;8;ecran_par_defaut;Test -AccessoirePosteDeTravail;false;souris calvier, camera casque;7;stationTravail_par_defaut;Test -Connectique;false;;7;;Test -Autre;false;;2;;Test diff --git a/services/api-referentiel/src/test/resources/csv/unit/facteurCaracterisation.csv b/services/api-referentiel/src/test/resources/csv/unit/facteurCaracterisation.csv new file mode 100644 index 0000000000000000000000000000000000000000..e9611bb43993df1da7a6ae5e307cece533f7b53e --- /dev/null +++ b/services/api-referentiel/src/test/resources/csv/unit/facteurCaracterisation.csv @@ -0,0 +1,6 @@ +nom;etapeacv;critere;description;niveau;tiers;categorie;consoElecMoyenne;localisation;valeur;unite;source +Electricity Mix/ Production mix/ Low voltage/ FR;FABRICATION;Changement climatique;;0-Base data;;electricity-mix;;France;0.0813225;kWh;BaseImpact +Laptop;DISTRIBUTION;Ressources use, minerals and metals;HP;2-Equipement;End-user/Terminals;Consultation;0.4;Allemagne;0.000882;Item;NegaOctet +Blade server;DISTRIBUTION;Climate change;;2-Equipement;Datacenter;IT equipment;0.4;Allemagne;0.0092;Item;NegaOctet +Mobile network;FABRICATION;Climate change;;3-System;Network;;0.8;;0.00000159;GB;NegaOctet + diff --git a/services/api-referentiel/src/test/resources/csv/unit/facteurCaracterisation_errorInMiddle.csv b/services/api-referentiel/src/test/resources/csv/unit/facteurCaracterisation_errorInMiddle.csv new file mode 100644 index 0000000000000000000000000000000000000000..a98bd5aa438cc6e1d384b3c532a8ce47e38f277a --- /dev/null +++ b/services/api-referentiel/src/test/resources/csv/unit/facteurCaracterisation_errorInMiddle.csv @@ -0,0 +1,9 @@ +nom;etapeacv;critere;description;niveau;tiers;categorie;consoElecMoyenne;localisation;valeur;unite;source +Electricity Mix/ Production mix/ Low voltage/ FR;FABRICATION;Changement climatique;;0-Base data;;electricity-mix;;France;0.0813225;kWh;BaseImpact +Laptop;DISTRIBUTION;Ressources use, minerals and metals;HP;2-Equipement;End-user/Terminals;Consultation;0.4;Allemagne;0.000882;Item;NegaOctet +;SansRefEquipement;Critère inconnu;;;;;;;;; +SansEtape;;Critère inconnu;;;;;;;;; +SansCritere;SansCritere;;;;;;;;;; +Blade server;DISTRIBUTION;Climate change;;2-Equipement;Datacenter;IT equipment;0.4;Allemagne;0.0092;Item;NegaOctet +Mobile network;FABRICATION;Climate change;;3-System;Network;;0.8;;0.00000159;GB;NegaOctet + diff --git a/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_criteres.feature b/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_criteres.feature deleted file mode 100644 index afab48b85b94f1069409450e440e5d719b556fd8..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_criteres.feature +++ /dev/null @@ -1,17 +0,0 @@ -#language: fr -#encoding: utf-8 - -Fonctionnalité: Gestion du referentiel DES CRITERES - Le but étant de rendre disponible le référentiel referentiel CRITERES afin de rendre possible - les calculs d'impacts environnementaux sur les équipements - - - Scénario: CAF1: alimentation en masse du referentiel CRITERES depuis un ficher csv - Quand le fichier CSV "csv/ref_Critere.csv" est inject - Alors Il existe 5 elements dans le referentiel critere - Et chacun des elements du referential ajouté est identique au element du fichier csv - - - - - diff --git a/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_etape_acv.feature b/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_etape_acv.feature deleted file mode 100644 index 2addaecdb5b021d88d49f960acb9fba2551043e4..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_etape_acv.feature +++ /dev/null @@ -1,16 +0,0 @@ -#language: fr -#encoding: utf-8 -Fonctionnalité: Gestion du referentiel ETAPE ACV - Le but étant de rendre disponible le référentiel referentiel ETAPE ACV afin de rendre possible - les calculs d'impacts environnementaux sur les équipements - - - Scénario: CAF1: alimentation en masse du referentiel etape acv depuis un ficher csv - Quand le fichier CSV "csv/ref_etapeACV.csv" est injecte - Alors Il existe 4 elements dans le referentiel Etape ACV - Et chacun des elements du referentiel ajouté est identique au element du fichier csv - - - - - diff --git a/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_facteurs_impact_reseau.feature b/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_facteurs_impact_reseau.feature deleted file mode 100644 index d567c0bd1a16605d168526bab6229befabc1f3df..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_facteurs_impact_reseau.feature +++ /dev/null @@ -1,31 +0,0 @@ -#language: fr -#encoding: utf-8 -Fonctionnalité: Gestion du referentiel impact reseau - Le but étant de rendre disponible le référentiel refImpactReseau afin de rendre possible - les calculs d'impacts environnementaux sur les équipements - - - Scénario: CAF1: Ajouter un facteur impact lié au reseau dans la table ref_impactReseau - Quand on ajoute un facteur impact reseau dont la refReseau est "impactReseauMobileMoyen", etapeACV est "UTILISATION" , critere est "Acidification" la source est "RefTest V1.00" la valeur est "8.28" et l'unité est "mol H^{+} eq" - Alors impact reseau est persister dans la table ref_impactReseau avec les elements suivants: la refReseau est "impactReseauMobileMoyen", etapeACV est "UTILISATION" , critere est "Acidification" la source est "RefTest V1.00" la valeur est "8.28" et l'unité est "mol H^{+} eq" - - - Scénario: CAF2: Ajouter un facteur impact lié au reseau dans la table ref_impactReseau sans unité ni valeur et modification des valeurs unite et valeur de l'impact reseau ajouté - Quand on persiste un facteur impact reseau dont la refReseau est "impactReseauMobileFRANCE", etapeACV est "FABRICATION" , critere est "Radiations ionisantes" la source est "RefTest V1.00" - Alors il est possible de modifier impact Reseau avec les élements suivants: le refReseau est "impactReseauMobileFRANCE", etapeACV est "FABRICATION" , critere est "Radiations ionisantes" la source est "RefTest V1.00", valeur est "10" et l'unité est "kBq U-235 eq" - - Scénario: CAF3: interdir l'ajout d'un facteur impact lié au reseau dans la table ref_impactReseau sans source - Quand on ajoute un facteur impact reseau dont la refReseau est "impactReseauMobileMoyenSansSource", etapeACV est "UTILISATION" , critere est "Changement Climatique" la valeur est "8.28" et l'unité est "CO2 eq / an" - Alors Impossible d ajouter l'impact réseau dans la table ref_impactreseau - - Scénario: CAF4: alimentation en masse du referentiel impact reseau depuis un ficher csv - Quand le fichier CSV "csv/ref_impactreseau.csv" est envoyé - Alors l impact reseau refReseal est "impactReseauMobile2G", etapeACV est "UTILISATION" , critere est "Radiations ionisantes" la source est "RefTest V1.00" la valeur est "18.8" et l'unité est "kBq U-235 eq" existe - - - Scénario: CAF5: impact reseau qui n'existe pas - Quand on cherche l impact reseau dont la refReseau est "nexistepas", etapeACV est "nexistepas" , critere est "nexistepas" - Alors lecture reponse impact resau n existe pas - - - diff --git a/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_hypothese.feature b/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_hypothese.feature deleted file mode 100644 index 4a29f7174acb57cd6e455d7812f60b35c2fb5ba1..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_hypothese.feature +++ /dev/null @@ -1,19 +0,0 @@ -#language: fr -#encoding: utf-8 -Fonctionnalité: Gestion du referentiel DES HYPOTHESES - Le but étant de rendre disponible le référentiel referentiel DES HYPOTHESES afin de rendre possible - les calculs d'impacts environnementaux sur les équipements - - - Scénario: CAF1: alimentation en masse du referentiel DES HYPOTHESES depuis un ficher csv - Quand le fichier CSV REF HYPOTHESE"csv/ref_Hypothese.csv" est inject - Alors le statut http est 200 - - - Scénario: CAF2: recherche d'une hypothese - Quand lors de la recherche de hypothese avec la cle "PUEPardDfault" - Alors Le resultat est : cle = "PUEPardDfault" valeur="1.6" et source="expertise IJO" - - - - diff --git a/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_impact_equipement.feature b/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_impact_equipement.feature deleted file mode 100644 index 4b6a862aff1b5c0f77012836479448bf2fff85e5..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_impact_equipement.feature +++ /dev/null @@ -1,25 +0,0 @@ -#language: fr -#encoding: utf-8 -Fonctionnalité: Gestion du referentiel ref_ImpactEquipement - Chargement et Mise à disposition du référentiel des impacts d'équipements. - - - Scénario: Sprint 10 - Taiga 869: Ajout d'une colonne description - Quand le fichier CSV des impacts d'équipements "csv/sprint10/ref_ImpactEquipement.csv" est importé par API et la réponse est 200 - Alors La récupération de tous les impacts d'équipements renvoie 6 lignes - Et Vérifications des impacts équipements disponibles - | etape | critere | refEquipement | valeur | consoElecMoyenne | source | type | description | - | FIN_DE_VIE | Acidification | computer monitor-01-23 | 0.020296259210277726 | 35.81692801813716 | reftest_20221013 | computer monitor | Description Impact Equipement computer monitor | - | FABRICATION | Radiations ionisantes | digital price tag - power unit-01 | 5.89E+01 | | reftest_20221013 | digital price tag - power unit | Description Impact Equipement digital price tag - power unit | - | FABRICATION | Radiations ionisantes | docking station-01 | 3.50E+01 | 1.28 | reftest_20221013 | docking station | Description Impact Equipement docking station | - | FABRICATION | Radiations ionisantes | empty 42u bay-01 | 5.87E+01 | | reftest_20221013 | empty 42u bay | Description Impact Equipement empty 42u bay | - | FABRICATION | Radiations ionisantes | feature phone-01 | 5.11E+00 | 0.09 | reftest_20221013 | feature phone | Description Impact Equipement feature phone | - | FABRICATION | Radiations ionisantes | firewall-01 | 2.65E+02 | 876 | reftest_20221013 | firewall | Description Impact Equipement firewall | - - - - - - - - diff --git a/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_sprint10.feature b/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_sprint10.feature deleted file mode 100644 index c60c9988efe00a25520134de3d144ce22a54506e..0000000000000000000000000000000000000000 --- a/services/api-referentiel/src/test/resources/org/mte/numecoeval/referentiel/referentiel_sprint10.feature +++ /dev/null @@ -1,42 +0,0 @@ -#language: fr -#encoding: utf-8 -Fonctionnalité: Sprint 10 - Features du Sprint 10 (type équipement par défaut, correspondances...) - Nouvelles features disponibles: - - Reférentiel TypeEquipement avec le refEquipementParDefaut correctement géré - - Nouveau référentiel CorrespondanceRefEquipement - - - Scénario: Sprint 10 - Taiga 862: Ajout d'une colonne refEquipementParDefaut dans ref_TypeEquipement - Quand le fichier CSV des types d'équipements "csv/sprint10/ref_TypeEquipement.csv" est importé par API et la réponse est 200 - Alors La récupération de tous les types d'équipements renvoie 17 lignes - Et La récupération unitaire d'un type équipement "ServeurCalcul" répond 200 - Et Vérifications des types d'équipements disponibles - | type | serveur | commentaire | dureeVieDefaut | refEquipementParDefaut | source | - | ServeurCalcul | true | commentaires | 6 | serveur_par_defaut | Test | - | ServeurStockage | true | | 6 | serveur_par_defaut | Test | - | Armoire | false | | 7 | armoir_par_defaut | Test | - | NAS | false | | 6 | baie_stockage_par_defaut | Test | - | Switch | false | | 6 | switch_par_defaut | Test | - | OrdinateurPortable | false | | 4 | laptop_par_defaut | Test | - | OrdinateurDeBureau | false | | 5 | desktop_par_defaut | Test | - | Tablette | false | | 2.5 | tablette_par_defaut | Test | - | TelephoneMobile | false | commentaires | 2.5 | smartphone_par_defaut | Test | - | TelephoneFixe | false | | 10 | telephone_fixe_par_defaut | Test | - | EquipementReseau | false | commentaires | 5 | switch_par_defaut | Test | - | BorneWifi | false | | 4 | borneWifi_par_defaut | Test | - | Imprimante | false | | 5 | imprimante_par_defaut | Test | - | Ecran | false | | 8 | ecran_par_defaut | Test | - | AccessoirePosteDeTravail | false | souris calvier, camera casque | 7 | stationTravail_par_defaut | Test | - | Connectique | false | | 7 | | Test | - | Autre | false | | 2 | | Test | - - - Scénario: Sprint 10 - Taiga 319: Import des données de correspondances de références d'équipements - Quand le fichier CSV des correspondances d'équipements "csv/sprint10/ref_CorrespondanceRefEquipement.csv" est importé par API et la réponse est 200 - Alors La récupération de tous les correspondances d'équipements renvoie 3 lignes - Et Vérifications des correspondances d'équipements disponibles - | modeleEquipementSource | refEquipementCible | - | Fairphone V1 | smartphone01 | - | Fairphone V2 | smartphone01 | - | Ecran 27 pouces | ecran01 | - diff --git a/services/calculs/README.md b/services/calculs/README.md index d1a5f7b2c0370887b775ae7b17e86adba8d61ec8..f5dc0eb276400ef8756aeefe7e75070a1a3fd62d 100644 --- a/services/calculs/README.md +++ b/services/calculs/README.md @@ -6,11 +6,11 @@ Module contenant l'intégralité des règles de calculs et du code métier lié ## Requirements -- Any JDK 17 Implementation +- Any JDK 21 Implementation - [Coretto](https://docs.aws.amazon.com/corretto/latest/corretto-17-ug/downloads-list.html) - - [Open JDK](https://jdk.java.net/java-se-ri/17) + - [Open JDK](https://jdk.java.net/java-se-ri/21) - [Maven 3](https://maven.apache.org/download.cgi) -- IDE compatible with Maven 3 and JDK 17 are highly recommended to develop +- IDE compatible with Maven 3 and JDK 21 are highly recommended to develop ### Build @@ -21,7 +21,11 @@ mvn clean install ``` ## License + Le projet est sous licence Apache 2 ## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. + +If you have run out of energy or time for your project, put a note at the top of the README saying that development has +slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or +owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/services/calculs/calculs.iml b/services/calculs/calculs.iml new file mode 100644 index 0000000000000000000000000000000000000000..414ea6b18396a09b0e45b23d6b342a6188c090d4 --- /dev/null +++ b/services/calculs/calculs.iml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<module version="4"> + <component name="SonarLintModuleSettings"> + <option name="uniqueId" value="b1e53fa9-a237-4c73-a70d-14e75d060468" /> + </component> +</module> \ No newline at end of file diff --git a/services/calculs/dependency_check_suppressions.xml b/services/calculs/dependency_check_suppressions.xml deleted file mode 100644 index 8e4bfe629077460e8a73135f51fe1dd571b06ee0..0000000000000000000000000000000000000000 --- a/services/calculs/dependency_check_suppressions.xml +++ /dev/null @@ -1,12 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<suppressions xmlns="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.3.xsd"> - - <suppress> - <notes><![CDATA[ - Non-applicable : json-smart est une dépendance transitive. - Les json sont limités à la taille des inventaires : la taille des listes n'a pas réellement de limite - et c'est souhaités comme cela (traitement de gros volumes de données). - ]]></notes> - <cve>CVE-2023-1370</cve> - </suppress> -</suppressions> diff --git a/services/calculs/pom.xml b/services/calculs/pom.xml index c7349f4927e92ad4eedc5af68ceb6f4962588880..dd2164c679a501b3be3f734c5f1512c1e9693fac 100644 --- a/services/calculs/pom.xml +++ b/services/calculs/pom.xml @@ -5,11 +5,11 @@ <parent> <groupId>org.mte.numecoeval</groupId> <artifactId>core</artifactId> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <relativePath/> <!-- lookup parent from repository --> </parent> <artifactId>calculs</artifactId> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <name>calculs</name> <description>Module contenant l'intégralité des règles de calculs et du code métier lié aux calculs d'impact d'équipement @@ -54,16 +54,6 @@ <artifactId>commons-lang3</artifactId> <version>${apache-commons-lang3.version}</version> </dependency> - <dependency> - <groupId>org.apache.commons</groupId> - <artifactId>commons-collections4</artifactId> - <version>${apache-commons-collection4.version}</version> - </dependency> - <dependency> - <groupId>commons-io</groupId> - <artifactId>commons-io</artifactId> - <version>${apache-commons-io.version}</version> - </dependency> <dependency> <groupId>org.projectlombok</groupId> diff --git a/services/calculs/src/main/java/org/mte/numecoeval/calculs/domain/data/demande/DemandeCalculImpactEquipementPhysique.java b/services/calculs/src/main/java/org/mte/numecoeval/calculs/domain/data/demande/DemandeCalculImpactEquipementPhysique.java index 535d1b7752e34cdeaf23f35c48df00c5f808914d..4e4247f964a5d4ced269f7defbaa65ab402926e3 100644 --- a/services/calculs/src/main/java/org/mte/numecoeval/calculs/domain/data/demande/DemandeCalculImpactEquipementPhysique.java +++ b/services/calculs/src/main/java/org/mte/numecoeval/calculs/domain/data/demande/DemandeCalculImpactEquipementPhysique.java @@ -4,7 +4,6 @@ import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.Setter; -import org.apache.commons.collections4.CollectionUtils; import org.mte.numecoeval.calculs.domain.data.entree.EquipementPhysique; import org.mte.numecoeval.calculs.domain.data.referentiel.*; @@ -38,21 +37,26 @@ public class DemandeCalculImpactEquipementPhysique { List<ReferentielMixElectrique> mixElectriques; public Optional<ReferentielHypothese> getHypotheseFromCode(String code) { - if (code == null) { + if (code == null || hypotheses == null) { return Optional.empty(); } - return CollectionUtils.emptyIfNull(hypotheses) - .stream() + + return hypotheses.stream() .filter(hypothese -> code.equals(hypothese.getCode())) .findFirst(); } + public List<ReferentielHypothese> getHypothesesStartingWith(String startString) { + return hypotheses == null ? List.of() : hypotheses.stream() + .filter(hypothese -> hypothese.getCode().startsWith(startString)) + .toList(); + } + public Optional<ReferentielImpactEquipement> getImpactEquipement(String refEquipement) { - if (refEquipement == null) { + if (refEquipement == null || impactEquipements == null) { return Optional.empty(); } - return CollectionUtils.emptyIfNull(impactEquipements) - .stream() + return impactEquipements.stream() .filter(Objects::nonNull) .filter(impactEquipement -> refEquipement.equals(impactEquipement.getRefEquipement()) && critere.getNomCritere().equals(impactEquipement.getCritere()) @@ -62,11 +66,10 @@ public class DemandeCalculImpactEquipementPhysique { } public Optional<ReferentielMixElectrique> getMixElectrique(String pays) { - if (pays == null) { + if (pays == null || mixElectriques == null) { return Optional.empty(); } - return CollectionUtils.emptyIfNull(mixElectriques) - .stream() + return mixElectriques.stream() .filter(Objects::nonNull) .filter(mixElectrique -> pays.equals(mixElectrique.getPays()) && critere.getNomCritere().equals(mixElectrique.getCritere()) diff --git a/services/calculs/src/main/java/org/mte/numecoeval/calculs/domain/port/input/service/impl/CalculImpactEquipementPhysiqueServiceImpl.java b/services/calculs/src/main/java/org/mte/numecoeval/calculs/domain/port/input/service/impl/CalculImpactEquipementPhysiqueServiceImpl.java index a35d29cddf2b1173eca02136f512883077ebbf53..3dcdfe0a167e67091853e653241ba500a778fd71 100644 --- a/services/calculs/src/main/java/org/mte/numecoeval/calculs/domain/port/input/service/impl/CalculImpactEquipementPhysiqueServiceImpl.java +++ b/services/calculs/src/main/java/org/mte/numecoeval/calculs/domain/port/input/service/impl/CalculImpactEquipementPhysiqueServiceImpl.java @@ -19,6 +19,7 @@ import org.mte.numecoeval.calculs.domain.traceur.TraceCalculImpactEquipementPhys import org.mte.numecoeval.calculs.domain.traceur.TraceUtils; import java.util.Optional; +import java.util.stream.Collectors; @Slf4j @AllArgsConstructor @@ -257,17 +258,24 @@ public class CalculImpactEquipementPhysiqueServiceImpl implements CalculImpactEq /** - * compute the tauxUtilisationEquipementPhysique - * if the tauxUtilisation has been completed, we directly use this value - * else we retrieve the value of modeUtilisation and get the corresponding default value in ref_hypotheses + * Récupère le taux d'utilisation d'un équipement physique + * si le tauxUtilisation existe, on utilise la valeur, entre 0 et 1 + * si le modeUtilisation existe, on récupère la valeur dans les hypotheses + * sinon, on retourne 1 (=100% d'utilisation) * * @param demandeCalcul la demande de calcul * @return le taux d'utilsiation pour l'equipement physique + * @throws CalculImpactException si taux utilisation existe mais n'est pas entre 0 et 1 ou si le mode d'utilisation n'est pas connu */ - private Double getTauxUtilisationEqPhysique(DemandeCalculImpactEquipementPhysique demandeCalcul) { + private Double getTauxUtilisationEqPhysique(DemandeCalculImpactEquipementPhysique demandeCalcul) throws CalculImpactException { + var tauxUtilisation = demandeCalcul.getEquipementPhysique().getTauxUtilisation(); - if (tauxUtilisation != null && tauxUtilisation > 0.0 && tauxUtilisation <= 1.0) { + if (tauxUtilisation != null && (tauxUtilisation < 0 || tauxUtilisation > 1)) { + throw new CalculImpactException(TypeErreurCalcul.ERREUR_FONCTIONNELLE.getCode(), "Le taux d'utilisation doit être entre 0 et 1"); + } + + if (tauxUtilisation != null) { return tauxUtilisation; } @@ -275,10 +283,21 @@ public class CalculImpactEquipementPhysiqueServiceImpl implements CalculImpactEq return 1.0; } - var tauxUtilisationEqPhysique = demandeCalcul.getHypotheseFromCode("taux_utilisation_" + demandeCalcul.getEquipementPhysique().getModeUtilisation()); + final var tauxUtilisationStr = "taux_utilisation_"; + var tauxUtilisationEqPhysique = demandeCalcul.getHypotheseFromCode(tauxUtilisationStr + demandeCalcul.getEquipementPhysique().getModeUtilisation()); if (tauxUtilisationEqPhysique.isPresent()) { return tauxUtilisationEqPhysique.get().getValeur(); + } else { + var valeursTauxUtilisation = demandeCalcul.getHypothesesStartingWith(tauxUtilisationStr).stream() + .map(hypothese -> hypothese.getCode().replace(tauxUtilisationStr, "")) + .sorted() + .collect(Collectors.joining(", ")); + + throw new CalculImpactException( + TypeErreurCalcul.ERREUR_FONCTIONNELLE.getCode(), + valeursTauxUtilisation.isEmpty() ? + "Il n'y a pas d'hypotheses pour le taux d'utilisation" : + "Le mode d'utilisation doit avoir les valeurs " + valeursTauxUtilisation); } - return 1.0; } } diff --git a/services/calculs/src/main/java/org/mte/numecoeval/calculs/domain/port/input/service/impl/CalculImpactReseauServiceImpl.java b/services/calculs/src/main/java/org/mte/numecoeval/calculs/domain/port/input/service/impl/CalculImpactReseauServiceImpl.java index aa94858196d3d6c25247ee0f162fe1f7c16ad12d..d9fe16ac9451b6a4778464733aa0624de5932d33 100644 --- a/services/calculs/src/main/java/org/mte/numecoeval/calculs/domain/port/input/service/impl/CalculImpactReseauServiceImpl.java +++ b/services/calculs/src/main/java/org/mte/numecoeval/calculs/domain/port/input/service/impl/CalculImpactReseauServiceImpl.java @@ -3,7 +3,6 @@ package org.mte.numecoeval.calculs.domain.port.input.service.impl; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; import org.mte.numecoeval.calculs.domain.data.demande.DemandeCalculImpactReseau; import org.mte.numecoeval.calculs.domain.data.erreur.TypeErreurCalcul; import org.mte.numecoeval.calculs.domain.data.indicateurs.ImpactReseau; @@ -56,7 +55,7 @@ public class CalculImpactReseauServiceImpl implements CalculImpactReseauService .filter(refImpactReseau -> demandeCalcul.getEtape().getCode().equals(refImpactReseau.getEtapeACV()) && demandeCalcul.getCritere().getNomCritere().equals(refImpactReseau.getCritere()) - && StringUtils.equals(refImpactReseau.getRefReseau(), refReseau) + && refReseau.equals(refImpactReseau.getRefReseau()) ) .findFirst() .orElseThrow(() -> new CalculImpactException( diff --git a/services/calculs/src/test/java/org/mte/numecoeval/calculs/domain/service/CalculImpactEquipementPhysiqueServiceTest.java b/services/calculs/src/test/java/org/mte/numecoeval/calculs/domain/service/CalculImpactEquipementPhysiqueServiceTest.java index ffa130a08601b3757bb8c23d9baf34c0c4dd84ad..7d644ac5b0626e4878ecd18ad61315ace5d535de 100644 --- a/services/calculs/src/test/java/org/mte/numecoeval/calculs/domain/service/CalculImpactEquipementPhysiqueServiceTest.java +++ b/services/calculs/src/test/java/org/mte/numecoeval/calculs/domain/service/CalculImpactEquipementPhysiqueServiceTest.java @@ -2050,7 +2050,6 @@ class CalculImpactEquipementPhysiqueServiceTest { .quantite(1.0) .nbJourUtiliseAn(216.0) .consoElecAnnuelle(0.09) - .modeUtilisation("") .build(); ReferentielHypothese referentielHypothese = ReferentielHypothese.builder() .valeur(0.57) @@ -2122,11 +2121,10 @@ class CalculImpactEquipementPhysiqueServiceTest { ); //Then assertContentIndicateur(demandeCalcul, actual); - assertEquals("OK", actual.getStatutIndicateur()); - assertNotNull(actual.getImpactUnitaire()); - double actualImpactUnitaireLimited = BigDecimal.valueOf(actual.getImpactUnitaire()).setScale(4, RoundingMode.DOWN).doubleValue(); - assertEquals(0.0073, actualImpactUnitaireLimited); - assertEquals(referentielImpactEquipement.getConsoElecMoyenne(), actual.getConsoElecMoyenne()); + assertEquals("ERREUR", actual.getStatutIndicateur()); + assertEquals(""" + {"erreur":"ErrCalcFonc : Le mode d'utilisation doit avoir les valeurs BYOD"} + """.trim(), actual.getTrace()); } @Test @@ -2163,11 +2161,10 @@ class CalculImpactEquipementPhysiqueServiceTest { ); //Then assertContentIndicateur(demandeCalcul, actual); - assertEquals("OK", actual.getStatutIndicateur()); - assertNotNull(actual.getImpactUnitaire()); - double actualImpactUnitaireLimited = BigDecimal.valueOf(actual.getImpactUnitaire()).setScale(4, RoundingMode.DOWN).doubleValue(); - assertEquals(0.0073, actualImpactUnitaireLimited); - assertEquals(referentielImpactEquipement.getConsoElecMoyenne(), actual.getConsoElecMoyenne()); + assertEquals("ERREUR", actual.getStatutIndicateur()); + assertEquals(""" + {"erreur":"ErrCalcFonc : Il n'y a pas d'hypotheses pour le taux d'utilisation"} + """.trim(), actual.getTrace()); } @Test diff --git a/services/common/.gitlab-ci-library.yml b/services/common/.gitlab-ci-library.yml index 333d3823909ad520f920c27976c1d29a58d341fc..5a4d8cb674261be545dafcdb3d2a0e0ae02ac84a 100644 --- a/services/common/.gitlab-ci-library.yml +++ b/services/common/.gitlab-ci-library.yml @@ -25,12 +25,11 @@ cache: - .m2/ variables: + MAVEN_DOCKER_IMAGE: "maven:3.9.6-eclipse-temurin-21" MAVEN_PROJECT_DIR: services/$COMPONENT PROJECT_DIR: services/$COMPONENT MAVEN_CLI_OPTS: "-s ci_settings.xml --batch-mode" MAVEN_OPTS: "-Dmaven.repo.local=.m2" - DEPENDENCY_CHECK_SCAN_PATH: $CI_PROJECT_DIR/services/$COMPONENT - DEPENDENCY_CHECK_SUPPRESSION_PATH: $CI_PROJECT_DIR/services/$COMPONENT #Compilation et Tests pour les Merges requests et les commits test-application: @@ -45,3 +44,8 @@ build-application: extends: - .tags-runner - .java:build + +dependency-check: + variables: + DEPENDENCY_CHECK_SCAN_PATH: $CI_PROJECT_DIR/services/$COMPONENT + DEPENDENCY_CHECK_SUPPRESSION_PATH: $CI_PROJECT_DIR/services/core diff --git a/services/common/.gitlab-ci-maven.yml b/services/common/.gitlab-ci-maven.yml index 8a32043ea82b00b487775faeeb405233f45a6db2..3961c7081dfbb55cdca02bf0e57cb1e0b568ad40 100644 --- a/services/common/.gitlab-ci-maven.yml +++ b/services/common/.gitlab-ci-maven.yml @@ -29,12 +29,11 @@ stages: - analysis variables: + MAVEN_DOCKER_IMAGE: "maven:3.9.6-eclipse-temurin-21" MAVEN_PROJECT_DIR: services/$COMPONENT PROJECT_DIR: services/$COMPONENT MAVEN_CLI_OPTS: "-s $CI_PROJECT_DIR/services/common/ci_settings.xml --batch-mode" MAVEN_OPTS: "-Dmaven.repo.local=.m2" - DEPENDENCY_CHECK_SCAN_PATH: $CI_PROJECT_DIR/services/$COMPONENT - DEPENDENCY_CHECK_SUPPRESSION_PATH: $CI_PROJECT_DIR/services/$COMPONENT DOCKER_IMAGE: "$CI_REGISTRY_IMAGE/$COMPONENT:$CI_COMMIT_REF_NAME" #Compilation et Tests pour les Merges requests et les commits @@ -60,10 +59,6 @@ build-application: extends: - .tags-runner - .java:build - only: - - main - - develop - - tags build-image: stage: build-image @@ -80,7 +75,8 @@ build-image: DOCKER_PASSWORD: $CI_REGISTRY_PASSWORD REGISTRY_URL: $CI_REGISTRY IMAGE_URL: $CI_REGISTRY_IMAGE/$COMPONENT - only: - - main - - develop - - tags + +dependency-check: + variables: + DEPENDENCY_CHECK_SCAN_PATH: $CI_PROJECT_DIR/services/$COMPONENT + DEPENDENCY_CHECK_SUPPRESSION_PATH: $CI_PROJECT_DIR/services/core diff --git a/services/common/Dockerfile b/services/common/Dockerfile index 9ba5cf5d87a84da687f5ebd42624ee1420a3e190..adda00c1b7624157d6a5b2989eb1599d2289aa15 100644 --- a/services/common/Dockerfile +++ b/services/common/Dockerfile @@ -1,4 +1,4 @@ -FROM openjdk:17-jdk-slim +FROM openjdk:21-jdk-slim # Logs ENV LOGS_DIR=/app/logs diff --git a/services/common/common.iml b/services/common/common.iml new file mode 100644 index 0000000000000000000000000000000000000000..c629cd037f47c018dac4b9438e05232ad5561f96 --- /dev/null +++ b/services/common/common.iml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<module version="4"> + <component name="SonarLintModuleSettings"> + <option name="uniqueId" value="9e0ab373-3f2a-4cd1-ba71-af6699d17219" /> + </component> +</module> \ No newline at end of file diff --git a/services/common/dependency_check_suppressions.xml b/services/common/dependency_check_suppressions.xml deleted file mode 100644 index 790bf7a1a3b282690efe670d18df127d68d6f791..0000000000000000000000000000000000000000 --- a/services/common/dependency_check_suppressions.xml +++ /dev/null @@ -1,20 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<suppressions xmlns="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.3.xsd"> - - <suppress> - <notes><![CDATA[ - Non-applicable : Snakeyaml n'est utilisé que par Spring Boot pour les fichiers application.yml - et non des fichiers externes. - ]]></notes> - <cve>CVE-2022-1471</cve> - </suppress> - - <suppress> - <notes><![CDATA[ - Non-applicable : json-smart est une dépendance transitive. - Les json sont limités à la taille des inventaires : la taille des listes n'a pas réellement de limite - et c'est souhaités comme cela (traitement de gros volumes de données). - ]]></notes> - <cve>CVE-2023-1370</cve> - </suppress> -</suppressions> diff --git a/services/common/pom.xml b/services/common/pom.xml index 9847ddbe1b9b567e6a2f993ee22f79dc99db2000..ff6143a84a4f2eda2e6a3e68ea947f4f51078cd1 100644 --- a/services/common/pom.xml +++ b/services/common/pom.xml @@ -5,12 +5,12 @@ <parent> <groupId>org.mte.numecoeval</groupId> <artifactId>core</artifactId> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <relativePath/> <!-- lookup parent from repository --> </parent> <artifactId>common</artifactId> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <name>common</name> <description>Module commun</description> diff --git a/services/common/src/main/resources/static/api-referentiels-openapi.yaml b/services/common/src/main/resources/static/api-referentiels-openapi.yaml index 5aa7407325becbc6d78c8dce1d2bbb6fb54020e2..d6e764c017f0a83ce97f2515f85222f9281eab4a 100644 --- a/services/common/src/main/resources/static/api-referentiels-openapi.yaml +++ b/services/common/src/main/resources/static/api-referentiels-openapi.yaml @@ -25,6 +25,11 @@ paths: tags: - Export Référentiels summary: Exporter les impacts des types d'équipements sous format csv + description: | + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_TypeEquipement </li> + </ul> operationId: exportTypeEquipementCSV responses: '200': @@ -51,6 +56,13 @@ paths: tags: - Import Référentiels summary: 'Alimentation du référentiel Type Equipement par csv : annule et remplace.' + description: | + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> operationId: importTypeEquipementCSV requestBody: content: @@ -93,6 +105,11 @@ paths: tags: - Export Référentiels summary: Exporter les impacts des mix électrique sous format csv + description: | + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_MexElectriques </li> + </ul> operationId: exportImpactEquipementCSV responses: '200': @@ -119,6 +136,13 @@ paths: tags: - Import Référentiels summary: 'Alimentation du référentiel ImpactEquipement par csv : annule et remplace.' + description: | + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> operationId: importImpactEquipementCSV requestBody: content: @@ -161,6 +185,11 @@ paths: tags: - Export Référentiels summary: Exporter les impacts réseaux sous format csv + description: | + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_ImpactReseau </li> + </ul> operationId: exportImpactReseauxCSV responses: '200': @@ -187,6 +216,13 @@ paths: tags: - Import Référentiels summary: 'Alimentation du référentiel ImpactReseau par csv : annule et remplace.' + description: | + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> operationId: importImpactReseauxCSV requestBody: content: @@ -229,6 +265,11 @@ paths: tags: - Export Référentiels summary: Exporter les impacts d'équipements sous format csv + description: | + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_ImpactEquipement </li> + </ul> operationId: exportImpactEquipementCSV_1 responses: '200': @@ -255,7 +296,13 @@ paths: tags: - Import Référentiels summary: 'Alimentation du référentiel ImpactEquipement par csv : annule et remplace.' - description: 'Alimentation du référentiel ImpactEquipement par csv : annule et remplace.' + description: | + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> operationId: importImpactEquipementCSV_1 requestBody: content: @@ -298,6 +345,11 @@ paths: tags: - Export Référentiels summary: Exporter les impacts de messagerie sous format csv + description: | + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_ImpactMessagerie </li> + </ul> operationId: exportImpactMessagerieCSV responses: '200': @@ -324,7 +376,13 @@ paths: tags: - Import Référentiels summary: 'Alimentation du référentiel Impact Messagerie par csv : annule et remplace.' - description: 'Alimentation du référentiel Impact Messagerie par csv : annule et remplace.' + description: | + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> operationId: importImpactMessagerieCSV requestBody: content: @@ -367,6 +425,11 @@ paths: tags: - Export Référentiels summary: Exporter les hypothèses sous format csv + description: | + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_Hypotheses </li> + </ul> operationId: exportHypothesesCSV responses: '200': @@ -393,7 +456,13 @@ paths: tags: - Import Référentiels summary: 'Alimentation des Hypothèses par csv : annule et remplace.' - description: 'Alimentation des Hypothèses par csv : annule et remplace.' + description: | + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> operationId: importHypothesesCSV requestBody: content: @@ -431,11 +500,105 @@ paths: application/hal+json: schema: $ref: '#/components/schemas/ErrorResponseDTO' + /referentiel/facteursCaracterisation/csv: + get: + tags: + - Export Référentiels + summary: Exporter les facteurs de caractérisation sous format csv + description: | + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_FacteurCaracterisation </li> + </ul> + operationId: exportFacteurCaracterisationCSV + responses: + '200': + description: OK + '400': + description: Bad Request + content: + application/hal+json: + schema: + $ref: '#/components/schemas/ErrorResponseDTO' + '404': + description: Not Found + content: + application/hal+json: + schema: + $ref: '#/components/schemas/ErrorResponseDTO' + '500': + description: Internal Server Error + content: + application/hal+json: + schema: + $ref: '#/components/schemas/ErrorResponseDTO' + post: + tags: + - Import Référentiels + summary: 'Alimentation du référentiel FacteurCaracterisation par csv : annule et remplace.' + description: | + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, on peut choisir le mode pour supprimer les données déjà présentes dans la base ou pas. Par défaut, les anciennes données sont conservées. + <ul> + <li>Entrée : Le mode d'import 'FULL' ou 'DELTA' et le fichier CSV avec les données à insérer</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> + operationId: importFacteurCaracterisationCSV + parameters: + - name: mode + in: query + description: 'Choix du mode d''insertion FULL (purge puis insertion des nouvelles données) ou DELTA (upsert : maj de la base de données existante)' + required: false + schema: + type: string + description: 'Choix du mode d''insertion FULL (purge puis insertion des nouvelles données) ou DELTA (upsert : maj de la base de données existante)' + default: DELTA + requestBody: + content: + multipart/form-data: + schema: + required: + - file + type: object + properties: + file: + type: string + format: binary + responses: + '200': + description: Rapport d'import du fichier CSV + content: + application/hal+json: + schema: + $ref: '#/components/schemas/RapportImportDTO' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponseDTO' + '404': + description: Not Found + content: + application/hal+json: + schema: + $ref: '#/components/schemas/ErrorResponseDTO' + '500': + description: Internal Server Error + content: + application/hal+json: + schema: + $ref: '#/components/schemas/ErrorResponseDTO' /referentiel/etapes/csv: get: tags: - Export Référentiels summary: Exporter les etapes sous format csv + description: | + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_EtapeACV </li> + </ul> operationId: exportEtapesCSV responses: '200': @@ -462,7 +625,13 @@ paths: tags: - Import Référentiels summary: 'Alimentation Etape ACV par csv : annule et remplace.' - description: 'Alimentation Etape ACV par csv : annule et remplace.' + description: | + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> operationId: importEtapesCSV requestBody: content: @@ -505,6 +674,11 @@ paths: tags: - Export Référentiels summary: Exporter les criteres sous format csv + description: | + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des Critères de ref_Critere </li> + </ul> operationId: exportCriteresCSV responses: '200': @@ -530,8 +704,14 @@ paths: post: tags: - Import Référentiels - summary: Alimentation des Criteres par csv (annule et remplace). - description: Alimentation des Criteres par csv (annule et remplace). + summary: 'Alimentation des Criteres par csv : annule et remplace.' + description: | + Le référentiel est global à tout le système. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> operationId: importCriteresCSV requestBody: content: @@ -574,6 +754,11 @@ paths: tags: - Export Référentiels summary: Exporter les correspondances de RefEquipement sous format csv + description: | + <ul> + <li>Entrée : Aucune </li> + <li>Sortie : Renvoie la liste des étapes de ref_CorrespondanceRefEquipement </li> + </ul> operationId: exportCorrespondanceRefEquipementCSV responses: '200': @@ -600,6 +785,13 @@ paths: tags: - Import Référentiels summary: 'Alimentation du référentiel des correspondances de RefEquipement par csv : annule et remplace.' + description: | + Le référentiel est lié à une organisation donnée. L’import se fait uniquement avec un fichier CSV. + Lors de l’import, les données précédentes sont supprimées. + <ul> + <li>Entrée : Le nom d’organisation pour laquelle les données sont établies et le fichier CSV du référentiel</li> + <li>Sortie : Rapport du fichier CSV (nombre de lignes totales, nombre de lignes en erreur, nombre de lignes traitées, liste des erreurs par lignes).</li> + </ul> operationId: importCorrespondanceRefEquipementCSV requestBody: content: @@ -715,7 +907,7 @@ paths: - Interne NumEcoEval summary: Endpoint interne à NumEcoEval - Récupération d'un type d'équipement via son type description: | - V2 - Endpoint interne utilisé à l'enrichissement données pour un équipement physique. + Endpoint interne utilisé à la réception de données d'entrées par le module api-expositiondonneesentrees de NumEcoEval. Renvoie l'intégralité des types d'équipements d'un certain type. operationId: getTypeEquipement parameters: - name: type @@ -1096,6 +1288,68 @@ paths: application/hal+json: schema: $ref: '#/components/schemas/ErrorResponseDTO' + /referentiel/facteursCaracterisation: + get: + tags: + - Interne NumEcoEval + summary: Endpoint interne à NumEcoEval - Récupération d'un Facteur de Caractérisation + description: | + Endpoint interne utilisé dans la génération des indicateurs par le module api-calcul de NumEcoEval. + Récupération d'un impact équipement en fonction de 3 paramètres: + <ul> + <li>Le nom du facteur de caractérisation: nom</li> + <li>L'étape ACV: etape</li> + <li>Le critère d'impact: critere</li> + </ul> + . + operationId: getFacteurCaracterisation + parameters: + - name: nom + in: query + description: Nom du facteur de caractérisation recherché + required: true + schema: + type: string + description: Nom du facteur de caractérisation recherché + - name: critere + in: query + description: Nom du critère d'impact écologique + required: true + schema: + type: string + description: Nom du critère d'impact écologique + - name: etapeacv + in: query + description: Code de l'étape ACV + required: true + schema: + type: string + description: Code de l'étape ACV + responses: + '200': + description: Facteur Caractérisation trouvé + content: + application/json: + schema: + $ref: '#/components/schemas/FacteurCaracterisationDTO' + '400': + description: Invalid request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponseDTO' + '404': + description: Facteur Caractérisation non trouvé + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponseDTO' + '500': + description: Internal Server Error + content: + application/hal+json: + schema: + $ref: '#/components/schemas/ErrorResponseDTO' /referentiel/etapes: get: tags: @@ -1138,7 +1392,7 @@ paths: - Interne NumEcoEval summary: Endpoint interne à NumEcoEval - Récupération de tous les critères d'impacts écologiques description: | - Endpoint interne utilisé dans la génération des indicateurs par le module api-calcul de NumEcoEval. + Renvoie l'intégralité des types des critères d'impacts écologiques utilisés dans NumEcoEval. operationId: getAllCriteres responses: '200': @@ -1172,9 +1426,6 @@ paths: tags: - Interne NumEcoEval summary: Endpoint interne à NumEcoEval - Récupération d'une correspondance de refEquipement à partir d'un modèle d'équipement. - description: | - Endpoint interne utilisé dans l'import de données d'entrées dans NumEcoEval - pour déterminer la référence d'équipement à utiliser dans les référentiels'. operationId: getCorrespondanceRefEquipement parameters: - name: modele @@ -1448,6 +1699,48 @@ components: type: string description: Source de l'hypothèse description: Référentiel des hypothèses utilisées pour les calculs + FacteurCaracterisationDTO: + type: object + properties: + nom: + type: string + description: Nom du facteur de caractérisation, fait partie de la clé dans le référentiel + etape: + type: string + description: Étape ACV concernée, fait partie de la clé dans le référentiel + critere: + type: string + description: Critère d'impact écologique concerné, fait partie de la clé dans le référentiel + description: + type: string + description: Description de l'entrée dans le référentiel + niveau: + type: string + description: Niveau du facteur de caractérisation concerné + tiers: + type: string + description: Tiers du facteur de caractérisation concerné + categorie: + type: string + description: Catégorie du facteur de caractérisation concerné + consoElecMoyenne: + type: number + description: Consommation électrique moyenne + format: double + localisation: + type: string + description: Localisation du facteur de caractérisation concerné + valeur: + type: number + description: Valeur de l'impact écologique + format: double + unite: + type: string + description: Unité du critère d'impact écologique + source: + type: string + description: Source de l'impact écologique pour ce facteur de caractérisation + description: Référentiel de l'impact écologique d'un facteur de caractérisation. La clé est composé des champs nom, etape et critere. EtapeDTO: type: object properties: diff --git a/services/core/core.iml b/services/core/core.iml new file mode 100644 index 0000000000000000000000000000000000000000..59ed6d7d09fdd7d5630f167d782b57ecbfb8fdef --- /dev/null +++ b/services/core/core.iml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<module version="4"> + <component name="SonarLintModuleSettings"> + <option name="uniqueId" value="35175603-f965-494d-ba38-5fadd7245abe" /> + </component> +</module> \ No newline at end of file diff --git a/services/core/dependency_check_suppressions.xml b/services/core/dependency_check_suppressions.xml index fbf9371b9855dacda4603cfaba33e10d71151dd1..9f9224ad8603be91c6310af4ce4de8d939103735 100644 --- a/services/core/dependency_check_suppressions.xml +++ b/services/core/dependency_check_suppressions.xml @@ -1,3 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> <suppressions xmlns="https://jeremylong.github.io/DependencyCheck/dependency-suppression.1.3.xsd"> + + <suppress> + <notes><![CDATA[ + Faux-Positif : Concerne hutool-json et json-java qui ne sont pas utilisés. + Le faux-positif se trouve sur json-path + cf. https://github.com/jeremylong/DependencyCheck/issues/5502 + ]]></notes> + <cve>CVE-2022-45688</cve> + </suppress> + </suppressions> diff --git a/services/core/pom.xml b/services/core/pom.xml index 25da500959a061600fa2835ca814b9e79d31c84b..11d23366aa69968953c5a7fdaa62f6753253062f 100644 --- a/services/core/pom.xml +++ b/services/core/pom.xml @@ -5,13 +5,13 @@ <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> - <version>3.0.7</version> + <version>3.2.1</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>org.mte.numecoeval</groupId> <artifactId>core</artifactId> - <version>1.2.2</version> + <version>1.2.3-SNAPSHOT</version> <name>core</name> <packaging>pom</packaging> <description>Projet parent du projet NumEcoEval</description> @@ -36,44 +36,41 @@ </distributionManagement> <properties> - <java.version>17</java.version> + <java.version>21</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- Utilitaires --> - <apache-commons-lang3.version>3.12.0</apache-commons-lang3.version> + <apache-commons-lang3.version>3.14.0</apache-commons-lang3.version> <apache-commons-collection4.version>4.4</apache-commons-collection4.version> - <apache-commons-io.version>2.11.0</apache-commons-io.version> - <apache-commons-csv.version>1.9.0</apache-commons-csv.version> - <mapstruct.version>1.5.3.Final</mapstruct.version> + <apache-commons-io.version>2.15.1</apache-commons-io.version> + <apache-commons-csv.version>1.10.0</apache-commons-csv.version> + <mapstruct.version>1.5.5.Final</mapstruct.version> - <!-- CVE multiples sur Snakeyaml (CVE-2020-13936, CVE-2022-38749, CVE-2022-38751, CVE-2022-38750, CVE-2022-38752)--> - <snakeyaml.version>1.33</snakeyaml.version> - <!-- CVE sur Postgres (CVE-2022-41946) --> - <postgresql.version>42.5.4</postgresql.version> - - <!-- CVE sur Spring CVE-2023-20863--> - <spring-framework.version>6.0.8</spring-framework.version> + <postgresql.version>42.7.1</postgresql.version> + <!-- L'erreur vient d'une de ces 4 lib --> <!-- Documentation automatique des API REST en OpenAPI 3.0 --> - <springdoc-openapi-ui.version>2.0.4</springdoc-openapi-ui.version> + <springdoc-openapi-ui.version>2.3.0</springdoc-openapi-ui.version> <!-- OpenAPI Generator (API REST generator) --> - <openapi-generator-version>6.4.0</openapi-generator-version> + <openapi-generator-version>7.2.0</openapi-generator-version> <jackson-databind-nullable-version>0.2.6</jackson-databind-nullable-version> + <swagger-annotations.version>2.2.20</swagger-annotations.version> + <!-- scs-multiapi-maven-plugin (Async API generator)--> - <scs-multiapi-maven-plugin.version>4.5.0</scs-multiapi-maven-plugin.version> + <scs-multiapi-maven-plugin.version>5.3.3</scs-multiapi-maven-plugin.version> <!-- Tests --> <meanbean.version>2.0.3</meanbean.version> - <equalsverifier.version>3.10.1</equalsverifier.version> - <wiremock.version>2.34.0</wiremock.version> + <equalsverifier.version>3.15.6</equalsverifier.version> + <wiremock.version>3.0.1</wiremock.version> <javafaker.version>1.0.2</javafaker.version> - <cucumber-bom.version>7.11.1</cucumber-bom.version> - <jacoco.version>0.8.8</jacoco.version> - <instancio-junit.version>2.2.0</instancio-junit.version> + <cucumber-bom.version>7.15.0</cucumber-bom.version> + <jacoco.version>0.8.11</jacoco.version> + <instancio-junit.version>4.1.0</instancio-junit.version> <surefireArgLine>-Dfile.encoding=UTF-8</surefireArgLine> - <embedded-database-spring-test.version>2.2.0</embedded-database-spring-test.version> - <embedded-postgres.version>2.0.3</embedded-postgres.version> + <embedded-database-spring-test.version>2.5.0</embedded-database-spring-test.version> + <embedded-postgres.version>2.0.6</embedded-postgres.version> </properties> <dependencyManagement> @@ -139,6 +136,11 @@ <artifactId>jackson-databind-nullable</artifactId> <version>${jackson-databind-nullable-version}</version> </dependency> + <dependency> + <groupId>io.swagger.core.v3</groupId> + <artifactId>swagger-annotations</artifactId> + <version>${swagger-annotations.version}</version> + </dependency> <!-- Cucumber (Tests) --> <dependency> @@ -222,7 +224,7 @@ <plugin> <groupId>org.owasp</groupId> <artifactId>dependency-check-maven</artifactId> - <version>8.1.2</version> + <version>9.0.9</version> <executions> <execution> <goals>