diff --git a/.env b/.env new file mode 100644 index 00000000..ed63aed8 --- /dev/null +++ b/.env @@ -0,0 +1,6 @@ +PEARL_DB_USER=mypostgresuser +PEARL_DB_PASSWORD=mypostgrespassword +PEARL_DB_PORT=5434 +PEARL_DB=pearl + +KEYCLOAK_PORT=7080 diff --git a/.github/workflows/docker-snapshot.yml b/.github/workflows/docker-snapshot.yml new file mode 100644 index 00000000..32064420 --- /dev/null +++ b/.github/workflows/docker-snapshot.yml @@ -0,0 +1,67 @@ +name: Build snapshot docker image + +on: + push: + branches-ignore: + - main + +jobs: + build-snapshot: + runs-on: ubuntu-latest + outputs: + branch: ${{ steps.extract_branch.outputs.branch }} + steps: + - name: Extract branch name + shell: bash + run: echo "branch=$(echo ${GITHUB_REF#refs/heads/})" >>$GITHUB_OUTPUT + id: extract_branch + + - uses: actions/checkout@v4 + with: + ref: ${{ steps.extract_branch.outputs.branch }} + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + distribution: "temurin" + java-version: "21" + + - name: Build API + run: mvn package --no-transfer-progress + + - name: Upload API jar + uses: actions/upload-artifact@v4 + with: + name: app-jar + path: target/*.jar + + docker: + needs: + - build-snapshot + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Download uploaded jar + uses: actions/download-artifact@v4 + with: + name: app-jar + path: target/ + + - name: Create docker version tag + id: docker-version + run: | + # replace '/' by '-' for docker tags + docker_tag="${{ needs.build-snapshot.outputs.branch }}" + docker_tag=$(echo "$docker_tag" | sed 's/[\/+]/-/g') + echo "docker_tag=${docker_tag}" >> $GITHUB_ENV + + - name: Publish to Docker Hub + uses: elgohr/Publish-Docker-Github-Action@v5 + with: + name: inseefr/pearl-jam-back-office + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + default_branch: ${{ github.ref }} + tags: "snapshot-${{ env.docker_tag }}" + workdir: . \ No newline at end of file diff --git a/.gitignore b/.gitignore index 8872a5e5..d482843e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ target/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/** !**/src/test/** +htmlReport/** ### STS ### .apt_generated diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index 443d8849..d58dfb70 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -14,5 +14,6 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -wrapperVersion=3.3.1 +wrapperVersion=3.3.2 +distributionType=only-script distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/Dockerfile b/Dockerfile index 1f7a666e..10776c5a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM eclipse-temurin:21.0.4_7-jre-alpine +FROM eclipse-temurin:21.0.6_7-jre-alpine@sha256:4c07db858c3b8bfed4cb9163f4aeedbff9c0c2b8212ec1fa75c13a169dec8dc6 WORKDIR /opt/app/ COPY ./target/*.jar /opt/app/app.jar diff --git a/README.md b/README.md index c656613a..eb18138d 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,8 @@ logging: - `GET /api/campaign/{id}/survey-units/not-attributed` : Get numberSUNotAttributed - `PUT /api/campaign/{idCampaign}/organizational-unit/{idOu}/visibility` : Change visibility of a campaign for an Organizational Unit - `GET /api/campaigns` : Get Campaigns +- `GET /campaigns/{id}/ongoing` campaign is ongoing +- `GET /api/campaigns/ongoing` : Campaigns is ongoing (BATCH extraction-transfert-synchronisation) ### Closing-Cause-Controller - `GET /api/campaign/{id}/survey-units/interviewer/{idep}/closing-causes` : Get interviewerStateCount diff --git a/compose.yml b/compose.yml new file mode 100644 index 00000000..aec1ba2d --- /dev/null +++ b/compose.yml @@ -0,0 +1,28 @@ +services: + pearl-db: + image: postgres:15.1 + environment: + - POSTGRES_USER=${PEARL_DB_USER} + - POSTGRES_PASSWORD=${PEARL_DB_PASSWORD} + - POSTGRES_DB=${PEARL_DB} + command: ["postgres"] + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${PEARL_DB_USER} -d ${PEARL_DB} -h localhost"] + interval: 5s + timeout: 10s + retries: 10 + ports: + - ${PEARL_DB_PORT}:5432 + + keycloak: + image: quay.io/keycloak/keycloak:24.0 + environment: + KEYCLOAK_ADMIN: administrator + KEYCLOAK_ADMIN_PASSWORD: administrator + KC_HEALTH_ENABLED: "true" + KC_LOG_LEVEL: info + command: ["start-dev", "--import-realm"] + ports: + - "${KEYCLOAK_PORT}:8080" + volumes: + - ./container/keycloak/realms:/opt/keycloak/data/import \ No newline at end of file diff --git a/container/keycloak/realms/sabiane.json b/container/keycloak/realms/sabiane.json new file mode 100644 index 00000000..38ad8d30 --- /dev/null +++ b/container/keycloak/realms/sabiane.json @@ -0,0 +1,233 @@ +{ + "realm": "sabiane", + "enabled": true, + "users": [ + { + "username": "gestio1", + "enabled": true, + "emailVerified": true, + "firstName": "Gertrude", + "lastName": "Gestionnaire1", + "email": "gestion@insee.fr", + "credentials": [ + { + "type": "password", + "value": "gestio1", + "temporary": false + } + ], + "realmRoles": ["gestionnaire"] + }, + { + "username": "gestio2", + "enabled": true, + "emailVerified": true, + "firstName": "Gontrand", + "lastName": "Gestionnaire2", + "email": "gestion2@insee.fr", + "credentials": [ + { + "type": "password", + "value": "gestio2", + "temporary": false + } + ], + "realmRoles": ["gestionnaire"] + }, + { + "username": "gestio3", + "enabled": true, + "emailVerified": true, + "firstName": "Gerard", + "lastName": "Gestionnaire3", + "email": "gestion3@insee.fr", + "credentials": [ + { + "type": "password", + "value": "gestio3", + "temporary": false + } + ], + "realmRoles": ["gestionnaire"] + }, + { + "username": "gestio4", + "enabled": true, + "emailVerified": true, + "firstName": "Gustave", + "lastName": "Gestionnaire4", + "email": "gestion4@insee.fr", + "credentials": [ + { + "type": "password", + "value": "gestio4", + "temporary": false + } + ], + "realmRoles": ["gestionnaire"] + }, + { + "username": "interv1", + "enabled": true, + "emailVerified": true, + "firstName": "Isabelle", + "lastName": "Interviewer 1", + "email": "interviewer1@insee.fr", + "credentials": [ + { + "type": "password", + "value": "interv1", + "temporary": false + } + ], + "realmRoles": ["interviewer"] + }, + { + "username": "interv2", + "enabled": true, + "emailVerified": true, + "firstName": "Ingrid", + "lastName": "Interviewer 2", + "email": "interviewer2@insee.fr", + "credentials": [ + { + "type": "password", + "value": "interv2", + "temporary": false + } + ], + "realmRoles": ["interviewer"] + }, + { + "username": "interv3", + "enabled": true, + "emailVerified": true, + "firstName": "Isaac", + "lastName": "Interviewer 3", + "email": "interviewer3@insee.fr", + "credentials": [ + { + "type": "password", + "value": "interv3", + "temporary": false + } + ], + "realmRoles": ["interviewer"] + }, + { + "username": "interv4", + "enabled": true, + "emailVerified": true, + "firstName": "Isidore", + "lastName": "Interviewer 4", + "email": "interviewer4@insee.fr", + "credentials": [ + { + "type": "password", + "value": "interv4", + "temporary": false + } + ], + "realmRoles": ["interviewer"] + }, + { + "username": "interv5", + "enabled": true, + "emailVerified": true, + "firstName": "Irma", + "lastName": "Interviewer 5", + "email": "interviewer5@insee.fr", + "credentials": [ + { + "type": "password", + "value": "interv5", + "temporary": false + } + ], + "realmRoles": ["interviewer"] + }, + { + "username": "admin", + "enabled": true, + "emailVerified": true, + "firstName": "Adele", + "lastName": "Admin", + "email": "adele@insee.fr", + "credentials": [ + { + "type": "password", + "value": "admin", + "temporary": false + } + ], + "realmRoles": ["admin"] + }, + { + "id": "15cfea92-65bc-441e-bf55-1234c73b3129", + "username": "service-account-webclient", + "emailVerified": false, + "createdTimestamp": 1739881777223, + "enabled": true, + "totp": false, + "serviceAccountClientId": "webclient", + "disableableCredentialTypes": [], + "requiredActions": [], + "realmRoles": [ + "default-roles-sabiane", + "webclient" + ], + "notBefore": 0, + "groups": [] + } + ], + "clients": [ + { + "clientId": "myclient", + "enabled": true, + "serviceAccountsEnabled": false, + "authorizationServicesEnabled": false, + "publicClient": true, + "directAccessGrantsEnabled": true, + "redirectUris": ["*"], + "webOrigins": ["*"], + "protocol": "openid-connect", + "standardFlowEnabled": true, + "implicitFlowEnabled": false + }, + { + "clientId": "webclient", + "enabled": true, + "serviceAccountsEnabled": true, + "authorizationServicesEnabled": false, + "publicClient": false, + "directAccessGrantsEnabled": false, + "redirectUris": ["*"], + "webOrigins": ["*"], + "protocol": "openid-connect", + "standardFlowEnabled": false, + "implicitFlowEnabled": false, + "clientAuthenticatorType": "client-secret", + "secret": "webclient" + } + ], + "roles": { + "realm": [ + { + "name": "gestionnaire", + "description": "gestionnaire role" + }, + { + "name": "admin", + "description": "Admin role" + }, + { + "name": "interviewer", + "description": "Interviewer role" + }, + { + "name": "webclient", + "description": "webclient role" + } + ] + } +} \ No newline at end of file diff --git a/mvnw b/mvnw index 9adcade3..19529ddf 100644 --- a/mvnw +++ b/mvnw @@ -19,7 +19,7 @@ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- -# Apache Maven Wrapper startup batch script, version 3.3.1 +# Apache Maven Wrapper startup batch script, version 3.3.2 # # Optional ENV vars # ----------------- @@ -97,11 +97,19 @@ die() { exit 1 } +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + # parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties while IFS="=" read -r key value; do case "${key-}" in - distributionUrl) distributionUrl="${value-}" ;; - distributionSha256Sum) distributionSha256Sum="${value-}" ;; + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; esac done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" [ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" @@ -131,7 +139,8 @@ esac distributionUrlName="${distributionUrl##*/}" distributionUrlNameMain="${distributionUrlName%.*}" distributionUrlNameMain="${distributionUrlNameMain%-bin}" -MAVEN_HOME="$HOME/.m2/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" exec_maven() { unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : @@ -247,4 +256,4 @@ printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvn mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" clean || : -exec_maven "$@" \ No newline at end of file +exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd index 7b0c0943..b150b91e 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -1,146 +1,149 @@ -<# : batch portion -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Apache Maven Wrapper startup batch script, version 3.3.1 -@REM -@REM Optional ENV vars -@REM MVNW_REPOURL - repo url base for downloading maven distribution -@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven -@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output -@REM ---------------------------------------------------------------------------- - -@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) -@SET __MVNW_CMD__= -@SET __MVNW_ERROR__= -@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% -@SET PSModulePath= -@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( - IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) -) -@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% -@SET __MVNW_PSMODULEP_SAVE= -@SET __MVNW_ARG0_NAME__= -@SET MVNW_USERNAME= -@SET MVNW_PASSWORD= -@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) -@echo Cannot start maven from wrapper >&2 && exit /b 1 -@GOTO :EOF -: end batch / begin powershell #> - -$ErrorActionPreference = "Stop" -if ($env:MVNW_VERBOSE -eq "true") { - $VerbosePreference = "Continue" -} - -# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties -$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl -if (!$distributionUrl) { - Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" -} - -switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { - "maven-mvnd-*" { - $USE_MVND = $true - $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" - $MVN_CMD = "mvnd.cmd" - break - } - default { - $USE_MVND = $false - $MVN_CMD = $script -replace '^mvnw','mvn' - break - } -} - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ -if ($env:MVNW_REPOURL) { - $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } - $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" -} -$distributionUrlName = $distributionUrl -replace '^.*/','' -$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' -$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" -$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' -$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" - -if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { - Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" - Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" - exit $? -} - -if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { - Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" -} - -# prepare tmp dir -$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile -$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" -$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null -trap { - if ($TMP_DOWNLOAD_DIR.Exists) { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } - } -} - -New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null - -# Download and Install Apache Maven -Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." -Write-Verbose "Downloading from: $distributionUrl" -Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" - -$webclient = New-Object System.Net.WebClient -if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { - $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) -} -[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null - -# If specified, validate the SHA-256 sum of the Maven distribution zip file -$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum -if ($distributionSha256Sum) { - if ($USE_MVND) { - Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." - } - Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash - if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { - Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." - } -} - -# unzip and move -Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null -Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null -try { - Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null -} catch { - if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { - Write-Error "fail to move MAVEN_HOME" - } -} finally { - try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } - catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } -} - -Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/pom.xml b/pom.xml index 54b58bd9..e0d429e5 100644 --- a/pom.xml +++ b/pom.xml @@ -7,14 +7,14 @@ fr.insee.pearljam pearljam-back-office - 5.1.9 + 5.6.9 Pearl-Jam-Back-Office Back-office services for PearlJam org.springframework.boot spring-boot-starter-parent - 3.3.3 + 3.4.4 @@ -22,9 +22,10 @@ 21 UTF-8 UTF-8 - 42.7.4 + 42.7.5 inseefr https://sonarcloud.io + 7.21.1 @@ -48,7 +49,7 @@ org.springdoc springdoc-openapi-starter-webmvc-ui - 2.6.0 + 2.8.4 @@ -98,6 +99,11 @@ test + + org.springframework.boot + spring-boot-docker-compose + + org.springframework.security spring-security-test @@ -123,6 +129,30 @@ true + + + org.junit.platform + junit-platform-suite + test + + + io.cucumber + cucumber-java + ${cucumber.version} + test + + + io.cucumber + cucumber-spring + ${cucumber.version} + + + io.cucumber + cucumber-junit-platform-engine + ${cucumber.version} + + + org.codehaus.janino @@ -155,6 +185,7 @@ XML + HTML @@ -250,12 +281,13 @@ org.apache.maven.plugins maven-surefire-plugin - 3.5.0 + 3.5.2 **/TestAuthKeyCloak **/TestNoAuth **/*Test + **/*TestRunner **/*IT @@ -263,4 +295,4 @@ - \ No newline at end of file + diff --git a/renovate.json b/renovate.json index 1f79db43..89ead0cb 100644 --- a/renovate.json +++ b/renovate.json @@ -1,44 +1,80 @@ { - "extends": ["config:best-practices", ":semanticCommits", ":disableRateLimiting"], - "baseBranches": ["develop", "main"], + "extends": [ + "config:best-practices", + ":semanticCommits", + ":disableRateLimiting" + ], + "baseBranchPatterns": [ + "develop", + "main" + ], "packageRules": [ { "enabled": false, - "matchPackagePatterns": ["*"], - "matchBaseBranches": ["main"] + "matchBaseBranches": [ + "main" + ], + "matchPackageNames": [ + "*" + ] }, { - "matchPackagePatterns": ["*"], - "matchBaseBranches": ["develop"], - "labels": ["dependencies"], + "matchBaseBranches": [ + "develop" + ], + "labels": [ + "dependencies" + ], "bumpVersion": "patch", - "dependencyDashboardApproval": true + "dependencyDashboardApproval": true, + "matchPackageNames": [ + "*" + ] }, { "groupName": "spring", "groupSlug": "spring", - "matchPackagePatterns": ["org.springframework.*"], - "matchBaseBranches": ["develop"], + "matchBaseBranches": [ + "develop" + ], "bumpVersion": "minor", - "dependencyDashboardApproval": true + "dependencyDashboardApproval": true, + "matchPackageNames": [ + "/org.springframework.*/" + ] }, { "groupName": "all minor dependencies", "groupSlug": "all-minor-patch", - "matchPackagePatterns": ["*"], - "matchBaseBranches": ["develop"], - "matchUpdateTypes": ["minor", "patch"], + "matchBaseBranches": [ + "develop" + ], + "matchUpdateTypes": [ + "minor", + "patch" + ], "bumpVersion": "patch", - "dependencyDashboardApproval": false + "dependencyDashboardApproval": false, + "matchPackageNames": [ + "*" + ] } ], "vulnerabilityAlerts": { "enabled": true, - "baseBranches": ["main"], - "addLabels": ["security"], + "baseBranchPatterns": [ + "main" + ], + "addLabels": [ + "security" + ], "bumpVersion": "patch", - "schedule": ["before 5:00am"] + "schedule": [ + "before 5:00am" + ] }, - "schedule": ["every weekend"], + "schedule": [ + "every weekend" + ], "timezone": "Europe/Paris" -} \ No newline at end of file +} diff --git a/src/main/java/fr/insee/pearljam/api/bussinessrules/BusinessRules.java b/src/main/java/fr/insee/pearljam/api/bussinessrules/BusinessRules.java new file mode 100644 index 00000000..246cbab5 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/bussinessrules/BusinessRules.java @@ -0,0 +1,76 @@ +package fr.insee.pearljam.api.bussinessrules; + +import fr.insee.pearljam.api.domain.StateType; +import fr.insee.pearljam.api.dto.state.StateDto; + +import java.util.*; +import java.util.stream.Collectors; + +public class BusinessRules { + private BusinessRules() { + throw new IllegalStateException("BusinessRules static class"); + } + + /* + * Checks if a survey unit is allowed to pass from a state to another + * via a manager action + */ + public static Boolean stateCanBeModifiedByManager(StateType currentState, StateType targetState) { + switch (targetState) { + case NVA: + return currentState != StateType.NVA; + case ANV: + return currentState == StateType.NNS; + case VIN: + return List.of(StateType.NNS,StateType.ANV).contains(currentState); + case FIN: + return currentState == StateType.TBR; + case WFT: + return List.of(StateType.FIN, StateType.TBR).contains(currentState); + case CLO: + return true; + default: + return false; + } + } + + + + + /* + * Checks if a survey unit can be seen by the interviewer + * via an automatic business rule + */ + public static Boolean stateCanBeSeenByInterviewerBussinessRules(StateType currentState) { + StateType[] possibleTypes = { + StateType.VIN, + StateType.VIC, + StateType.PRC, + StateType.AOC, + StateType.APS, + StateType.INS, + StateType.WFT, + StateType.WFS, + StateType.TBR, + StateType.FIN, + StateType.CLO, + }; + return Arrays.asList(possibleTypes).contains(currentState); + } + + public static Boolean shouldFallBackToTbrOrFin(List states) { + // If survey-unit has NVA 'Not Visible to All' => no fall-back + Set presentTypes = states.stream().map(StateDto::type).collect(Collectors.toSet()); + if (presentTypes.contains(StateType.NVA)) + return false; + // Survey-unit should not already be in TBR or FIN state + Optional optCurrentState = states.stream().max(Comparator.comparingLong(StateDto::date)); + if (optCurrentState.isEmpty()) { + return false; + } + StateType currentState = optCurrentState.get().type(); + StateType[] fallBackTypes = { StateType.FIN, StateType.TBR }; + return Arrays.stream(fallBackTypes).noneMatch(currentState::equals); + } + +} \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/api/bussinessrules/BussinessRules.java b/src/main/java/fr/insee/pearljam/api/bussinessrules/BussinessRules.java deleted file mode 100644 index 0c02d67a..00000000 --- a/src/main/java/fr/insee/pearljam/api/bussinessrules/BussinessRules.java +++ /dev/null @@ -1,164 +0,0 @@ -package fr.insee.pearljam.api.bussinessrules; - -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import fr.insee.pearljam.api.domain.StateType; -import fr.insee.pearljam.api.dto.state.StateDto; - -public class BussinessRules { - private BussinessRules() { - throw new IllegalStateException("BusinessRules static class"); - } - - // Checks if a survey unit is allowed to pass from a state to another - public static Boolean stateCanBeModified(StateType currentState, StateType targetState) { - switch (targetState) { - case NVA: - return currentState != StateType.NVA; - case ANV: - return currentState == StateType.NNS; - case VIN: - return currentState == StateType.NNS || currentState == StateType.ANV; - case VIC: - return currentState == StateType.VIN; - case FIN: - return currentState == StateType.TBR || currentState == StateType.WFS; - case WFT: - return currentState == StateType.FIN || currentState == StateType.TBR - || currentState == StateType.INS; - case PRC: - return currentState == StateType.VIC; - case AOC: - return currentState == StateType.APS || currentState == StateType.PRC; - case APS: - return currentState == StateType.AOC || currentState == StateType.PRC; - case INS: - return currentState == StateType.APS || currentState == StateType.PRC - || currentState == StateType.FIN || currentState == StateType.TBR; - case WFS: - return currentState == StateType.WFT; - case TBR: - return currentState == StateType.WFS; - case NVM: - return currentState == StateType.ANV; - default: - return false; - } - } - - /* - * Checks if a survey unit is allowed to pass from a state to another - * via a manager action - */ - public static Boolean stateCanBeModifiedByManager(StateType currentState, StateType targetState) { - switch (targetState) { - case NVA: - return currentState != StateType.NVA; - case ANV: - return currentState == StateType.NNS; - case VIN: - return currentState == StateType.NNS || currentState == StateType.ANV; - case FIN: - return currentState == StateType.TBR; - case WFT: - return currentState == StateType.FIN || currentState == StateType.TBR; - case CLO: - return true; - default: - return false; - } - } - - /* - * Checks if a survey unit is allowed to pass from a state to another - * via an interviewer action - */ - public static Boolean stateCanBeModifiedByInterviewer(StateType currentState, StateType targetState) { - switch (targetState) { - case PRC: - return currentState == StateType.VIC; - case AOC: - return currentState == StateType.APS || currentState == StateType.PRC; - case APS: - return currentState == StateType.AOC || currentState == StateType.PRC; - case INS: - return currentState == StateType.APS || currentState == StateType.PRC - || currentState == StateType.FIN || currentState == StateType.TBR; - case WFT: - return currentState == StateType.INS; - case WFS: - return currentState == StateType.WFT; - case TBR: - return currentState == StateType.WFS; - case FIN: - return currentState == StateType.WFS; - default: - return false; - } - } - - /* - * Checks if a survey unit is allowed to pass from a state to another - * via an automatic bussiness rule - */ - public static Boolean stateCanBeModifiedBussinessRules(StateType currentState, StateType targetState) { - switch (targetState) { - case VIC: - return currentState == StateType.VIN; - case WFT: - return currentState == StateType.INS; - case FIN: - return currentState == StateType.WFS; - case TBR: - return currentState == StateType.WFS; - case ANV: - return currentState == StateType.FIN; - case NVM: - return currentState == StateType.ANV; - default: - return false; - } - } - - /* - * Checks if a survey unit can be seen by the interviewer - * via an automatic bussiness rule - */ - public static Boolean stateCanBeSeenByInterviewerBussinessRules(StateType currentState) { - StateType[] possibleTypes = { - StateType.VIN, - StateType.VIC, - StateType.PRC, - StateType.AOC, - StateType.APS, - StateType.INS, - StateType.WFT, - StateType.WFS, - StateType.TBR, - StateType.FIN, - StateType.CLO, - }; - return Arrays.stream(possibleTypes).anyMatch(currentState::equals); - } - - public static Boolean shouldFallBackToTbrOrFin(List states) { - // If survey-unit has NVA 'Not Visible to All' => no fall-back - Set presentTypes = states.stream().map(StateDto::getType).collect(Collectors.toSet()); - if (presentTypes.contains(StateType.NVA)) - return false; - // Survey-unit should not already be in TBR or FIN state - Optional optCurrentState = states.stream().max(Comparator.comparingLong(StateDto::getDate)); - if (optCurrentState.isEmpty()) { - return false; - } - StateType currentState = optCurrentState.get().getType(); - StateType[] fallBackTypes = { StateType.FIN, StateType.TBR }; - return Arrays.stream(fallBackTypes).noneMatch(currentState::equals); - } - -} \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java index aea8c958..9386d973 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignCreateDto.java @@ -9,6 +9,7 @@ import fr.insee.pearljam.api.domain.IdentificationConfiguration; import fr.insee.pearljam.api.dto.referent.ReferentDto; import fr.insee.pearljam.api.web.annotation.NoDuplicateMediumAndType; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty; @@ -24,10 +25,13 @@ public record CampaignCreateDto ( List visibilities, @Valid @NoDuplicateMediumAndType + @Schema(description = "List of communication templates", defaultValue = "[]") List communicationTemplates, List referents, String email, IdentificationConfiguration identificationConfiguration, ContactOutcomeConfiguration contactOutcomeConfiguration, - ContactAttemptConfiguration contactAttemptConfiguration) { + ContactAttemptConfiguration contactAttemptConfiguration, + @Schema(description = "Is campaign data sensitive", defaultValue = "false") + Boolean sensitivity) { } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java index 31f6b4b1..e124aae6 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CampaignUpdateDto.java @@ -3,7 +3,6 @@ import com.fasterxml.jackson.annotation.JsonInclude; import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; -import fr.insee.pearljam.api.domain.IdentificationConfiguration; import fr.insee.pearljam.api.dto.referent.ReferentDto; import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; @@ -17,7 +16,6 @@ * @param visibilities A list of visibility context DTOs. * @param referents A list of referent DTOs. * @param email The email associated with the campaign. - * @param identificationConfiguration The identification configuration of the campaign. */ @JsonInclude(JsonInclude.Include.NON_NULL) public record CampaignUpdateDto( @@ -27,7 +25,6 @@ public record CampaignUpdateDto( List visibilities, List referents, String email, - IdentificationConfiguration identificationConfiguration, ContactOutcomeConfiguration contactOutcomeConfiguration, ContactAttemptConfiguration contactAttemptConfiguration ) {} \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java index 48868960..64b29d2c 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDto.java @@ -4,7 +4,6 @@ import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; import jakarta.validation.constraints.NotNull; - import java.util.ArrayList; import java.util.List; @@ -23,21 +22,21 @@ public record CommunicationTemplateCreateDto( @NotNull CommunicationType type ) { - public static List toModel(List communicationTemplates) { + public static List toModel(List communicationTemplates, String campaignId) { if(communicationTemplates == null) { return new ArrayList<>(); } - return communicationTemplates.stream() - .map(CommunicationTemplateCreateDto::toModel) - .toList(); + return communicationTemplates.stream() + .map(template -> toModel(template, campaignId)) + .toList(); } - public static CommunicationTemplate toModel(CommunicationTemplateCreateDto communicationTemplate) { + public static CommunicationTemplate toModel(CommunicationTemplateCreateDto communicationTemplate, String campaignId) { if(communicationTemplate == null) { return null; } return new CommunicationTemplate( - null, + campaignId, communicationTemplate.meshuggahId(), communicationTemplate.medium(), communicationTemplate.type()); diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java index 41581915..93929567 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/input/VisibilityCampaignCreateDto.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import fr.insee.pearljam.domain.campaign.model.Visibility; +import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import org.springframework.lang.NonNull; @@ -37,6 +38,7 @@ public record VisibilityCampaignCreateDto( @NotBlank String organizationalUnit, @NotNull + @Schema(description = "Allow letter sending feature", defaultValue = "false") Boolean useLetterCommunication, @NotNull String mail, diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java index 3dcf719d..a5289827 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CampaignResponseDto.java @@ -30,7 +30,8 @@ public record CampaignResponseDto( String email, IdentificationConfiguration identificationConfiguration, ContactOutcomeConfiguration contactOutcomeConfiguration, - ContactAttemptConfiguration contactAttemptConfiguration + ContactAttemptConfiguration contactAttemptConfiguration, + Boolean sensitivity ) { public static CampaignResponseDto fromModel(Campaign campaignDB, List referents, @@ -42,7 +43,8 @@ public static CampaignResponseDto fromModel(Campaign campaignDB, campaignDB.getEmail(), campaignDB.getIdentificationConfiguration(), campaignDB.getContactOutcomeConfiguration(), - campaignDB.getContactAttemptConfiguration() + campaignDB.getContactAttemptConfiguration(), + campaignDB.getSensitivity() ); } } diff --git a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java index 67a1ee10..dd17cd7f 100644 --- a/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDto.java @@ -7,7 +7,9 @@ import java.util.List; public record CommunicationTemplateResponseDto( - Long id, + String id, + String campaignId, + String meshuggahId, CommunicationMedium medium, CommunicationType type ) { @@ -15,7 +17,9 @@ public static List fromModel(List new CommunicationTemplateResponseDto( - communicationTemplate.id(), + communicationTemplate.meshuggahId(), //The id field corresponds to the meshuggahId to prevent regression. + communicationTemplate.campaignId(), + communicationTemplate.meshuggahId(), communicationTemplate.medium(), communicationTemplate.type())) .toList(); diff --git a/src/main/java/fr/insee/pearljam/api/constants/Constants.java b/src/main/java/fr/insee/pearljam/api/constants/Constants.java index 3a7ff0d0..7addea7e 100644 --- a/src/main/java/fr/insee/pearljam/api/constants/Constants.java +++ b/src/main/java/fr/insee/pearljam/api/constants/Constants.java @@ -9,148 +9,151 @@ private Constants() { public static final String INTERVIEWER = "interviewer"; public static final String REVIEWER = "reviewer"; - public static final String USER = "user"; public static final String GUEST = "GUEST"; public static final String AUTHORIZATION = "Authorization"; - - public static final String API_QUEEN_SURVEYUNITS_STATEDATA = "/api/survey-units/state-data"; - - // API - public static final String API_ADMIN_SURVEYUNITS = "/api/admin/survey-units"; - public static final String API_ADMIN_CAMPAIGN_ID_SURVEYUNITS = "/api/admin/campaign/{id}/survey-units"; - public static final String API_SURVEYUNITS = "/api/survey-units"; - public static final String API_SURVEYUNITS_INTERVIEWERS = "/api/survey-units/interviewers"; - public static final String API_SURVEYUNITS_CLOSABLE = "/api/survey-units/closable"; - public static final String API_SURVEYUNIT_ID_INTERVIEWER = "/api/interviewer/survey-unit/{id}"; - public static final String API_SURVEYUNIT_ID = "/api/survey-unit/{id}"; - public static final String API_SURVEYUNIT_ID_STATE = "/api/survey-unit/{id}/state/{state}"; - public static final String API_SURVEYUNIT_ID_STATES = "/api/survey-unit/{id}/states"; - public static final String API_SURVEYUNIT_ID_COMMENT = "/api/survey-unit/{id}/comment"; - public static final String API_SURVEYUNIT_ID_VIEWED = "/api/survey-unit/{id}/viewed"; - public static final String API_SURVEYUNIT_ID_CLOSE = "/api/survey-unit/{id}/close/{closingCause}"; - public static final String API_SURVEYUNIT_ID_CLOSINGCAUSE = "/api/survey-unit/{id}/closing-cause/{closingCause}"; - - public static final String API_SURVEYUNIT_ID_TEMP_ZONE = "/api/survey-unit/{id}/temp-zone"; - public static final String API_SURVEYUNITS_TEMP_ZONE = "/api/survey-units/temp-zone"; - - public static final String API_CAMPAIGNS = "/api/campaigns"; - public static final String API_ADMIN_CAMPAIGNS = "/api/admin/campaigns"; - public static final String API_INTERVIEWER_CAMPAIGNS = "/api/interviewer/campaigns"; - public static final String API_CAMPAIGNS_SU_STATECOUNT = "/api/campaigns/survey-units/state-count"; - public static final String API_CAMPAIGNS_SU_CONTACTOUTCOMES = "/api/campaigns/survey-units/contact-outcomes"; - - public static final String API_CAMPAIGN = "/api/campaign"; - public static final String API_CAMPAIGN_ID = "/api/campaign/{id}"; - public static final String API_CAMPAIGN_COLLECTION_DATES = "/api/campaign/{id}/collection-dates"; - public static final String API_CAMPAIGN_ID_INTERVIEWERS = "/api/campaign/{id}/interviewers"; - public static final String API_CAMPAIGN_ID_SURVEYUNITS = "/api/campaign/{id}/survey-units"; - public static final String API_CAMPAIGN_ID_SU_ABANDONED = "/api/campaign/{id}/survey-units/abandoned"; - public static final String API_CAMPAIGN_ID_SU_NOTATTRIBUTED = "/api/campaign/{id}/survey-units/not-attributed"; - public static final String API_CAMPAIGN_ID_SU_STATECOUNT = "/api/campaign/{id}/survey-units/state-count"; - public static final String API_CAMPAIGN_ID_SU_INTERVIEWER_STATECOUNT = "/api/campaign/{id}/survey-units/interviewer/{idep}/state-count"; - public static final String API_CAMPAIGN_ID_SU_NOT_ATTRIBUTED_STATECOUNT = "/api/campaign/{id}/survey-units/not-attributed/state-count"; - public static final String API_CAMPAIGN_ID_SU_CONTACTOUTCOMES = "/api/campaign/{id}/survey-units/contact-outcomes"; - public static final String API_CAMPAIGN_ID_SU_INTERVIEWER_CONTACTOUTCOMES = "/api/campaign/{id}/survey-units/interviewer/{idep}/contact-outcomes"; - public static final String API_CAMPAIGN_ID_SU_NOT_ATTRIBUTED_CONTACTOUTCOMES = "/api/campaign/{id}/survey-units/not-attributed/contact-outcomes"; - public static final String API_CAMPAIGN_ID_SU_INTERVIEWER_CLOSINGCAUSES = "/api/campaign/{id}/survey-units/interviewer/{idep}/closing-causes"; - public static final String API_CAMPAIGN_ID_OU_ID_VISIBILITY = "/api/campaign/{idCampaign}/organizational-unit/{idOu}/visibility"; - public static final String API_CAMPAIGN_ID_OU_ID_COMMUNICATION_INFORMATION = "/api/campaign/{idCampaign}/organizational-unit/{idOu}/communication-information"; - public static final String API_CAMPAIGN_ID_VISIBILITIES = "/api/campaign/{id}/visibilities"; - public static final String API_CAMPAIGN_ID_COMMUNICATION_TEMPLATES = "/api/campaign/{id}/communication-templates"; - public static final String API_CAMPAIGN_ID_COMMUNICATION_INFORMATIONS = "/api/campaign/{id}/communication-informations"; - public static final String API_CAMPAIGN_ID_REFERENTS = "/api/campaigns/{id}/referents"; - public static final String API_CAMPAIGNS_ID_ON_GOING = "/campaigns/{id}/ongoing"; - - public static final String API_INTERVIEWERS = "/api/interviewers"; - public static final String API_INTERVIEWERS_SU_STATECOUNT = "/api/interviewers/survey-units/state-count"; - public static final String API_INTERVIEWER_ID = "/api/interviewer/{id}"; - public static final String API_INTERVIEWER_ID_CAMPAIGNS = "/api/interviewer/{id}/campaigns"; - public static final String API_ADMIN_INTERVIEWERS = "/api/admin/interviewers"; - - public static final String API_USER = "/api/user"; - public static final String API_USER_ID = "/api/user/{id}"; - public static final String API_USER_ID_ORGANIZATIONUNIT_ID = "/api/user/{id}/organization-unit/{id2}"; - public static final String API_ORGANIZATIONUNIT = "/api/organization-unit"; - public static final String API_ORGANIZATIONUNITS = "/api/organization-units"; - public static final String API_ORGANIZATIONUNIT_ID = "/api/organization-unit/{id}"; - public static final String API_ORGANIZATIONUNIT_ID_USERS = "/api/organization-unit/{id}/users"; - - public static final String API_PREFERENCES = "/api/preferences"; - - public static final String API_MESSAGE = "/api/message"; - public static final String API_MESSAGES_ID = "/api/messages/{id}"; - public static final String API_VERIFYNAME = "/api/verify-name"; - public static final String API_MESSAGEHISTORY = "/api/message-history"; - public static final String API_MESSAGE_MARK_AS_READ = "/api/message/{id}/interviewer/{idep}/read"; - public static final String API_MESSAGE_MARK_AS_DELETED = "/api/message/{id}/interviewer/{idep}/delete"; - - public static final String API_CREATEDATASET = "/api/create-dataset"; - public static final String API_DELETEDATASET = "/api/delete-dataset"; - - public static final String API_CHECK_HABILITATION = "/api/check-habilitation"; - - public static final String API_HEALTH_CHECK = "/api/healthcheck"; - - public static final String API_MAIL = "/api/mail"; - - public static final String API_ENUM_STATE = "/api/enum/state"; - public static final String API_ENUM_CONTACT_OUTCOME = "/api/enum/contact-outcome"; - public static final String API_ENUM_CONTACT_ATTEMPT = "/api/enum/contact-attempt"; - // Error messages - public static final String ERR_USER_NOT_EXIST = "User {} does not exist"; - public static final String ERR_CAMPAIGN_NOT_EXIST = "Campaign {} does not exist"; - public static final String ERR_NO_OU_FOR_CAMPAIGN = "There is no Organisation Unit for Campaign {} affiliated to user {}"; - - // Front expected variables names - - public static final String NVM_COUNT = "nvmCount"; - public static final String NNS_COUNT = "nnsCount"; - public static final String ANV_COUNT = "anvCount"; - public static final String VIN_COUNT = "vinCount"; - public static final String VIC_COUNT = "vicCount"; - public static final String PRC_COUNT = "prcCount"; - public static final String AOC_COUNT = "aocCount"; - public static final String APS_COUNT = "apsCount"; - public static final String INS_COUNT = "insCount"; - public static final String WFT_COUNT = "wftCount"; - public static final String WFS_COUNT = "wfsCount"; - public static final String TBR_COUNT = "tbrCount"; - public static final String FIN_COUNT = "finCount"; - public static final String CLO_COUNT = "cloCount"; - public static final String NVA_COUNT = "nvaCount"; - public static final String TOTAL_COUNT = "total"; - - public static final String NPA_COUNT = "npaCount"; - public static final String NPI_COUNT = "npiCount"; - public static final String NPX_COUNT = "npxCount"; - public static final String ROW_COUNT = "rowCount"; - - public static final String INA_COUNT = "inaCount"; - public static final String REF_COUNT = "refCount"; - public static final String IMP_COUNT = "impCount"; - public static final String UCD_COUNT = "ucdCount"; - public static final String UTR_COUNT = "utrCount"; - public static final String ALA_COUNT = "alaCount"; - public static final String DCD_COUNT = "dcdCount"; - public static final String NUH_COUNT = "nuhCount"; - public static final String DUK_COUNT = "dukCount"; - public static final String DUU_COUNT = "duuCount"; - public static final String NOA_COUNT = "noaCount"; - - public static final List STATE_COUNT_FIELDS = List.of(NVM_COUNT, NNS_COUNT, ANV_COUNT, VIN_COUNT, VIC_COUNT, - PRC_COUNT, AOC_COUNT, APS_COUNT, INS_COUNT, WFT_COUNT, WFS_COUNT, TBR_COUNT, FIN_COUNT, CLO_COUNT, - NVA_COUNT, TOTAL_COUNT); - - public static final List STATECOUNT_CLOSED_CLOSING_CAUSE_FIELDS = List.of(NPA_COUNT, NPI_COUNT, NPX_COUNT, - ROW_COUNT); - - public static final List CLOSING_CAUSE_FIELDS = List.of(NPA_COUNT, NPI_COUNT, NPX_COUNT, ROW_COUNT, - TOTAL_COUNT); - - public static final List CONTACT_OUTCOME_FIELDS = List.of(INA_COUNT, REF_COUNT, IMP_COUNT, UCD_COUNT, - UTR_COUNT, - ALA_COUNT, DCD_COUNT, NUH_COUNT, DUK_COUNT, DUU_COUNT, NOA_COUNT); - - public static final String UNAVAILABLE = "UNAVAILABLE"; + public static final String USER = "user"; + + public static final String API_QUEEN_SURVEYUNITS_STATEDATA = "/api/survey-units/state-data"; + + // API + public static final String API_ADMIN_SURVEYUNITS = "/api/admin/survey-units"; + public static final String API_ADMIN_CAMPAIGN_ID_SURVEYUNITS = "/api/admin/campaign/{id}/survey-units"; + public static final String API_SURVEYUNITS = "/api/survey-units"; + public static final String API_SURVEYUNITS_INTERVIEWERS = "/api/survey-units/interviewers"; + public static final String API_SURVEYUNITS_CLOSABLE = "/api/survey-units/closable"; + public static final String API_SURVEYUNIT_ID_INTERVIEWER = "/api/interviewer/survey-unit/{id}"; + public static final String API_SURVEYUNIT_ID = "/api/survey-unit/{id}"; + public static final String API_SURVEYUNIT_ID_STATE = "/api/survey-unit/{id}/state/{state}"; + public static final String API_SURVEYUNIT_ID_STATES = "/api/survey-unit/{id}/states"; + public static final String API_SURVEYUNIT_ID_COMMENT = "/api/survey-unit/{id}/comment"; + public static final String API_SURVEYUNIT_ID_VIEWED = "/api/survey-unit/{id}/viewed"; + public static final String API_SURVEYUNIT_ID_CLOSE = "/api/survey-unit/{id}/close/{closingCause}"; + public static final String API_SURVEYUNIT_ID_CLOSINGCAUSE = "/api/survey-unit/{id}/closing-cause/{closingCause}"; + + public static final String API_SURVEYUNIT_ID_TEMP_ZONE = "/api/survey-unit/{id}/temp-zone"; + public static final String API_SURVEYUNITS_TEMP_ZONE = "/api/survey-units/temp-zone"; + + public static final String API_CAMPAIGNS = "/api/campaigns"; + public static final String API_ADMIN_CAMPAIGNS = "/api/admin/campaigns"; + public static final String API_INTERVIEWER_CAMPAIGNS = "/api/interviewer/campaigns"; + public static final String API_CAMPAIGNS_SU_STATECOUNT = "/api/campaigns/survey-units/state-count"; + public static final String API_CAMPAIGNS_SU_CONTACTOUTCOMES = "/api/campaigns/survey-units/contact-outcomes"; + + public static final String API_CAMPAIGN = "/api/campaign"; + public static final String API_CAMPAIGN_ID = "/api/campaign/{id}"; + public static final String API_CAMPAIGN_COLLECTION_DATES = "/api/campaign/{id}/collection-dates"; + public static final String API_CAMPAIGN_ID_INTERVIEWERS = "/api/campaign/{id}/interviewers"; + public static final String API_CAMPAIGN_ID_SURVEYUNITS = "/api/campaign/{id}/survey-units"; + public static final String API_CAMPAIGN_ID_SU_ABANDONED = "/api/campaign/{id}/survey-units/abandoned"; + public static final String API_CAMPAIGN_ID_SU_NOTATTRIBUTED = "/api/campaign/{id}/survey-units/not-attributed"; + public static final String API_CAMPAIGN_ID_SU_STATECOUNT = "/api/campaign/{id}/survey-units/state-count"; + public static final String API_CAMPAIGN_ID_SU_INTERVIEWER_STATECOUNT = "/api/campaign/{id}/survey-units/interviewer/{idep}/state-count"; + public static final String API_CAMPAIGN_ID_SU_NOT_ATTRIBUTED_STATECOUNT = "/api/campaign/{id}/survey-units/not-attributed/state-count"; + public static final String API_CAMPAIGN_ID_SU_CONTACTOUTCOMES = "/api/campaign/{id}/survey-units/contact-outcomes"; + public static final String API_CAMPAIGN_ID_SU_INTERVIEWER_CONTACTOUTCOMES = "/api/campaign/{id}/survey-units/interviewer/{idep}/contact-outcomes"; + public static final String API_CAMPAIGN_ID_SU_NOT_ATTRIBUTED_CONTACTOUTCOMES = "/api/campaign/{id}/survey-units/not-attributed/contact-outcomes"; + public static final String API_CAMPAIGN_ID_SU_INTERVIEWER_CLOSINGCAUSES = "/api/campaign/{id}/survey-units/interviewer/{idep}/closing-causes"; + public static final String API_CAMPAIGN_ID_OU_ID_VISIBILITY = "/api/campaign/{idCampaign}/organizational-unit/{idOu}/visibility"; + public static final String API_CAMPAIGN_ID_OU_ID_COMMUNICATION_INFORMATION = "/api/campaign/{idCampaign}/organizational-unit/{idOu}/communication-information"; + public static final String API_CAMPAIGN_ID_VISIBILITIES = "/api/campaign/{id}/visibilities"; + public static final String API_CAMPAIGN_ID_COMMUNICATION_TEMPLATES = "/api/campaign/{id}/communication-templates"; + public static final String API_CAMPAIGN_ID_COMMUNICATION_INFORMATIONS = "/api/campaign/{id}/communication-informations"; + public static final String API_CAMPAIGN_ID_REFERENTS = "/api/campaigns/{id}/referents"; + public static final String API_CAMPAIGNS_ID_ON_GOING = "/campaigns/{id}/ongoing"; + public static final String API_CAMPAIGNS_ON_GOING = "/api/campaigns/ongoing"; + public static final String API_CAMPAIGN_ID_INTERVIEWERS_STATECOUNT = "api/campaign/{id}/interviewers/state-count"; + + public static final String API_INTERVIEWERS = "/api/interviewers"; + public static final String API_INTERVIEWERS_SU_STATECOUNT = "/api/interviewers/survey-units/state-count"; + public static final String API_INTERVIEWER_ID = "/api/interviewer/{id}"; + public static final String API_INTERVIEWER_ID_CAMPAIGNS = "/api/interviewer/{id}/campaigns"; + public static final String API_ADMIN_INTERVIEWERS = "/api/admin/interviewers"; + + public static final String API_USER = "/api/user"; + public static final String API_USER_ID = "/api/user/{id}"; + public static final String API_USER_ID_ORGANIZATIONUNIT_ID = "/api/user/{id}/organization-unit/{id2}"; + public static final String API_USER_ID_ORGANIZATION_ID_OUID = "/api/user/{userId}/organization-unit/{ouId}"; + public static final String API_ORGANIZATIONUNIT = "/api/organization-unit"; + public static final String API_ORGANIZATIONUNITS = "/api/organization-units"; + public static final String API_ORGANIZATIONUNIT_ID = "/api/organization-unit/{id}"; + public static final String API_ORGANIZATIONUNIT_ID_USERS = "/api/organization-unit/{id}/users"; + + public static final String API_PREFERENCES = "/api/preferences"; + + public static final String API_MESSAGE = "/api/message"; + public static final String API_MESSAGES_ID = "/api/messages/{id}"; + public static final String API_VERIFYNAME = "/api/verify-name"; + public static final String API_MESSAGEHISTORY = "/api/message-history"; + public static final String API_MESSAGE_MARK_AS_READ = "/api/message/{id}/interviewer/{idep}/read"; + public static final String API_MESSAGE_MARK_AS_DELETED = "/api/message/{id}/interviewer/{idep}/delete"; + + public static final String API_CREATEDATASET = "/api/create-dataset"; + public static final String API_DELETEDATASET = "/api/delete-dataset"; + + public static final String API_CHECK_HABILITATION = "/api/check-habilitation"; + + public static final String API_HEALTH_CHECK = "/api/healthcheck"; + + public static final String API_MAIL = "/api/mail"; + + public static final String API_ENUM_STATE = "/api/enum/state"; + public static final String API_ENUM_CONTACT_OUTCOME = "/api/enum/contact-outcome"; + public static final String API_ENUM_CONTACT_ATTEMPT = "/api/enum/contact-attempt"; + // Error messages + public static final String ERR_USER_NOT_EXIST = "User {} does not exist"; + public static final String ERR_CAMPAIGN_NOT_EXIST = "Campaign {} does not exist"; + public static final String ERR_NO_OU_FOR_CAMPAIGN = "There is no Organisation Unit for Campaign {} affiliated to user {}"; + + // Front expected variables names + + public static final String NVM_COUNT = "nvmCount"; + public static final String NNS_COUNT = "nnsCount"; + public static final String ANV_COUNT = "anvCount"; + public static final String VIN_COUNT = "vinCount"; + public static final String VIC_COUNT = "vicCount"; + public static final String PRC_COUNT = "prcCount"; + public static final String AOC_COUNT = "aocCount"; + public static final String APS_COUNT = "apsCount"; + public static final String INS_COUNT = "insCount"; + public static final String WFT_COUNT = "wftCount"; + public static final String WFS_COUNT = "wfsCount"; + public static final String TBR_COUNT = "tbrCount"; + public static final String FIN_COUNT = "finCount"; + public static final String CLO_COUNT = "cloCount"; + public static final String NVA_COUNT = "nvaCount"; + public static final String TOTAL_COUNT = "total"; + + public static final String NPA_COUNT = "npaCount"; + public static final String NPI_COUNT = "npiCount"; + public static final String NPX_COUNT = "npxCount"; + public static final String ROW_COUNT = "rowCount"; + + public static final String INA_COUNT = "inaCount"; + public static final String REF_COUNT = "refCount"; + public static final String IMP_COUNT = "impCount"; + public static final String UCD_COUNT = "ucdCount"; + public static final String UTR_COUNT = "utrCount"; + public static final String ALA_COUNT = "alaCount"; + public static final String NUH_COUNT = "nuhCount"; + public static final String DUK_COUNT = "dukCount"; + public static final String DUU_COUNT = "duuCount"; + public static final String NOA_COUNT = "noaCount"; + public static final String NOTICE_COUNT = "noticeCount"; + public static final String REMINDER_COUNT = "reminderCount"; + + public static final List STATE_COUNT_FIELDS = List.of(NVM_COUNT, NNS_COUNT, ANV_COUNT, + VIN_COUNT, VIC_COUNT, PRC_COUNT, AOC_COUNT, APS_COUNT, INS_COUNT, WFT_COUNT, WFS_COUNT, TBR_COUNT, FIN_COUNT, + CLO_COUNT, NVA_COUNT, TOTAL_COUNT, NOTICE_COUNT, REMINDER_COUNT); + + public static final List STATECOUNT_CLOSED_CLOSING_CAUSE_FIELDS = List.of(NPA_COUNT, + NPI_COUNT, NPX_COUNT, ROW_COUNT); + + public static final List CLOSING_CAUSE_FIELDS = List.of(NPA_COUNT, NPI_COUNT, NPX_COUNT, + ROW_COUNT, TOTAL_COUNT); + + public static final List CONTACT_OUTCOME_FIELDS = List.of(INA_COUNT, REF_COUNT, IMP_COUNT, + UCD_COUNT, UTR_COUNT, ALA_COUNT, NUH_COUNT, DUK_COUNT, DUU_COUNT, NOA_COUNT); + + public static final String UNAVAILABLE = "UNAVAILABLE"; } diff --git a/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java b/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java index d4ea37cf..d7a66b8a 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/CampaignController.java @@ -4,6 +4,7 @@ import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; +import fr.insee.pearljam.api.dto.campaign.CampaignSensitivityDto; import fr.insee.pearljam.domain.exception.*; import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; import jakarta.validation.Valid; @@ -251,6 +252,17 @@ public ResponseEntity isOngoing(@PathVariable(value = "id") String i return new ResponseEntity<>(campaignOngoing, HttpStatus.OK); } + /** + * This method returns campaign ongoing + * + * @return {@link CampaignSensitivityDto} the campaign + */ + @Operation(summary = "get ongoing sensitive campaigns") + @GetMapping(value = Constants.API_CAMPAIGNS_ON_GOING, produces = "application/json") + public List getCampaignSensitivityDto() throws CampaignNotFoundException { + return campaignService.getCampaignSensitivityDto(); + } + /** * This method returns target campaign * diff --git a/src/main/java/fr/insee/pearljam/api/controller/ClosingCauseController.java b/src/main/java/fr/insee/pearljam/api/controller/ClosingCauseController.java index 28192eb5..b2b636d6 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/ClosingCauseController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/ClosingCauseController.java @@ -1,65 +1,61 @@ package fr.insee.pearljam.api.controller; -import java.util.List; - -import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; -import org.apache.commons.lang3.StringUtils; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; +import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.dto.closingcause.ClosingCauseCountDto; -import fr.insee.pearljam.api.dto.state.StateCountDto; import fr.insee.pearljam.api.exception.NotFoundException; import fr.insee.pearljam.api.service.ClosingCauseService; import fr.insee.pearljam.api.service.UtilsService; +import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; @RestController -@RequestMapping(path = "/api") @Tag(name = "06. Closing causes", description = "Endpoints for closing causes") @Slf4j @RequiredArgsConstructor public class ClosingCauseController { - private final ClosingCauseService closingCauseService; - private final UtilsService utilsService; - private final AuthenticatedUserService authenticatedUserService; + private final ClosingCauseService closingCauseService; + private final UtilsService utilsService; + private final AuthenticatedUserService authenticatedUserService; - /** - * This method is used to count survey units by states, interviewer and campaign - * - * @param request - * @param id - * @param idep - * @param date - * @return {@link StateCountDto} if exist, {@link HttpStatus} NOT_FOUND, or - * {@link HttpStatus} FORBIDDEN - */ - @Operation(summary = "Get interviewerStateCount") - @GetMapping(path = "/campaign/{id}/survey-units/interviewer/{idep}/closing-causes") - public ResponseEntity getClosingCauseCount( - @PathVariable(value = "id") String id, @PathVariable(value = "idep") String idep, - @RequestParam(required = false, name = "date") Long date) { - String userId = authenticatedUserService.getCurrentUserId(); - List associatedOrgUnits = utilsService.getRelatedOrganizationUnits(userId); + /** + * This method is used to count survey units by states, interviewer and campaign + * + * @param request + * @param id + * @param idep + * @param date + * @return {@link ClosingCauseCountDto} if exist, {@link HttpStatus} NOT_FOUND, or + * {@link HttpStatus} FORBIDDEN + */ + @Operation(summary = "Get interviewerStateCount") + @GetMapping(Constants.API_CAMPAIGN_ID_SU_INTERVIEWER_CLOSINGCAUSES) + public ResponseEntity getClosingCauseCount( + @PathVariable(value = "id") String id, @PathVariable(value = "idep") String idep, + @RequestParam(required = false, name = "date") Long date) { + String userId = authenticatedUserService.getCurrentUserId(); + List associatedOrgUnits = utilsService.getRelatedOrganizationUnits(userId); - ClosingCauseCountDto closingCountDto; - try { - closingCountDto = closingCauseService.getClosingCauseCount(userId, id, idep, date, - associatedOrgUnits); - } catch (NotFoundException e) { - log.error(e.getMessage()); - log.info("Get ClosingCauseCount resulting in 404"); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - log.info("Get ClosingCauseCount resulting in 200"); - return new ResponseEntity<>(closingCountDto, HttpStatus.OK); - } + ClosingCauseCountDto closingCountDto; + try { + closingCountDto = closingCauseService.getClosingCauseCount(userId, id, idep, date, + associatedOrgUnits); + } catch (NotFoundException e) { + log.error(e.getMessage()); + log.info("Get ClosingCauseCount resulting in 404"); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + log.info("Get ClosingCauseCount resulting in 200"); + return new ResponseEntity<>(closingCountDto, HttpStatus.OK); + } } diff --git a/src/main/java/fr/insee/pearljam/api/controller/ContactOutcomeController.java b/src/main/java/fr/insee/pearljam/api/controller/ContactOutcomeController.java index 8f1fa132..ff6f3baa 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/ContactOutcomeController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/ContactOutcomeController.java @@ -1,141 +1,138 @@ package fr.insee.pearljam.api.controller; -import java.util.List; - -import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; -import org.apache.commons.lang3.StringUtils; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - +import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.domain.Interviewer; import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeTypeCountCampaignDto; import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeTypeCountDto; import fr.insee.pearljam.api.dto.state.StateCountCampaignDto; -import fr.insee.pearljam.api.dto.state.StateCountDto; import fr.insee.pearljam.api.exception.NotFoundException; import fr.insee.pearljam.api.service.ContactOutcomeService; +import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; import io.swagger.v3.oas.annotations.Operation; +import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; @RestController -@RequestMapping(path = "/api") @RequiredArgsConstructor @Slf4j public class ContactOutcomeController { - private final ContactOutcomeService contactOutcomeService; - private final AuthenticatedUserService authenticatedUserService; + private final ContactOutcomeService contactOutcomeService; + private final AuthenticatedUserService authenticatedUserService; - /** - * This method is used to count survey units not attributed by contact-outcomes - * - * @param request - * @param id - * @return {@link StateCountDto} if exist, {@link HttpStatus} NOT_FOUND, or - * {@link HttpStatus} FORBIDDEN - */ - @Operation(summary = "Get Contact-outcomes count for non attributted SUs") - @GetMapping(path = "/campaign/{id}/survey-units/not-attributed/contact-outcomes") - public ResponseEntity getNbSUNotAttributedContactOutcomes( - @PathVariable(value = "id") String id, @RequestParam(required = false, name = "date") Long date) { - String userId = authenticatedUserService.getCurrentUserId(); - ContactOutcomeTypeCountDto contactOutcomes; - try { - contactOutcomes = contactOutcomeService.getNbSUNotAttributedContactOutcomes(userId, id, date); - } catch (NotFoundException e) { - log.error(e.getMessage()); - log.info("Get Contact-outcomes count for non attributted SUs resulting in 404"); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - log.info("Get Contact-outcomes count for non attributted SUs resulting in 200"); - return new ResponseEntity<>(contactOutcomes, HttpStatus.OK); + /** + * This method is used to count survey units not attributed by contact-outcomes + * + * @param request + * @param id + * @return {@link ContactOutcomeTypeCountDto} if exist, {@link HttpStatus} NOT_FOUND, or + * {@link HttpStatus} FORBIDDEN + */ + @Operation(summary = "Get Contact-outcomes count for non attributted SUs") + @GetMapping(Constants.API_CAMPAIGN_ID_SU_NOT_ATTRIBUTED_CONTACTOUTCOMES) + public ResponseEntity getNbSUNotAttributedContactOutcomes( + @PathVariable(value = "id") String id, + @RequestParam(required = false, name = "date") Long date) { + String userId = authenticatedUserService.getCurrentUserId(); + ContactOutcomeTypeCountDto contactOutcomes; + try { + contactOutcomes = contactOutcomeService.getNbSUNotAttributedContactOutcomes(userId, id, date); + } catch (NotFoundException e) { + log.error(e.getMessage()); + log.info("Get Contact-outcomes count for non attributted SUs resulting in 404"); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + log.info("Get Contact-outcomes count for non attributted SUs resulting in 200"); + return new ResponseEntity<>(contactOutcomes, HttpStatus.OK); - } + } - /** - * Return the contact-outcome type count - * for each campaign - * - * @param request - * @param date - * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, - * or {@link HttpStatus} FORBIDDEN - */ - @Operation(summary = "Get campaignStateCount") - @GetMapping(path = "/campaigns/survey-units/contact-outcomes") - public ResponseEntity> getCampaignsContactOutcomeTypeCount( - @RequestParam(required = false, name = "date") Long date) { - String userId = authenticatedUserService.getCurrentUserId(); + /** + * Return the contact-outcome type count for each campaign + * + * @param request + * @param date + * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, or + * {@link HttpStatus} FORBIDDEN + */ + @Operation(summary = "Get campaignStateCount") + @GetMapping(Constants.API_CAMPAIGNS_SU_CONTACTOUTCOMES) + public ResponseEntity> getCampaignsContactOutcomeTypeCount( + @RequestParam(required = false, name = "date") Long date) { + String userId = authenticatedUserService.getCurrentUserId(); - List listContactOutcomeTypeCountDto = contactOutcomeService - .getContactOutcomeTypeCountByCampaign(userId, date); - if (listContactOutcomeTypeCountDto == null) { - log.info("Get contactOutcomeTypeCount resulting in 404"); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - log.info("Get contactOutcomeTypeCount resulting in 200"); - return new ResponseEntity<>(listContactOutcomeTypeCountDto, HttpStatus.OK); - } + List listContactOutcomeTypeCountDto = contactOutcomeService + .getContactOutcomeTypeCountByCampaign(userId, date); + if (listContactOutcomeTypeCountDto == null) { + log.info("Get contactOutcomeTypeCount resulting in 404"); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + log.info("Get contactOutcomeTypeCount resulting in 200"); + return new ResponseEntity<>(listContactOutcomeTypeCountDto, HttpStatus.OK); + } - /** - * This method is used to count the contact-outcome types - * by organizational units and campaign - * - * @param request - * @param id - * @param date - * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, - * or {@link HttpStatus} FORBIDDEN - */ - @Operation(summary = "Get campaignStateCount") - @GetMapping(path = "/campaign/{id}/survey-units/contact-outcomes") - public ResponseEntity getContactOutcomeTypeCountByCampaign( - @PathVariable(value = "id") String id, @RequestParam(required = false, name = "date") Long date) { - String userId = authenticatedUserService.getCurrentUserId(); - ContactOutcomeTypeCountCampaignDto stateCountCampaignDto; - try { - stateCountCampaignDto = contactOutcomeService.getContactOutcomeCountTypeByCampaign(userId, id, date); - } catch (NotFoundException e) { - log.error(e.getMessage()); - log.info("Get contact-outcome type count resulting in 404"); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - log.info("Get contact-outcome type count resulting in 200"); - return new ResponseEntity<>(stateCountCampaignDto, HttpStatus.OK); - } + /** + * This method is used to count the contact-outcome types by organizational units and campaign + * + * @param request + * @param id + * @param date + * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, or + * {@link HttpStatus} FORBIDDEN + */ + @Operation(summary = "Get campaignStateCount") + @GetMapping(Constants.API_CAMPAIGN_ID_SU_CONTACTOUTCOMES) + public ResponseEntity getContactOutcomeTypeCountByCampaign( + @PathVariable(value = "id") String id, + @RequestParam(required = false, name = "date") Long date) { + String userId = authenticatedUserService.getCurrentUserId(); + ContactOutcomeTypeCountCampaignDto stateCountCampaignDto; + try { + stateCountCampaignDto = contactOutcomeService.getContactOutcomeCountTypeByCampaign(userId, id, + date); + } catch (NotFoundException e) { + log.error(e.getMessage()); + log.info("Get contact-outcome type count resulting in 404"); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + log.info("Get contact-outcome type count resulting in 200"); + return new ResponseEntity<>(stateCountCampaignDto, HttpStatus.OK); + } - /** - * This method is used to get the contact outcome type count associated with the - * campaign {id} for current an interviewer - * - * @param request - * @param id - * @return List of {@link Interviewer} if exist, {@link HttpStatus} NOT_FOUND, - * or {@link HttpStatus} FORBIDDEN - */ - @Operation(summary = "Get contact-outcome type for an interviewer on a specific campaign") - @GetMapping(path = "/campaign/{id}/survey-units/interviewer/{idep}/contact-outcomes") - public ResponseEntity getContactOuctomeByCampaignAndInterviewer( - @PathVariable(value = "id") String id, @PathVariable(value = "idep") String idep, - @RequestParam(required = false, name = "date") Long date) { - String userId = authenticatedUserService.getCurrentUserId(); - ContactOutcomeTypeCountDto cotd; - try { - cotd = contactOutcomeService.getContactOutcomeByInterviewerAndCampaign(userId, id, idep, date); - } catch (NotFoundException e) { - log.error(e.getMessage()); - log.info("Get contactOutcomeTypeCount resulting in 404"); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - log.info("Get contactOutcomeTypeCount resulting in 200"); - return new ResponseEntity<>(cotd, HttpStatus.OK); + /** + * This method is used to get the contact outcome type count associated with the campaign {id} for + * current an interviewer + * + * @param request + * @param id + * @return List of {@link Interviewer} if exist, {@link HttpStatus} NOT_FOUND, or + * {@link HttpStatus} FORBIDDEN + */ + @Operation(summary = "Get contact-outcome type for an interviewer on a specific campaign") + @GetMapping(Constants.API_CAMPAIGN_ID_SU_INTERVIEWER_CONTACTOUTCOMES) + public ResponseEntity getContactOuctomeByCampaignAndInterviewer( + @PathVariable(value = "id") String id, @PathVariable(value = "idep") String idep, + @RequestParam(required = false, name = "date") Long date) { + String userId = authenticatedUserService.getCurrentUserId(); + ContactOutcomeTypeCountDto cotd; + try { + cotd = contactOutcomeService.getContactOutcomeByInterviewerAndCampaign(userId, id, idep, + date); + } catch (NotFoundException e) { + log.error(e.getMessage()); + log.info("Get contactOutcomeTypeCount resulting in 404"); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + log.info("Get contactOutcomeTypeCount resulting in 200"); + return new ResponseEntity<>(cotd, HttpStatus.OK); - } + } } diff --git a/src/main/java/fr/insee/pearljam/api/controller/EnumController.java b/src/main/java/fr/insee/pearljam/api/controller/EnumController.java index 8c772ccb..67a9fd37 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/EnumController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/EnumController.java @@ -1,24 +1,22 @@ package fr.insee.pearljam.api.controller; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - +import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.domain.ContactOutcomeType; import fr.insee.pearljam.api.domain.StateType; import fr.insee.pearljam.api.domain.Status; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; @RestController @Tag(name = "11. Enums", description = "Endpoints for enums") -@RequestMapping(path = "/api") public class EnumController { @Operation(summary = "Get enum") - @GetMapping(path = "/enum/state") + @GetMapping(Constants.API_ENUM_STATE) public ResponseEntity getStateEnum() { StateType[] enumValues = StateType.values(); @@ -26,7 +24,7 @@ public ResponseEntity getStateEnum() { } @Operation(summary = "Get enum") - @GetMapping(path = "/enum/contact-attempt") + @GetMapping(Constants.API_ENUM_CONTACT_ATTEMPT) public ResponseEntity getContactAttemptEnum() { Status[] enumValues = Status.values(); @@ -34,7 +32,7 @@ public ResponseEntity getContactAttemptEnum() { } @Operation(summary = "Get enum") - @GetMapping(path = "/enum/contact-outcome") + @GetMapping(Constants.API_ENUM_CONTACT_OUTCOME) public ResponseEntity getContactOutcomeEnum() { ContactOutcomeType[] enumValues = ContactOutcomeType.values(); diff --git a/src/main/java/fr/insee/pearljam/api/controller/MessageController.java b/src/main/java/fr/insee/pearljam/api/controller/MessageController.java index f1dc0a60..2e05e920 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/MessageController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/MessageController.java @@ -1,28 +1,31 @@ package fr.insee.pearljam.api.controller; -import java.util.List; - -import fr.insee.pearljam.infrastructure.mail.MailSender; -import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; -import fr.insee.pearljam.infrastructure.mail.exception.SendMailException; -import jakarta.validation.Valid; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.messaging.simp.SimpMessagingTemplate; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -import fr.insee.pearljam.api.message.dto.MailDto; +import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.dto.message.MessageDto; import fr.insee.pearljam.api.dto.message.VerifyNameResponseDto; +import fr.insee.pearljam.api.message.dto.MailDto; import fr.insee.pearljam.api.service.MessageService; +import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; +import fr.insee.pearljam.infrastructure.mail.MailSender; +import fr.insee.pearljam.infrastructure.mail.exception.SendMailException; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +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.RestController; @RestController -@RequestMapping(path = "/api") @Tag(name = "12. Messages", description = "Endpoints for messages") @Slf4j @RequiredArgsConstructor @@ -38,7 +41,7 @@ public class MessageController{ * This method is used to post a message */ @Operation(summary = "Post a message") - @PostMapping(path = "/message") + @PostMapping(Constants.API_MESSAGE) public ResponseEntity postMessage(@RequestBody MessageDto message) { String userId = authenticatedUserService.getCurrentUserId(); String text = message.getText(); @@ -57,7 +60,7 @@ public ResponseEntity postMessage(@RequestBody MessageDto message) { * interviewer {idep} */ @Operation(summary = "Mark a message as read") - @PutMapping(path = "/message/{id}/interviewer/{idep}/read") + @PutMapping(Constants.API_MESSAGE_MARK_AS_READ) public ResponseEntity postMessage( @PathVariable(value = "id") Long id, @PathVariable(value = "idep") String idep) { @@ -74,7 +77,7 @@ public ResponseEntity postMessage( * the interviewer {idep} */ @Operation(summary = "Mark a message as deleted") - @PutMapping(path = "/message/{id}/interviewer/{idep}/delete") + @PutMapping(Constants.API_MESSAGE_MARK_AS_DELETED) public ResponseEntity postDeletedMessage( @PathVariable(value = "id") Long id, @PathVariable(value = "idep") String idep) { @@ -90,7 +93,7 @@ public ResponseEntity postDeletedMessage( * Retrieves messages sent to the interviewer with id {id} */ @Operation(summary = "Get a message") - @GetMapping(path = "/messages/{id}") + @GetMapping(Constants.API_MESSAGES_ID) public ResponseEntity> getMessages(@PathVariable(value = "id") String id) { List messages = messageService.getMessages(id); return new ResponseEntity<>(messages, HttpStatus.OK); @@ -100,7 +103,7 @@ public ResponseEntity> getMessages(@PathVariable(value = "id") * Retrieves message history */ @Operation(summary = "Get the message history") - @GetMapping(path = "/message-history") + @GetMapping(Constants.API_MESSAGEHISTORY) public ResponseEntity> getMessageHistory() { String userId = authenticatedUserService.getCurrentUserId(); List messages = messageService.getMessageHistory(userId); @@ -111,7 +114,7 @@ public ResponseEntity> getMessageHistory() { * Retrieves matching interviewers and campaigns */ @Operation(summary = "Update Messages with campaigns or interviewers listed in request body") - @PostMapping(path = "/verify-name") + @PostMapping(Constants.API_VERIFYNAME) public ResponseEntity postMessage(@RequestBody WsText name) { String userId = authenticatedUserService.getCurrentUserId(); String text = name.getText(); @@ -128,7 +131,7 @@ public ResponseEntity postMessage(@RequestBody WsText name) { * @throws SendMailException exception thrown when sending mail problems */ @Operation(summary = "Post a mail to admins") - @PostMapping(path = "/mail") + @PostMapping(Constants.API_MAIL) public void postMailMessage(@Valid @RequestBody MailDto mail) throws SendMailException { String userId = authenticatedUserService.getCurrentUserId(); log.info("User {} send a mail", userId); diff --git a/src/main/java/fr/insee/pearljam/api/controller/OrganizationUnitController.java b/src/main/java/fr/insee/pearljam/api/controller/OrganizationUnitController.java index 045842ef..1de355b6 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/OrganizationUnitController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/OrganizationUnitController.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.controller; +import fr.insee.pearljam.api.constants.Constants; import java.util.Collections; import java.util.List; @@ -29,7 +30,6 @@ @RestController @Tag(name = "05. Organization-units", description = "Endpoints for organization-units") -@RequestMapping(path = "/api") @RequiredArgsConstructor @Slf4j public class OrganizationUnitController { @@ -47,7 +47,7 @@ public class OrganizationUnitController { * @param idOu */ @Operation(summary = "Create Context with Organizational Unit and users associated") - @PostMapping(path = "/organization-units") + @PostMapping(Constants.API_ORGANIZATIONUNITS) public ResponseEntity postContext(@RequestBody List organizationUnits) { String userId = authenticatedUserService.getCurrentUserId(); Response response; @@ -68,7 +68,7 @@ public ResponseEntity postContext(@RequestBody List postOrganizationUnit(@RequestBody OrganizationUnitContextDto organizationUnit) { String userId = authenticatedUserService.getCurrentUserId(); log.info("{} try to create a new OU", userId); @@ -92,7 +92,7 @@ public ResponseEntity postOrganizationUnit(@RequestBody OrganizationUnit * @param idOu */ @Operation(summary = "Create users by organization-unit") - @PostMapping(path = "/organization-unit/{id}/users") + @PostMapping(Constants.API_ORGANIZATIONUNIT_ID_USERS) public ResponseEntity postUsersByOrganizationUnit(@PathVariable(value = "id") String id, @RequestBody List users) { Response response; @@ -114,7 +114,7 @@ public ResponseEntity postUsersByOrganizationUnit(@PathVariable(value = * @param idOu */ @Operation(summary = "Get all organization-units") - @GetMapping(path = "/organization-units") + @GetMapping(Constants.API_ORGANIZATIONUNITS) public ResponseEntity> getOrganizationUnits() { String userId = authenticatedUserService.getCurrentUserId(); log.info("{} try to get all OUs", userId); @@ -129,7 +129,7 @@ public ResponseEntity> getOrganizationUnits() { * @param idOu */ @Operation(summary = "Delete an organization-unit") - @DeleteMapping(path = "/organization-unit/{id}") + @DeleteMapping(Constants.API_ORGANIZATIONUNIT_ID) public ResponseEntity deleteOrganizationUnit(@PathVariable(value = "id") String id) { String userId = authenticatedUserService.getCurrentUserId(); HttpStatus response = organizationUnitService.delete(id); diff --git a/src/main/java/fr/insee/pearljam/api/controller/PreferenceController.java b/src/main/java/fr/insee/pearljam/api/controller/PreferenceController.java index 8c022b53..a991f2f6 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/PreferenceController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/PreferenceController.java @@ -1,25 +1,21 @@ package fr.insee.pearljam.api.controller; -import java.util.List; - +import fr.insee.pearljam.api.constants.Constants; +import fr.insee.pearljam.api.service.PreferenceService; import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; -import org.apache.commons.lang3.StringUtils; +import io.swagger.v3.oas.annotations.Operation; +import java.util.List; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import fr.insee.pearljam.api.service.PreferenceService; -import io.swagger.v3.oas.annotations.Operation; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; - @RestController @Slf4j @RequiredArgsConstructor -@RequestMapping(path = "/api") public class PreferenceController { private final PreferenceService preferenceService; @@ -29,13 +25,12 @@ public class PreferenceController { * This method is using to update the state of Survey Units listed in request * body * - * @param request - * @param listPreference - * @return + * @param listPreference list + * @return void */ - @Operation(summary = "Update preferences with campaigns listed in request body") - @PutMapping(path = "/preferences") - public ResponseEntity updateSurveyUnit(@RequestBody List listPreference) { + @Operation(summary = "Update current user preferences with campaigns listed in request body") + @PutMapping(Constants.API_PREFERENCES) + public ResponseEntity updatePreferences(@RequestBody List listPreference) { String userId = authenticatedUserService.getCurrentUserId(); HttpStatus returnCode = preferenceService.setPreferences(listPreference, userId); log.info("PUT preferences '{}' for user {} resulting in {}", String.join(", ", listPreference), userId, diff --git a/src/main/java/fr/insee/pearljam/api/controller/StateController.java b/src/main/java/fr/insee/pearljam/api/controller/StateController.java index 6f14926d..41c1ce7f 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/StateController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/StateController.java @@ -1,163 +1,180 @@ package fr.insee.pearljam.api.controller; -import java.util.List; - -import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; -import org.apache.commons.lang3.StringUtils; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - +import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.dto.state.StateCountCampaignDto; import fr.insee.pearljam.api.dto.state.StateCountDto; import fr.insee.pearljam.api.exception.NotFoundException; import fr.insee.pearljam.api.service.StateService; import fr.insee.pearljam.api.service.UtilsService; +import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; @RestController -@RequestMapping(path = "/api") @Tag(name = "07. State-count", description = "Endpoints for state counts") @Slf4j @RequiredArgsConstructor public class StateController { - private final StateService stateService; - private final UtilsService utilsService; - private final AuthenticatedUserService authenticatedUserService; + private final StateService stateService; + private final UtilsService utilsService; + private final AuthenticatedUserService authenticatedUserService; + + /** + * This method is used to count survey units by states, interviewer and campaign + * + * @param id + * @param idep + * @param date + * @return {@link StateCountDto} if exist, {@link HttpStatus} NOT_FOUND, or {@link HttpStatus} + * FORBIDDEN + */ + @Operation(summary = "Get interviewerStateCount") + @GetMapping(Constants.API_CAMPAIGN_ID_SU_INTERVIEWER_STATECOUNT) + public ResponseEntity getInterviewerStateCount( + @PathVariable(value = "id") String id, @PathVariable(value = "idep") String idep, + @RequestParam(required = false, name = "date") Long date) { + String userId = authenticatedUserService.getCurrentUserId(); + List associatedOrgUnits = utilsService.getRelatedOrganizationUnits(userId); - /** - * This method is used to count survey units by states, interviewer and campaign - * - * @param request - * @param id - * @param idep - * @param date - * @return {@link StateCountDto} if exist, {@link HttpStatus} NOT_FOUND, or - * {@link HttpStatus} FORBIDDEN - */ - @Operation(summary = "Get interviewerStateCount") - @GetMapping(path = "/campaign/{id}/survey-units/interviewer/{idep}/state-count") - public ResponseEntity getInterviewerStateCount( - @PathVariable(value = "id") String id, @PathVariable(value = "idep") String idep, - @RequestParam(required = false, name = "date") Long date) { - String userId = authenticatedUserService.getCurrentUserId(); - List associatedOrgUnits = utilsService.getRelatedOrganizationUnits(userId); + StateCountDto stateCountDto; + try { + stateCountDto = stateService.getStateCount(userId, id, idep, date, associatedOrgUnits); + } catch (NotFoundException e) { + log.error(e.getMessage()); + log.info("Get interviewerStateCount resulting in 404"); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + log.info("Get interviewerStateCount resulting in 200"); + return new ResponseEntity<>(stateCountDto, HttpStatus.OK); + } - StateCountDto stateCountDto; - try { - stateCountDto = stateService.getStateCount(userId, id, idep, date, associatedOrgUnits); - } catch (NotFoundException e) { - log.error(e.getMessage()); - log.info("Get interviewerStateCount resulting in 404"); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - log.info("Get interviewerStateCount resulting in 200"); - return new ResponseEntity<>(stateCountDto, HttpStatus.OK); - } + /** + * Return the interviewer state count by campaign + * + * @param id + * @param date + * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, or + * {@link HttpStatus} FORBIDDEN + */ + @Operation(summary = "Get interviewersStateCount") + @GetMapping(Constants.API_CAMPAIGN_ID_INTERVIEWERS_STATECOUNT) + public ResponseEntity> getInterviewersStateCountByCampaign( + @PathVariable(value = "id") String id, + @RequestParam(required = false, name = "date") Long date) { + String userId = authenticatedUserService.getCurrentUserId(); + List stateCountCampaignsDto = stateService.getInterviewersStateCountByCampaign( + userId, id, date); + if (stateCountCampaignsDto == null) { + log.info("Get interviewersStateCount resulting in 404"); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + log.info("Get interviewersStateCount resulting in 200"); + return new ResponseEntity<>(stateCountCampaignsDto, HttpStatus.OK); + } - /** - * This method is used to count survey units not attributed by states - * - * @param request - * @param id - * @return {@link StateCountDto} if exist, {@link HttpStatus} NOT_FOUND, or - * {@link HttpStatus} FORBIDDEN - */ - @Operation(summary = "Get state count for non attributted SUs") - @GetMapping(path = "/campaign/{id}/survey-units/not-attributed/state-count") - public ResponseEntity getNbSUNotAttributedStateCount( - @PathVariable(value = "id") String id, - @RequestParam(required = false, name = "date") Long date) { - String userId = authenticatedUserService.getCurrentUserId(); - StateCountDto stateCountDto; - try { - stateCountDto = stateService.getNbSUNotAttributedStateCount(userId, id, date); - } catch (NotFoundException e) { - log.error(e.getMessage()); - log.info("Get state count for non attributted SUs resulting in 404"); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - log.info("Get state count for non attributted SUs resulting in 200"); - return new ResponseEntity<>(stateCountDto, HttpStatus.OK); - } + /** + * This method is used to count survey units not attributed by states + * + * @param id + * @param date + * @return {@link StateCountDto} if exist, {@link HttpStatus} NOT_FOUND, or {@link HttpStatus} + * FORBIDDEN + */ + @Operation(summary = "Get state count for non attributted SUs") + @GetMapping(Constants.API_CAMPAIGN_ID_SU_NOT_ATTRIBUTED_STATECOUNT) + public ResponseEntity getNbSUNotAttributedStateCount( + @PathVariable(value = "id") String id, + @RequestParam(required = false, name = "date") Long date) { + String userId = authenticatedUserService.getCurrentUserId(); + StateCountDto stateCountDto; + try { + stateCountDto = stateService.getNbSUNotAttributedStateCount(userId, id, date); + } catch (NotFoundException e) { + log.error(e.getMessage()); + log.info("Get state count for non attributted SUs resulting in 404"); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + log.info("Get state count for non attributted SUs resulting in 200"); + return new ResponseEntity<>(stateCountDto, HttpStatus.OK); + } - /** - * This method is used to count survey units by states, organizational units and - * campaign - * - * @param request - * @param id - * @param date - * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, - * or {@link HttpStatus} FORBIDDEN - */ - @Operation(summary = "Get campaignStateCount") - @GetMapping(path = "/campaign/{id}/survey-units/state-count") - public ResponseEntity getCampaignStateCount( - @PathVariable(value = "id") String id, - @RequestParam(required = false, name = "date") Long date) { - String userId = authenticatedUserService.getCurrentUserId(); - StateCountCampaignDto stateCountCampaignDto; - try { - stateCountCampaignDto = stateService.getStateCountByCampaign(userId, id, date); - } catch (NotFoundException e) { - log.error(e.getMessage()); - log.info("Get campaignStateCount resulting in 404"); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - log.info("Get campaignStateCount resulting in 200"); - return new ResponseEntity<>(stateCountCampaignDto, HttpStatus.OK); - } + /** + * This method is used to count survey units by states, organizational units and campaign + * + * @param id + * @param date + * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, or + * {@link HttpStatus} FORBIDDEN + */ + @Operation(summary = "Get campaignStateCount") + @GetMapping(Constants.API_CAMPAIGN_ID_SU_STATECOUNT) + public ResponseEntity getCampaignStateCount( + @PathVariable(value = "id") String id, + @RequestParam(required = false, name = "date") Long date) { + String userId = authenticatedUserService.getCurrentUserId(); + StateCountCampaignDto stateCountCampaignDto; + try { + stateCountCampaignDto = stateService.getStateCountByCampaign(userId, id, date); + } catch (NotFoundException e) { + log.error(e.getMessage()); + log.info("Get campaignStateCount resulting in 404"); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + log.info("Get campaignStateCount resulting in 200"); + return new ResponseEntity<>(stateCountCampaignDto, HttpStatus.OK); + } - /** - * Return the sum of survey units states by interviewer as a list - * - * @param request - * @param date - * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, - * or {@link HttpStatus} FORBIDDEN - */ - @Operation(summary = "Get interviewersStateCount") - @GetMapping(path = "/interviewers/survey-units/state-count") - public ResponseEntity> getInterviewersStateCount( - @RequestParam(required = false, name = "date") Long date) { - String userId = authenticatedUserService.getCurrentUserId(); - List stateCountCampaignsDto = stateService.getStateCountByInterviewer(userId, date); - if (stateCountCampaignsDto == null) { - log.info("Get interviewersStateCount resulting in 404"); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - log.info("Get interviewersStateCount resulting in 200"); - return new ResponseEntity<>(stateCountCampaignsDto, HttpStatus.OK); - } + /** + * Return the sum of survey units states by interviewer as a list + * + * @param date + * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, or + * {@link HttpStatus} FORBIDDEN + */ + @Operation(summary = "Get interviewersStateCount") + @GetMapping(Constants.API_INTERVIEWERS_SU_STATECOUNT) + public ResponseEntity> getInterviewersStateCount( + @RequestParam(required = false, name = "date") Long date) { + String userId = authenticatedUserService.getCurrentUserId(); + List stateCountCampaignsDto = stateService.getStateCountByInterviewer(userId, + date); + if (stateCountCampaignsDto == null) { + log.info("Get interviewersStateCount resulting in 404"); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + log.info("Get interviewersStateCount resulting in 200"); + return new ResponseEntity<>(stateCountCampaignsDto, HttpStatus.OK); + } - /** - * Return the sum of survey units states by campaign as a list - * - * @param request - * @param date - * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, - * or {@link HttpStatus} FORBIDDEN - */ - @Operation(summary = "Get campaignStateCount") - @GetMapping(path = "/campaigns/survey-units/state-count") - public ResponseEntity> getCampaignsStateCount( - @RequestParam(required = false, name = "date") Long date) { - String userId = authenticatedUserService.getCurrentUserId(); - List stateCountCampaignsDto = stateService.getStateCountByCampaigns(userId, date); - if (stateCountCampaignsDto == null) { - log.info("Get campaignStateCount resulting in 404"); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - log.info("Get campaignStateCount resulting in 200"); - return new ResponseEntity<>(stateCountCampaignsDto, HttpStatus.OK); - } + /** + * Return the sum of survey units states by campaign as a list + * + * @param date + * @return {@link StateCountCampaignDto} if exist, {@link HttpStatus} NOT_FOUND, or + * {@link HttpStatus} FORBIDDEN + */ + @Operation(summary = "Get campaignStateCount") + @GetMapping(Constants.API_CAMPAIGNS_SU_STATECOUNT) + public ResponseEntity> getCampaignsStateCount( + @RequestParam(required = false, name = "date") Long date) { + String userId = authenticatedUserService.getCurrentUserId(); + List stateCountCampaignsDto = stateService.getStateCountByCampaigns(userId, + date); + if (stateCountCampaignsDto == null) { + log.info("Get campaignStateCount resulting in 404"); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + log.info("Get campaignStateCount resulting in 200"); + return new ResponseEntity<>(stateCountCampaignsDto, HttpStatus.OK); + } } diff --git a/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java b/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java index 9e7053b5..07d546ff 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/SurveyUnitController.java @@ -1,18 +1,35 @@ package fr.insee.pearljam.api.controller; -import java.util.List; -import java.util.Set; - -import fr.insee.pearljam.api.dto.surveyunit.*; +import com.fasterxml.jackson.databind.JsonNode; +import fr.insee.pearljam.api.constants.Constants; +import fr.insee.pearljam.api.domain.ClosingCauseType; +import fr.insee.pearljam.api.domain.Response; +import fr.insee.pearljam.api.domain.StateType; +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.api.domain.SurveyUnitTempZone; +import fr.insee.pearljam.api.dto.state.StateDto; +import fr.insee.pearljam.api.dto.state.SurveyUnitStatesDto; +import fr.insee.pearljam.api.dto.surveyunit.HabilitationDto; +import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitCampaignDto; +import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitContextDto; +import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDetailDto; +import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDto; +import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitInterviewerLinkDto; +import fr.insee.pearljam.api.service.SurveyUnitService; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitInterviewerResponseDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.domain.exception.EntityNotFoundException; +import fr.insee.pearljam.domain.security.model.AuthorityRole; import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; -import com.fasterxml.jackson.databind.JsonNode; -import fr.insee.pearljam.api.domain.*; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; +import java.util.List; +import java.util.Set; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; @@ -22,20 +39,9 @@ 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.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import fr.insee.pearljam.domain.security.model.AuthorityRole; -import fr.insee.pearljam.api.constants.Constants; -import fr.insee.pearljam.api.dto.state.StateDto; -import fr.insee.pearljam.api.dto.state.SurveyUnitStatesDto; -import fr.insee.pearljam.api.service.SurveyUnitService; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.tags.Tag; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; - /** * SurveyUnitController is the Controller managing {@link SurveyUnit} * entity @@ -45,7 +51,6 @@ */ @RestController @Tag(name = "02. Survey-units", description = "Endpoints for survey-units") -@RequestMapping(path = "/api") @RequiredArgsConstructor @Slf4j @Validated @@ -61,7 +66,7 @@ public class SurveyUnitController { * {@link HttpStatus} FORBIDDEN */ @Operation(summary = "Create survey-units") - @PostMapping(path = "/survey-units") + @PostMapping(Constants.API_SURVEYUNITS) public ResponseEntity postSurveyUnits(@RequestBody List surveyUnits) { Response response = surveyUnitService.createSurveyUnits(surveyUnits); log.info("POST /survey-units resulting in {} with response [{}]", response.getHttpStatus(), @@ -77,7 +82,7 @@ public ResponseEntity postSurveyUnits(@RequestBody List postSurveyUnitInterviewerLinks(@RequestBody List surveyUnits) { Response response = surveyUnitService.createSurveyUnitInterviewerLinks(surveyUnits); log.info("POST /survey-units/interviewers resulting in {} with response [{}]", response.getHttpStatus(), @@ -93,7 +98,7 @@ public ResponseEntity postSurveyUnitInterviewerLinks(@RequestBody List> getListSurveyUnit( @RequestParam(value = "extended", defaultValue = "false", required = false) Boolean extended) { String userId = authenticatedUserService.getCurrentUserId(); @@ -114,7 +119,7 @@ public ResponseEntity> getListSurveyUnit( * {@link HttpStatus} FORBIDDEN */ @Operation(summary = "Get detail of specific survey unit ") - @GetMapping(path = {"/interviewer/survey-unit/{id}", "/survey-unit/{id}"}) + @GetMapping(path = {Constants.API_SURVEYUNIT_ID_INTERVIEWER, Constants.API_SURVEYUNIT_ID}) public SurveyUnitInterviewerResponseDto getSurveyUnitById(@PathVariable(value = "id") String surveyUnitId) { String userId = authenticatedUserService.getCurrentUserId(); return surveyUnitService.getSurveyUnitInterviewerDetail(userId, surveyUnitId); @@ -122,13 +127,13 @@ public SurveyUnitInterviewerResponseDto getSurveyUnitById(@PathVariable(value = /** * This method is used to update a specific survey unit - * @param surveyUnitUpdateDto survey unit informations to update + * @param surveyUnitUpdateDto survey unit information to update * @param id survey unit id * @return {@link SurveyUnitDetailDto} * @throws EntityNotFoundException exception thrown if entity not found */ @Operation(summary = "Update the Survey Unit") - @PutMapping(path = "/survey-unit/{id}") + @PutMapping(Constants.API_SURVEYUNIT_ID) public SurveyUnitDetailDto updateSurveyUnit( @Valid @NotNull @RequestBody SurveyUnitUpdateDto surveyUnitUpdateDto, @PathVariable(value = "id") String id) throws EntityNotFoundException { @@ -143,7 +148,7 @@ public SurveyUnitDetailDto updateSurveyUnit( * This method is used to post a survey-unit by id to a temp-zone */ @Operation(summary = "Post survey-unit to temp-zone") - @PostMapping(path = "/survey-unit/{id}/temp-zone") + @PostMapping(Constants.API_SURVEYUNIT_ID_TEMP_ZONE) public ResponseEntity postSurveyUnitByIdInTempZone( @RequestBody JsonNode surveyUnit, @PathVariable(value = "id") String id) { @@ -157,7 +162,7 @@ public ResponseEntity postSurveyUnitByIdInTempZone( * This method is used to retrieve survey-units in temp-zone */ @Operation(summary = "GET all survey-units in temp-zone") - @GetMapping(path = "/survey-units/temp-zone") + @GetMapping(Constants.API_SURVEYUNITS_TEMP_ZONE) public ResponseEntity getSurveyUnitsInTempZone() { List surveyUnitTempZones = surveyUnitService.getAllSurveyUnitTempZone(); log.info("GET survey-units in temp-zone resulting in 200"); @@ -172,7 +177,7 @@ public ResponseEntity getSurveyUnitsInTempZone() { * @return {@link HttpStatus} */ @Operation(summary = "Update the state of Survey Units listed in request body") - @PutMapping(path = "/survey-unit/{id}/state/{state}") + @PutMapping(Constants.API_SURVEYUNIT_ID_STATE) public ResponseEntity updateSurveyUnitState( @PathVariable(value = "id") String surveyUnitId, @PathVariable(value = "state") StateType state) { @@ -191,7 +196,7 @@ public ResponseEntity updateSurveyUnitState( * @return {@link HttpStatus} */ @Operation(summary = "Closes a survey unit") - @PutMapping(path = "/survey-unit/{id}/close/{closingCause}") + @PutMapping(Constants.API_SURVEYUNIT_ID_CLOSE) public ResponseEntity closeSurveyUnit( @PathVariable(value = "id") String surveyUnitId, @PathVariable(value = "closingCause") ClosingCauseType closingCause) { @@ -212,7 +217,7 @@ public ResponseEntity closeSurveyUnit( * @return {@link HttpStatus} */ @Operation(summary = "Add Closing cause") - @PutMapping(path = "/survey-unit/{id}/closing-cause/{closingCause}") + @PutMapping(Constants.API_SURVEYUNIT_ID_CLOSINGCAUSE) public ResponseEntity updateClosingCause( @PathVariable(value = "id") String surveyUnitId, @PathVariable(value = "closingCause") ClosingCauseType closingCause) { @@ -223,7 +228,7 @@ public ResponseEntity updateClosingCause( } @Operation(summary = "Update the state of Survey Units listed in request body") - @PutMapping(path = "/survey-unit/{id}/viewed") + @PutMapping(Constants.API_SURVEYUNIT_ID_VIEWED) public ResponseEntity updateSurveyUnitViewed(@PathVariable(value = "id") String surveyUnitId) { String userId = authenticatedUserService.getCurrentUserId(); HttpStatus returnCode = surveyUnitService.updateSurveyUnitViewed(userId, surveyUnitId); @@ -240,7 +245,7 @@ public ResponseEntity updateSurveyUnitViewed(@PathVariable(value = "id") * {@link HttpStatus} FORBIDDEN or NOT_FOUND */ @Operation(summary = "Get Survey Units in target campaign") - @GetMapping(path = "/campaign/{id}/survey-units") + @GetMapping(Constants.API_CAMPAIGN_ID_SURVEYUNITS) public ResponseEntity> getSurveyUnitByCampaignId( @PathVariable(value = "id") String id, @RequestParam(value = "state", required = false) String state) { @@ -261,7 +266,7 @@ public ResponseEntity> getSurveyUnitByCampaignId( * @return {@link HabilitationDto} the habilitation object */ @Operation(summary = "Check habilitation") - @GetMapping(path = "/check-habilitation") + @GetMapping(Constants.API_CHECK_HABILITATION) public ResponseEntity checkHabilitation( @RequestParam(value = "id") String surveyUnitId, @RequestParam(value = "role", required = false) String role) { @@ -308,7 +313,7 @@ public ResponseEntity checkHabilitation( * or NOT_FOUND */ @Operation(summary = "Get states of given survey unit") - @GetMapping(path = "/survey-unit/{id}/states") + @GetMapping(Constants.API_SURVEYUNIT_ID_STATES) public ResponseEntity getStatesBySurveyUnitId( @PathVariable(value = "id") String id) { @@ -329,7 +334,7 @@ public ResponseEntity getStatesBySurveyUnitId( * or NOT_FOUND */ @Operation(summary = "Get closable survey units") - @GetMapping(path = "/survey-units/closable") + @GetMapping(Constants.API_SURVEYUNITS_CLOSABLE) public ResponseEntity> getClosableSurveyUnits(HttpServletRequest request) { String userId = authenticatedUserService.getCurrentUserId(); @@ -343,10 +348,9 @@ public ResponseEntity> getClosableSurveyUnits(HttpSe * This method is used to delete a survey-unit * * @param surveyUnitId the id of survey-unit - * @return {@link HttpStatus} */ @Operation(summary = "Delete survey-unit") - @DeleteMapping(path = "/survey-unit/{id}") + @DeleteMapping(Constants.API_SURVEYUNIT_ID) public void deleteSurveyUnit(@PathVariable(value = "id") String surveyUnitId) { String userId = authenticatedUserService.getCurrentUserId(); log.info("{} try to DELETE survey-unit {}", userId, surveyUnitId); @@ -360,7 +364,7 @@ public void deleteSurveyUnit(@PathVariable(value = "id") String surveyUnitId) { * @return List of {@link String} */ @Operation(summary = "Get survey units id") - @GetMapping(path = "/admin/survey-units") + @GetMapping(Constants.API_ADMIN_SURVEYUNITS) public ResponseEntity> getAllSurveyUnitsId() { String userId = authenticatedUserService.getCurrentUserId(); List suIds = surveyUnitService.getAllIds(); @@ -375,7 +379,7 @@ public ResponseEntity> getAllSurveyUnitsId() { * @return List of {@link String} */ @Operation(summary = "Get survey units id by campaign") - @GetMapping(path = "/admin/campaign/{id}/survey-units") + @GetMapping(Constants.API_ADMIN_CAMPAIGN_ID_SURVEYUNITS) public ResponseEntity> getAllSurveyUnitsIdByCampaignId(@PathVariable(value = "id") String id) { List suIds = surveyUnitService.getAllIdsByCampaignId(id); log.info("GET admin survey units for campaign {} resulting in 200", id); diff --git a/src/main/java/fr/insee/pearljam/api/controller/UserController.java b/src/main/java/fr/insee/pearljam/api/controller/UserController.java index 118666d3..05535d3a 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/UserController.java +++ b/src/main/java/fr/insee/pearljam/api/controller/UserController.java @@ -1,21 +1,6 @@ package fr.insee.pearljam.api.controller; -import java.util.Collections; -import java.util.Optional; - -import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; -import org.apache.commons.lang3.StringUtils; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -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.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - +import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; import fr.insee.pearljam.api.dto.user.UserDto; import fr.insee.pearljam.api.exception.NotFoundException; @@ -23,14 +8,25 @@ import fr.insee.pearljam.api.service.OrganizationUnitService; import fr.insee.pearljam.api.service.PreferenceService; import fr.insee.pearljam.api.service.UserService; +import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import java.util.Collections; +import java.util.Optional; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +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.RestController; @RestController @Tag(name = "03. Users", description = "Endpoints for users") -@RequestMapping(path = "/api") @Slf4j @RequiredArgsConstructor public class UserController { @@ -49,7 +45,7 @@ public class UserController { * {@link HttpStatus} FORBIDDEN */ @Operation(summary = "Get User") - @GetMapping(path = "/user") + @GetMapping(Constants.API_USER) public ResponseEntity getUser() { String userId = authenticatedUserService.getCurrentUserId(); Optional user = userService.getUser(userId); @@ -69,7 +65,7 @@ public ResponseEntity getUser() { * {@link HttpStatus} FORBIDDEN */ @Operation(summary = "Get User by id") - @GetMapping(path = "/user/{id}") + @GetMapping(Constants.API_USER_ID) public ResponseEntity getUserById( @PathVariable(value = "id") String id) { String userId = authenticatedUserService.getCurrentUserId(); @@ -89,7 +85,7 @@ public ResponseEntity getUserById( * @param request */ @Operation(summary = "Create User") - @PostMapping(path = "/user") + @PostMapping(Constants.API_USER) public ResponseEntity createUser( @RequestBody UserDto user) { String userId = authenticatedUserService.getCurrentUserId(); @@ -126,7 +122,7 @@ public ResponseEntity createUser( * @param request */ @Operation(summary = "Update User") - @PutMapping(path = "/user/{id}") + @PutMapping(Constants.API_USER_ID) public ResponseEntity updateUser( @PathVariable(value = "id") String id, @RequestBody UserDto user) { @@ -170,7 +166,7 @@ public ResponseEntity updateUser( * @param request */ @Operation(summary = "Assign User to Organization Unit") - @PutMapping(path = "/user/{userId}/organization-unit/{ouId}") + @PutMapping(Constants.API_USER_ID_ORGANIZATION_ID_OUID) public ResponseEntity assignUserToOU( @PathVariable(value = "userId") String userId, @PathVariable(value = "ouId") String ouId) { @@ -212,7 +208,7 @@ public ResponseEntity assignUserToOU( * @param request */ @Operation(summary = "Delete User") - @DeleteMapping(path = "/user/{id}") + @DeleteMapping(Constants.API_USER_ID) public ResponseEntity deleteUser(@PathVariable(value = "id") String id) { String userId = authenticatedUserService.getCurrentUserId(); log.info("{} try to delete user {}", userId, id); diff --git a/src/main/java/fr/insee/pearljam/api/controller/WsText.java b/src/main/java/fr/insee/pearljam/api/controller/WsText.java index 15d3a257..8bfa4a80 100644 --- a/src/main/java/fr/insee/pearljam/api/controller/WsText.java +++ b/src/main/java/fr/insee/pearljam/api/controller/WsText.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.controller; +import java.io.Serial; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonProperty; @@ -9,6 +10,7 @@ public class WsText implements Serializable{ /** * */ + @Serial private static final long serialVersionUID = 1L; @JsonProperty("text") private String text; diff --git a/src/main/java/fr/insee/pearljam/api/domain/Address.java b/src/main/java/fr/insee/pearljam/api/domain/Address.java index be29a41b..da7eaf61 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/Address.java +++ b/src/main/java/fr/insee/pearljam/api/domain/Address.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import jakarta.persistence.Entity; @@ -19,6 +20,7 @@ public abstract class Address implements Serializable { /** * */ + @Serial private static final long serialVersionUID = 5680240598264620967L; /** diff --git a/src/main/java/fr/insee/pearljam/api/domain/Campaign.java b/src/main/java/fr/insee/pearljam/api/domain/Campaign.java index 8cf5163b..d673359b 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/Campaign.java +++ b/src/main/java/fr/insee/pearljam/api/domain/Campaign.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import java.util.List; @@ -33,6 +34,7 @@ public class Campaign implements Serializable { /** * */ + @Serial private static final long serialVersionUID = 1L; /** @@ -75,8 +77,11 @@ public class Campaign implements Serializable { @OneToMany(mappedBy = "campaign", cascade = CascadeType.ALL, orphanRemoval = true) private List communicationTemplates; + @Column + private Boolean sensitivity; + public Campaign(String id, String label, IdentificationConfiguration identConfig, - ContactOutcomeConfiguration contOutConfig, ContactAttemptConfiguration contAttConfig, String email) { + ContactOutcomeConfiguration contOutConfig, ContactAttemptConfiguration contAttConfig, String email, boolean sensitivity) { super(); this.id = id; this.label = label; @@ -84,5 +89,6 @@ public Campaign(String id, String label, IdentificationConfiguration identConfig this.contactOutcomeConfiguration = contOutConfig; this.identificationConfiguration = identConfig; this.email = email; + this.sensitivity = sensitivity; } } diff --git a/src/main/java/fr/insee/pearljam/api/domain/CampaignMessageRecipient.java b/src/main/java/fr/insee/pearljam/api/domain/CampaignMessageRecipient.java index fa93f81e..63b493fb 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/CampaignMessageRecipient.java +++ b/src/main/java/fr/insee/pearljam/api/domain/CampaignMessageRecipient.java @@ -1,18 +1,12 @@ package fr.insee.pearljam.api.domain; -import java.io.Serializable; - -import jakarta.persistence.Entity; -import jakarta.persistence.Table; +import jakarta.persistence.*; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import jakarta.persistence.EmbeddedId; -import jakarta.persistence.JoinColumn; - -import jakarta.persistence.FetchType; -import jakarta.persistence.ManyToOne; +import java.io.Serial; +import java.io.Serializable; /** * Entity MessageRecipient : represent the entity table in DB @@ -28,6 +22,7 @@ @NoArgsConstructor public class CampaignMessageRecipient implements Serializable { + @Serial private static final long serialVersionUID = 1L; @EmbeddedId @@ -47,10 +42,4 @@ public class CampaignMessageRecipient implements Serializable { @JoinColumn(name = "campaign_id", insertable = false, updatable = false) private Campaign campaign; - public CampaignMessageRecipient(Message message, Campaign campaign) { - super(); - this.message = message; - this.campaign = campaign; - } - } diff --git a/src/main/java/fr/insee/pearljam/api/domain/CampaignMessageRecipientId.java b/src/main/java/fr/insee/pearljam/api/domain/CampaignMessageRecipientId.java index 7e20cf79..16c2208a 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/CampaignMessageRecipientId.java +++ b/src/main/java/fr/insee/pearljam/api/domain/CampaignMessageRecipientId.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import java.util.Objects; @@ -23,6 +24,7 @@ @Setter public class CampaignMessageRecipientId implements Serializable { + @Serial private static final long serialVersionUID = 1L; /** diff --git a/src/main/java/fr/insee/pearljam/api/domain/ClosingCause.java b/src/main/java/fr/insee/pearljam/api/domain/ClosingCause.java index 157047d4..3f12ea9c 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/ClosingCause.java +++ b/src/main/java/fr/insee/pearljam/api/domain/ClosingCause.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import jakarta.persistence.Column; @@ -32,6 +33,7 @@ public class ClosingCause implements Serializable { /** * */ + @Serial private static final long serialVersionUID = 1306796886154551063L; /** * the id of ContactOutcome diff --git a/src/main/java/fr/insee/pearljam/api/domain/ClosingCauseType.java b/src/main/java/fr/insee/pearljam/api/domain/ClosingCauseType.java index 91af2ef5..22a3339b 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/ClosingCauseType.java +++ b/src/main/java/fr/insee/pearljam/api/domain/ClosingCauseType.java @@ -6,29 +6,8 @@ * */ public enum ClosingCauseType { - NPA("Not processed because of interviewer absence"), - NPI("Not processed by interviewer"), - NPX("Not processed for exceptional reason"), - ROW("Right of withdrawal"); - - /** - * label of the ContactOutcomeType - */ - private String label; - - /** - * Defaut constructor for a ContactOutcomeType - * @param label - */ - ClosingCauseType(String label) { - this.label = label; - } - - /** - * Get the label for a ContactOutcomeType - * @return label - */ - public String getLabel() { - return label; - } + NPA,//Not processed because of interviewer absence + NPI,//Not processed by interviewer + NPX,//Not processed for exceptional reason + ROW,//Right of withdrawal } diff --git a/src/main/java/fr/insee/pearljam/api/domain/ContactAttempt.java b/src/main/java/fr/insee/pearljam/api/domain/ContactAttempt.java index 9bb1f4dd..e3a151d0 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/ContactAttempt.java +++ b/src/main/java/fr/insee/pearljam/api/domain/ContactAttempt.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; @@ -31,6 +32,7 @@ public class ContactAttempt implements Serializable { /** * */ + @Serial private static final long serialVersionUID = 2015739722235846385L; /** * the id of ContactAttempt diff --git a/src/main/java/fr/insee/pearljam/api/domain/ContactAttemptConfiguration.java b/src/main/java/fr/insee/pearljam/api/domain/ContactAttemptConfiguration.java index 99e2abf0..b7975035 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/ContactAttemptConfiguration.java +++ b/src/main/java/fr/insee/pearljam/api/domain/ContactAttemptConfiguration.java @@ -1,28 +1,6 @@ package fr.insee.pearljam.api.domain; public enum ContactAttemptConfiguration { - F2F("Face-to-face"), TEL("Telephone"); + F2F, TEL - /** - * label of the ContactAttemptConfiguration - */ - private String label; - - /** - * Defaut constructor for a ContactAttemptConfiguration - * - * @param label - */ - ContactAttemptConfiguration(String label) { - this.label = label; - } - - /** - * Get the label for a ContactAttemptConfiguration - * - * @return label - */ - public String getLabel() { - return label; - } } diff --git a/src/main/java/fr/insee/pearljam/api/domain/ContactOutcome.java b/src/main/java/fr/insee/pearljam/api/domain/ContactOutcome.java deleted file mode 100644 index b4196a1b..00000000 --- a/src/main/java/fr/insee/pearljam/api/domain/ContactOutcome.java +++ /dev/null @@ -1,72 +0,0 @@ -package fr.insee.pearljam.api.domain; - -import java.io.Serializable; - -import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.EnumType; -import jakarta.persistence.Enumerated; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.OneToOne; -import jakarta.persistence.Table; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -/** - * Entity ContactOutcome : represent the entity table in DB - * - * @author Claudel Benjamin - * - */ -@Entity -@Table -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -public class ContactOutcome implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1056818927018376638L; - /** - * the id of ContactOutcome - */ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - /** - * the date of ContactOutcome - */ - @Column - private Long date; - /** - * the OutcomeType of ContactOutcome - */ - @Enumerated(EnumType.STRING) - @Column - private ContactOutcomeType type; - /** - * the totalNumberOfContactAttempts of ContactOutcome - */ - @Column - private Integer totalNumberOfContactAttempts; - /** - * The SurveyUnit associated to ContactOutcome - */ - @OneToOne - private SurveyUnit surveyUnit; - - public ContactOutcome(ContactOutcomeDto contactOutcome, SurveyUnit surveyUnit) { - this.date = contactOutcome.getDate(); - this.type = contactOutcome.getType(); - this.totalNumberOfContactAttempts = contactOutcome.getTotalNumberOfContactAttempts(); - this.surveyUnit = surveyUnit; - } - -} diff --git a/src/main/java/fr/insee/pearljam/api/domain/ContactOutcomeConfiguration.java b/src/main/java/fr/insee/pearljam/api/domain/ContactOutcomeConfiguration.java index ac158855..884371e4 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/ContactOutcomeConfiguration.java +++ b/src/main/java/fr/insee/pearljam/api/domain/ContactOutcomeConfiguration.java @@ -1,28 +1,6 @@ package fr.insee.pearljam.api.domain; public enum ContactOutcomeConfiguration { - F2F("Face-to-face"), TEL("Telephone"); + F2F, TEL - /** - * label of the ContactOutcomeConfiguration - */ - private String label; - - /** - * Defaut constructor for a ContactOutcomeConfiguration - * - * @param label - */ - ContactOutcomeConfiguration(String label) { - this.label = label; - } - - /** - * Get the label for a ContactOutcomeConfiguration - * - * @return label - */ - public String getLabel() { - return label; - } } diff --git a/src/main/java/fr/insee/pearljam/api/domain/ContactOutcomeType.java b/src/main/java/fr/insee/pearljam/api/domain/ContactOutcomeType.java index 76931fbb..9414b993 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/ContactOutcomeType.java +++ b/src/main/java/fr/insee/pearljam/api/domain/ContactOutcomeType.java @@ -2,43 +2,20 @@ /** * Define the type of the ContactOutcome entity - * - * @author scorcaud * + * @author scorcaud */ public enum ContactOutcomeType { - INA("Interview accepted"), - REF("Refusal"), - IMP("Imposssible to reach"), - UCD("Unusable Contact Data"), - UTR("Unable To Respond"), - ALA("Already answered"), - DUK("Definitly Unavailable for a Known reason"), - DUU("Definitly Unavailable for an Unknown reason"), - DCD("Deceased"), - NUH("No longer Used for Habitation"), - NOA("Not Applicable"); - - /** - * label of the ContactOutcomeType - */ - private String label; - - /** - * Defaut constructor for a ContactOutcomeType - * - * @param label - */ - ContactOutcomeType(String label) { - this.label = label; - } + INA,//Interview accepted + REF,//Refusal + IMP,//Impossible to reach + UCD,//Unusable Contact Data + UTR,//Unable To Respond + ALA,//Already answered + DUK,//Definitely Unavailable for a Known reason + DUU,//Definitely Unavailable for an Unknown reason => deprecated + NUH,//No longer Used for Habitation + DCD,//Deceased => deprecated + NOA//Not Applicable - /** - * Get the label for a ContactOutcomeType - * - * @return label - */ - public String getLabel() { - return label; - } } diff --git a/src/main/java/fr/insee/pearljam/api/domain/IdentificationConfiguration.java b/src/main/java/fr/insee/pearljam/api/domain/IdentificationConfiguration.java index bbdbe355..eb24cb84 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/IdentificationConfiguration.java +++ b/src/main/java/fr/insee/pearljam/api/domain/IdentificationConfiguration.java @@ -1,29 +1,34 @@ package fr.insee.pearljam.api.domain; +import lombok.Getter; + +@Getter public enum IdentificationConfiguration { - IASCO("Identification - Access - Situation - Category - Occupant"), - NOIDENT("No identification"); + @Deprecated(forRemoval = true) + IASCO,//Identification - Access - Situation - Category - Occupant => will be replaced by `HOUSEF2F` + HOUSEF2F,//Household identification - Face to face + HOUSETEL,//Household identification - Telephone + HOUSETELWSR,//Household identification - Telephone - including secondary residence + INDF2F,//Individual identification - Face to face + INDF2FNOR,//Individual identification - Face to face - including Non Ordinary residence + INDTEL,//Individual identification - Telephone + INDTELNOR,//Individual identification - Telephone - including Non Ordinary residence + SRCVREINT,//Only for SRCV campaign re-interrogation + NOIDENT;//No identification - /** - * label of the IdentificationConfiguration - */ - private String label; - /** - * Defaut constructor for a IdentificationConfiguration - * - * @param label - */ - IdentificationConfiguration(String label) { - this.label = label; - } + /** + * Finds the IdentificationConfiguration enum by its name. + * + * @param name the name to search for + * @return the corresponding IdentificationConfiguration enum + */ + public static IdentificationConfiguration fromName(String name) { + try { + return IdentificationConfiguration.valueOf(name.toUpperCase()); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException("No matching IdentificationConfiguration for name: " + name, e); + } + } - /** - * Get the label for a IdentificationConfiguration - * - * @return label - */ - public String getLabel() { - return label; - } } diff --git a/src/main/java/fr/insee/pearljam/api/domain/InseeAddress.java b/src/main/java/fr/insee/pearljam/api/domain/InseeAddress.java index 3138b195..4cfb0d0e 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/InseeAddress.java +++ b/src/main/java/fr/insee/pearljam/api/domain/InseeAddress.java @@ -2,6 +2,7 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; +import java.io.Serial; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -23,6 +24,7 @@ public class InseeAddress extends Address { /** * */ + @Serial private static final long serialVersionUID = -4901950808854835782L; /** * The line 1 of INSEE address diff --git a/src/main/java/fr/insee/pearljam/api/domain/InseeSampleIdentifier.java b/src/main/java/fr/insee/pearljam/api/domain/InseeSampleIdentifier.java index a44590d9..2c79ee64 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/InseeSampleIdentifier.java +++ b/src/main/java/fr/insee/pearljam/api/domain/InseeSampleIdentifier.java @@ -1,18 +1,19 @@ package fr.insee.pearljam.api.domain; +import fr.insee.pearljam.api.dto.sampleidentifier.SampleIdentifiersDto; import jakarta.persistence.Column; import jakarta.persistence.Entity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import fr.insee.pearljam.api.dto.sampleidentifier.SampleIdentifiersDto; + +import java.io.Serial; /** * Entity InseeSampleIdentifier : represent the entity table in DB - * + * * @author Claudel Benjamin - * */ @Entity @Getter @@ -20,9 +21,8 @@ @AllArgsConstructor @NoArgsConstructor public class InseeSampleIdentifier extends SampleIdentifier { - /** - * - */ + + @Serial private static final long serialVersionUID = 1044333540440142996L; @Column private Integer bs; diff --git a/src/main/java/fr/insee/pearljam/api/domain/Interviewer.java b/src/main/java/fr/insee/pearljam/api/domain/Interviewer.java index 3e2665b1..049cb45c 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/Interviewer.java +++ b/src/main/java/fr/insee/pearljam/api/domain/Interviewer.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import java.util.HashSet; import java.util.Optional; @@ -32,9 +33,7 @@ @Setter public class Interviewer implements Serializable { - /** - * - */ + @Serial private static final long serialVersionUID = -5488798660579904552L; /** @@ -75,18 +74,6 @@ public class Interviewer implements Serializable { @Enumerated(EnumType.STRING) private Title title = Title.MISTER; - public Interviewer(String id, String firstName, String lastName, String email, String phoneNumber, - Set surveyUnits, Title title) { - super(); - this.id = id; - this.firstName = firstName; - this.lastName = lastName; - this.email = email; - this.phoneNumber = phoneNumber; - this.surveyUnits = surveyUnits; - this.title = Optional.ofNullable(title).orElse(Title.MISTER); - } - public Interviewer(InterviewerContextDto interviewerDto) { super(); this.id = interviewerDto.getId(); diff --git a/src/main/java/fr/insee/pearljam/api/domain/Message.java b/src/main/java/fr/insee/pearljam/api/domain/Message.java index 98db5189..62cd8e14 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/Message.java +++ b/src/main/java/fr/insee/pearljam/api/domain/Message.java @@ -1,30 +1,18 @@ package fr.insee.pearljam.api.domain; -import java.io.Serializable; -import java.util.List; - -import jakarta.persistence.CascadeType; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.JoinColumn; -import jakarta.persistence.JoinTable; -import jakarta.persistence.ManyToMany; -import jakarta.persistence.ManyToOne; -import jakarta.persistence.OneToMany; -import jakarta.persistence.Table; +import jakarta.persistence.*; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; +import java.io.Serial; +import java.io.Serializable; +import java.util.List; + /** * Entity Message : represent the entity table in DB - * + * * @author Paul Guillemet - * */ @Entity @@ -34,9 +22,7 @@ @Setter public class Message implements Serializable { - /** - * - */ + @Serial private static final long serialVersionUID = 1439604738865064692L; /** @@ -62,8 +48,8 @@ public class Message implements Serializable { * The List of campaign for the Interviewer */ @ManyToMany - @JoinTable(name = "ouMessageRecipient", joinColumns = { @JoinColumn(name = "message_id") }, inverseJoinColumns = { - @JoinColumn(name = "organization_unit_id") }) + @JoinTable(name = "ouMessageRecipient", joinColumns = {@JoinColumn(name = "message_id")}, inverseJoinColumns = { + @JoinColumn(name = "organization_unit_id")}) private List ouMessageRecipients; /** @@ -71,7 +57,7 @@ public class Message implements Serializable { */ @ManyToMany @JoinTable(name = "campaignMessageRecipient", joinColumns = { - @JoinColumn(name = "message_id") }, inverseJoinColumns = { @JoinColumn(name = "campaign_id") }) + @JoinColumn(name = "message_id")}, inverseJoinColumns = {@JoinColumn(name = "campaign_id")}) private List campaignMessageRecipients; /** @@ -93,13 +79,4 @@ public Message(String text, User sender, Long date) { this.date = date; } - public Message(String text, User sender, List ouMessageRecipients, - List interviewerMessageRecipients, Long date) { - super(); - this.text = text; - this.sender = sender; - this.ouMessageRecipients = ouMessageRecipients; - this.date = date; - } - } diff --git a/src/main/java/fr/insee/pearljam/api/domain/MessageStatus.java b/src/main/java/fr/insee/pearljam/api/domain/MessageStatus.java index 6ec420c7..63fe8741 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/MessageStatus.java +++ b/src/main/java/fr/insee/pearljam/api/domain/MessageStatus.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import jakarta.persistence.Entity; @@ -31,6 +32,7 @@ @NoArgsConstructor public class MessageStatus implements Serializable { + @Serial private static final long serialVersionUID = 1L; @EmbeddedId diff --git a/src/main/java/fr/insee/pearljam/api/domain/MessageStatusId.java b/src/main/java/fr/insee/pearljam/api/domain/MessageStatusId.java index 3b7afda1..81535cd1 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/MessageStatusId.java +++ b/src/main/java/fr/insee/pearljam/api/domain/MessageStatusId.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import java.util.Objects; @@ -23,6 +24,7 @@ @Setter public class MessageStatusId implements Serializable { + @Serial private static final long serialVersionUID = 1L; /** diff --git a/src/main/java/fr/insee/pearljam/api/domain/MessageStatusType.java b/src/main/java/fr/insee/pearljam/api/domain/MessageStatusType.java index 6e2eda01..4723ffc1 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/MessageStatusType.java +++ b/src/main/java/fr/insee/pearljam/api/domain/MessageStatusType.java @@ -7,30 +7,8 @@ */ public enum MessageStatusType { - REA("Read"), - DEL("Deleted"), - NRD("Not read"); + REA,//Read + DEL,//Deleted + NRD//Not read - /** - * label of the State type - */ - private String label; - - /** - * Defaut constructor for a StateType - * - * @param label - */ - MessageStatusType(String label) { - this.label = label; - } - - /** - * Get the label for a StateType - * - * @return label - */ - public String getLabel() { - return label; - } } diff --git a/src/main/java/fr/insee/pearljam/api/domain/OUMessageRecipient.java b/src/main/java/fr/insee/pearljam/api/domain/OUMessageRecipient.java index 704cfa17..97bd5eb7 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/OUMessageRecipient.java +++ b/src/main/java/fr/insee/pearljam/api/domain/OUMessageRecipient.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import jakarta.persistence.Entity; @@ -28,6 +29,7 @@ @Setter public class OUMessageRecipient implements Serializable { + @Serial private static final long serialVersionUID = 1L; @EmbeddedId diff --git a/src/main/java/fr/insee/pearljam/api/domain/OUMessageRecipientId.java b/src/main/java/fr/insee/pearljam/api/domain/OUMessageRecipientId.java index 2e325695..2f078246 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/OUMessageRecipientId.java +++ b/src/main/java/fr/insee/pearljam/api/domain/OUMessageRecipientId.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import java.util.Objects; @@ -23,6 +24,7 @@ @Getter public class OUMessageRecipientId implements Serializable { + @Serial private static final long serialVersionUID = 1L; /** diff --git a/src/main/java/fr/insee/pearljam/api/domain/OrganizationUnit.java b/src/main/java/fr/insee/pearljam/api/domain/OrganizationUnit.java index 4eebbeb8..f925e411 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/OrganizationUnit.java +++ b/src/main/java/fr/insee/pearljam/api/domain/OrganizationUnit.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import java.util.List; @@ -33,6 +34,7 @@ public class OrganizationUnit implements Serializable { /** * */ + @Serial private static final long serialVersionUID = 1L; /** diff --git a/src/main/java/fr/insee/pearljam/api/domain/Person.java b/src/main/java/fr/insee/pearljam/api/domain/Person.java index 3e9dec77..7fb64f75 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/Person.java +++ b/src/main/java/fr/insee/pearljam/api/domain/Person.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import java.util.HashSet; import java.util.Set; @@ -35,6 +36,7 @@ public class Person implements Serializable { /** * */ + @Serial private static final long serialVersionUID = 1L; @Id @@ -105,8 +107,8 @@ public Person(PersonDto p, SurveyUnit su) { this.firstName = p.getFirstName(); this.lastName = p.getLastName(); this.email = p.getEmail(); - this.favoriteEmail = p.isFavoriteEmail(); - this.privileged = p.isPrivileged(); + this.favoriteEmail = p.getFavoriteEmail(); + this.privileged = p.getPrivileged(); this.birthdate = p.getBirthdate(); this.phoneNumbers = p.getPhoneNumbers().stream().map(pn -> new PhoneNumber(pn, this)) .collect(Collectors.toSet()); diff --git a/src/main/java/fr/insee/pearljam/api/domain/PhoneNumber.java b/src/main/java/fr/insee/pearljam/api/domain/PhoneNumber.java index f742a985..a92285f8 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/PhoneNumber.java +++ b/src/main/java/fr/insee/pearljam/api/domain/PhoneNumber.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import jakarta.persistence.Entity; @@ -30,6 +31,7 @@ public class PhoneNumber implements Serializable { /** * */ + @Serial private static final long serialVersionUID = 1L; @Id diff --git a/src/main/java/fr/insee/pearljam/api/domain/Referent.java b/src/main/java/fr/insee/pearljam/api/domain/Referent.java index 505d5f21..2b023f75 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/Referent.java +++ b/src/main/java/fr/insee/pearljam/api/domain/Referent.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import jakarta.persistence.Column; @@ -19,7 +20,8 @@ @Setter public class Referent implements Serializable { - private static final long serialVersionUID = 1987l; + @Serial + private static final long serialVersionUID = 1987L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/src/main/java/fr/insee/pearljam/api/domain/SampleIdentifier.java b/src/main/java/fr/insee/pearljam/api/domain/SampleIdentifier.java index 9751aad1..4a16ff6e 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/SampleIdentifier.java +++ b/src/main/java/fr/insee/pearljam/api/domain/SampleIdentifier.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import jakarta.persistence.Entity; @@ -22,6 +23,7 @@ public abstract class SampleIdentifier implements Serializable { /** * */ + @Serial private static final long serialVersionUID = 5088394603526415418L; /** * The id of SampleIdentifier diff --git a/src/main/java/fr/insee/pearljam/api/domain/State.java b/src/main/java/fr/insee/pearljam/api/domain/State.java index 46a37a39..a895b90f 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/State.java +++ b/src/main/java/fr/insee/pearljam/api/domain/State.java @@ -1,20 +1,13 @@ package fr.insee.pearljam.api.domain; -import java.io.Serializable; - -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.EnumType; -import jakarta.persistence.Enumerated; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; -import jakarta.persistence.ManyToOne; -import jakarta.persistence.Table; +import fr.insee.pearljam.api.dto.state.StateDto; +import jakarta.persistence.*; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import fr.insee.pearljam.api.dto.state.StateDto; + +import java.io.Serial; +import java.io.Serializable; /** * Entity State : represent the entity table in DB @@ -28,9 +21,8 @@ @Getter @Setter public class State implements Serializable { - /** - * - */ + + @Serial private static final long serialVersionUID = 4610792644448862048L; /** @@ -70,9 +62,9 @@ public State(Long date, SurveyUnit surveyUnit, StateType type) { public State(StateDto s, SurveyUnit surveyUnit) { super(); - this.date = s.getDate(); + this.date = s.date(); this.surveyUnit = surveyUnit; - this.type = s.getType(); + this.type = s.type(); } } diff --git a/src/main/java/fr/insee/pearljam/api/domain/SurveyUnit.java b/src/main/java/fr/insee/pearljam/api/domain/SurveyUnit.java index 6f08a2a6..404c3a1f 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/SurveyUnit.java +++ b/src/main/java/fr/insee/pearljam/api/domain/SurveyUnit.java @@ -1,36 +1,35 @@ package fr.insee.pearljam.api.domain; -import java.io.Serializable; -import java.util.*; -import java.util.stream.Collectors; - -import fr.insee.pearljam.api.surveyunit.dto.IdentificationDto; -import fr.insee.pearljam.domain.surveyunit.model.Identification; -import fr.insee.pearljam.infrastructure.surveyunit.entity.IdentificationDB; +import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitContextDto; import fr.insee.pearljam.api.surveyunit.dto.CommentDto; +import fr.insee.pearljam.api.surveyunit.dto.ContactOutcomeDto; +import fr.insee.pearljam.api.surveyunit.dto.identification.IdentificationDto; import fr.insee.pearljam.domain.surveyunit.model.Comment; +import fr.insee.pearljam.domain.surveyunit.model.ContactOutcome; +import fr.insee.pearljam.domain.surveyunit.model.Identification; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommentDB; -import jakarta.persistence.CascadeType; -import jakarta.persistence.Column; -import jakarta.persistence.Entity; -import jakarta.persistence.FetchType; -import jakarta.persistence.Id; -import jakarta.persistence.ManyToOne; -import jakarta.persistence.OneToMany; -import jakarta.persistence.OneToOne; -import jakarta.persistence.Table; +import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; +import fr.insee.pearljam.infrastructure.surveyunit.entity.ContactOutcomeDB; +import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationMetadataDB; +import fr.insee.pearljam.infrastructure.surveyunit.entity.identification.IdentificationDB; +import jakarta.persistence.*; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; -import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitContextDto; + +import java.io.Serial; +import java.io.Serializable; +import java.util.Date; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; /** * Entity SurveyUnit : represent the entity table in DB - * + * * @author Claudel Benjamin - * */ @Entity @@ -39,9 +38,8 @@ @Getter @Setter public class SurveyUnit implements Serializable { - /** - * - */ + + @Serial private static final long serialVersionUID = 8615711600423725468L; /** @@ -69,6 +67,12 @@ public class SurveyUnit implements Serializable { @Column private Boolean move = false; + /** + * display name (business id) + */ + @Column + private String displayName; + /** * The address of SurveyUnit */ @@ -84,13 +88,16 @@ public class SurveyUnit implements Serializable { /** * The contactOutcome of SurveyUnit */ - @OneToOne(fetch = FetchType.LAZY, targetEntity = ContactOutcome.class, cascade = CascadeType.ALL, mappedBy = "surveyUnit", orphanRemoval = true) - private ContactOutcome contactOucome; + @OneToOne(fetch = FetchType.LAZY, targetEntity = ContactOutcomeDB.class, cascade = CascadeType.ALL, mappedBy = + "surveyUnit", orphanRemoval = true) + private ContactOutcomeDB contactOutcome; - @OneToOne(fetch = FetchType.LAZY, targetEntity = ClosingCause.class, cascade = CascadeType.ALL, mappedBy = "surveyUnit", orphanRemoval = true) + @OneToOne(fetch = FetchType.LAZY, targetEntity = ClosingCause.class, cascade = CascadeType.ALL, mappedBy = + "surveyUnit", orphanRemoval = true) private ClosingCause closingCause; - @OneToOne(fetch = FetchType.LAZY, targetEntity = IdentificationDB.class, cascade = CascadeType.ALL, mappedBy = "surveyUnit", orphanRemoval = true) + @OneToOne(fetch = FetchType.LAZY, targetEntity = IdentificationDB.class, cascade = CascadeType.ALL, mappedBy = + "surveyUnit", orphanRemoval = true) private IdentificationDB identification; /** @@ -108,23 +115,33 @@ public class SurveyUnit implements Serializable { @ManyToOne(fetch = FetchType.LAZY) private OrganizationUnit organizationUnit; - @OneToMany(fetch = FetchType.LAZY, targetEntity = Person.class, cascade = CascadeType.ALL, mappedBy = "surveyUnit", orphanRemoval = true) + @OneToMany(fetch = FetchType.LAZY, targetEntity = Person.class, cascade = CascadeType.ALL, mappedBy = "surveyUnit" + , orphanRemoval = true) private Set persons = new HashSet<>(); - @OneToMany(fetch = FetchType.LAZY, targetEntity = ContactAttempt.class, cascade = CascadeType.ALL, mappedBy = "surveyUnit", orphanRemoval = true) + @OneToMany(fetch = FetchType.LAZY, targetEntity = ContactAttempt.class, cascade = CascadeType.ALL, mappedBy = + "surveyUnit", orphanRemoval = true) private Set contactAttempts = new HashSet<>(); - @OneToMany(fetch = FetchType.LAZY, targetEntity = CommentDB.class, cascade = CascadeType.ALL, mappedBy = "surveyUnit", orphanRemoval = true) + @OneToMany(fetch = FetchType.LAZY, targetEntity = CommentDB.class, cascade = CascadeType.ALL, mappedBy = + "surveyUnit", orphanRemoval = true) private Set comments = new HashSet<>(); - @OneToMany(fetch = FetchType.LAZY, targetEntity = State.class, cascade = CascadeType.ALL, mappedBy = "surveyUnit", orphanRemoval = true) + @OneToMany(fetch = FetchType.LAZY, targetEntity = State.class, cascade = CascadeType.ALL, mappedBy = "surveyUnit", + orphanRemoval = true) private Set states = new HashSet<>(); - @OneToMany(fetch = FetchType.LAZY, targetEntity = CommunicationRequestDB.class, cascade = CascadeType.ALL, mappedBy = "surveyUnit", orphanRemoval = true) + @OneToMany(fetch = FetchType.LAZY, targetEntity = CommunicationRequestDB.class, cascade = CascadeType.ALL, + mappedBy = "surveyUnit", orphanRemoval = true) private Set communicationRequests = new HashSet<>(); + @OneToMany(fetch = FetchType.LAZY, targetEntity = CommunicationMetadataDB.class, cascade = CascadeType.ALL, + mappedBy = "surveyUnit", orphanRemoval = true) + private Set communicationMetadata = new HashSet<>(); + public SurveyUnit(String id, boolean priority, boolean viewed, Address address, SampleIdentifier sampleIdentifier, - Campaign campaign, Interviewer interviewer, OrganizationUnit organizationUnit, Set persons) { + Campaign campaign, Interviewer interviewer, OrganizationUnit organizationUnit, + Set persons) { super(); this.id = id; this.priority = priority; @@ -137,30 +154,27 @@ public SurveyUnit(String id, boolean priority, boolean viewed, Address address, this.persons = persons; } - public SurveyUnit(String id, boolean priority, boolean viewed, Address address, SampleIdentifier sampleIdentifier, - Campaign campaign, Interviewer interviewer) { - super(); - this.id = id; - this.priority = priority; - this.viewed = viewed; - this.address = address; - this.sampleIdentifier = sampleIdentifier; - this.campaign = campaign; - this.interviewer = interviewer; - } - public SurveyUnit(SurveyUnitContextDto su, OrganizationUnit organizationUnit, Campaign campaign) { this.id = su.getId(); + this.displayName = su.getDisplayName(); + //TODO: delete this test when displayName becomes mandatory in creation endpoint + if (this.displayName == null) { + this.displayName = this.id; + } this.priority = su.getPriority(); this.viewed = false; this.address = new InseeAddress(su.getAddress()); this.sampleIdentifier = new InseeSampleIdentifier(su.getSampleIdentifiers()); this.campaign = campaign; this.interviewer = null; - this.identification = new IdentificationDB(IdentificationDto.toModel(su.getIdentification()), this); + + IdentificationConfiguration identificationType = safeGetIdentificationConfiguration(campaign); + this.identification = IdentificationDB.fromModel(this, IdentificationDto.toModel(su.getIdentification(), + identificationType), identificationType); this.organizationUnit = organizationUnit; this.persons = su.getPersons().stream().map(p -> new Person(p, this)).collect(Collectors.toSet()); + this.comments = new HashSet<>( Optional.ofNullable(su.getComments()).orElse(new HashSet<>()).stream() .map(commentDto -> CommentDto.toModel(this.getId(), commentDto)) @@ -168,7 +182,9 @@ public SurveyUnit(SurveyUnitContextDto su, OrganizationUnit organizationUnit, Ca .toList()); if (su.getContactOutcome() != null) { - this.contactOucome = new ContactOutcome(su.getContactOutcome(), this); + ContactOutcomeDto inputContactOutcome = su.getContactOutcome(); + this.contactOutcome = ContactOutcomeDB.fromModel(this, new ContactOutcome(null, inputContactOutcome.date() + , inputContactOutcome.type(), inputContactOutcome.totalNumberOfContactAttempts(), su.getId())); } if (su.getContactAttempts() != null && !su.getContactAttempts().isEmpty()) { this.contactAttempts = su.getContactAttempts().stream().map(c -> new ContactAttempt(c, this)) @@ -186,6 +202,8 @@ public SurveyUnit(SurveyUnitContextDto su, OrganizationUnit organizationUnit, Ca } else { this.closingCause = null; } + + } public Boolean isAtLeastState(String state) { @@ -213,8 +231,9 @@ public void updateIdentification(Identification identification) { } IdentificationDB identificationDB = getIdentification(); - if(identificationDB == null) { - identificationDB = new IdentificationDB(identification, this); + if (identificationDB == null) { + IdentificationConfiguration identificationType = safeGetIdentificationConfiguration(campaign); + identificationDB = IdentificationDB.fromModel(this, identification, identificationType); setIdentification(identificationDB); return; } @@ -222,8 +241,16 @@ public void updateIdentification(Identification identification) { identificationDB.update(identification); } + private IdentificationConfiguration safeGetIdentificationConfiguration(Campaign campaign) { + if (campaign == null) { + return null; + } + return campaign.getIdentificationConfiguration(); + } + /** * update a list of comments for a survey unit + * * @param commentsToUpdate the comment to update */ public void updateComments(Set commentsToUpdate) { @@ -254,4 +281,23 @@ public Identification getModelIdentification() { public Set getModelCommunicationRequests() { return CommunicationRequestDB.toModel(this.getCommunicationRequests()); } + + public ContactOutcome getModelContactOutcome() { + return ContactOutcomeDB.toModel(this.getContactOutcome()); + } + + public void updateContactOutcome(ContactOutcome contactOutcome) { + if (contactOutcome == null) { + return; + } + ContactOutcomeDB currentContactOutcome = getContactOutcome(); + if (currentContactOutcome == null) { + + ContactOutcomeDB newContactOutcome = ContactOutcomeDB.fromModel(this, contactOutcome); + setContactOutcome(newContactOutcome); + return; + } + currentContactOutcome.updateContactOutcome(contactOutcome); + + } } diff --git a/src/main/java/fr/insee/pearljam/api/domain/User.java b/src/main/java/fr/insee/pearljam/api/domain/User.java index 3533e29b..ecc567c6 100644 --- a/src/main/java/fr/insee/pearljam/api/domain/User.java +++ b/src/main/java/fr/insee/pearljam/api/domain/User.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.api.domain; +import java.io.Serial; import java.io.Serializable; import java.util.List; @@ -32,6 +33,7 @@ public class User implements Serializable { /** * */ + @Serial private static final long serialVersionUID = -3490006766811003946L; /** diff --git a/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignDto.java b/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignDto.java index 5288ef13..92f65d92 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignDto.java @@ -1,10 +1,6 @@ package fr.insee.pearljam.api.dto.campaign; -import java.util.List; - import com.fasterxml.jackson.annotation.JsonInclude; - -import fr.insee.pearljam.api.domain.Campaign; import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; import fr.insee.pearljam.api.domain.IdentificationConfiguration; @@ -13,6 +9,8 @@ import lombok.NoArgsConstructor; import lombok.Setter; +import java.util.List; + @NoArgsConstructor @Getter @Setter @@ -39,18 +37,6 @@ public class CampaignDto { private ContactOutcomeConfiguration contactOutcomeConfiguration; private List referents; - public CampaignDto(String id, String label) { - super(); - this.id = id; - this.label = label; - } - - public CampaignDto(Campaign camp) { - super(); - this.id = camp.getId(); - this.label = camp.getLabel(); - } - public CampaignDto(String id, String label, Long managementStartDate, Long endDate) { super(); this.id = id; diff --git a/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignSensitivityDto.java b/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignSensitivityDto.java new file mode 100644 index 00000000..318df078 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/dto/campaign/CampaignSensitivityDto.java @@ -0,0 +1,17 @@ +package fr.insee.pearljam.api.dto.campaign; + +import fr.insee.pearljam.api.domain.Campaign; +import jakarta.validation.constraints.NotBlank; + + +public record CampaignSensitivityDto( + @NotBlank + String id, + Boolean sensitivity) +{ + public static CampaignSensitivityDto fromModel(Campaign campaignDB) { + return new CampaignSensitivityDto(campaignDB.getId(), + campaignDB.getSensitivity() + ); + } +} \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/api/dto/closingcause/ClosingCauseDto.java b/src/main/java/fr/insee/pearljam/api/dto/closingcause/ClosingCauseDto.java index 205a7d74..c3d784ab 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/closingcause/ClosingCauseDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/closingcause/ClosingCauseDto.java @@ -1,11 +1,15 @@ package fr.insee.pearljam.api.dto.closingcause; import fr.insee.pearljam.api.domain.ClosingCauseType; +import lombok.AllArgsConstructor; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter +@NoArgsConstructor +@AllArgsConstructor public class ClosingCauseDto { /** * the date of ContactOutcome @@ -16,14 +20,4 @@ public class ClosingCauseDto { */ private ClosingCauseType type; - public ClosingCauseDto(Long date, ClosingCauseType type) { - super(); - this.date = date; - this.type = type; - } - - public ClosingCauseDto() { - super(); - } - } diff --git a/src/main/java/fr/insee/pearljam/api/dto/contactattempt/ContactAttemptDto.java b/src/main/java/fr/insee/pearljam/api/dto/contactattempt/ContactAttemptDto.java index 5a790789..6d1554af 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/contactattempt/ContactAttemptDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/contactattempt/ContactAttemptDto.java @@ -3,77 +3,27 @@ import fr.insee.pearljam.api.domain.ContactAttempt; import fr.insee.pearljam.api.domain.Medium; import fr.insee.pearljam.api.domain.Status; - +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Setter +@Getter +@NoArgsConstructor +@AllArgsConstructor public class ContactAttemptDto { - - /** - * The date of the ContactAttemptDto - */ + private Long date; - - /** - * The status of the ContactAttemptDto - */ private Status status; - private Medium medium; - - public ContactAttemptDto(Long date, Status status, Medium medium) { - super(); - this.date = date; - this.status = status; - this.medium = medium; - } - + public ContactAttemptDto(ContactAttempt contactAttempt) { super(); this.date = contactAttempt.getDate(); this.status = contactAttempt.getStatus(); this.medium = contactAttempt.getMedium(); } - - - public ContactAttemptDto() { - super(); - } - - /** - * @return the date - */ - public Long getDate() { - return date; - } - - /** - * @param date the date to set - */ - public void setDate(Long date) { - this.date = date; - } - - /** - * @return the status - */ - public Status getStatus() { - return status; - } - - /** - * @param status the status to set - */ - public void setStatus(Status status) { - this.status = status; - } - - - public Medium getMedium() { - return this.medium; - } - - public void setMedium(Medium medium) { - this.medium = medium; - } - @Override public String toString() { diff --git a/src/main/java/fr/insee/pearljam/api/dto/contactoutcome/ContactOutcomeDto.java b/src/main/java/fr/insee/pearljam/api/dto/contactoutcome/ContactOutcomeDto.java deleted file mode 100644 index 7d35c865..00000000 --- a/src/main/java/fr/insee/pearljam/api/dto/contactoutcome/ContactOutcomeDto.java +++ /dev/null @@ -1,95 +0,0 @@ -package fr.insee.pearljam.api.dto.contactoutcome; - -import fr.insee.pearljam.api.domain.ContactOutcome; -import fr.insee.pearljam.api.domain.ContactOutcomeType; - -public class ContactOutcomeDto { - - /** - * The date of the ContactOutcomeDto - */ - private Long date; - - /** - * The type of the ContactOutcomeDto - */ - private ContactOutcomeType type; - - /** - * The total number of contact attempt for the current ContactOutcomeDto - */ - private Integer totalNumberOfContactAttempts; - - - public ContactOutcomeDto(Long date, ContactOutcomeType type, Integer totalNumberOfContactAttempts) { - super(); - this.date = date; - this.type = type; - this.totalNumberOfContactAttempts = totalNumberOfContactAttempts; - } - - - public ContactOutcomeDto(ContactOutcome contactOutcome) { - super(); - if(contactOutcome!=null) { - this.date = contactOutcome.getDate(); - this.type = contactOutcome.getType(); - this.totalNumberOfContactAttempts = contactOutcome.getTotalNumberOfContactAttempts(); - } - } - - - public ContactOutcomeDto() { - super(); - } - - - /** - * @return the date - */ - public Long getDate() { - return date; - } - - /** - * @param date the date to set - */ - public void setDate(Long date) { - this.date = date; - } - - /** - * @return the type - */ - public ContactOutcomeType getType() { - return type; - } - - /** - * @param type the type to set - */ - public void setType(ContactOutcomeType type) { - this.type = type; - } - - /** - * @return the totalNumberOfContactAttempts - */ - public Integer getTotalNumberOfContactAttempts() { - return totalNumberOfContactAttempts; - } - - /** - * @param totalNumberOfContactAttempts the totalNumberOfContactAttempts to set - */ - public void setTotalNumberOfContactAttempts(Integer totalNumberOfContactAttempts) { - this.totalNumberOfContactAttempts = totalNumberOfContactAttempts; - } - - @Override - public String toString() { - return "ContactOutcomeDto [date=" + date + ", type=" + type + ", totalNumberOfContactAttempts=" - + totalNumberOfContactAttempts + "]"; - } - -} diff --git a/src/main/java/fr/insee/pearljam/api/dto/contactoutcome/ContactOutcomeTypeCountCampaignDto.java b/src/main/java/fr/insee/pearljam/api/dto/contactoutcome/ContactOutcomeTypeCountCampaignDto.java index af2bc5eb..2eb2a462 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/contactoutcome/ContactOutcomeTypeCountCampaignDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/contactoutcome/ContactOutcomeTypeCountCampaignDto.java @@ -1,53 +1,17 @@ package fr.insee.pearljam.api.dto.contactoutcome; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + import java.util.List; +@Setter +@Getter +@NoArgsConstructor public class ContactOutcomeTypeCountCampaignDto { - + private List organizationUnits; - private ContactOutcomeTypeCountDto france; - - /** - * @param organizationUnits - * @param france - */ - public ContactOutcomeTypeCountCampaignDto(List organizationUnits, ContactOutcomeTypeCountDto france) { - super(); - this.organizationUnits = organizationUnits; - this.france = france; - } - - public ContactOutcomeTypeCountCampaignDto() { - super(); - } - - /** - * @return the organizationUnits - */ - public List getOrganizationUnits() { - return organizationUnits; - } - - /** - * @return the france - */ - public ContactOutcomeTypeCountDto getFrance() { - return france; - } - - /** - * @param organizationUnits the organizationUnits to set - */ - public void setOrganizationUnits(List organizationUnits) { - this.organizationUnits = organizationUnits; - } - - /** - * @param france the france to set - */ - public void setFrance(ContactOutcomeTypeCountDto france) { - this.france = france; - } } diff --git a/src/main/java/fr/insee/pearljam/api/dto/contactoutcome/ContactOutcomeTypeCountDto.java b/src/main/java/fr/insee/pearljam/api/dto/contactoutcome/ContactOutcomeTypeCountDto.java index d202ac19..f881a65e 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/contactoutcome/ContactOutcomeTypeCountDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/contactoutcome/ContactOutcomeTypeCountDto.java @@ -1,90 +1,89 @@ package fr.insee.pearljam.api.dto.contactoutcome; +import static fr.insee.pearljam.api.constants.Constants.CONTACT_OUTCOME_FIELDS; + +import fr.insee.pearljam.api.dto.campaign.CampaignDto; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import java.util.Optional; - -import static fr.insee.pearljam.api.constants.Constants.CONTACT_OUTCOME_FIELDS; -import fr.insee.pearljam.api.dto.campaign.CampaignDto; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @Getter @Setter +@NoArgsConstructor @Slf4j public class ContactOutcomeTypeCountDto { - private String idDem; - - private String labelDem; + private String idDem; - private CampaignDto campaign; + private String labelDem; - private Long inaCount; + private CampaignDto campaign; - private Long refCount; + private Long inaCount; - private Long impCount; + private Long refCount; - private Long ucdCount; + private Long impCount; - private Long utrCount; + private Long ucdCount; - private Long alaCount; + private Long utrCount; - private Long dcdCount; + private Long alaCount; - private Long nuhCount; + private Long dcdCount; - private Long dukCount; + private Long nuhCount; - private Long duuCount; + private Long dukCount; - private Long noaCount; + private Long duuCount; - private Long total; + private Long noaCount; - public ContactOutcomeTypeCountDto() { - super(); - } + private Long total; public ContactOutcomeTypeCountDto(Map obj) { dispatchAttributeValues(obj, CONTACT_OUTCOME_FIELDS); } - public ContactOutcomeTypeCountDto(Map obj, CampaignDto campaign) { - this.campaign = campaign; - dispatchAttributeValues(obj, CONTACT_OUTCOME_FIELDS); - } - - public ContactOutcomeTypeCountDto(String idDem, String labelDem, Map obj) { - this(obj); - this.idDem = idDem; - this.labelDem = labelDem; - dispatchAttributeValues(obj, CONTACT_OUTCOME_FIELDS); - } - - @SuppressWarnings("null") // to refactor with typed input - private void dispatchAttributeValues(Map obj, List fieldKeys) { - boolean nullOrEmpty = (obj == null || obj.isEmpty()); - for (String str : fieldKeys) { - if (nullOrEmpty) { - setLongField(str, 0L); - } else { - setLongField(str, Optional.ofNullable(obj.get(str)).orElse(0L)); - } - } - } - - private void setLongField(String fieldName, Long value) { - try { - Field field = getClass().getDeclaredField(fieldName); - field.set(this, value); - } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - log.warn("Couldn't set field {} with value {}", fieldName, value); - } - } + public ContactOutcomeTypeCountDto(Map obj, CampaignDto campaign) { + this.campaign = campaign; + dispatchAttributeValues(obj, CONTACT_OUTCOME_FIELDS); + } + + public ContactOutcomeTypeCountDto(String idDem, String labelDem, Map obj) { + this(obj); + this.idDem = idDem; + this.labelDem = labelDem; + dispatchAttributeValues(obj, CONTACT_OUTCOME_FIELDS); + } + + @SuppressWarnings("null") // to refactor with typed input + private void dispatchAttributeValues(Map obj, List fieldKeys) { + boolean nullOrEmpty = (obj == null || obj.isEmpty()); + for (String str : fieldKeys) { + if (nullOrEmpty) { + setLongField(str, 0L); + } else { + setLongField(str, Optional.ofNullable(obj.get(str)).orElse(0L)); + } + } + } + + private void setLongField(String fieldName, Long value) { + try { + Field field = getClass().getDeclaredField(fieldName); + field.set(this, value); + } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | + IllegalAccessException e) { + log.warn("Couldn't set field {} with value {}", fieldName, value); + } + } } diff --git a/src/main/java/fr/insee/pearljam/api/dto/count/CountDto.java b/src/main/java/fr/insee/pearljam/api/dto/count/CountDto.java index 2b580943..cee5f577 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/count/CountDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/count/CountDto.java @@ -1,28 +1,13 @@ package fr.insee.pearljam.api.dto.count; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@AllArgsConstructor +@Getter +@Setter public class CountDto { private int count; - - public CountDto(int count) { - super(); - this.count = count; - } - - /** - * @return the count - */ - public int getCount() { - return count; - } - - /** - * @param count the count to set - */ - public void setCount(int count) { - this.count = count; - } - - - } diff --git a/src/main/java/fr/insee/pearljam/api/dto/interviewer/InterviewerContextDto.java b/src/main/java/fr/insee/pearljam/api/dto/interviewer/InterviewerContextDto.java index 512210e7..f2378c72 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/interviewer/InterviewerContextDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/interviewer/InterviewerContextDto.java @@ -1,5 +1,8 @@ package fr.insee.pearljam.api.dto.interviewer; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import org.apache.commons.validator.routines.EmailValidator; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -7,6 +10,9 @@ import fr.insee.pearljam.api.domain.Interviewer; import fr.insee.pearljam.api.domain.Title; +@NoArgsConstructor +@Getter +@Setter public class InterviewerContextDto { private String id; private String firstName; @@ -36,88 +42,6 @@ public InterviewerContextDto(Interviewer interviewer) { this.title = interviewer.getTitle(); } - public InterviewerContextDto() { - super(); - } - - /** - * @return the id - */ - public String getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(String id) { - this.id = id; - } - - /** - * @return the firstName - */ - public String getFirstName() { - return firstName; - } - - /** - * @param firstName the firstName to set - */ - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - /** - * @return the lastName - */ - public String getLastName() { - return lastName; - } - - /** - * @param lastName the lastName to set - */ - public void setLastName(String lastName) { - this.lastName = lastName; - } - - /** - * @return the email - */ - public String getEmail() { - return email; - } - - /** - * @param email the email to set - */ - public void setEmail(String email) { - this.email = email; - } - - /** - * @return the phoneNumber - */ - public String getPhoneNumber() { - return phoneNumber; - } - - /** - * @param phoneNumber the phoneNumber to set - */ - public void setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - } - - public Title getTitle() { - return title; - } - - public void setTitle(Title title) { - this.title = title; - } - @JsonIgnore public boolean isValid() { return this.id != null && !this.id.isBlank() diff --git a/src/main/java/fr/insee/pearljam/api/dto/interviewer/InterviewerCountDto.java b/src/main/java/fr/insee/pearljam/api/dto/interviewer/InterviewerCountDto.java new file mode 100644 index 00000000..676fe679 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/dto/interviewer/InterviewerCountDto.java @@ -0,0 +1,6 @@ +package fr.insee.pearljam.api.dto.interviewer; + +public record InterviewerCountDto(String interviewerId, Long count) { + +} + diff --git a/src/main/java/fr/insee/pearljam/api/dto/interviewer/InterviewerDto.java b/src/main/java/fr/insee/pearljam/api/dto/interviewer/InterviewerDto.java index 2001d511..454cfbf4 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/interviewer/InterviewerDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/interviewer/InterviewerDto.java @@ -3,7 +3,15 @@ import com.fasterxml.jackson.annotation.JsonInclude; import fr.insee.pearljam.api.domain.Interviewer; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +@NoArgsConstructor +@Getter +@Setter +@AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class InterviewerDto { private String id; @@ -11,15 +19,6 @@ public class InterviewerDto { private String interviewerLastName; private Long surveyUnitCount; - - public InterviewerDto(String id, String interviewerFirstName, String interviewerLastName, Long surveyUnitCount) { - super(); - this.id = id; - this.interviewerFirstName = interviewerFirstName; - this.interviewerLastName = interviewerLastName; - this.surveyUnitCount = surveyUnitCount; - } - public InterviewerDto(String id, String interviewerFirstName, String interviewerLastName) { super(); this.id = id; @@ -33,62 +32,6 @@ public InterviewerDto(Interviewer interviewer) { this.interviewerFirstName = interviewer.getFirstName(); this.interviewerLastName = interviewer.getLastName(); } - - - public InterviewerDto() { - super(); - } - - /** - * @return the id - */ - public String getId() { - return id; - } - /** - * @param id the id to set - */ - public void setId(String id) { - this.id = id; - } - /** - * @return the interviewerFirstName - */ - public String getInterviewerFirstName() { - return interviewerFirstName; - } - /** - * @param interviewerFirstName the interviewerFirstName to set - */ - public void setInterviewerFirstName(String interviewerFirstName) { - this.interviewerFirstName = interviewerFirstName; - } - /** - * @return the interviewerLastName - */ - public String getInterviewerLastName() { - return interviewerLastName; - } - /** - * @param interviewerLastName the interviewerLastName to set - */ - public void setInterviewerLastName(String interviewerLastName) { - this.interviewerLastName = interviewerLastName; - } - /** - * @return the collectionEndDate - */ - public Long getSurveyUnitCount() { - return surveyUnitCount; - } - /** - * @param surveyUnitCount the collectionEndDate to set - */ - public void setSurveyUnitCount(Long surveyUnitCount) { - this.surveyUnitCount = surveyUnitCount; - } - - } diff --git a/src/main/java/fr/insee/pearljam/api/dto/message/MessageDto.java b/src/main/java/fr/insee/pearljam/api/dto/message/MessageDto.java index 26a76b82..dd72d678 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/message/MessageDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/message/MessageDto.java @@ -1,9 +1,15 @@ package fr.insee.pearljam.api.dto.message; -import java.util.List; - import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.List; +@Setter +@Getter +@NoArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class MessageDto { private Long id; @@ -14,16 +20,7 @@ public class MessageDto { private Long date; private String status; - - public MessageDto(Long id, String text, String sender, List recipients, Long date) { - super(); - this.id = id; - this.text = text; - this.sender = sender; - this.recipients = recipients; - this.date = date; - } - + // don't remove : called from SQL public MessageDto(Long id, String text, String sender, Long date) { super(); this.id = id; @@ -37,95 +34,5 @@ public MessageDto(String text, List recipients) { this.text = text; this.recipients = recipients; } - - public MessageDto() { - super(); - } - - /** - * @return the id of the Message - */ - public Long getId() { - return id; - } - - /** - * @param id of the Message - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the text of the Message - */ - public String getText() { - return text; - } - - /** - * @param text of the Message - */ - public void setText(String text) { - this.text = text; - } - - /** - * @return the last name of the Message - */ - public String getSender() { - return sender; - } - - /** - * @param the last name of the Message - */ - public void setSender(String sender) { - this.sender = sender; - } - - /** - * @return the email of the Message - */ - public List getRecipients() { - return recipients; - } - - /** - * @param the email of the Message - */ - public void setRecipients(List recipients) { - this.recipients = recipients; - } - - /** - * @return the phone number of the Message - */ - public Long getDate() { - return date; - } - - /** - * @param the phone number of the Message - */ - public void setDate(Long date) { - this.date = date; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public List getTypedRecipients() { - return typedRecipients; - } - public void setTypedRecipients(List typedRecipients) { - this.typedRecipients = typedRecipients; - } - } diff --git a/src/main/java/fr/insee/pearljam/api/dto/organizationunit/OrganizationUnitContextDto.java b/src/main/java/fr/insee/pearljam/api/dto/organizationunit/OrganizationUnitContextDto.java index bdac4c14..e2b6de3b 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/organizationunit/OrganizationUnitContextDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/organizationunit/OrganizationUnitContextDto.java @@ -1,15 +1,20 @@ package fr.insee.pearljam.api.dto.organizationunit; -import java.util.List; -import java.util.stream.Collectors; - import com.fasterxml.jackson.annotation.JsonInclude; - import fr.insee.pearljam.api.domain.OrganizationUnit; import fr.insee.pearljam.api.domain.OrganizationUnitType; import fr.insee.pearljam.api.domain.User; import fr.insee.pearljam.api.dto.user.UserContextDto; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.List; +import java.util.stream.Collectors; +@NoArgsConstructor +@Getter +@Setter @JsonInclude(JsonInclude.Include.NON_NULL) public class OrganizationUnitContextDto { private String id; @@ -17,84 +22,27 @@ public class OrganizationUnitContextDto { private OrganizationUnitType type; private List users; private List organisationUnitRef; - + public OrganizationUnitContextDto(String id, String label, OrganizationUnitType type, - List users) { + List users) { super(); this.id = id; this.label = label; this.type = type; this.users = users; } - public OrganizationUnitContextDto() { - super(); - } - + public OrganizationUnitContextDto(OrganizationUnit ou, List lstUser, List lstOURef) { this.id = ou.getId(); this.label = ou.getLabel(); this.type = ou.getType(); - this.users = lstUser.stream().map(u -> new UserContextDto(u.getId(), u.getFirstName(), u.getLastName(), null, null)).collect(Collectors.toList()); - if(lstOURef.isEmpty()) { + this.users = lstUser.stream().map(u -> new UserContextDto(u.getId(), u.getFirstName(), u.getLastName(), null, + null)).toList(); + if (lstOURef.isEmpty()) { this.organisationUnitRef = null; } else { this.organisationUnitRef = lstOURef; } } - /** - * @return the organisationUnit - */ - public String getId() { - return id; - } - /** - * @param id the organisationUnit id to set - */ - public void setId(String id) { - this.id = id; - } - /** - * @return the organisationUnitLabel - */ - public String getLabel() { - return label; - } - /** - * @param label the organisationUnit label to set - */ - public void setLabel(String label) { - this.label = label; - } - /** - * @return the type - */ - public OrganizationUnitType getType() { - return type; - } - /** - * @param type the type to set - */ - public void setType(OrganizationUnitType type) { - this.type = type; - } - /** - * @return the users - */ - public List getUsers() { - return users; - } - /** - * @param users the users to set - */ - public void setUsers(List users) { - this.users = users; - } - public List getOrganisationUnitRef() { - return organisationUnitRef; - } - public void setOrganisationUnitRef(List organisationUnitRef) { - this.organisationUnitRef = organisationUnitRef; - } - - + } diff --git a/src/main/java/fr/insee/pearljam/api/dto/organizationunit/OrganizationUnitDto.java b/src/main/java/fr/insee/pearljam/api/dto/organizationunit/OrganizationUnitDto.java index d002a6bd..80392b65 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/organizationunit/OrganizationUnitDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/organizationunit/OrganizationUnitDto.java @@ -1,7 +1,12 @@ package fr.insee.pearljam.api.dto.organizationunit; -import fr.insee.pearljam.api.domain.OrganizationUnit; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +@Getter +@Setter +@NoArgsConstructor public class OrganizationUnitDto { private String id; private String label; @@ -12,44 +17,6 @@ public OrganizationUnitDto(String id, String label) { this.label = label; } - public OrganizationUnitDto(OrganizationUnit ou) { - super(); - this.id = ou.getId(); - this.label = ou.getLabel(); - } - - public OrganizationUnitDto() { - super(); - } - - /** - * @return the id - */ - public String getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(String id) { - this.id = id; - } - - /** - * @return the label - */ - public String getLabel() { - return label; - } - - /** - * @param label the label to set - */ - public void setLabel(String label) { - this.label = label; - } - public String toString() { return String.format("Id : %s - label : %s", id, label); } diff --git a/src/main/java/fr/insee/pearljam/api/dto/person/PersonDto.java b/src/main/java/fr/insee/pearljam/api/dto/person/PersonDto.java index ce93c3cc..311c243c 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/person/PersonDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/person/PersonDto.java @@ -1,14 +1,17 @@ package fr.insee.pearljam.api.dto.person; import java.util.List; -import java.util.stream.Collectors; import com.fasterxml.jackson.annotation.JsonInclude; import fr.insee.pearljam.api.domain.Person; import fr.insee.pearljam.api.domain.Title; import fr.insee.pearljam.api.dto.phonenumber.PhoneNumberDto; +import lombok.Getter; +import lombok.Setter; +@Getter +@Setter @JsonInclude(JsonInclude.Include.NON_NULL) public class PersonDto { private Long id; @@ -28,7 +31,7 @@ public class PersonDto { public PersonDto() { super(); } - + public PersonDto(Person person) { this.id = person.getId(); this.title = person.getTitle(); @@ -38,15 +41,14 @@ public PersonDto(Person person) { this.favoriteEmail = person.isFavoriteEmail(); this.birthdate = person.getBirthdate(); this.privileged = person.isPrivileged(); - this.phoneNumbers = person.getPhoneNumbers().stream() - .map(phoneNum -> new PhoneNumberDto(phoneNum)) - .collect(Collectors.toList()); + this.phoneNumbers = person.getPhoneNumbers().stream().map(PhoneNumberDto::new).toList(); } /** * Constructor with all args */ - public PersonDto(Title title, String firstName, String lastName, String email, boolean favoriteEmail, boolean privileged, Long birthdate) { + public PersonDto(Title title, String firstName, String lastName, String email, boolean favoriteEmail, + boolean privileged, Long birthdate) { this.title = title; this.firstName = firstName; this.lastName = lastName; @@ -56,131 +58,5 @@ public PersonDto(Title title, String firstName, String lastName, String email, b this.birthdate = birthdate; } - /** - * @return the id - */ - public Long getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the title - */ - public Title getTitle() { - return title; - } - - /** - * @param title the title to set - */ - public void setTitle(Title title) { - this.title = title; - } - - /** - * @return the firstName - */ - public String getFirstName() { - return firstName; - } - - /** - * @param firstName the firstName to set - */ - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - /** - * @return the lastName - */ - public String getLastName() { - return lastName; - } - - /** - * @param lastName the lastName to set - */ - public void setLastName(String lastName) { - this.lastName = lastName; - } - - /** - * @return the email - */ - public String getEmail() { - return email; - } - - /** - * @param email the email to set - */ - public void setEmail(String email) { - this.email = email; - } - - /** - * @return the birthdate - */ - public Long getBirthdate() { - return birthdate; - } - - /** - * @param birthdate the birthdate to set - */ - public void setBirthdate(Long birthdate) { - this.birthdate = birthdate; - } - - /** - * @return the favoriteEmail - */ - public Boolean isFavoriteEmail() { - return favoriteEmail; - } - - /** - * @param favoriteEmail the favoriteEmail to set - */ - public void setFavoriteEmail(Boolean favoriteEmail) { - this.favoriteEmail = favoriteEmail; - } - - /** - * @return the privileged - */ - public Boolean isPrivileged() { - return privileged; - } - - /** - * @param privileged the privileged to set - */ - public void setPrivileged(Boolean privileged) { - this.privileged = privileged; - } - - /** - * @return the phoneNumbers - */ - public List getPhoneNumbers() { - return phoneNumbers; - } - - /** - * @param phoneNumbers the phoneNumbers to set - */ - public void setPhoneNumbers(List phoneNumbers) { - this.phoneNumbers = phoneNumbers; - } - } diff --git a/src/main/java/fr/insee/pearljam/api/dto/state/StateCountDto.java b/src/main/java/fr/insee/pearljam/api/dto/state/StateCountDto.java index 3624be27..3b0e2aa9 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/state/StateCountDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/state/StateCountDto.java @@ -1,18 +1,16 @@ package fr.insee.pearljam.api.dto.state; -import java.lang.reflect.Field; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import static fr.insee.pearljam.api.constants.Constants.STATECOUNT_CLOSED_CLOSING_CAUSE_FIELDS; +import static fr.insee.pearljam.api.constants.Constants.STATE_COUNT_FIELDS; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; - -import static fr.insee.pearljam.api.constants.Constants.*; - import fr.insee.pearljam.api.dto.campaign.CampaignDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerContextDto; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Map; +import java.util.Objects; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -48,6 +46,8 @@ public class StateCountDto { private Long npiCount; private Long npxCount; private Long rowCount; + private Long noticeCount; + private Long reminderCount; private Long total; public StateCountDto(Map obj) { @@ -67,15 +67,25 @@ public void addClosingCauseCount(Map obj) { @SuppressWarnings("null") // to refactor with typed input private void dispatchAttributeValues(Map obj, List fieldKeys) { boolean nullOrEmpty = (obj == null || obj.isEmpty()); + for (String str : fieldKeys) { if (nullOrEmpty) { setLongField(str, 0L); } else { - setLongField(str, Optional.ofNullable(obj.get(str)).orElse(0L)); + // Recherche insensible à la casse + Long value = obj.entrySet().stream() + .filter(entry -> entry.getKey().equalsIgnoreCase(str)) + .map(Map.Entry::getValue) + .filter(Objects::nonNull) + .findFirst() + .orElse(0L); + + setLongField(str, value); } } } + private void setLongField(String fieldName, Long value) { try { Field field = getClass().getDeclaredField(fieldName); diff --git a/src/main/java/fr/insee/pearljam/api/dto/state/StateDto.java b/src/main/java/fr/insee/pearljam/api/dto/state/StateDto.java index e39e0fa7..8dd3f19d 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/state/StateDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/state/StateDto.java @@ -11,17 +11,4 @@ public record StateDto( public StateDto(State state) { this(state.getId(), state.getDate(), state.getType()); } - - public Long getId() { - return id; - } - - public Long getDate() { - return date; - } - - public StateType getType() { - return type; - } - } diff --git a/src/main/java/fr/insee/pearljam/api/dto/statedata/StateDataDto.java b/src/main/java/fr/insee/pearljam/api/dto/statedata/StateDataDto.java index 1d9104ae..3d50f915 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/statedata/StateDataDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/statedata/StateDataDto.java @@ -1,36 +1,17 @@ package fr.insee.pearljam.api.dto.statedata; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter public class StateDataDto { private String state; private Long date; private String currentPage; - - public StateDataDto() { - super(); - } - - public StateDataDto(String state, Long date, String currentPage) { - super(); - this.state = state; - this.date = date; - this.currentPage = currentPage; - } - public String getState() { - return state; - } - public void setState(String state) { - this.state = state; - } - public Long getDate() { - return date; - } - public void setDate(Long date) { - this.date = date; - } - public String getCurrentPage() { - return currentPage; - } - public void setCurrentPage(String currentPage) { - this.currentPage = currentPage; - } + } diff --git a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitCampaignDto.java b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitCampaignDto.java index 9f46de37..96e60647 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitCampaignDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitCampaignDto.java @@ -1,31 +1,27 @@ package fr.insee.pearljam.api.dto.surveyunit; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; -import java.util.stream.Collectors; - +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; - -import fr.insee.pearljam.api.domain.ClosingCauseType; -import fr.insee.pearljam.api.domain.InseeAddress; -import fr.insee.pearljam.api.domain.InseeSampleIdentifier; -import fr.insee.pearljam.api.domain.State; -import fr.insee.pearljam.api.domain.StateType; -import fr.insee.pearljam.api.domain.SurveyUnit; -import fr.insee.pearljam.api.surveyunit.dto.CommentDto; -import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; +import fr.insee.pearljam.api.domain.*; import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; +import fr.insee.pearljam.api.surveyunit.dto.CommentDto; +import fr.insee.pearljam.api.surveyunit.dto.ContactOutcomeDto; import fr.insee.pearljam.domain.surveyunit.model.IdentificationState; import lombok.Getter; import lombok.Setter; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + @JsonInclude(JsonInclude.Include.NON_NULL) @Getter @Setter public class SurveyUnitCampaignDto { private String id; + private String displayName; private Integer ssech; private String location; private String city; @@ -40,31 +36,17 @@ public class SurveyUnitCampaignDto { private IdentificationState identificationState; private List comments; + @JsonIgnore // used to process identificationState server side, not exposed via API + private IdentificationConfiguration identificationConfiguration; + @JsonIgnoreProperties(value = { "surveyUnitCount" }) private InterviewerDto interviewer; - public SurveyUnitCampaignDto() { - super(); - } - - public SurveyUnitCampaignDto(String id, Integer ssech, String location, String city, Long finalizationDate, - Boolean reading, Boolean viewed, InterviewerDto interviewer) { - super(); - this.id = id; - this.ssech = ssech; - this.location = location; - this.city = city; - this.finalizationDate = finalizationDate; - this.interviewer = interviewer; - this.reading = reading; - this.viewed = viewed; - - } - public SurveyUnitCampaignDto(SurveyUnit su) { super(); this.id = su.getId(); + this.displayName = su.getDisplayName(); this.reading = false; this.viewed = su.getViewed(); if (su.getSampleIdentifier() instanceof InseeSampleIdentifier) { @@ -99,10 +81,11 @@ public SurveyUnitCampaignDto(SurveyUnit su) { } this.state = currentState == null ? null : currentState.getType(); this.campaign = su.getCampaign().getLabel(); + this.identificationConfiguration = su.getCampaign().getIdentificationConfiguration(); this.interviewer = su.getInterviewer() != null ? new InterviewerDto(su.getInterviewer()) : null; this.comments = CommentDto.fromModel(su.getModelComments()); - if (su.getContactOucome() != null) { - this.contactOutcome = new ContactOutcomeDto(su.getContactOucome()); + if (su.getContactOutcome() != null) { + this.contactOutcome = ContactOutcomeDto.fromModel(su.getModelContactOutcome()); } } diff --git a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitContextDto.java b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitContextDto.java index 02035cef..a1a8c4cf 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitContextDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitContextDto.java @@ -1,24 +1,30 @@ package fr.insee.pearljam.api.dto.surveyunit; -import java.util.List; -import java.util.Set; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; - import fr.insee.pearljam.api.dto.address.AddressDto; import fr.insee.pearljam.api.dto.closingcause.ClosingCauseDto; -import fr.insee.pearljam.api.surveyunit.dto.CommentDto; import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; -import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; -import fr.insee.pearljam.api.surveyunit.dto.IdentificationDto; import fr.insee.pearljam.api.dto.person.PersonDto; import fr.insee.pearljam.api.dto.sampleidentifier.SampleIdentifiersDto; import fr.insee.pearljam.api.dto.state.StateDto; +import fr.insee.pearljam.api.surveyunit.dto.CommentDto; +import fr.insee.pearljam.api.surveyunit.dto.ContactOutcomeDto; +import fr.insee.pearljam.api.surveyunit.dto.identification.RawIdentificationDto; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.List; +import java.util.Set; +@Getter +@Setter +@NoArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class SurveyUnitContextDto { private String id; + private String displayName; private List persons; private AddressDto address; private String organizationUnitId; @@ -29,201 +35,9 @@ public class SurveyUnitContextDto { private List contactAttempts; private ContactOutcomeDto contactOutcome; private ClosingCauseDto closingCause; - private IdentificationDto identification; + private RawIdentificationDto identification; private Set comments; - public SurveyUnitContextDto() { - } - - public SurveyUnitContextDto(String id, List persons, AddressDto address, - - String organizationUnitId, Boolean priority, String campaign, SampleIdentifiersDto sampleIdentifiers, - List states, List contactAttempts, ContactOutcomeDto contactOutcome, - ClosingCauseDto closingCause) { - super(); - this.id = id; - this.persons = persons; - this.address = address; - this.organizationUnitId = organizationUnitId; - this.priority = priority; - this.campaign = campaign; - this.sampleIdentifiers = sampleIdentifiers; - this.states = states; - this.contactAttempts = contactAttempts; - this.contactOutcome = contactOutcome; - this.closingCause = closingCause; - } - - /** - * @return the id - */ - public String getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(String id) { - this.id = id; - } - - /** - * @return the persons - */ - public List getPersons() { - return persons; - } - - /** - * @param persons the persons to set - */ - public void setPersons(List persons) { - this.persons = persons; - } - - /** - * @return the address - */ - public AddressDto getAddress() { - return address; - } - - /** - * @param address the address to set - */ - public void setAddress(AddressDto address) { - this.address = address; - } - - /** - * @return the organizationUnitId - */ - public String getOrganizationUnitId() { - return organizationUnitId; - } - - /** - * @param organizationUnitId the organizationUnitId to set - */ - public void setOrganizationUnitId(String organizationUnitId) { - this.organizationUnitId = organizationUnitId; - } - - /** - * @return the priority - */ - public Boolean getPriority() { - return priority; - } - - /** - * @param priority the priority to set - */ - public void setPriority(Boolean priority) { - this.priority = priority; - } - - /** - * @return the campaign - */ - public String getCampaign() { - return campaign; - } - - /** - * @param campaign the campaign to set - */ - public void setCampaign(String campaign) { - this.campaign = campaign; - } - - /** - * @return the sampleIdentifiers - */ - public SampleIdentifiersDto getSampleIdentifiers() { - return sampleIdentifiers; - } - - /** - * @param sampleIdentifiers the sampleIdentifiers to set - */ - public void setSampleIdentifiers(SampleIdentifiersDto sampleIdentifiers) { - this.sampleIdentifiers = sampleIdentifiers; - } - - /** - * @return the states - */ - public List getStates() { - return states; - } - - /** - * @param states the states to set - */ - public void setStates(List states) { - this.states = states; - } - - /** - * @return the contactAttempts - */ - public List getContactAttempts() { - return contactAttempts; - } - - /** - * @param contactAttempts the contactAttempts to set - */ - public void setContactAttempts(List contactAttempts) { - this.contactAttempts = contactAttempts; - } - - /** - * @return the contactOutcome - */ - public ContactOutcomeDto getContactOutcome() { - return contactOutcome; - } - - /** - * @param contactOutcome the contactOutcome to set - */ - public void setContactOutcome(ContactOutcomeDto contactOutcome) { - this.contactOutcome = contactOutcome; - } - - /** - * @return the closingCause - */ - public ClosingCauseDto getClosingCause() { - return closingCause; - } - - /** - * @param closingCause the closingCause to set - */ - public void setClosingCause(ClosingCauseDto closingCause) { - this.closingCause = closingCause; - } - - public IdentificationDto getIdentification() { - return this.identification; - } - - public void setIdentification(IdentificationDto identification) { - this.identification = identification; - } - - public Set getComments() { - return this.comments; - } - - public void setComments(Set comments) { - this.comments = comments; - } - /** * This method checks if mandatory fields in the Survey Unit are valid or not * diff --git a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDetailDto.java b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDetailDto.java index e4d15e69..2373ec82 100644 --- a/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDetailDto.java +++ b/src/main/java/fr/insee/pearljam/api/dto/surveyunit/SurveyUnitDetailDto.java @@ -1,27 +1,27 @@ package fr.insee.pearljam.api.dto.surveyunit; -import java.util.Comparator; -import java.util.List; - -import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestResponseDto; -import lombok.Data; - import com.fasterxml.jackson.annotation.JsonInclude; - -import fr.insee.pearljam.api.bussinessrules.BussinessRules; +import fr.insee.pearljam.api.bussinessrules.BusinessRules; import fr.insee.pearljam.api.domain.State; import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.api.dto.address.AddressDto; -import fr.insee.pearljam.api.surveyunit.dto.CommentDto; import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; -import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; -import fr.insee.pearljam.api.surveyunit.dto.IdentificationDto; import fr.insee.pearljam.api.dto.person.PersonDto; import fr.insee.pearljam.api.dto.sampleidentifier.SampleIdentifiersDto; import fr.insee.pearljam.api.dto.state.StateDto; +import fr.insee.pearljam.api.surveyunit.dto.CommentDto; +import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestResponseDto; +import fr.insee.pearljam.api.surveyunit.dto.ContactOutcomeDto; +import fr.insee.pearljam.api.surveyunit.dto.identification.IdentificationDto; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Comparator; +import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) @Data +@NoArgsConstructor public class SurveyUnitDetailDto { private String id; private List persons; @@ -37,9 +37,6 @@ public class SurveyUnitDetailDto { private IdentificationDto identification; private List communicationRequests; - public SurveyUnitDetailDto() { - } - public SurveyUnitDetailDto(SurveyUnit surveyUnit) { this.id = surveyUnit.getId(); this.setPersons(surveyUnit.getPersons().stream() @@ -54,12 +51,12 @@ public SurveyUnitDetailDto(SurveyUnit surveyUnit) { this.comments = CommentDto.fromModel(surveyUnit.getModelComments()); this.contactAttempts = surveyUnit.getContactAttempts().stream().map(ContactAttemptDto::new) .toList(); - if (surveyUnit.getContactOucome() != null) { - this.contactOutcome = new ContactOutcomeDto(surveyUnit.getContactOucome()); + if (surveyUnit.getContactOutcome() != null) { + this.contactOutcome = ContactOutcomeDto.fromModel(surveyUnit.getModelContactOutcome()); } this.states = surveyUnit.getStates().stream() .sorted(Comparator.comparing(State::getDate, Comparator.nullsLast(Comparator.reverseOrder()))) - .filter(s -> BussinessRules.stateCanBeSeenByInterviewerBussinessRules(s.getType())) + .filter(s -> BusinessRules.stateCanBeSeenByInterviewerBussinessRules(s.getType())) .map(StateDto::new) .toList(); diff --git a/src/main/java/fr/insee/pearljam/api/exception/BadRequestException.java b/src/main/java/fr/insee/pearljam/api/exception/BadRequestException.java index 05490575..56ac0462 100644 --- a/src/main/java/fr/insee/pearljam/api/exception/BadRequestException.java +++ b/src/main/java/fr/insee/pearljam/api/exception/BadRequestException.java @@ -1,33 +1,22 @@ package fr.insee.pearljam.api.exception; +import lombok.Getter; + +import java.io.Serial; + +@Getter public class BadRequestException extends RuntimeException { - /** - * - */ + @Serial private static final long serialVersionUID = 8206024945370390220L; private final int code; - private final String message; - - public BadRequestException(int code, String message) { - this.code = code; - this.message = message; - } - - /** - * @return the code - */ - public int getCode() { - return code; - } + private final String message; - /** - * @return the message - */ - @Override - public String getMessage() { - return message; + public BadRequestException(int code, String message) { + this.code = code; + this.message = message; } - + + } diff --git a/src/main/java/fr/insee/pearljam/api/exception/NoOrganizationUnitException.java b/src/main/java/fr/insee/pearljam/api/exception/NoOrganizationUnitException.java index a5bcf9cc..7750c354 100644 --- a/src/main/java/fr/insee/pearljam/api/exception/NoOrganizationUnitException.java +++ b/src/main/java/fr/insee/pearljam/api/exception/NoOrganizationUnitException.java @@ -1,10 +1,10 @@ package fr.insee.pearljam.api.exception; +import java.io.Serial; + public class NoOrganizationUnitException extends Exception { - /** - * - */ + @Serial private static final long serialVersionUID = -4821409258862477873L; public NoOrganizationUnitException(String message) { diff --git a/src/main/java/fr/insee/pearljam/api/exception/NotFoundException.java b/src/main/java/fr/insee/pearljam/api/exception/NotFoundException.java index 75697b1e..0c08bb55 100644 --- a/src/main/java/fr/insee/pearljam/api/exception/NotFoundException.java +++ b/src/main/java/fr/insee/pearljam/api/exception/NotFoundException.java @@ -1,11 +1,10 @@ package fr.insee.pearljam.api.exception; -public class NotFoundException extends Exception { +import java.io.Serial; +public class NotFoundException extends Exception { - /** - * - */ + @Serial private static final long serialVersionUID = -784002885484509004L; public NotFoundException(String message) { diff --git a/src/main/java/fr/insee/pearljam/api/exception/SurveyUnitException.java b/src/main/java/fr/insee/pearljam/api/exception/SurveyUnitException.java index 7669027a..d7e4ca3a 100644 --- a/src/main/java/fr/insee/pearljam/api/exception/SurveyUnitException.java +++ b/src/main/java/fr/insee/pearljam/api/exception/SurveyUnitException.java @@ -1,10 +1,13 @@ package fr.insee.pearljam.api.exception; +import java.io.Serial; + public class SurveyUnitException extends Exception { /** * */ + @Serial private static final long serialVersionUID = 5447456941599467523L; public SurveyUnitException(String message) { diff --git a/src/main/java/fr/insee/pearljam/api/exception/UserAlreadyExistsException.java b/src/main/java/fr/insee/pearljam/api/exception/UserAlreadyExistsException.java index 9d7976b8..ba49ef7a 100644 --- a/src/main/java/fr/insee/pearljam/api/exception/UserAlreadyExistsException.java +++ b/src/main/java/fr/insee/pearljam/api/exception/UserAlreadyExistsException.java @@ -1,10 +1,13 @@ package fr.insee.pearljam.api.exception; +import java.io.Serial; + public class UserAlreadyExistsException extends Exception { /** * */ + @Serial private static final long serialVersionUID = 1816091565879107055L; public UserAlreadyExistsException(String message) { diff --git a/src/main/java/fr/insee/pearljam/api/repository/AddressRepository.java b/src/main/java/fr/insee/pearljam/api/repository/AddressRepository.java index 5bc9934f..ea11ac36 100644 --- a/src/main/java/fr/insee/pearljam/api/repository/AddressRepository.java +++ b/src/main/java/fr/insee/pearljam/api/repository/AddressRepository.java @@ -1,10 +1,8 @@ package fr.insee.pearljam.api.repository; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; - import fr.insee.pearljam.api.domain.InseeAddress; import fr.insee.pearljam.api.dto.address.AddressDto; +import org.springframework.data.jpa.repository.JpaRepository; /** * AddressRepository is the repository using to access to Address table in DB @@ -16,8 +14,4 @@ public interface AddressRepository extends JpaRepository { AddressDto findDtoById(Long id); - @Query(value="SELECT l6 from address add " - + "INNER JOIN survey_unit su ON su.address_id = add.id " - + "WHERE su.id = ?1", nativeQuery=true) - String findLocationAndCityBySurveyUnitId(String idSurveyUnit); } diff --git a/src/main/java/fr/insee/pearljam/api/repository/CampaignRepository.java b/src/main/java/fr/insee/pearljam/api/repository/CampaignRepository.java index 41fb8a1b..a4de3f3a 100644 --- a/src/main/java/fr/insee/pearljam/api/repository/CampaignRepository.java +++ b/src/main/java/fr/insee/pearljam/api/repository/CampaignRepository.java @@ -23,9 +23,6 @@ public interface CampaignRepository extends JpaRepository { Optional findByIdIgnoreCase(String id); - @Query(value = "SELECT c.id FROM Campaign c") - List findAllIds(); - @Query(value = "SELECT DISTINCT(campaign_id) FROM visibility WHERE " + "organization_unit_id IN (:OuIds) " + "AND management_start_date <= :date " diff --git a/src/main/java/fr/insee/pearljam/api/repository/ClosingCauseRepository.java b/src/main/java/fr/insee/pearljam/api/repository/ClosingCauseRepository.java index afd2c1d7..77935377 100644 --- a/src/main/java/fr/insee/pearljam/api/repository/ClosingCauseRepository.java +++ b/src/main/java/fr/insee/pearljam/api/repository/ClosingCauseRepository.java @@ -1,13 +1,12 @@ package fr.insee.pearljam.api.repository; -import java.util.List; -import java.util.Map; - +import fr.insee.pearljam.api.domain.ClosingCause; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import fr.insee.pearljam.api.domain.ClosingCause; +import java.util.List; +import java.util.Map; public interface ClosingCauseRepository extends JpaRepository { @@ -126,32 +125,6 @@ Map getClosingCauseCountSumByInterviewer(@Param("campaignIds") List + "SUM(CASE WHEN type='NPI' THEN 1 ELSE 0 END) AS npiCount, " + "SUM(CASE WHEN type='NPX' THEN 1 ELSE 0 END) AS npxCount, " + "SUM(CASE WHEN type='ROW' THEN 1 ELSE 0 END) AS rowCount " - + "FROM ( " - + "SELECT DISTINCT(survey_unit_id), type, date FROM closing_cause WHERE (survey_unit_id, date) IN (" - + "SELECT survey_unit_id, MAX(date) FROM closing_cause WHERE survey_unit_id IN (" - + "SELECT id FROM survey_unit su " - + "WHERE campaign_id IN (:campaignIds) " - + "AND organization_unit_id IN (:ouIds) " - // SU state needs to be CLO - + "AND 'CLO' IN ( " - + "SELECT type FROM state WHERE (survey_unit_id, date) IN ( " - + "SELECT survey_unit_id, MAX(date) " - + "FROM state where survey_unit_id = su.id GROUP BY survey_unit_id" - + ")" - + ") " - + "AND interviewer_id IS NULL " - + ") " - + "AND (date<=:date OR :date<0) GROUP BY survey_unit_id" - + ") " - + ") as t", nativeQuery = true) - Map getClosingCauseCountNotAttributed(@Param("campaignIds") List campaignId, - @Param("ouIds") List ouIds, @Param("date") Long date); - - @Query(value = "SELECT " - + "SUM(CASE WHEN type='NPA' THEN 1 ELSE 0 END) AS npaCount, " - + "SUM(CASE WHEN type='NPI' THEN 1 ELSE 0 END) AS npiCount, " - + "SUM(CASE WHEN type='NPX' THEN 1 ELSE 0 END) AS npxCount, " - + "SUM(CASE WHEN type='ROW' THEN 1 ELSE 0 END) AS rowCount " + "FROM ( " + "SELECT DISTINCT(survey_unit_id), type, date FROM closing_cause WHERE (survey_unit_id, date) IN (" + "SELECT survey_unit_id, MAX(date) FROM closing_cause WHERE survey_unit_id IN (" diff --git a/src/main/java/fr/insee/pearljam/api/repository/ContactAttemptRepository.java b/src/main/java/fr/insee/pearljam/api/repository/ContactAttemptRepository.java deleted file mode 100644 index 6c952ddc..00000000 --- a/src/main/java/fr/insee/pearljam/api/repository/ContactAttemptRepository.java +++ /dev/null @@ -1,46 +0,0 @@ -package fr.insee.pearljam.api.repository; - -import java.util.List; -import java.util.Optional; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.transaction.annotation.Transactional; - -import fr.insee.pearljam.api.domain.ContactAttempt; -import fr.insee.pearljam.api.domain.Status; -import fr.insee.pearljam.api.domain.SurveyUnit; -import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; - -/** -* ContactAttemptRepository is the repository using to access to ContactAttempt table in DB -* -* @author scorcaud -* -*/ -public interface ContactAttemptRepository extends JpaRepository { - - /** - * Retrieve all the ContactAttempt in db by the SurveyUnit associated - * @param surveyUnit - * @return ContactAttemptDto - */ - List findAllDtoBySurveyUnit(SurveyUnit surveyUnit); - - /** - * Retrieve the ContactAttempt in db by the SurveyUnit and his status - * @param SurveyUnit - * @param Status - * @return ContactAttempt - */ - Optional findBySurveyUnitAndStatus(SurveyUnit surveyUnit, Status status); - - /** - * Delete the ContactAttempt in db by his id and status - * @param id - * @param status - */ - @Transactional - void deleteByIdAndStatus(Long id, Status status); - - -} diff --git a/src/main/java/fr/insee/pearljam/api/repository/ContactOutcomeRepository.java b/src/main/java/fr/insee/pearljam/api/repository/ContactOutcomeRepository.java index e273bfd1..9534895c 100644 --- a/src/main/java/fr/insee/pearljam/api/repository/ContactOutcomeRepository.java +++ b/src/main/java/fr/insee/pearljam/api/repository/ContactOutcomeRepository.java @@ -1,16 +1,12 @@ package fr.insee.pearljam.api.repository; -import java.util.List; -import java.util.Map; -import java.util.Optional; - +import fr.insee.pearljam.infrastructure.surveyunit.entity.ContactOutcomeDB; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import fr.insee.pearljam.api.domain.ContactOutcome; -import fr.insee.pearljam.api.domain.SurveyUnit; -import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; +import java.util.List; +import java.util.Map; /** * ContactOutcomeRepository is the repository using to access to ContactOutcome table in DB @@ -18,21 +14,8 @@ * @author scorcaud * */ -public interface ContactOutcomeRepository extends JpaRepository { - /** - * Retrieve all the ContactOutcome in db by the SurveyUnit associated - * @param surveyUnit - * @return ContactOutcome - */ - ContactOutcomeDto findDtoBySurveyUnit(SurveyUnit surveyUnit); +public interface ContactOutcomeRepository extends JpaRepository { - /** - * Retrieve the ContactOutcome in db by the SurveyUnit and the type of ContactOutcome - * @param SurveyUnit - * @return ContactOutcome - */ - Optional findBySurveyUnit(SurveyUnit surveyUnit); - @Query(value = "SELECT " + "SUM(CASE WHEN type='INA' THEN 1 ELSE 0 END) AS inaCount, " + "SUM(CASE WHEN type='REF' THEN 1 ELSE 0 END) AS refCount, " @@ -40,7 +23,6 @@ public interface ContactOutcomeRepository extends JpaRepository findContactOutcomeTypeByInterviewerAndCampaign(@Param("campaig + "SUM(CASE WHEN type='UCD' THEN 1 ELSE 0 END) AS ucdCount, " + "SUM(CASE WHEN type='UTR' THEN 1 ELSE 0 END) AS utrCount, " + "SUM(CASE WHEN type='ALA' THEN 1 ELSE 0 END) AS alaCount, " - + "SUM(CASE WHEN type='DCD' THEN 1 ELSE 0 END) AS dcdCount, " + "SUM(CASE WHEN type='NUH' THEN 1 ELSE 0 END) AS nuhCount, " + "SUM(CASE WHEN type='DUK' THEN 1 ELSE 0 END) AS dukCount, " + "SUM(CASE WHEN type='DUU' THEN 1 ELSE 0 END) AS duuCount, " @@ -116,7 +97,6 @@ Map findContactOutcomeTypeNotAttributed(@Param("campaignId") Strin + "SUM(CASE WHEN type='UCD' THEN 1 ELSE 0 END) AS ucdCount, " + "SUM(CASE WHEN type='UTR' THEN 1 ELSE 0 END) AS utrCount, " + "SUM(CASE WHEN type='ALA' THEN 1 ELSE 0 END) AS alaCount, " - + "SUM(CASE WHEN type='DCD' THEN 1 ELSE 0 END) AS dcdCount, " + "SUM(CASE WHEN type='NUH' THEN 1 ELSE 0 END) AS nuhCount, " + "SUM(CASE WHEN type='DUK' THEN 1 ELSE 0 END) AS dukCount, " + "SUM(CASE WHEN type='DUU' THEN 1 ELSE 0 END) AS duuCount, " @@ -150,7 +130,6 @@ Map findContactOutcomeTypeNotAttributed(@Param("campaignId") Strin + "SUM(CASE WHEN type='UCD' THEN 1 ELSE 0 END) AS ucdCount, " + "SUM(CASE WHEN type='UTR' THEN 1 ELSE 0 END) AS utrCount, " + "SUM(CASE WHEN type='ALA' THEN 1 ELSE 0 END) AS alaCount, " - + "SUM(CASE WHEN type='DCD' THEN 1 ELSE 0 END) AS dcdCount, " + "SUM(CASE WHEN type='NUH' THEN 1 ELSE 0 END) AS nuhCount, " + "SUM(CASE WHEN type='DUK' THEN 1 ELSE 0 END) AS dukCount, " + "SUM(CASE WHEN type='DUU' THEN 1 ELSE 0 END) AS duuCount, " diff --git a/src/main/java/fr/insee/pearljam/api/repository/InterviewerRepository.java b/src/main/java/fr/insee/pearljam/api/repository/InterviewerRepository.java index 273c6fba..862e8d8a 100644 --- a/src/main/java/fr/insee/pearljam/api/repository/InterviewerRepository.java +++ b/src/main/java/fr/insee/pearljam/api/repository/InterviewerRepository.java @@ -1,18 +1,14 @@ package fr.insee.pearljam.api.repository; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import org.springframework.data.domain.Pageable; +import fr.insee.pearljam.api.domain.Interviewer; +import fr.insee.pearljam.api.dto.interviewer.InterviewerContextDto; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import fr.insee.pearljam.api.domain.Interviewer; -import fr.insee.pearljam.api.dto.interviewer.InterviewerContextDto; -import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; -import fr.insee.pearljam.api.dto.message.VerifyNameResponseDto; +import java.util.List; +import java.util.Optional; +import java.util.Set; /** * InterviewerRepository is the repository using to access to Interviewer table @@ -37,12 +33,6 @@ public interface InterviewerRepository extends JpaRepository findInterviewersWorkingOnCampaign(@Param("campId") String campId, @Param("ouIds") List ouIds); - @Query("SELECT new fr.insee.pearljam.api.dto.message.VerifyNameResponseDto(interv.id, 'interviewer', concat(interv.firstName, ' ', interv.lastName)) " - + "FROM Interviewer interv " - + "INNER JOIN SurveyUnit su ON su.interviewer.id = interv.id " - + "WHERE (su.organizationUnit.id in (:ouIds) OR 'GUEST' in (:ouIds)) " - + "AND (LOWER(interv.id) LIKE LOWER(concat('%',:text,'%')) " - + "OR LOWER(interv.firstName) LIKE LOWER(concat('%',:text,'%')) " - + "OR LOWER(interv.lastName) LIKE LOWER(concat('%',:text,'%'))) ") - List findMatchingInterviewers(@Param("text") String text, @Param("ouIds") List ouIds, - Pageable pageable); - @Query("SELECT interv.id " + "FROM Interviewer interv " + "INNER JOIN SurveyUnit su " diff --git a/src/main/java/fr/insee/pearljam/api/repository/MessageRepository.java b/src/main/java/fr/insee/pearljam/api/repository/MessageRepository.java index 2673bc61..9efbf37d 100644 --- a/src/main/java/fr/insee/pearljam/api/repository/MessageRepository.java +++ b/src/main/java/fr/insee/pearljam/api/repository/MessageRepository.java @@ -1,16 +1,15 @@ package fr.insee.pearljam.api.repository; -import java.util.List; -import java.util.Optional; - +import fr.insee.pearljam.api.domain.Message; +import fr.insee.pearljam.api.dto.message.MessageDto; +import fr.insee.pearljam.api.dto.message.VerifyNameResponseDto; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import fr.insee.pearljam.api.domain.Message; -import fr.insee.pearljam.api.dto.message.MessageDto; -import fr.insee.pearljam.api.dto.message.VerifyNameResponseDto; +import java.util.List; +import java.util.Optional; /** * MessageRepository is the repository using to access to Message table in DB @@ -97,12 +96,6 @@ public interface MessageRepository extends JpaRepository { + " WHERE oumr.message_id = ?1 ", nativeQuery=true) void deleteOUMessageRecipientByMessageId(Long messageId); - @Modifying - @Query(value="DELETE FROM message_status as ms " - + " WHERE ms.message_id = ?1 ", nativeQuery=true) - void deleteMessageStatusByMessageId(Long messageId); - - List findAllBySenderId(String userId); } diff --git a/src/main/java/fr/insee/pearljam/api/repository/SurveyUnitRepository.java b/src/main/java/fr/insee/pearljam/api/repository/SurveyUnitRepository.java index a1890274..d03465c5 100644 --- a/src/main/java/fr/insee/pearljam/api/repository/SurveyUnitRepository.java +++ b/src/main/java/fr/insee/pearljam/api/repository/SurveyUnitRepository.java @@ -6,7 +6,6 @@ import java.util.Set; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; @@ -32,9 +31,9 @@ public interface SurveyUnitRepository extends JpaRepository List findIdsByInterviewerId(String idInterviewer); /** - * This method retrieve all Id of SurveyUnits with a certain state and idInterviewer in DB + * This method count SurveyUnits with contactOutcome = INA and states contains TBR * - * @return List of all {@link SurveyUnit} + * @return count of matching surveyUnits {@link Integer} */ @Query(value="SELECT COUNT(DISTINCT su.id) FROM state s " + "JOIN survey_unit su ON s.survey_unit_id=su.id " + @@ -60,28 +59,7 @@ public interface SurveyUnitRepository extends JpaRepository + "FROM survey_unit ", nativeQuery=true) List findAllIds(); - @Query(value="SELECT DISTINCT(su.id) as id FROM survey_unit su " + - "INNER JOIN campaign camp on camp.id = su.campaign_id " + - "INNER JOIN visibility vi ON vi.campaign_id = camp.id "+ - "INNER JOIN organization_unit ou ON ou.id = vi.organization_unit_id "+ - "WHERE ou.id=su.organization_unit_id AND camp.id =?1 AND ou.id ILIKE ?2", nativeQuery=true) - List findIdsByCampaignIdAndOu(String id, String ouId); - - - @Query(value="SELECT su FROM SurveyUnit su " + - "WHERE EXISTS (SELECT vi FROM VisibilityDB vi " + - "WHERE vi.campaign.id = su.campaign.id " + - "AND vi.organizationUnit.id = su.organizationUnit.id " + - "AND vi.collectionEndDate < ?1 " + - "AND vi.endDate > ?1) " + - "AND NOT EXISTS (" + - "SELECT st FROM State st WHERE " + - "st.surveyUnit.id = su.id " + - "AND st.type IN ('CLO', 'FIN', 'TBR') " + - ")") - List findAllSurveyUnitsInProcessingPhase(Long date); - - @Query(value="SELECT su.id FROM SurveyUnit su " + + @Query(value="SELECT su.id FROM SurveyUnit su " + "WHERE su.organizationUnit.id IN (:lstOuId) " + // in campaign with expected IdentificationConfiguration "AND su.campaign.identificationConfiguration = :config " + @@ -102,52 +80,81 @@ public interface SurveyUnitRepository extends JpaRepository "WHERE su.id IN (:ids) " + // Contact outcome must be null or INA "AND NOT EXISTS ( " + - "SELECT 1 FROM ContactOutcome co WHERE co.surveyUnit.id = su.id " + + "SELECT 1 FROM ContactOutcomeDB co WHERE co.surveyUnit.id = su.id " + "AND co.type <> 'INA' " + ")") List findClosableNoIdentSurveyUnitId(@Param("ids") List ids); - @Query(value="SELECT su FROM SurveyUnit su left join fetch su.identification ident " + - "WHERE su.id IN (:ids) " + - "AND ( "+ - // First case : Contact outcome is IMP and identification not finished - "( " + - "EXISTS ( " + - "SELECT 1 FROM ContactOutcome co WHERE co.surveyUnit.id = su.id " + - "AND co.type = 'IMP' " + - ") "+ - // and missing/incomplete identification - "AND ( "+ - "(ident IS NULL ) " + - "OR (ident.identification IS NULL )" + - "OR (ident.identification = 'IDENTIFIED' AND ident.access IS NULL ) " + - "OR (ident.identification = 'IDENTIFIED' AND ident.access IS NOT NULL AND ident.situation IS NULL ) " + - "OR (ident.identification = 'IDENTIFIED' AND ident.access IS NOT NULL AND ident.situation = 'ORDINARY' AND ident.category IS NULL ) " + - "OR (ident.identification = 'IDENTIFIED' AND ident.access IS NOT NULL AND ident.situation = 'ORDINARY' AND ident.category IN ('PRIMARY', 'OCCASIONAL', 'UNKNOWN') AND ident.occupant IS NULL ) " + - ") "+ - ") " + - "OR "+ - "( " + - // Second case : contact outcome must be null or INA or NOA - "NOT EXISTS ( "+ - "SELECT 1 FROM ContactOutcome co WHERE co.surveyUnit.id = su.id " + - "AND co.type NOT IN('INA','NOA')"+ - " ) " + - // and identification is not started / incomplete / and doesn't lead to Out_of_scope (business rule here, not an enum) - "AND ( "+ - "(ident IS NULL ) " + - "OR (ident.identification IS NULL )" + - "OR (ident.identification = 'IDENTIFIED' AND ident.access IS NULL ) " + - "OR (ident.identification = 'IDENTIFIED' AND ident.access IS NOT NULL AND ident.situation IS NULL ) " + - "OR (ident.identification = 'IDENTIFIED' AND ident.access IS NOT NULL AND ident.situation = 'ORDINARY' AND ident.category IS NULL ) " + - "OR (ident.identification = 'IDENTIFIED' AND ident.access IS NOT NULL AND ident.situation = 'ORDINARY' AND ident.category NOT IN ('SECONDARY', 'VACANT') ) " + - ") " + - ") " + - " )" - ) - List findClosableIascoSurveyUnitId(@Param("ids") List ids); - - + @Query(value = """ + SELECT su + FROM SurveyUnit su + LEFT JOIN FETCH su.identification ident + WHERE su.id IN (:ids) + AND ( + ( + EXISTS ( + SELECT 1 + FROM ContactOutcomeDB co + WHERE co.surveyUnit.id = su.id + AND co.type = 'IMP' + ) + AND ( + ident IS NULL + OR ident.identificationState = 'MISSING' + OR ident.identificationState = 'ONGOING' + ) + ) + OR + ( + NOT EXISTS ( + SELECT 1 + FROM ContactOutcomeDB co + WHERE co.surveyUnit.id = su.id + AND co.type NOT IN ('INA','NOA') + ) + AND ( + ident IS NULL + OR ident.identificationState = 'MISSING' + OR ident.identificationState = 'ONGOING' + OR (ident.identificationState = 'FINISHED' AND ident.access IS NOT NULL AND ident.situation = 'ORDINARY' AND ident.category NOT IN ('SECONDARY', 'VACANT') ) + + ) + ) + ) +""") + List findClosableHousef2fSurveyUnitId(@Param("ids") List ids); + + @Query(value = """ + SELECT su + FROM SurveyUnit su + LEFT JOIN FETCH su.identification ident + WHERE su.id IN (:ids) + """) + List findClosableIndf2fFSurveyUnitId(@Param("ids") List ids); + + @Query(value = """ + SELECT su + FROM SurveyUnit su + LEFT JOIN FETCH su.identification ident + WHERE su.id IN (:ids) + """) + List findClosableIndf2fnorFSurveyUnitId(@Param("ids") List ids); + + @Query(value = """ + SELECT su + FROM SurveyUnit su + LEFT JOIN FETCH su.identification ident + WHERE su.id IN (:ids) + """) + List findClosableIndtelFSurveyUnitId(@Param("ids") List ids); + + @Query(value = """ + SELECT su + FROM SurveyUnit su + LEFT JOIN FETCH su.identification ident + WHERE su.id IN (:ids) + """) + List findClosableIndtelnorFSurveyUnitId(@Param("ids") List ids); @Query(value="SELECT su FROM SurveyUnit su " +" LEFT JOIN fetch su.comments" @@ -155,7 +162,7 @@ public interface SurveyUnitRepository extends JpaRepository +" LEFT JOIN fetch su.address" +" LEFT JOIN fetch su.sampleIdentifier " +" LEFT JOIN fetch su.interviewer " - +" LEFT JOIN fetch su.contactOucome " + +" LEFT JOIN fetch su.contactOutcome " +" LEFT JOIN fetch su.closingCause " +" LEFT JOIN fetch su.identification " + "WHERE su.campaign.id=:id AND su.organizationUnit.id IN (:lstOuId)") @@ -183,9 +190,6 @@ public interface SurveyUnitRepository extends JpaRepository List findByOrganizationUnitIdIn(List lstOuId); - @Modifying - @Query(value="UPDATE survey_unit SET interviewer_id=NULL", nativeQuery=true) - void updateAllinterviewersToNull(); @Query(value="SELECT su FROM SurveyUnit su WHERE " + "su.id=:id AND su.organizationUnit.id IN (:OUids)") diff --git a/src/main/java/fr/insee/pearljam/api/service/CampaignService.java b/src/main/java/fr/insee/pearljam/api/service/CampaignService.java index 3541d158..08f7c2f5 100644 --- a/src/main/java/fr/insee/pearljam/api/service/CampaignService.java +++ b/src/main/java/fr/insee/pearljam/api/service/CampaignService.java @@ -5,6 +5,7 @@ import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; +import fr.insee.pearljam.api.dto.campaign.CampaignSensitivityDto; import fr.insee.pearljam.domain.exception.*; import fr.insee.pearljam.api.domain.Campaign; @@ -63,4 +64,6 @@ public interface CampaignService { boolean isCampaignOngoing(String id) throws CampaignNotFoundException; CampaignResponseDto getCampaignDtoById(String id) throws CampaignNotFoundException; + + List getCampaignSensitivityDto() throws CampaignNotFoundException; } diff --git a/src/main/java/fr/insee/pearljam/api/service/InterviewerService.java b/src/main/java/fr/insee/pearljam/api/service/InterviewerService.java index 61a85e41..2ac60d4e 100644 --- a/src/main/java/fr/insee/pearljam/api/service/InterviewerService.java +++ b/src/main/java/fr/insee/pearljam/api/service/InterviewerService.java @@ -23,8 +23,6 @@ public interface InterviewerService { Set getListInterviewers(String userId); - boolean isPresent(String interviewerId); - boolean delete(String id); Optional update(String id, InterviewerContextDto interviewer); diff --git a/src/main/java/fr/insee/pearljam/api/service/StateService.java b/src/main/java/fr/insee/pearljam/api/service/StateService.java index b2579c91..82ac7d11 100644 --- a/src/main/java/fr/insee/pearljam/api/service/StateService.java +++ b/src/main/java/fr/insee/pearljam/api/service/StateService.java @@ -1,10 +1,9 @@ package fr.insee.pearljam.api.service; -import java.util.List; - import fr.insee.pearljam.api.dto.state.StateCountCampaignDto; import fr.insee.pearljam.api.dto.state.StateCountDto; import fr.insee.pearljam.api.exception.NotFoundException; +import java.util.List; /** * Service for the Campaign entity @@ -48,5 +47,19 @@ StateCountDto getStateCount(String userId, String campaignId, String interviewer */ List getStateCountByInterviewer(String userId, Long date); + /** + * @param userId + * @param campaignId + * @param date + * @return {@link List} + */ + List getInterviewersStateCountByCampaign(String userId, String campaignId, Long date); + + /** + * @param userId + * @param id + * @param date + * @return {@link StateCountDto} + */ StateCountDto getNbSUNotAttributedStateCount(String userId, String id, Long date) throws NotFoundException; } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java index a98cca9c..e85a7bfa 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/CampaignServiceImpl.java @@ -9,6 +9,7 @@ import fr.insee.pearljam.api.domain.Referent; import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.api.dto.campaign.CampaignDto; +import fr.insee.pearljam.api.dto.campaign.CampaignSensitivityDto; import fr.insee.pearljam.api.dto.count.CountDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerDto; import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; @@ -153,12 +154,18 @@ public void createCampaign(CampaignCreateDto campaignDto) throw new CampaignAlreadyExistException(); } + boolean sensitivity=false; + if(campaignDto.sensitivity()!=null){ + sensitivity=campaignDto.sensitivity(); + } + // Creating campaign Campaign campaign = new Campaign(campaignId, campaignDto.campaignLabel(), campaignDto.identificationConfiguration(), campaignDto.contactOutcomeConfiguration(), campaignDto.contactAttemptConfiguration(), - campaignDto.email()); + campaignDto.email(), + sensitivity); campaign.setReferents(new ArrayList<>()); campaign.setCommunicationTemplates(new ArrayList<>()); @@ -178,7 +185,7 @@ public void createCampaign(CampaignCreateDto campaignDto) updateReferents(campaign, campaignDto.referents()); } - List communicationTemplatesToCreate = CommunicationTemplateCreateDto.toModel(campaignDto.communicationTemplates()); + List communicationTemplatesToCreate = CommunicationTemplateCreateDto.toModel(campaignDto.communicationTemplates(), campaignId); if(communicationTemplatesToCreate != null) { List communicationsDBToCreate = CommunicationTemplateDB.fromModel(communicationTemplatesToCreate, campaign); campaign.setCommunicationTemplates(communicationsDBToCreate); @@ -241,9 +248,7 @@ public void updateCampaign(String campaignId, CampaignUpdateDto campaignToUpdate private void updateConfiguration(Campaign currentCampaign, CampaignUpdateDto campDto) { - if (campDto.identificationConfiguration() != null) { - currentCampaign.setIdentificationConfiguration(campDto.identificationConfiguration()); - } + // identificationConfiguration should not be updated anymore if (campDto.contactOutcomeConfiguration() != null) { currentCampaign.setContactOutcomeConfiguration(campDto.contactOutcomeConfiguration()); } @@ -306,4 +311,9 @@ public CampaignResponseDto getCampaignDtoById(String campaignId) throws Campaign ); return CampaignResponseDto.fromModel(campaignDB, referents, visibilities); } + + @Override + public List getCampaignSensitivityDto() { + return campaignRepository.findAll().stream().map(CampaignSensitivityDto::fromModel).toList(); + } } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/InterviewerServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/InterviewerServiceImpl.java index 58e47aeb..26cbd498 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/InterviewerServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/InterviewerServiceImpl.java @@ -48,18 +48,18 @@ public class InterviewerServiceImpl implements InterviewerService { public Optional> findCampaignsOfInterviewer(String interviewerId) { Optional intwOpt = interviewerRepository.findById(interviewerId); - if (!intwOpt.isPresent()) { + if (intwOpt.isEmpty()) { return Optional.empty(); } Interviewer intw = intwOpt.get(); - List suIds = intw.getSurveyUnits().stream().map(SurveyUnit::getId).collect(Collectors.toList()); + List suIds = intw.getSurveyUnits().stream().map(SurveyUnit::getId).toList(); List visibilities = visibilityRepository.findAllVisibilityBySurveyUnitIds(suIds); List dtos = new ArrayList<>(); for (VisibilityDB vi : visibilities) { Optional dtoOpt = dtos.stream() .filter(dto -> dto.getId().equals(vi.getCampaign().getId())) .findFirst(); - if (!dtoOpt.isPresent()) { + if (dtoOpt.isEmpty()) { dtos.add(new CampaignDto( vi.getCampaign().getId(), vi.getCampaign().getLabel(), @@ -120,7 +120,7 @@ public Response createInterviewers(List interviewers) { @Override public Set getListInterviewers(String userId) { List lstOuId = userService.getUserOUs(userId, true).stream().map(OrganizationUnitDto::getId) - .collect(Collectors.toList()); + .toList(); return surveyUnitService.getSurveyUnitIdByOrganizationUnits(lstOuId).stream() .map(SurveyUnit::getInterviewer) .filter(Objects::nonNull) @@ -130,15 +130,10 @@ public Set getListInterviewers(String userId) { .collect(Collectors.toSet()); } - @Override - public boolean isPresent(String interviewerId) { - return interviewerRepository.existsById(interviewerId); - } - @Override public boolean delete(String id) { Optional optInterviewer = interviewerRepository.findById(id); - if (!optInterviewer.isPresent()) { + if (optInterviewer.isEmpty()) { return false; } List ids = surveyUnitService.getAllIdsByInterviewerId(id); @@ -153,7 +148,7 @@ public boolean delete(String id) { public Optional update(String id, InterviewerContextDto interviewer) { Optional optInterviewer = interviewerRepository.findById(id); - if (!optInterviewer.isPresent()) { + if (optInterviewer.isEmpty()) { return Optional.empty(); } Interviewer interviewerToUpdate = optInterviewer.get(); @@ -176,7 +171,7 @@ public Optional findDtoById(String id) { @Override public List getCompleteListInterviewers() { - return interviewerRepository.findAll().stream().map(InterviewerContextDto::new).collect(Collectors.toList()); + return interviewerRepository.findAll().stream().map(InterviewerContextDto::new).toList(); } } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/OrganizationUnitServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/OrganizationUnitServiceImpl.java index 4532b8e4..24e33ead 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/OrganizationUnitServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/OrganizationUnitServiceImpl.java @@ -133,13 +133,13 @@ public List findAllOrganizationUnits() { return organizationUnitRepository.findAll().stream() .map(ou -> new OrganizationUnitContextDto(ou, userRepository.findAllByOrganizationUnitId(ou.getId()), organizationUnitRepository.findChildrenId(ou.getId()))) - .collect(Collectors.toList()); + .toList(); } @Override public HttpStatus delete(String id) { Optional ou = organizationUnitRepository.findById(id); - if (!ou.isPresent()) { + if (ou.isEmpty()) { return HttpStatus.NOT_FOUND; } List lstSu = surveyUnitRepository.findByOrganizationUnitIdIn(List.of(id)); diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/StateServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/StateServiceImpl.java index c40b6927..fb059e2e 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/StateServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/StateServiceImpl.java @@ -1,16 +1,8 @@ package fr.insee.pearljam.api.service.impl; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - import fr.insee.pearljam.api.constants.Constants; import fr.insee.pearljam.api.dto.campaign.CampaignDto; +import fr.insee.pearljam.api.dto.interviewer.InterviewerCountDto; import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; import fr.insee.pearljam.api.dto.state.StateCountCampaignDto; import fr.insee.pearljam.api.dto.state.StateCountDto; @@ -23,14 +15,26 @@ import fr.insee.pearljam.api.service.StateService; import fr.insee.pearljam.api.service.UserService; import fr.insee.pearljam.api.service.UtilsService; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; +import fr.insee.pearljam.domain.campaign.port.serverside.VisibilityRepository; +import fr.insee.pearljam.domain.surveyunit.port.serverside.CommunicationRequestRepository; +import fr.insee.pearljam.infrastructure.campaign.jpa.CommunicationTemplateJpaRepository; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; /** * Implementation of the Service for the Interviewer entity - * - * @author scorcaud * + * @author scorcaud */ @Service @Transactional @@ -38,159 +42,251 @@ @RequiredArgsConstructor public class StateServiceImpl implements StateService { - private static final String USER_CAMP_CONST_MSG = "No campaign with id %s associated to the user %s"; - - private final CampaignRepository campaignRepository; - private final StateRepository stateRepository; - private final ClosingCauseRepository closingCauseRepository; - private final InterviewerRepository interviewerRepository; - private final VisibilityRepository visibilityRepository; - private final OrganizationUnitRepository organizationUnitRepository; - private final UserService userService; - private final UtilsService utilsService; - - public StateCountDto getStateCount(String userId, String campaignId, String interviewerId, Long date, - List associatedOrgUnits) throws NotFoundException { - StateCountDto stateCountDto = new StateCountDto(); - if (!utilsService.checkUserCampaignOUConstraints(userId, campaignId)) { - throw new NotFoundException(String.format(USER_CAMP_CONST_MSG, campaignId, userId)); - } - if (!interviewerRepository.findById(interviewerId).isPresent()) { - log.error("No interviewer found for the id {}", interviewerId); - throw new NotFoundException(String.format("No interviewers found for the id %s", interviewerId)); - - } - List userOuIds; - if (!userId.equals(Constants.GUEST)) { - userOuIds = utilsService.getRelatedOrganizationUnits(userId); - } else { - userOuIds = organizationUnitRepository.findAllId(); - } - - List intervIds = interviewerRepository.findInterviewersByOrganizationUnits(associatedOrgUnits); - Long dateToUse = date; - if (dateToUse == null) { - dateToUse = System.currentTimeMillis(); - } - if (!intervIds.isEmpty() && (intervIds.contains(interviewerId)) || userId.equals(Constants.GUEST)) { - stateCountDto = new StateCountDto( - stateRepository.getStateCount(campaignId, interviewerId, userOuIds, dateToUse)); - stateCountDto.addClosingCauseCount(closingCauseRepository.getStateClosedByClosingCauseCount(campaignId, - interviewerId, userOuIds, dateToUse)); - } - if (stateCountDto.getTotal() == null) { - throw new NotFoundException(String.format( - "No matching interviewers %s were found for the user % and the campaign %s", interviewerId, - userId, campaignId)); - } - return stateCountDto; - } - - public StateCountCampaignDto getStateCountByCampaign(String userId, String campaignId, Long date) - throws NotFoundException { - StateCountCampaignDto stateCountCampaignDto = new StateCountCampaignDto(); - if (!utilsService.checkUserCampaignOUConstraints(userId, campaignId)) { - throw new NotFoundException(String.format(USER_CAMP_CONST_MSG, campaignId, userId)); - } - List stateCountList = new ArrayList<>(); - Long dateToUse = date; - if (dateToUse == null) { - dateToUse = System.currentTimeMillis(); - } - for (String id : organizationUnitRepository.findAllId()) { - if (organizationUnitRepository.findChildren(id).isEmpty() - && visibilityRepository.findVisibility(campaignId, id).isPresent()) { - StateCountDto dto = new StateCountDto(id, organizationUnitRepository.findLabel(id), - stateRepository.getStateCountByCampaignAndOU(campaignId, id, dateToUse)); - dto.addClosingCauseCount( - closingCauseRepository.getClosingCauseCountByCampaignAndOU(campaignId, id, dateToUse)); - stateCountList.add(dto); - } - } - stateCountCampaignDto.setOrganizationUnits(stateCountList); - - StateCountDto dtoFrance = new StateCountDto(stateRepository.getStateCountByCampaignId(campaignId, dateToUse)); - dtoFrance.addClosingCauseCount(closingCauseRepository.getClosingCauseCountByCampaignId(campaignId, dateToUse)); - stateCountCampaignDto.setFrance(dtoFrance); - if (stateCountCampaignDto.getFrance() == null || stateCountCampaignDto.getOrganizationUnits() == null) { - throw new NotFoundException(String.format( - "No matching survey units states were found for the user %s and the campaign %s", userId, - campaignId)); - } - return stateCountCampaignDto; - } - - public List getStateCountByCampaigns(String userId, Long date) { - List returnList = new ArrayList<>(); - List organizationUnits = userService.getUserOUs(userId, true); - for (OrganizationUnitDto dto : organizationUnits) { - log.info(dto.getId()); - } - List userOrgUnitIds = organizationUnits.stream().map(OrganizationUnitDto::getId) - .collect(Collectors.toList()); - Long dateToUse = date; - if (dateToUse == null) { - dateToUse = System.currentTimeMillis(); - } - List campaignIds = campaignRepository.findAllCampaignIdsByOuIds(userOrgUnitIds); - - for (String id : campaignIds) { - StateCountDto campaignSum = new StateCountDto( - stateRepository.getStateCountSumByCampaign(id, userOrgUnitIds, dateToUse)); - campaignSum.addClosingCauseCount(closingCauseRepository.getgetStateClosedByClosingCauseCountByCampaign(id, - userOrgUnitIds, dateToUse)); - if (campaignSum.getTotal() != null) { - CampaignDto dto = campaignRepository.findDtoById(id); - campaignSum.setCampaign(dto); - returnList.add(campaignSum); - } - } - return returnList; - } - - public List getStateCountByInterviewer(String userId, Long date) { - List returnList = new ArrayList<>(); - List organizationUnits = userService.getUserOUs(userId, true); - List userOrgUnitIds = organizationUnits.stream().map(OrganizationUnitDto::getId) - .collect(Collectors.toList()); - Long dateToUse = date; - if (dateToUse == null) { - dateToUse = System.currentTimeMillis(); - } - Set interviewerIds = interviewerRepository.findIdsByOrganizationUnits(userOrgUnitIds); - List campaignIds = campaignRepository.findAllCampaignIdsByOuIds(userOrgUnitIds); - for (String id : interviewerIds) { - StateCountDto interviewerSum = new StateCountDto( - stateRepository.getStateCountSumByInterviewer(campaignIds, id, userOrgUnitIds, dateToUse)); - interviewerSum.addClosingCauseCount(closingCauseRepository.getClosingCauseCountSumByInterviewer(campaignIds, - id, userOrgUnitIds, dateToUse)); - if (interviewerSum.getTotal() != null) { - interviewerSum.setInterviewer(interviewerRepository.findDtoById(id)); - returnList.add(interviewerSum); - } - } - return returnList; - } - - @Override - public StateCountDto getNbSUNotAttributedStateCount(String userId, String id, Long date) throws NotFoundException { - if (!utilsService.checkUserCampaignOUConstraints(userId, id)) { - throw new NotFoundException(String.format(USER_CAMP_CONST_MSG, id, userId)); - } - - List organizationUnits = userService.getUserOUs(userId, true) - .stream().map(OrganizationUnitDto::getId) - .collect(Collectors.toList()); - Long dateToUse = date; - if (dateToUse == null) { - dateToUse = System.currentTimeMillis(); - } - - StateCountDto interviewerSum = new StateCountDto( - stateRepository.getStateCountNotAttributed(id, organizationUnits, dateToUse)); - interviewerSum.addClosingCauseCount( - closingCauseRepository.getClosingCauseCountNotAttributed(id, organizationUnits, dateToUse)); - - return interviewerSum; - } + private static final String USER_CAMP_CONST_MSG = "No campaign with id %s associated to the user %s"; + + private final CampaignRepository campaignRepository; + private final StateRepository stateRepository; + private final ClosingCauseRepository closingCauseRepository; + private final InterviewerRepository interviewerRepository; + private final VisibilityRepository visibilityRepository; + private final OrganizationUnitRepository organizationUnitRepository; + private final CommunicationTemplateJpaRepository communicationTemplateRepository; + private final UserService userService; + private final UtilsService utilsService; + private final CommunicationRequestRepository communicationRequestRepository; + + + public StateCountDto getStateCount(String userId, String campaignId, String interviewerId, + Long date, + List associatedOrgUnits) throws NotFoundException { + StateCountDto stateCountDto = new StateCountDto(); + if (!utilsService.checkUserCampaignOUConstraints(userId, campaignId)) { + throw new NotFoundException(String.format(USER_CAMP_CONST_MSG, campaignId, userId)); + } + if (!interviewerRepository.findById(interviewerId).isPresent()) { + log.error("No interviewer found for the id {}", interviewerId); + throw new NotFoundException( + String.format("No interviewers found for the id %s", interviewerId)); + + } + List userOuIds; + if (!userId.equals(Constants.GUEST)) { + userOuIds = utilsService.getRelatedOrganizationUnits(userId); + } else { + userOuIds = organizationUnitRepository.findAllId(); + } + + List intervIds = interviewerRepository.findInterviewersByOrganizationUnits( + associatedOrgUnits); + Long dateToUse = date; + if (dateToUse == null) { + dateToUse = System.currentTimeMillis(); + } + if (!intervIds.isEmpty() && (intervIds.contains(interviewerId)) || userId.equals( + Constants.GUEST)) { + Map stateCounts = new HashMap<>( + stateRepository.getStateCount(campaignId, interviewerId, userOuIds, dateToUse)); + stateCounts.put(Constants.NOTICE_COUNT, + communicationRequestRepository.getCommRequestCountByInterviewersAndType( + List.of(campaignId), Set.of(interviewerId), CommunicationType.NOTICE, userOuIds, dateToUse) + .stream().findFirst().map(InterviewerCountDto::count).orElse(0L)); + + stateCounts.put(Constants.REMINDER_COUNT, + communicationRequestRepository.getCommRequestCountByInterviewersAndType( + List.of(campaignId), Set.of(interviewerId), CommunicationType.REMINDER, userOuIds, dateToUse) + .stream().findFirst().map(InterviewerCountDto::count).orElse(0L)); + + + + stateCountDto = new StateCountDto(stateCounts); + stateCountDto.addClosingCauseCount( + closingCauseRepository.getStateClosedByClosingCauseCount(campaignId, + interviewerId, userOuIds, dateToUse)); + } + if (stateCountDto.getTotal() == null) { + throw new NotFoundException(String.format( + "No matching interviewers %s were found for the user % and the campaign %s", + interviewerId, + userId, campaignId)); + } + return stateCountDto; + } + + public StateCountCampaignDto getStateCountByCampaign(String userId, String campaignId, Long date) + throws NotFoundException { + StateCountCampaignDto stateCountCampaignDto = new StateCountCampaignDto(); + if (!utilsService.checkUserCampaignOUConstraints(userId, campaignId)) { + throw new NotFoundException(String.format(USER_CAMP_CONST_MSG, campaignId, userId)); + } + List stateCountList = new ArrayList<>(); + Long dateToUse = date; + if (dateToUse == null) { + dateToUse = System.currentTimeMillis(); + } + for (String id : organizationUnitRepository.findAllId()) { + if (organizationUnitRepository.findChildren(id).isEmpty() + && visibilityRepository.findVisibility(campaignId, id).isPresent()) { + + Map stateCountsByCampaign = new HashMap<>( + stateRepository.getStateCountByCampaignAndOU(campaignId, id, dateToUse)); + stateCountsByCampaign.put(Constants.NOTICE_COUNT, + communicationRequestRepository.getCommRequestCountByCampaignTypeAndOrgaUnit( + campaignId, CommunicationType.NOTICE, dateToUse, List.of(id))); + stateCountsByCampaign.put(Constants.REMINDER_COUNT, + communicationRequestRepository.getCommRequestCountByCampaignTypeAndOrgaUnit( + campaignId, CommunicationType.REMINDER, dateToUse, List.of(id))); + + StateCountDto dto = new StateCountDto(id, organizationUnitRepository.findLabel(id), stateCountsByCampaign); + dto.addClosingCauseCount( + closingCauseRepository.getClosingCauseCountByCampaignAndOU(campaignId, id, dateToUse)); + stateCountList.add(dto); + } + } + stateCountCampaignDto.setOrganizationUnits(stateCountList); + + Map stateCountsByCampaign = new HashMap<>( + stateRepository.getStateCountByCampaignId(campaignId, dateToUse)); + stateCountsByCampaign.put(Constants.NOTICE_COUNT, + communicationRequestRepository.getCommRequestCountByCampaignAndType( + campaignId, CommunicationType.NOTICE, dateToUse)); + stateCountsByCampaign.put(Constants.REMINDER_COUNT, + communicationRequestRepository.getCommRequestCountByCampaignAndType( + campaignId, CommunicationType.REMINDER, dateToUse)); + StateCountDto dtoFrance = new StateCountDto(stateCountsByCampaign); + dtoFrance.addClosingCauseCount( + closingCauseRepository.getClosingCauseCountByCampaignId(campaignId, dateToUse)); + stateCountCampaignDto.setFrance(dtoFrance); + if (stateCountCampaignDto.getFrance() == null + || stateCountCampaignDto.getOrganizationUnits() == null) { + throw new NotFoundException(String.format( + "No matching survey units states were found for the user %s and the campaign %s", userId, + campaignId)); + } + return stateCountCampaignDto; + } + + public List getStateCountByCampaigns(String userId, Long date) { + List returnList = new ArrayList<>(); + List organizationUnits = userService.getUserOUs(userId, true); + if (organizationUnits.isEmpty()) { + return Collections.emptyList(); + } + for (OrganizationUnitDto dto : organizationUnits) { + log.info(dto.getId()); + } + List userOrgUnitIds = organizationUnits.stream().map(OrganizationUnitDto::getId) + .collect(Collectors.toList()); + Long dateToUse = date; + if (dateToUse == null) { + dateToUse = System.currentTimeMillis(); + } + List campaignIds = campaignRepository.findAllCampaignIdsByOuIds(userOrgUnitIds); + + for (String id : campaignIds) { + Map stateCountsByCampaign = new HashMap<>( + stateRepository.getStateCountSumByCampaign(id, userOrgUnitIds, dateToUse)); + stateCountsByCampaign.put(Constants.NOTICE_COUNT, + communicationRequestRepository.getCommRequestCountByCampaignTypeAndOrgaUnit( + id, CommunicationType.NOTICE, dateToUse, userOrgUnitIds)); + stateCountsByCampaign.put(Constants.REMINDER_COUNT, + communicationRequestRepository.getCommRequestCountByCampaignTypeAndOrgaUnit( + id, CommunicationType.REMINDER, dateToUse, userOrgUnitIds)); + StateCountDto campaignSum = new StateCountDto(stateCountsByCampaign); + campaignSum.addClosingCauseCount( + closingCauseRepository.getgetStateClosedByClosingCauseCountByCampaign(id, + userOrgUnitIds, dateToUse)); + if (campaignSum.getTotal() != null) { + CampaignDto dto = campaignRepository.findDtoById(id); + campaignSum.setCampaign(dto); + returnList.add(campaignSum); + } + } + return returnList; + } + + @Override + public List getStateCountByInterviewer(String userId, Long date) { + List campaignIds = campaignRepository.findAllCampaignIdsByOuIds( + userService.getUserOUs(userId, true).stream() + .map(OrganizationUnitDto::getId) + .toList() + ); + return getStateCountByInterviewerCommon(userId, campaignIds, date); + } + + @Override + public List getInterviewersStateCountByCampaign(String userId, String campaignId, + Long date) { + return getStateCountByInterviewerCommon(userId, List.of(campaignId), date); + } + + + private List getStateCountByInterviewerCommon(String userId, + List campaignIds, Long date) { + List returnList = new ArrayList<>(); + + List userOrgUnitIds = userService.getUserOUs(userId, true).stream() + .map(OrganizationUnitDto::getId) + .collect(Collectors.toList()); + + Long dateToUse = (date != null) ? date : System.currentTimeMillis(); + Set interviewerIds = interviewerRepository.findIdsByOrganizationUnits(userOrgUnitIds); + + Map noticeCounts = communicationRequestRepository + .getCommRequestCountByInterviewersAndType(campaignIds, interviewerIds, + CommunicationType.NOTICE, userOrgUnitIds, dateToUse) + .stream() + .collect(Collectors.toMap(InterviewerCountDto::interviewerId, InterviewerCountDto::count)); + + Map reminderCounts = communicationRequestRepository + .getCommRequestCountByInterviewersAndType(campaignIds, interviewerIds, + CommunicationType.REMINDER, userOrgUnitIds, dateToUse) + .stream() + .collect(Collectors.toMap(InterviewerCountDto::interviewerId, InterviewerCountDto::count)); + + for (String id : interviewerIds) { + Map stateCountsByInterviewerId = new HashMap<>( + stateRepository.getStateCountSumByInterviewer(campaignIds, id, userOrgUnitIds, dateToUse) + ); + + StateCountDto interviewerSum = new StateCountDto(stateCountsByInterviewerId); + interviewerSum.addClosingCauseCount( + closingCauseRepository.getClosingCauseCountSumByInterviewer(campaignIds, id, + userOrgUnitIds, dateToUse) + ); + interviewerSum.setNoticeCount(noticeCounts.getOrDefault(id, 0L)); + interviewerSum.setReminderCount(reminderCounts.getOrDefault(id, 0L)); + + if (interviewerSum.getTotal() != null) { + interviewerSum.setInterviewer(interviewerRepository.findDtoById(id)); + returnList.add(interviewerSum); + } + } + + return returnList; + } + + + @Override + public StateCountDto getNbSUNotAttributedStateCount(String userId, String id, Long date) + throws NotFoundException { + if (!utilsService.checkUserCampaignOUConstraints(userId, id)) { + throw new NotFoundException(String.format(USER_CAMP_CONST_MSG, id, userId)); + } + + List organizationUnits = userService.getUserOUs(userId, true) + .stream().map(OrganizationUnitDto::getId) + .collect(Collectors.toList()); + Long dateToUse = date; + if (dateToUse == null) { + dateToUse = System.currentTimeMillis(); + } + + StateCountDto interviewerSum = new StateCountDto( + stateRepository.getStateCountNotAttributed(id, organizationUnits, dateToUse)); + interviewerSum.addClosingCauseCount( + closingCauseRepository.getClosingCauseCountNotAttributed(id, organizationUnits, dateToUse)); + + return interviewerSum; + } } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java index b2be293a..8743280f 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitServiceImpl.java @@ -1,17 +1,21 @@ package fr.insee.pearljam.api.service.impl; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - +import com.fasterxml.jackson.databind.JsonNode; +import fr.insee.pearljam.api.bussinessrules.BusinessRules; +import fr.insee.pearljam.api.constants.Constants; +import fr.insee.pearljam.api.domain.*; +import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; +import fr.insee.pearljam.api.dto.person.PersonDto; +import fr.insee.pearljam.api.dto.state.StateDto; import fr.insee.pearljam.api.dto.surveyunit.*; +import fr.insee.pearljam.api.exception.BadRequestException; +import fr.insee.pearljam.api.repository.*; +import fr.insee.pearljam.api.service.SurveyUnitService; +import fr.insee.pearljam.api.service.SurveyUnitUpdateService; +import java.util.function.Function; +import fr.insee.pearljam.api.service.UserService; +import fr.insee.pearljam.api.service.UtilsService; +import fr.insee.pearljam.api.surveyunit.dto.ContactOutcomeDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitInterviewerResponseDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitVisibilityDto; @@ -21,32 +25,18 @@ import fr.insee.pearljam.domain.exception.PersonNotFoundException; import fr.insee.pearljam.domain.exception.SurveyUnitNotFoundException; import fr.insee.pearljam.domain.surveyunit.model.IdentificationState; -import fr.insee.pearljam.api.service.SurveyUnitUpdateService; import fr.insee.pearljam.domain.surveyunit.model.SurveyUnitForInterviewer; import jakarta.servlet.http.HttpServletRequest; - -import com.fasterxml.jackson.databind.JsonNode; -import fr.insee.pearljam.api.domain.*; -import fr.insee.pearljam.api.repository.*; - +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatusCode; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import fr.insee.pearljam.api.bussinessrules.BussinessRules; -import fr.insee.pearljam.api.constants.Constants; -import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; -import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; -import fr.insee.pearljam.api.dto.person.PersonDto; -import fr.insee.pearljam.api.dto.state.StateDto; -import fr.insee.pearljam.api.exception.BadRequestException; -import fr.insee.pearljam.api.service.SurveyUnitService; -import fr.insee.pearljam.api.service.UserService; -import fr.insee.pearljam.api.service.UtilsService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; +import java.util.*; +import java.util.stream.Collectors; /** * @author scorcaud @@ -66,7 +56,6 @@ public class SurveyUnitServiceImpl implements SurveyUnitService { private final SurveyUnitRepository surveyUnitRepository; private final SurveyUnitTempZoneRepository surveyUnitTempZoneRepository; private final AddressRepository addressRepository; - private final ContactOutcomeRepository contactOutcomeRepository; private final StateRepository stateRepository; private final InterviewerRepository interviewerRepository; private final CampaignRepository campaignRepository; @@ -143,8 +132,8 @@ public List getSurveyUnitDto(String userId, Boolean extended) { @Override public boolean canBeSeenByInterviewer(String suId) { StateDto dto = stateRepository.findFirstDtoBySurveyUnitIdOrderByDateDesc(suId); - StateType currentState = dto != null ? dto.getType() : null; - return currentState != null && BussinessRules.stateCanBeSeenByInterviewerBussinessRules(currentState); + StateType currentState = dto != null ? dto.type() : null; + return currentState != null && BusinessRules.stateCanBeSeenByInterviewerBussinessRules(currentState); } @Transactional @@ -165,7 +154,6 @@ public SurveyUnitDetailDto updateSurveyUnit(String userId, String surveyUnitId, updateStates(surveyUnit, surveyUnitUpdate); updateContactAttempt(surveyUnit, surveyUnitUpdate); - updateContactOutcome(surveyUnit, surveyUnitUpdate); surveyUnitUpdateService.updateSurveyUnitInfos(surveyUnit, surveyUnitUpdate); surveyUnitRepository.save(surveyUnit); @@ -174,21 +162,6 @@ public SurveyUnitDetailDto updateSurveyUnit(String userId, String surveyUnitId, return new SurveyUnitDetailDto(surveyUnitRepository.findById(surveyUnitId).get()); } - private void updateContactOutcome(SurveyUnit surveyUnit, SurveyUnitUpdateDto surveyUnitUpdateDto) { - if (surveyUnitUpdateDto.contactOutcome() != null) { - ContactOutcome contactOutcome = contactOutcomeRepository.findBySurveyUnit(surveyUnit) - .orElseGet(ContactOutcome::new); - contactOutcome.setDate(surveyUnitUpdateDto.contactOutcome().getDate()); - contactOutcome.setType(surveyUnitUpdateDto.contactOutcome().getType()); - contactOutcome.setTotalNumberOfContactAttempts( - surveyUnitUpdateDto.contactOutcome().getTotalNumberOfContactAttempts()); - contactOutcome.setSurveyUnit(surveyUnit); - surveyUnit.setContactOucome(contactOutcome); - contactOutcomeRepository.save(contactOutcome); - } - log.info("Survey-unit {} - Contact outcome updated", surveyUnit.getId()); - } - private void updateContactAttempt(SurveyUnit surveyUnit, SurveyUnitUpdateDto surveyUnitUpdateDto) { if (surveyUnitUpdateDto.contactAttempts() != null) { Set contactAttemps = surveyUnit.getContactAttempts(); @@ -203,16 +176,16 @@ private void updateContactAttempt(SurveyUnit surveyUnit, SurveyUnitUpdateDto sur private void updateStates(SurveyUnit surveyUnit, SurveyUnitUpdateDto surveyUnitUpdateDto) { if (surveyUnitUpdateDto.states() != null) { surveyUnitUpdateDto.states().stream() - .filter(s -> s.getId() == null || !stateRepository.existsById(s.getId())) - .forEach(s -> stateRepository.save(new State(s.getDate(), surveyUnit, s.getType()))); + .filter(s -> s.id() == null || !stateRepository.existsById(s.id())) + .forEach(s -> stateRepository.save(new State(s.date(), surveyUnit, s.type()))); } StateType currentState = stateRepository.findFirstDtoBySurveyUnitIdOrderByDateDesc(surveyUnit.getId()) - .getType(); + .type(); if (currentState == StateType.WFS) { addStateAuto(surveyUnit); } List dbStates = stateRepository.findAllDtoBySurveyUnitIdOrderByDateAsc(surveyUnit.getId()); - if (Boolean.TRUE.equals(BussinessRules.shouldFallBackToTbrOrFin(dbStates))) { + if (Boolean.TRUE.equals(BusinessRules.shouldFallBackToTbrOrFin(dbStates))) { Set ueStates = surveyUnit.getStates(); if (ueStates.stream().anyMatch(s -> s.getType() == StateType.FIN)) { ueStates.add(new State(new Date().getTime(), surveyUnit, StateType.FIN)); @@ -259,11 +232,11 @@ private void updatePerson(PersonDto person, Person pers) { if (person.getEmail() != null) { pers.setEmail(person.getEmail()); } - if (person.isFavoriteEmail() != null) { - pers.setFavoriteEmail(person.isFavoriteEmail()); + if (person.getFavoriteEmail() != null) { + pers.setFavoriteEmail(person.getFavoriteEmail()); } - if (person.isPrivileged() != null) { - pers.setPrivileged(person.isPrivileged()); + if (person.getPrivileged() != null) { + pers.setPrivileged(person.getPrivileged()); } if (person.getPhoneNumbers() != null) { Set phoneNumbers = person.getPhoneNumbers().stream().map(pn -> new PhoneNumber(pn, pers)) @@ -303,7 +276,7 @@ private void updateAddress(SurveyUnit surveyUnit, SurveyUnitUpdateDto surveyUnit @Transactional public HttpStatus updateSurveyUnitViewed(String userId, String suId) { Optional surveyUnitOpt = surveyUnitRepository.findById(suId); - if (!surveyUnitOpt.isPresent()) { + if (surveyUnitOpt.isEmpty()) { log.error(SU_ID_NOT_FOUND_FOR_INTERVIEWER, suId, userId); return HttpStatus.NOT_FOUND; } @@ -331,26 +304,38 @@ public Set getSurveyUnitByCampaign(String campaignId, Str return lstSurveyUnit.stream().map(SurveyUnitCampaignDto::new).collect(Collectors.toSet()); } + // TODO : use future identification state in rules instead of specific identification attributes public List getClosableSurveyUnits(HttpServletRequest request, String userId) { List lstOuId = userService.getUserOUs(userId, true).stream().map(OrganizationUnitDto::getId) .toList(); - List noIdentSurveyUnitIds = surveyUnitRepository - .findSurveyUnitIdsOfOrganizationUnitsInProcessingPhaseByIdentificationConfiguration( - System.currentTimeMillis(), lstOuId, IdentificationConfiguration.NOIDENT); - List iascoSurveyUnitIds = surveyUnitRepository - .findSurveyUnitIdsOfOrganizationUnitsInProcessingPhaseByIdentificationConfiguration( - System.currentTimeMillis(), lstOuId, IdentificationConfiguration.IASCO); - - // apply different business rules to select SU - List noIdentSurveyUnitsToCheck = surveyUnitRepository - .findClosableNoIdentSurveyUnitId(noIdentSurveyUnitIds); - List iascoSurveyUnitsToCheck = surveyUnitRepository - .findClosableIascoSurveyUnitId(iascoSurveyUnitIds); - - // merge lists - List suToCheck = Stream.concat(noIdentSurveyUnitsToCheck.stream(), iascoSurveyUnitsToCheck.stream()) - .toList(); + // Retrieve SurveyUnitIds for each configuration + Map> surveyUnitIdsByConfig = Arrays.stream(IdentificationConfiguration.values()) + .collect(Collectors.toMap( + config -> config, + config -> surveyUnitRepository.findSurveyUnitIdsOfOrganizationUnitsInProcessingPhaseByIdentificationConfiguration( + System.currentTimeMillis(), lstOuId, config) + )); + + // Mapping between each configuration and the appropriate method to retrieve closable units + Map, List>> closableSurveyUnitMethods = Map.of( + IdentificationConfiguration.NOIDENT, surveyUnitRepository::findClosableNoIdentSurveyUnitId, + IdentificationConfiguration.IASCO, surveyUnitRepository::findClosableHousef2fSurveyUnitId, + IdentificationConfiguration.HOUSEF2F, surveyUnitRepository::findClosableHousef2fSurveyUnitId, + IdentificationConfiguration.INDF2F, surveyUnitRepository::findClosableIndf2fFSurveyUnitId, + IdentificationConfiguration.INDF2FNOR, surveyUnitRepository::findClosableIndf2fnorFSurveyUnitId, + IdentificationConfiguration.INDTEL, surveyUnitRepository::findClosableIndtelFSurveyUnitId, + IdentificationConfiguration.INDTELNOR, surveyUnitRepository::findClosableIndtelnorFSurveyUnitId + ); + + + // Retrieving SurveyUnits to check + List suToCheck = surveyUnitIdsByConfig.entrySet().stream() + .flatMap(entry -> { + IdentificationConfiguration config = entry.getKey(); + List surveyUnitIds = entry.getValue(); + return closableSurveyUnitMethods.getOrDefault(config, ids -> List.of()).apply(surveyUnitIds).stream(); + }).toList(); Map mapQuestionnaireStateBySu = Collections.emptyMap(); @@ -367,7 +352,9 @@ public List getClosableSurveyUnits(HttpServletRequest req return suToCheck.stream().map(su -> { SurveyUnitCampaignDto sudto = new SurveyUnitCampaignDto(su); - IdentificationState identificationResult = IdentificationState.getState(su.getModelIdentification()); + IdentificationState identificationResult = + IdentificationState.getState(su.getModelIdentification(), + sudto.getIdentificationConfiguration()); sudto.setIdentificationState(identificationResult); String questionnaireState = Optional.ofNullable(map.get(su.getId())).orElse(Constants.UNAVAILABLE); sudto.setQuestionnaireState(questionnaireState); @@ -385,7 +372,7 @@ private boolean isClosable(SurveyUnitCampaignDto sudto) { ContactOutcomeDto outcome = sudto.getContactOutcome(); if (outcome == null) return !hasQuestionnaire; - return switch (outcome.getType()) { + return switch (outcome.type()) { case INA, NOA -> !hasQuestionnaire; default -> true; }; @@ -417,8 +404,8 @@ private Map getQuestionnaireStatesFromDataCollection(HttpServlet public HttpStatus addStateToSurveyUnit(String surveyUnitId, StateType state) { Optional su = surveyUnitRepository.findById(surveyUnitId); if (su.isPresent()) { - StateType currentState = stateRepository.findFirstDtoBySurveyUnitOrderByDateDesc(su.get()).getType(); - if (Boolean.TRUE.equals(BussinessRules.stateCanBeModifiedByManager(currentState, state))) { + StateType currentState = stateRepository.findFirstDtoBySurveyUnitOrderByDateDesc(su.get()).type(); + if (Boolean.TRUE.equals(BusinessRules.stateCanBeModifiedByManager(currentState, state))) { if (StateType.TBR.equals(state) || StateType.FIN.equals(state)) { log.info("Deleting closing causes of survey unit {}", surveyUnitId); closingCauseRepository.deleteBySurveyUnitId(surveyUnitId); @@ -443,11 +430,11 @@ public HttpStatus closeSurveyUnit(String surveyUnitId, ClosingCauseType type) { if (su.isPresent()) { SurveyUnit surveyUnit = su.get(); log.info("{} -> {}", surveyUnitId, type); - StateType currentState = stateRepository.findFirstDtoBySurveyUnitIdOrderByDateDesc(surveyUnitId).getType(); + StateType currentState = stateRepository.findFirstDtoBySurveyUnitIdOrderByDateDesc(surveyUnitId).type(); if (currentState.equals(StateType.CLO)) { addOrModifyClosingCause(surveyUnit, type); return HttpStatus.OK; - } else if (Boolean.TRUE.equals(BussinessRules.stateCanBeModifiedByManager(currentState, StateType.CLO))) { + } else if (Boolean.TRUE.equals(BusinessRules.stateCanBeModifiedByManager(currentState, StateType.CLO))) { stateRepository.save(new State(new Date().getTime(), su.get(), StateType.CLO)); addOrModifyClosingCause(surveyUnit, type); return HttpStatus.OK; @@ -493,7 +480,7 @@ private void addOrModifyClosingCause(SurveyUnit surveyUnit, ClosingCauseType typ public List getListStatesBySurveyUnitId(String suId) { Optional su = surveyUnitRepository.findById(suId); - if (!su.isPresent()) { + if (su.isEmpty()) { log.error("SU {} not found in database", suId); return List.of(); } diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java index ac84ea3c..804b384a 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/SurveyUnitUpdateServiceImpl.java @@ -3,8 +3,9 @@ import fr.insee.pearljam.api.domain.*; import fr.insee.pearljam.api.surveyunit.dto.CommentDto; import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestCreateDto; -import fr.insee.pearljam.api.surveyunit.dto.IdentificationDto; +import fr.insee.pearljam.api.surveyunit.dto.ContactOutcomeDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; +import fr.insee.pearljam.api.surveyunit.dto.identification.IdentificationDto; import fr.insee.pearljam.domain.campaign.port.userside.DateService; import fr.insee.pearljam.domain.campaign.model.Visibility; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; @@ -14,10 +15,13 @@ import fr.insee.pearljam.domain.exception.CommunicationTemplateNotFoundException; import fr.insee.pearljam.domain.exception.VisibilityNotFoundException; import fr.insee.pearljam.domain.surveyunit.model.Comment; +import fr.insee.pearljam.domain.surveyunit.model.ContactOutcome; import fr.insee.pearljam.domain.surveyunit.model.Identification; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; import fr.insee.pearljam.api.service.SurveyUnitUpdateService; import fr.insee.pearljam.domain.surveyunit.port.serverside.CommunicationRequestRepository; +import fr.insee.pearljam.infrastructure.surveyunit.entity.identification.IdentificationDB; +import java.util.Optional; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -55,9 +59,33 @@ public void updateSurveyUnitInfos(SurveyUnit surveyUnit, SurveyUnitUpdateDto sur .toList(); communicationRequestRepository.addCommunicationRequests(surveyUnit, communicationRequestsToCreate); } + IdentificationConfiguration identificationConfiguration = surveyUnit.getCampaign().getIdentificationConfiguration(); + + Identification identification = Optional.ofNullable(surveyUnitUpdateDto.identification()) + .map(idDto -> IdentificationDto.toModel(idDto, identificationConfiguration)) + .orElseGet(() -> IdentificationDB.toModel(surveyUnit.getIdentification())); - Identification identification = IdentificationDto.toModel(surveyUnitUpdateDto.identification()); surveyUnit.updateIdentification(identification); + + //update ContactOutcome + ContactOutcome contactOutcome = ContactOutcomeDto.toModel(surveyUnit.getId(), + surveyUnitUpdateDto.contactOutcome()); + contactOutcome = convertDeprecatedContactOutcomeValue(contactOutcome); + surveyUnit.updateContactOutcome(contactOutcome); + } + + // when DCD and DUU values are not used anymore => to be removed + private ContactOutcome convertDeprecatedContactOutcomeValue(ContactOutcome contactOutcome) { + if (contactOutcome == null) { + return null; + } + return switch (contactOutcome.type()) { + case DCD -> new ContactOutcome(contactOutcome.id(), contactOutcome.date(), ContactOutcomeType.NOA, + contactOutcome.totalNumberOfContactAttempts(), contactOutcome.surveyUnitId()); + case DUU -> new ContactOutcome(contactOutcome.id(), contactOutcome.date(), ContactOutcomeType.DUK, + contactOutcome.totalNumberOfContactAttempts(), contactOutcome.surveyUnitId()); + case INA, REF, IMP, UCD, UTR, ALA, DUK, NUH, NOA -> contactOutcome; + }; } /** @@ -69,11 +97,12 @@ public void updateSurveyUnitInfos(SurveyUnit surveyUnit, SurveyUnitUpdateDto sur private CommunicationRequest getNewCommunicationRequest(CommunicationRequestCreateDto communicationRequestToCreate, SurveyUnit surveyUnit, Long readyTimestamp) { String campaignId = surveyUnit.getCampaign().getId(); CommunicationTemplate communicationTemplate = communicationTemplateRepository - .findCommunicationTemplate(communicationRequestToCreate.communicationTemplateId(), campaignId) + .findCommunicationTemplate(campaignId, communicationRequestToCreate.communicationTemplateId()) .orElseThrow(CommunicationTemplateNotFoundException::new); if(!communicationTemplate.medium().equals(CommunicationMedium.LETTER)) { return CommunicationRequest.create( + campaignId, communicationRequestToCreate.communicationTemplateId(), communicationRequestToCreate.creationTimestamp(), readyTimestamp, @@ -87,6 +116,7 @@ private CommunicationRequest getNewCommunicationRequest(CommunicationRequestCrea if(visibility.useLetterCommunication() != null && visibility.useLetterCommunication()) { return CommunicationRequest.create( + campaignId, communicationRequestToCreate.communicationTemplateId(), communicationRequestToCreate.creationTimestamp(), readyTimestamp, @@ -96,6 +126,7 @@ private CommunicationRequest getNewCommunicationRequest(CommunicationRequestCrea // if the communication request is a letter communication request, but the visibility doesn't admit it, // create a cancelled communication request return CommunicationRequest.createCancelled( + campaignId, communicationRequestToCreate.communicationTemplateId(), communicationRequestToCreate.creationTimestamp(), dateService.getCurrentTimestamp(), diff --git a/src/main/java/fr/insee/pearljam/api/service/impl/UtilsServiceImpl.java b/src/main/java/fr/insee/pearljam/api/service/impl/UtilsServiceImpl.java index 06407705..72a7383b 100644 --- a/src/main/java/fr/insee/pearljam/api/service/impl/UtilsServiceImpl.java +++ b/src/main/java/fr/insee/pearljam/api/service/impl/UtilsServiceImpl.java @@ -98,7 +98,7 @@ public boolean isTestProfile() { @Override public ResponseEntity getQuestionnairesStateFromDataCollection(HttpServletRequest request, List ids) { - final String dataCollectionUri = String.join(externalServicesProperties.datacollectionUrl(), + final String dataCollectionUri = String.join("", externalServicesProperties.datacollectionUrl(), Constants.API_QUEEN_SURVEYUNITS_STATEDATA); String authTokenHeader = request.getHeader(Constants.AUTHORIZATION); diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestCreateDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestCreateDto.java index e2279fc0..b9b9c67d 100644 --- a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestCreateDto.java +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestCreateDto.java @@ -1,10 +1,8 @@ package fr.insee.pearljam.api.surveyunit.dto; -import fr.insee.pearljam.domain.surveyunit.model.communication.*; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestReason; import jakarta.validation.constraints.NotNull; -import java.util.List; - /** * DTO for creating a communication request. * @@ -12,29 +10,16 @@ * communication request, including the configuration ID, the * creationTimestamp, and the reason for the request.

* - * @param communicationTemplateId the configuration ID, must not be null + * @param communicationTemplateId communicationTemplateId : AKA meshuggahId -> used for compatibility with interviewer app * @param creationTimestamp the creationTimestamp of the request, must not be null * @param reason the reason for the communication request, must not be null */ public record CommunicationRequestCreateDto( @NotNull - Long communicationTemplateId, + String communicationTemplateId, @NotNull Long creationTimestamp, @NotNull CommunicationRequestReason reason) { - /** - * Converts a list of communication request DTOs into a list of communication request models. - * - * @param requests the list of communication request DTOs - * @param readyTimestamp ready timestamp of the communication requests (when does the communication request are created in the back) - * @return the list of communication request models - */ - public static List toModel(List requests, Long readyTimestamp) { - return requests.stream() - .map(request -> - CommunicationRequest.create(request.communicationTemplateId(), request.creationTimestamp(), readyTimestamp, request.reason())) - .toList(); - } } diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestResponseDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestResponseDto.java index 560eb146..bf100f38 100644 --- a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestResponseDto.java +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/CommunicationRequestResponseDto.java @@ -7,13 +7,14 @@ /** * Record representing a CommunicationRequestResponseDto - * @param communicationTemplateId configuration id of the communication * @param reason The reason for the communication request * @param emitter The emitter of the communication request * @param status The status of the communication request */ public record CommunicationRequestResponseDto( - Long communicationTemplateId, + String communicationTemplateId, + String campaignId, + String meshuggahId, CommunicationRequestReason reason, CommunicationRequestEmitter emitter, List status) { @@ -30,7 +31,9 @@ public static List fromModel(Set persons, AddressDto address, Boolean priority, @@ -50,19 +51,19 @@ public static SurveyUnitInterviewerResponseDto fromModel(SurveyUnitForInterviewe .getStates() .stream() .sorted(Comparator.comparing(State::getDate, Comparator.nullsLast(Comparator.reverseOrder()))) - .filter(s -> BussinessRules.stateCanBeSeenByInterviewerBussinessRules(s.getType())) + .filter(s -> BusinessRules.stateCanBeSeenByInterviewerBussinessRules(s.getType())) .map(StateDto::new) .toList(); ContactOutcomeDto contactOutcome = null; - if (surveyUnit.getContactOucome() != null) { - contactOutcome = new ContactOutcomeDto(surveyUnit.getContactOucome()); + if (surveyUnit.getContactOutcome() != null) { + contactOutcome = ContactOutcomeDto.fromModel(surveyUnit.getModelContactOutcome()); } SampleIdentifiersDto sampleIdentifiers = null; if (surveyUnit.getSampleIdentifier() != null) { sampleIdentifiers = new SampleIdentifiersDto(surveyUnit.getSampleIdentifier()); } - return new SurveyUnitInterviewerResponseDto(surveyUnit.getId(), persons, address, + return new SurveyUnitInterviewerResponseDto(surveyUnit.getId(), surveyUnit.getDisplayName(), persons, address, surveyUnit.isPriority(), surveyUnit.getMove(), surveyUnit.getCampaign().getId(), comments, sampleIdentifiers, states, contactAttempts, contactOutcome, IdentificationDto.fromModel(surveyUnit.getModelIdentification()), diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitUpdateDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitUpdateDto.java index a3e4639f..4f03dd02 100644 --- a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitUpdateDto.java +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitUpdateDto.java @@ -3,9 +3,9 @@ import com.fasterxml.jackson.annotation.JsonInclude; import fr.insee.pearljam.api.dto.address.AddressDto; import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; -import fr.insee.pearljam.api.dto.contactoutcome.ContactOutcomeDto; import fr.insee.pearljam.api.dto.person.PersonDto; import fr.insee.pearljam.api.dto.state.StateDto; +import fr.insee.pearljam.api.surveyunit.dto.identification.RawIdentificationDto; import jakarta.validation.Valid; import java.util.List; @@ -35,7 +35,7 @@ public record SurveyUnitUpdateDto( List states, List contactAttempts, ContactOutcomeDto contactOutcome, - IdentificationDto identification, + RawIdentificationDto identification, @Valid List communicationRequests) { } diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/HouseF2FIdentificationDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/HouseF2FIdentificationDto.java new file mode 100644 index 00000000..4cf07b44 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/HouseF2FIdentificationDto.java @@ -0,0 +1,48 @@ +package fr.insee.pearljam.api.surveyunit.dto.identification; + +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationType; +import fr.insee.pearljam.domain.surveyunit.model.question.*; + +public record HouseF2FIdentificationDto + (IdentificationQuestionValue identification, + AccessQuestionValue access, + SituationQuestionValue situation, + CategoryQuestionValue category, + OccupantQuestionValue occupant) implements IdentificationDto { + + + /** + * Converts a HouseF2FIdentificationDto to an Identification domain model. + * + * @return the corresponding Identification domain model + */ + @Override + public Identification toModel() { + return Identification.builder() + .identificationType(IdentificationType.HOUSEF2F) + .identification(identification) + .access(access) + .situation(situation) + .category(category) + .occupant(occupant) + .build(); + } + + /** + * Converts an Identification domain model to a HouseF2FIdentificationDto. + * + * @param identification the Identification domain model to convert + * @return the corresponding HouseF2FIdentificationDto + */ + public static HouseF2FIdentificationDto fromModel(Identification identification) { + + return new HouseF2FIdentificationDto( + identification.identification(), + identification.access(), + identification.situation(), + identification.category(), + identification.occupant() + ); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/HouseTelIdentificationDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/HouseTelIdentificationDto.java new file mode 100644 index 00000000..b28ad01c --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/HouseTelIdentificationDto.java @@ -0,0 +1,41 @@ +package fr.insee.pearljam.api.surveyunit.dto.identification; + +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationType; +import fr.insee.pearljam.domain.surveyunit.model.question.*; + +public record HouseTelIdentificationDto + ( + SituationQuestionValue situation, + CategoryQuestionValue category) implements IdentificationDto { + + + /** + * Converts a HouseTelIdentificationDto to an Identification domain model. + * + * @return the corresponding Identification domain model + */ + + @Override + public Identification toModel() { + return Identification.builder() + .identificationType(IdentificationType.HOUSETEL) + .situation(situation) + .category(category) + .build(); + } + + /** + * Converts an Identification domain model to a HouseTelIdentificationDto. + * + * @param identification the Identification domain model to convert + * @return the corresponding HouseTelIdentificationDto + */ + public static HouseTelIdentificationDto fromModel(Identification identification) { + + return new HouseTelIdentificationDto( + identification.situation(), + identification.category() + ); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/IdentificationDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/IdentificationDto.java new file mode 100644 index 00000000..280ad46a --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/IdentificationDto.java @@ -0,0 +1,48 @@ +package fr.insee.pearljam.api.surveyunit.dto.identification; + +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.domain.surveyunit.model.Identification; + +public interface IdentificationDto { + Identification toModel(); + + static Identification toModel(RawIdentificationDto rawIdentificationDto, + IdentificationConfiguration identificationConfiguration) { + + if (rawIdentificationDto == null || IdentificationConfiguration.NOIDENT == identificationConfiguration || identificationConfiguration == null) { + return null; + } + + // get all attributes from dto + Identification identification = rawIdentificationDto.toModel(); + + // remove unexpected attributes + IdentificationDto identificationDto = switch (identificationConfiguration) { + case HOUSEF2F, IASCO -> HouseF2FIdentificationDto.fromModel(identification); + case HOUSETEL, HOUSETELWSR -> HouseTelIdentificationDto.fromModel(identification); + case INDF2F, INDF2FNOR -> IndividualF2FIdentificationDto.fromModel(identification); + case INDTEL, INDTELNOR -> IndividualTelIdentificationDto.fromModel(identification); + case SRCVREINT -> SrcvReintIdentificationDto.fromModel(identification); + default -> throw new IllegalStateException("Unexpected value: " + identificationConfiguration); + }; + + return identificationDto.toModel(); + } + + + static IdentificationDto fromModel(Identification identification) { + if (identification == null) { + return null; + } + + return switch (identification.identificationType()) { + case HOUSEF2F -> HouseF2FIdentificationDto.fromModel(identification); + case HOUSETEL -> HouseTelIdentificationDto.fromModel(identification); + case INDF2F -> IndividualF2FIdentificationDto.fromModel(identification); + case INDTEL -> IndividualTelIdentificationDto.fromModel(identification); + case SRCVREINT -> SrcvReintIdentificationDto.fromModel(identification); + }; + } + + +} diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/IndividualF2FIdentificationDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/IndividualF2FIdentificationDto.java new file mode 100644 index 00000000..ea94192d --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/IndividualF2FIdentificationDto.java @@ -0,0 +1,43 @@ +package fr.insee.pearljam.api.surveyunit.dto.identification; + +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.question.IndividualStatusQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.InterviewerCanProcessQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.SituationQuestionValue; + +public record IndividualF2FIdentificationDto + ( + IndividualStatusQuestionValue individualStatus, + InterviewerCanProcessQuestionValue interviewerCanProcess, + SituationQuestionValue situation) implements IdentificationDto { + + + /** + * Converts a IndividualF2FIdentificationDto to an Identification domain model. + * + * @return the corresponding Identification domain model + */ + @Override + public Identification toModel() { + return Identification.builder() + .individualStatus(individualStatus) + .interviewerCanProcess(interviewerCanProcess) + .situation(situation) + .build(); + } + + /** + * Converts an Identification domain model to a IndividualF2FIdentificationDto. + * + * @param identification the Identification domain model to convert + * @return the corresponding IndividualF2FIdentificationDto + */ + public static IndividualF2FIdentificationDto fromModel(Identification identification) { + + return new IndividualF2FIdentificationDto( + identification.individualStatus(), + identification.interviewerCanProcess(), + identification.situation() + ); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/IndividualTelIdentificationDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/IndividualTelIdentificationDto.java new file mode 100644 index 00000000..1272d2d4 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/IndividualTelIdentificationDto.java @@ -0,0 +1,40 @@ +package fr.insee.pearljam.api.surveyunit.dto.identification; + +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationType; +import fr.insee.pearljam.domain.surveyunit.model.question.IndividualStatusQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.SituationQuestionValue; + +public record IndividualTelIdentificationDto + (IndividualStatusQuestionValue individualStatus, + SituationQuestionValue situation) implements IdentificationDto { + + + /** + * Converts a IndividualTelIdentificationDto to an Identification domain model. + * + * @return the corresponding Identification domain model + */ + @Override + public Identification toModel() { + return Identification.builder() + .identificationType(IdentificationType.INDTEL) + .individualStatus(individualStatus) + .situation(situation) + .build(); + } + + /** + * Converts an Identification domain model to a IndividualTelIdentificationDto. + * + * @param identification the Identification domain model to convert + * @return the corresponding IndividualTelIdentificationDto + */ + public static IndividualTelIdentificationDto fromModel(Identification identification) { + + return new IndividualTelIdentificationDto( + identification.individualStatus(), + identification.situation() + ); + } +} diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/RawIdentificationDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/RawIdentificationDto.java new file mode 100644 index 00000000..9d5be413 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/RawIdentificationDto.java @@ -0,0 +1,35 @@ +package fr.insee.pearljam.api.surveyunit.dto.identification; + +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.question.*; + +public record RawIdentificationDto(IdentificationQuestionValue identification, + AccessQuestionValue access, + SituationQuestionValue situation, + CategoryQuestionValue category, + OccupantQuestionValue occupant, + IndividualStatusQuestionValue individualStatus, + InterviewerCanProcessQuestionValue interviewerCanProcess, + NumberOfRespondentsQuestionValue numberOfRespondents, + PresentInPreviousHomeQuestionValue presentInPreviousHome, + HouseholdCompositionQuestionValue householdComposition + +) implements IdentificationDto { + + @Override + public Identification toModel() { + return Identification.builder() + .identificationType(null) + .identification(identification) + .access(access) + .situation(situation) + .category(category) + .occupant(occupant) + .interviewerCanProcess(interviewerCanProcess) + .numberOfRespondents(numberOfRespondents) + .individualStatus(individualStatus) + .householdComposition(householdComposition) + .presentInPreviousHome(presentInPreviousHome) + .build(); + } +} \ No newline at end of file diff --git a/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/SrcvReintIdentificationDto.java b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/SrcvReintIdentificationDto.java new file mode 100644 index 00000000..d55a4e5a --- /dev/null +++ b/src/main/java/fr/insee/pearljam/api/surveyunit/dto/identification/SrcvReintIdentificationDto.java @@ -0,0 +1,48 @@ +package fr.insee.pearljam.api.surveyunit.dto.identification; + +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationType; +import fr.insee.pearljam.domain.surveyunit.model.question.*; + +public record SrcvReintIdentificationDto + (NumberOfRespondentsQuestionValue numberOfRespondents, + IndividualStatusQuestionValue individualStatus, + HouseholdCompositionQuestionValue householdComposition, + PresentInPreviousHomeQuestionValue presentInPreviousHome, + SituationQuestionValue situation) implements IdentificationDto { + + + /** + * Converts a SrcvReintdentificationDto to an Identification domain model. + * + * @return the corresponding Identification domain model + */ + @Override + public Identification toModel() { + return Identification.builder() + .identificationType(IdentificationType.SRCVREINT) + .numberOfRespondents(numberOfRespondents) + .individualStatus(individualStatus) + .householdComposition(householdComposition) + .presentInPreviousHome(presentInPreviousHome) + .situation(situation) + .build(); + } + + /** + * Converts an Identification domain model to a SrcvReintdentificationDto. + * + * @param identification the Identification domain model to convert + * @return the corresponding SrcvReintdentificationDto + */ + public static SrcvReintIdentificationDto fromModel(Identification identification) { + + return new SrcvReintIdentificationDto( + identification.numberOfRespondents(), + identification.individualStatus(), + identification.householdComposition(), + identification.presentInPreviousHome(), + identification.situation() + ); + } +} diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplate.java b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplate.java index 7e53bc9b..5e326e31 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplate.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/model/communication/CommunicationTemplate.java @@ -4,13 +4,12 @@ /** * A class representing the communication template of a visibility. * - * @param id The unique identifier of the communication template * @param meshuggahId The identifier for Messhugah * @param medium The medium of communication * @param type The type of communication */ public record CommunicationTemplate( - Long id, + String campaignId, String meshuggahId, CommunicationMedium medium, CommunicationType type diff --git a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationTemplateRepository.java b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationTemplateRepository.java index a40f712e..2880be7c 100644 --- a/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationTemplateRepository.java +++ b/src/main/java/fr/insee/pearljam/domain/campaign/port/serverside/CommunicationTemplateRepository.java @@ -12,7 +12,7 @@ public interface CommunicationTemplateRepository { * @param campaignId campaign id * @return the communication template */ - Optional findCommunicationTemplate(Long communicationTemplateId, String campaignId); + Optional findCommunicationTemplate(String campaignId, String meshuggahId); /** * diff --git a/src/main/java/fr/insee/pearljam/domain/exception/CommunicationInformationNotFoundException.java b/src/main/java/fr/insee/pearljam/domain/exception/CommunicationInformationNotFoundException.java deleted file mode 100644 index ac4d1eae..00000000 --- a/src/main/java/fr/insee/pearljam/domain/exception/CommunicationInformationNotFoundException.java +++ /dev/null @@ -1,10 +0,0 @@ -package fr.insee.pearljam.domain.exception; - -public class CommunicationInformationNotFoundException extends RuntimeException { - - public static final String MESSAGE = "Communication Information not found"; - - public CommunicationInformationNotFoundException() { - super(MESSAGE); - } -} diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/ContactOutcome.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/ContactOutcome.java new file mode 100644 index 00000000..3da36316 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/ContactOutcome.java @@ -0,0 +1,12 @@ +package fr.insee.pearljam.domain.surveyunit.model; + +import fr.insee.pearljam.api.domain.ContactOutcomeType; + +public record ContactOutcome( + Long id, + Long date, + ContactOutcomeType type, + Integer totalNumberOfContactAttempts, + String surveyUnitId +) { +} diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/Identification.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/Identification.java index da88805e..d45efbf8 100644 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/Identification.java +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/Identification.java @@ -1,11 +1,21 @@ package fr.insee.pearljam.domain.surveyunit.model; import fr.insee.pearljam.domain.surveyunit.model.question.*; +import lombok.Builder; +@Builder public record Identification( + Long id, + IdentificationType identificationType, IdentificationQuestionValue identification, AccessQuestionValue access, SituationQuestionValue situation, CategoryQuestionValue category, - OccupantQuestionValue occupant) { + OccupantQuestionValue occupant, + IndividualStatusQuestionValue individualStatus, + InterviewerCanProcessQuestionValue interviewerCanProcess, + NumberOfRespondentsQuestionValue numberOfRespondents, + PresentInPreviousHomeQuestionValue presentInPreviousHome, + HouseholdCompositionQuestionValue householdComposition +) { } diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/IdentificationState.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/IdentificationState.java index a963c487..7210a081 100644 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/IdentificationState.java +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/IdentificationState.java @@ -1,52 +1,122 @@ package fr.insee.pearljam.domain.surveyunit.model; +import fr.insee.pearljam.api.domain.IdentificationConfiguration; import fr.insee.pearljam.domain.surveyunit.model.question.CategoryQuestionValue; import fr.insee.pearljam.domain.surveyunit.model.question.IdentificationQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.IndividualStatusQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.InterviewerCanProcessQuestionValue; import fr.insee.pearljam.domain.surveyunit.model.question.SituationQuestionValue; +import java.util.EnumSet; public enum IdentificationState { MISSING, FINISHED, ONGOING; /** * Retrieve the identification state from the identification - * @param identification Identification form which the state is computed + * + * @param identification Identification from which the state is computed + * @param configuration Identification configuration to adapt rules * @return the identification state */ - public static IdentificationState getState(Identification identification) { - if(identification == null || identification.identification() == null) { + public static IdentificationState getState(Identification identification, + IdentificationConfiguration configuration) { + if (identification == null) { return IdentificationState.MISSING; } - IdentificationQuestionValue identificationQuestionValue = identification.identification(); - if(identificationQuestionValue == IdentificationQuestionValue.DESTROY || + return switch (configuration) { + case NOIDENT -> IdentificationState.MISSING; + + case IASCO, HOUSEF2F -> houseF2F(identification); + + case INDF2F, INDF2FNOR -> individuF2F(identification); + + case INDTEL, INDTELNOR -> individuTel(identification); + + // additional rules coming soon + case HOUSETEL, HOUSETELWSR, SRCVREINT -> IdentificationState.MISSING; + + }; + + } + + private static IdentificationState individuTel(Identification identification) { + IndividualStatusQuestionValue status = identification.individualStatus(); + if (status == null) return IdentificationState.ONGOING; + if (EnumSet.of(IndividualStatusQuestionValue.DCD, IndividualStatusQuestionValue.NOIDENT, IndividualStatusQuestionValue.NOFIELD) + .contains(status)) + return IdentificationState.FINISHED; + + SituationQuestionValue situation = identification.situation(); + if (EnumSet.of(IndividualStatusQuestionValue.SAME_ADDRESS, IndividualStatusQuestionValue.OTHER_ADDRESS).contains(status)) + return (situation == null) ? IdentificationState.ONGOING : IdentificationState.FINISHED; + + return (situation != null) ? IdentificationState.ONGOING : null; + } + + + private static IdentificationState individuF2F(Identification identification) { + IndividualStatusQuestionValue status = identification.individualStatus(); + if (status == null) return IdentificationState.ONGOING; + if (EnumSet.of(IndividualStatusQuestionValue.DCD, IndividualStatusQuestionValue.NOIDENT, IndividualStatusQuestionValue.NOFIELD) + .contains(status)) + return IdentificationState.FINISHED; + + SituationQuestionValue situation = identification.situation(); + if (status == IndividualStatusQuestionValue.SAME_ADDRESS) + return (situation == null) ? IdentificationState.ONGOING : IdentificationState.FINISHED; + + InterviewerCanProcessQuestionValue interviewer = identification.interviewerCanProcess(); + if (status == IndividualStatusQuestionValue.OTHER_ADDRESS) { + if (interviewer == null) return IdentificationState.ONGOING; + if (interviewer == InterviewerCanProcessQuestionValue.NO) return IdentificationState.FINISHED; + } + + if (interviewer == InterviewerCanProcessQuestionValue.YES && situation == null) return IdentificationState.ONGOING; + if (EnumSet.of(SituationQuestionValue.NOORDINARY, SituationQuestionValue.ABSORBED).contains(situation)) + return IdentificationState.FINISHED; + + if (interviewer == InterviewerCanProcessQuestionValue.NO) return IdentificationState.ONGOING; + + return null; + } + + private static IdentificationState houseF2F(Identification identification) { + IdentificationQuestionValue identificationQuestionValue = identification.identification(); + if (identificationQuestionValue == null) { + return IdentificationState.MISSING; + } + + if (identificationQuestionValue == IdentificationQuestionValue.DESTROY || identificationQuestionValue == IdentificationQuestionValue.UNIDENTIFIED) { return IdentificationState.FINISHED; } - if(identification.access() == null) { + if (identification.access() == null) { return IdentificationState.ONGOING; } SituationQuestionValue situationQuestionValue = identification.situation(); - if(situationQuestionValue == null) { + if (situationQuestionValue == null) { return IdentificationState.ONGOING; } - if(situationQuestionValue == SituationQuestionValue.ABSORBED || + if (situationQuestionValue == SituationQuestionValue.ABSORBED || situationQuestionValue == SituationQuestionValue.NOORDINARY) { return IdentificationState.FINISHED; } CategoryQuestionValue categoryQuestionValue = identification.category(); - if(categoryQuestionValue == null) { + if (categoryQuestionValue == null) { return IdentificationState.ONGOING; } - if(categoryQuestionValue == CategoryQuestionValue.VACANT || + if (categoryQuestionValue == CategoryQuestionValue.VACANT || categoryQuestionValue == CategoryQuestionValue.SECONDARY) { return IdentificationState.FINISHED; } - return identification.occupant() != null ? IdentificationState.FINISHED : IdentificationState.ONGOING; + return identification.occupant() == null ? IdentificationState.ONGOING : IdentificationState.FINISHED; } + } diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/IdentificationType.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/IdentificationType.java new file mode 100644 index 00000000..0174dd6a --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/IdentificationType.java @@ -0,0 +1,9 @@ +package fr.insee.pearljam.domain.surveyunit.model; + +import lombok.Getter; + +@Getter +public enum IdentificationType { + HOUSEF2F, HOUSETEL, INDF2F, INDTEL, SRCVREINT + +} diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java index 8db265e4..104f7e11 100644 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/communication/CommunicationRequest.java @@ -5,38 +5,41 @@ public record CommunicationRequest( Long id, - Long communicationTemplateId, + String campaignId, + String meshuggahId, CommunicationRequestReason reason, CommunicationRequestEmitter emitter, List status) { /** * Create a communication request for meshuggah - * @param communicationTemplateId communication configuration id + * @param campaignId campaign id + * @param meshuggahId meshuggah id * @param creationTimestamp creation date of the communication request (coming from the front) * @param readyTimestamp ready timestamp of the communication request (when does the communication request is created in the back) * @param reason reason why the communication request is created * @return {@link CommunicationRequest} communication request object */ - public static CommunicationRequest create(Long communicationTemplateId, Long creationTimestamp, Long readyTimestamp, CommunicationRequestReason reason) { + public static CommunicationRequest create(String campaignId, String meshuggahId, Long creationTimestamp, Long readyTimestamp, CommunicationRequestReason reason) { List status = new ArrayList<>(); status.add(CommunicationRequestStatus.create(creationTimestamp, CommunicationStatusType.INITIATED)); status.add(CommunicationRequestStatus.create(readyTimestamp, CommunicationStatusType.READY)); - return new CommunicationRequest(null, communicationTemplateId, reason, CommunicationRequestEmitter.INTERVIEWER, status); + return new CommunicationRequest(null, campaignId,meshuggahId, reason, CommunicationRequestEmitter.INTERVIEWER, status); } /** * Create a communication request for meshuggah - * @param communicationTemplateId communication configuration id + * @param campaignId campaign id + * @param meshuggahId meshuggah id * @param creationTimestamp creation date of the communication request (coming from the front) * @param readyTimestamp ready timestamp of the communication request (when does the communication request is created in the back) * @param reason reason why the communication request is created * @return {@link CommunicationRequest} communication request object */ - public static CommunicationRequest createCancelled(Long communicationTemplateId, Long creationTimestamp, Long readyTimestamp, CommunicationRequestReason reason) { + public static CommunicationRequest createCancelled(String campaignId, String meshuggahId, Long creationTimestamp, Long readyTimestamp, CommunicationRequestReason reason) { List status = new ArrayList<>(); status.add(CommunicationRequestStatus.create(creationTimestamp, CommunicationStatusType.INITIATED)); status.add(CommunicationRequestStatus.create(readyTimestamp, CommunicationStatusType.CANCELLED)); - return new CommunicationRequest(null, communicationTemplateId, reason, CommunicationRequestEmitter.INTERVIEWER, status); + return new CommunicationRequest(null, campaignId, meshuggahId, reason, CommunicationRequestEmitter.INTERVIEWER, status); } } diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/CategoryQuestionValue.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/CategoryQuestionValue.java index 333fc3bd..b0b1bb9e 100644 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/CategoryQuestionValue.java +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/CategoryQuestionValue.java @@ -1,5 +1,5 @@ package fr.insee.pearljam.domain.surveyunit.model.question; public enum CategoryQuestionValue { - PRIMARY, OCCASIONAL, DK, SECONDARY, VACANT; + PRIMARY, OCCASIONAL, SECONDARY, VACANT; } diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/HouseholdCompositionQuestionValue.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/HouseholdCompositionQuestionValue.java new file mode 100644 index 00000000..b5f31986 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/HouseholdCompositionQuestionValue.java @@ -0,0 +1,5 @@ +package fr.insee.pearljam.domain.surveyunit.model.question; + +public enum HouseholdCompositionQuestionValue { + SAME_COMPO, OTHER_COMPO +} diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/IndividualStatusQuestionValue.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/IndividualStatusQuestionValue.java new file mode 100644 index 00000000..d1b7719c --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/IndividualStatusQuestionValue.java @@ -0,0 +1,5 @@ +package fr.insee.pearljam.domain.surveyunit.model.question; + +public enum IndividualStatusQuestionValue { + DCD, NOIDENT, NOFIELD, SAME_ADDRESS, OTHER_ADDRESS +} diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/InterviewerCanProcessQuestionValue.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/InterviewerCanProcessQuestionValue.java new file mode 100644 index 00000000..e0973df7 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/InterviewerCanProcessQuestionValue.java @@ -0,0 +1,5 @@ +package fr.insee.pearljam.domain.surveyunit.model.question; + +public enum InterviewerCanProcessQuestionValue { + YES, NO +} diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/NumberOfRespondentsQuestionValue.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/NumberOfRespondentsQuestionValue.java new file mode 100644 index 00000000..52dd7308 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/NumberOfRespondentsQuestionValue.java @@ -0,0 +1,5 @@ +package fr.insee.pearljam.domain.surveyunit.model.question; + +public enum NumberOfRespondentsQuestionValue { + ONE, MANY +} diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/PresentInPreviousHomeQuestionValue.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/PresentInPreviousHomeQuestionValue.java new file mode 100644 index 00000000..31ac06aa --- /dev/null +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/model/question/PresentInPreviousHomeQuestionValue.java @@ -0,0 +1,5 @@ +package fr.insee.pearljam.domain.surveyunit.model.question; + +public enum PresentInPreviousHomeQuestionValue { + AT_LEAST_ONE, NONE +} diff --git a/src/main/java/fr/insee/pearljam/domain/surveyunit/port/serverside/CommunicationRequestRepository.java b/src/main/java/fr/insee/pearljam/domain/surveyunit/port/serverside/CommunicationRequestRepository.java index fdd5aa0b..5db25574 100644 --- a/src/main/java/fr/insee/pearljam/domain/surveyunit/port/serverside/CommunicationRequestRepository.java +++ b/src/main/java/fr/insee/pearljam/domain/surveyunit/port/serverside/CommunicationRequestRepository.java @@ -1,15 +1,26 @@ package fr.insee.pearljam.domain.surveyunit.port.serverside; import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.api.dto.interviewer.InterviewerCountDto; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; - import java.util.List; +import java.util.Set; public interface CommunicationRequestRepository { - /** - * Add communication requests to a survey unit - * @param surveyUnit survey unit to update - * @param communicationRequests communication requests to add - */ - void addCommunicationRequests(SurveyUnit surveyUnit, List communicationRequests); + + /** + * Add communication requests to a survey unit + * + * @param surveyUnit survey unit to update + * @param communicationRequests communication requests to add + */ + void addCommunicationRequests(SurveyUnit surveyUnit, + List communicationRequests); + + Long getCommRequestCountByCampaignAndType(String campaignId, CommunicationType type, Long date); + + Long getCommRequestCountByCampaignTypeAndOrgaUnit(String campaignId, CommunicationType type, Long date, List ouIds); + + List getCommRequestCountByInterviewersAndType(List campaignIds, Set interviewerId, CommunicationType type, List ouIds, Long date); } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationTemplateDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationTemplateDaoAdapter.java index 49c5dbf3..574f74ff 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationTemplateDaoAdapter.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/adapter/CommunicationTemplateDaoAdapter.java @@ -4,29 +4,28 @@ import fr.insee.pearljam.domain.campaign.port.serverside.CommunicationTemplateRepository; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.campaign.jpa.CommunicationTemplateJpaRepository; +import java.util.List; +import java.util.Optional; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Repository; -import java.util.Optional; -import java.util.List; - @Repository @RequiredArgsConstructor public class CommunicationTemplateDaoAdapter implements CommunicationTemplateRepository { - private final CommunicationTemplateJpaRepository communicationTemplateRepository; + private final CommunicationTemplateJpaRepository communicationTemplateRepository; - @Override - public List findCommunicationTemplates(String campaignId) { - List communicationTemplates = communicationTemplateRepository - .findCommunicationTemplates(campaignId); - return CommunicationTemplateDB.toModel(communicationTemplates); - } + @Override + public List findCommunicationTemplates(String campaignId) { + List communicationTemplates = communicationTemplateRepository + .findCommunicationTemplates(campaignId); + return CommunicationTemplateDB.toModel(communicationTemplates); + } - @Override - public Optional findCommunicationTemplate(Long communicationTemplateId, String campaignId) { - return communicationTemplateRepository - .findCommunicationTemplate(communicationTemplateId, campaignId) - .map(CommunicationTemplateDB::toModel); - } + @Override + public Optional findCommunicationTemplate(String campaignId, String meshuggahId) { + return communicationTemplateRepository + .findCommunicationTemplate(campaignId, meshuggahId) + .map(CommunicationTemplateDB::toModel); + } } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java index 02a6c6f1..b967634f 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDB.java @@ -5,6 +5,7 @@ import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; import jakarta.persistence.*; +import java.io.Serial; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -24,14 +25,11 @@ @AllArgsConstructor public class CommunicationTemplateDB implements Serializable { + @Serial private static final long serialVersionUID = 1L; - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @Column - private String meshuggahId; + @EmbeddedId + private CommunicationTemplateDBId communicationTemplateDBId; @Column @Enumerated(EnumType.STRING) @@ -42,6 +40,7 @@ public class CommunicationTemplateDB implements Serializable { private CommunicationType type; @ManyToOne(fetch = FetchType.LAZY) + @MapsId("campaignId") private Campaign campaign; public static List toModel(List communicationTemplatesDB) { @@ -55,19 +54,20 @@ public static CommunicationTemplate toModel(CommunicationTemplateDB communicatio return null; } return new CommunicationTemplate( - communicationTemplate.getId(), - communicationTemplate.getMeshuggahId(), + communicationTemplate.getCommunicationTemplateDBId().getCampaignId(), + communicationTemplate.getCommunicationTemplateDBId().getMeshuggahId(), communicationTemplate.getMedium(), communicationTemplate.getType()); } + public static List fromModel(List communicationTemplates, Campaign campaign) { return communicationTemplates.stream() - .map(communicationTemplate -> new CommunicationTemplateDB(null, - communicationTemplate.meshuggahId(), - communicationTemplate.medium(), - communicationTemplate.type(), - campaign)) - .toList(); + .map(communicationTemplate -> new CommunicationTemplateDB( + new CommunicationTemplateDBId(communicationTemplate.meshuggahId(), campaign.getId()), + communicationTemplate.medium(), + communicationTemplate.type(), + campaign)) + .toList(); } } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBId.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBId.java new file mode 100644 index 00000000..a92fa4c5 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBId.java @@ -0,0 +1,37 @@ +package fr.insee.pearljam.infrastructure.campaign.entity; + +import jakarta.persistence.Column; +import jakarta.persistence.Embeddable; +import java.io.Serial; +import java.io.Serializable; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * @author camille corbin + */ +@Embeddable +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class CommunicationTemplateDBId implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + /** + * The meshuggah Id + */ + @Column(name = "meshuggah_id") + private String meshuggahId; + + /** + * The campaign Id + */ + @Column(name = "campaign_id") + private String campaignId; + +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java index 211a120b..c03da141 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDB.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.infrastructure.campaign.entity; +import java.io.Serial; import java.io.Serializable; import java.util.List; @@ -22,6 +23,7 @@ @Slf4j public class VisibilityDB implements Serializable { + @Serial private static final long serialVersionUID = 1L; @EmbeddedId diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBId.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBId.java index a95cb55d..faeb23e1 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBId.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBId.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.infrastructure.campaign.entity; +import java.io.Serial; import java.io.Serializable; import jakarta.persistence.Column; @@ -22,6 +23,7 @@ @Setter public class VisibilityDBId implements Serializable { + @Serial private static final long serialVersionUID = 1L; /** diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationRequestJpaRepository.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationRequestJpaRepository.java new file mode 100644 index 00000000..82cec11e --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationRequestJpaRepository.java @@ -0,0 +1,108 @@ +package fr.insee.pearljam.infrastructure.campaign.jpa; + +import fr.insee.pearljam.api.dto.interviewer.InterviewerCountDto; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; +import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; +import java.util.List; +import java.util.Set; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +public interface CommunicationRequestJpaRepository extends + JpaRepository { + + /** + * Counts the number of communication requests for a given campaign and communication type. + * + * @param campaignId The ID of the campaign. + * @param type The type of communication. + * @param date The reference date for filtering requests. + * @return The number of communication requests matching the criteria. + */ + @Query(""" + SELECT COUNT(DISTINCT su.id) + FROM communication_request cr + INNER JOIN cr.surveyUnit su + INNER JOIN su.campaign c + INNER JOIN c.visibilities vi + INNER JOIN CommunicationTemplateDB ct ON ct.communicationTemplateDBId.campaignId = cr.communicationTemplateDBId.campaignId + AND ct.communicationTemplateDBId.meshuggahId = cr.communicationTemplateDBId.meshuggahId + INNER JOIN cr.status crs + WHERE cr.communicationTemplateDBId.campaignId = :campaignId + AND ct.type = :type + AND crs.date < :date + AND vi.endDate > :date + AND vi.managementStartDate < :date + AND crs.status = 'READY' + """) + Long getCommRequestCountByCampaignAndType(String campaignId, + CommunicationType type, Long date); + + + /** + * Counts the number of communication requests for a campaign, communication type, and a given organization unit. + * + * @param campaignId The ID of the campaign. + * @param type The type of communication. + * @param date The reference date for filtering requests. + * @param ouIds The list of organization unit IDs. + * @return The number of communication requests matching the criteria. + */ + @Query(""" + SELECT COUNT(DISTINCT su.id) + FROM communication_request cr + INNER JOIN cr.surveyUnit su + INNER JOIN su.campaign c + INNER JOIN c.visibilities vi + INNER JOIN CommunicationTemplateDB ct ON ct.communicationTemplateDBId.campaignId = cr.communicationTemplateDBId.campaignId + AND ct.communicationTemplateDBId.meshuggahId = cr.communicationTemplateDBId.meshuggahId + INNER JOIN cr.status crs + WHERE cr.communicationTemplateDBId.campaignId = :campaignId + AND ct.type = :type + AND crs.date < :date + AND vi.endDate > :date + AND vi.managementStartDate < :date + AND crs.status = 'READY' + AND su.organizationUnit.id IN (:ouIds) + """) + Long getCommRequestCountByCampaignTypeAndOrgaUnit(String campaignId, + CommunicationType type, Long date, List ouIds); + + + /** + * Counts the number of communication requests per interviewer for a given communication type. + * + * @param campaignIds The list of campaign IDs. + * @param interviewerIds The set of interviewer IDs. + * @param type The type of communication. + * @param ouIds The list of organization unit IDs. + * @param date The reference date for filtering requests. + * @return A list of {@link InterviewerCountDto} containing interviewer IDs and their respective request counts. + */ + @Query(""" + SELECT new fr.insee.pearljam.api.dto.interviewer.InterviewerCountDto(i.id, COUNT(DISTINCT su.id)) + FROM communication_request cr + INNER JOIN cr.surveyUnit su + INNER JOIN su.campaign c + INNER JOIN c.visibilities vi + INNER JOIN su.interviewer i + INNER JOIN CommunicationTemplateDB ct ON ct.communicationTemplateDBId.campaignId = cr.communicationTemplateDBId.campaignId + AND ct.communicationTemplateDBId.meshuggahId = cr.communicationTemplateDBId.meshuggahId + INNER JOIN cr.status crs + WHERE c.id IN :campaignIds + AND i.id IN :interviewerIds + AND ct.type = :type + AND crs.date < :date + AND vi.endDate > :date + AND vi.managementStartDate < :date + AND crs.status = 'READY' + AND su.organizationUnit.id IN (:ouIds) + GROUP BY i.id + """) + List getCommRequestCountByInterviewersAndType( + List campaignIds, + Set interviewerIds, + CommunicationType type, + List ouIds, + Long date); +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationTemplateJpaRepository.java b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationTemplateJpaRepository.java index 414373fb..b0e1e6f9 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationTemplateJpaRepository.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/campaign/jpa/CommunicationTemplateJpaRepository.java @@ -1,22 +1,24 @@ package fr.insee.pearljam.infrastructure.campaign.jpa; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; - import java.util.List; import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; -public interface CommunicationTemplateJpaRepository extends JpaRepository { +public interface CommunicationTemplateJpaRepository extends + JpaRepository { - @Query(""" - SELECT c FROM CommunicationTemplateDB c - WHERE c.id = ?1 - AND c.campaign.id = ?2""") - Optional findCommunicationTemplate(Long communicationTemplateId, String campaignId); + @Query(""" + SELECT c FROM CommunicationTemplateDB c + WHERE c.communicationTemplateDBId.campaignId = ?1 + AND c.communicationTemplateDBId.meshuggahId = ?2""") + Optional findCommunicationTemplate(String campaignId, String meshuggahId); - @Query(""" - SELECT c FROM CommunicationTemplateDB c - WHERE c.campaign.id = ?1""") - List findCommunicationTemplates(String campaignId); + @Query(""" + SELECT c FROM CommunicationTemplateDB c + LEFT JOIN FETCH c.campaign + WHERE c.communicationTemplateDBId.campaignId = ?1 + """) + List findCommunicationTemplates(String campaignId); } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java b/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java index 47ca6acf..5dd292cd 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/security/config/OidcSecurityConfiguration.java @@ -94,6 +94,7 @@ private void authorizeRequests(HttpSecurity http) throws Exception { final String localUserRole = AuthorityRole.LOCAL_USER.name(); final String nationalUserRole = AuthorityRole.NATIONAL_USER.name(); final String interviewerRole = AuthorityRole.INTERVIEWER.name(); + final String webclientRole = AuthorityRole.WEBCLIENT.name(); http .authorizeHttpRequests(configurer -> configurer @@ -186,6 +187,10 @@ private void authorizeRequests(HttpSecurity http) throws Exception { .hasAnyRole(adminRole, localUserRole, nationalUserRole) .requestMatchers(HttpMethod.GET, Constants.API_CAMPAIGNS_ID_ON_GOING) .hasRole(adminRole) + .requestMatchers(HttpMethod.GET, Constants.API_CAMPAIGNS_ON_GOING) + .hasAnyRole(adminRole, webclientRole) + .requestMatchers(HttpMethod.GET, Constants.API_CAMPAIGN_ID_INTERVIEWERS_STATECOUNT) + .hasAnyRole(adminRole, localUserRole, nationalUserRole) .requestMatchers(HttpMethod.GET, Constants.API_INTERVIEWERS) .hasAnyRole(adminRole, localUserRole, nationalUserRole) .requestMatchers(HttpMethod.POST, Constants.API_INTERVIEWERS) @@ -197,7 +202,7 @@ private void authorizeRequests(HttpSecurity http) throws Exception { .requestMatchers(HttpMethod.DELETE, Constants.API_INTERVIEWER_ID) .hasRole(adminRole) .requestMatchers(HttpMethod.GET, Constants.API_INTERVIEWER_ID) - .hasRole(adminRole) + .hasAnyRole(interviewerRole, adminRole) .requestMatchers(HttpMethod.GET, Constants.API_INTERVIEWERS_SU_STATECOUNT) .hasAnyRole(adminRole, localUserRole, nationalUserRole) .requestMatchers(HttpMethod.GET, Constants.API_INTERVIEWER_ID_CAMPAIGNS) diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommunicationRequestDaoAdapter.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommunicationRequestDaoAdapter.java index 2936446a..3000e22f 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommunicationRequestDaoAdapter.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/adapter/CommunicationRequestDaoAdapter.java @@ -1,41 +1,73 @@ package fr.insee.pearljam.infrastructure.surveyunit.adapter; import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.api.dto.interviewer.InterviewerCountDto; +import fr.insee.pearljam.api.repository.SurveyUnitRepository; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; import fr.insee.pearljam.domain.exception.CommunicationTemplateNotFoundException; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; import fr.insee.pearljam.domain.surveyunit.port.serverside.CommunicationRequestRepository; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; +import fr.insee.pearljam.infrastructure.campaign.jpa.CommunicationRequestJpaRepository; import fr.insee.pearljam.infrastructure.campaign.jpa.CommunicationTemplateJpaRepository; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; -import fr.insee.pearljam.api.repository.SurveyUnitRepository; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - import java.util.ArrayList; import java.util.List; import java.util.Set; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; @Repository @RequiredArgsConstructor public class CommunicationRequestDaoAdapter implements CommunicationRequestRepository { - private final SurveyUnitRepository surveyUnitRepository; - private final CommunicationTemplateJpaRepository communicationTemplateRepository; - - @Override - @Transactional - public void addCommunicationRequests(SurveyUnit surveyUnit, List communicationRequests) { - List newCommunicationRequests = new ArrayList<>(); - for(CommunicationRequest communicationRequest: communicationRequests) { - CommunicationTemplateDB communicationTemplate = communicationTemplateRepository - .findCommunicationTemplate(communicationRequest.communicationTemplateId(), surveyUnit.getCampaign().getId()) - .orElseThrow(CommunicationTemplateNotFoundException::new); - CommunicationRequestDB newCommunicationRequest = CommunicationRequestDB.fromModel(communicationRequest, surveyUnit, communicationTemplate); - newCommunicationRequests.add(newCommunicationRequest); - } - - Set currentCommunicationRequests = surveyUnit.getCommunicationRequests(); - currentCommunicationRequests.addAll(newCommunicationRequests); - surveyUnitRepository.save(surveyUnit); + + private final SurveyUnitRepository surveyUnitRepository; + private final CommunicationTemplateJpaRepository communicationTemplateRepository; + private final CommunicationRequestJpaRepository communicationRequestRepository; + + @Override + @Transactional + public void addCommunicationRequests(SurveyUnit surveyUnit, + List communicationRequests) { + List newCommunicationRequests = new ArrayList<>(); + for (CommunicationRequest communicationRequest : communicationRequests) { + CommunicationTemplateDB communicationTemplate = communicationTemplateRepository + .findCommunicationTemplate(communicationRequest.campaignId(), communicationRequest.meshuggahId()) + .orElseThrow(CommunicationTemplateNotFoundException::new); + CommunicationRequestDB newCommunicationRequest = CommunicationRequestDB.fromModel( + communicationRequest, surveyUnit, communicationTemplate ); + newCommunicationRequests.add(newCommunicationRequest); } + + Set currentCommunicationRequests = surveyUnit.getCommunicationRequests(); + currentCommunicationRequests.addAll(newCommunicationRequests); + surveyUnitRepository.save(surveyUnit); + } + + @Override + public Long getCommRequestCountByCampaignAndType(String campaignId, + CommunicationType type, Long date) { + + + return communicationRequestRepository.getCommRequestCountByCampaignAndType( + campaignId, type, date); + } + + @Override + public Long getCommRequestCountByCampaignTypeAndOrgaUnit(String campaignId, + CommunicationType type, Long date, List ouIds) { + + return communicationRequestRepository.getCommRequestCountByCampaignTypeAndOrgaUnit( + campaignId, type, date, ouIds); + } + + @Override + public List getCommRequestCountByInterviewersAndType(List campaignIds, + Set interviewersId, CommunicationType type, List ouIds, Long date) { + + return communicationRequestRepository.getCommRequestCountByInterviewersAndType( + campaignIds, interviewersId, type, ouIds, date); + } + } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommentDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommentDB.java index f5ac00cf..e42ec80d 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommentDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommentDB.java @@ -1,5 +1,6 @@ package fr.insee.pearljam.infrastructure.surveyunit.entity; +import java.io.Serial; import java.io.Serializable; import java.util.Set; import java.util.stream.Collectors; @@ -37,6 +38,7 @@ public class CommentDB implements Serializable { /** * */ + @Serial private static final long serialVersionUID = 6363481673399032153L; /** * The id of Address diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationMetadataDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationMetadataDB.java new file mode 100644 index 00000000..34e1fc21 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationMetadataDB.java @@ -0,0 +1,36 @@ +package fr.insee.pearljam.infrastructure.surveyunit.entity; + +import fr.insee.pearljam.api.domain.SurveyUnit; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import java.io.Serializable; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Entity(name = "communication_metadata") +@Table +@Getter +@Setter +@NoArgsConstructor +public class CommunicationMetadataDB implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @ManyToOne(fetch = FetchType.LAZY) + private SurveyUnit surveyUnit; + @Column(name = "metadata_key") + private String key; + @Column(name = "metadata_value") + private String value; + @Column(name = "campaign_id") + private String campaignId; + @Column(name = "meshuggah_id") + private String meshuggahId; +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDB.java index 89015055..bc244b81 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDB.java @@ -1,16 +1,15 @@ package fr.insee.pearljam.infrastructure.surveyunit.entity; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - import fr.insee.pearljam.api.domain.SurveyUnit; -import fr.insee.pearljam.domain.surveyunit.model.communication.*; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestEmitter; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestReason; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestStatus; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDBId; import jakarta.persistence.CascadeType; import jakarta.persistence.Column; +import jakarta.persistence.Embedded; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; @@ -18,9 +17,15 @@ import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.OneToMany; import jakarta.persistence.Table; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -38,8 +43,8 @@ public class CommunicationRequestDB implements Serializable { @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; - @ManyToOne(fetch = FetchType.LAZY) - private CommunicationTemplateDB communicationTemplate; + @Embedded + private CommunicationTemplateDBId communicationTemplateDBId; @Enumerated(EnumType.STRING) @Column @@ -55,16 +60,32 @@ public class CommunicationRequestDB implements Serializable { @OneToMany(fetch = FetchType.LAZY, targetEntity = CommunicationRequestStatusDB.class, cascade = CascadeType.ALL, mappedBy = "communicationRequest", orphanRemoval = true) private List status; + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "campaign_id", referencedColumnName = "campaign_id", insertable = false, updatable = false) + @JoinColumn(name = "meshuggah_id", referencedColumnName = "meshuggah_id", insertable = false, updatable = false) + private CommunicationTemplateDB communicationTemplate; + + public CommunicationRequestDB(Long id, CommunicationTemplateDBId communicationTemplateDBId, + CommunicationRequestReason reason, CommunicationRequestEmitter emitter, + SurveyUnit surveyUnit, List status) { + this.id = id; + this.communicationTemplateDBId = communicationTemplateDBId; + this.reason = reason; + this.emitter = emitter; + this.surveyUnit = surveyUnit; + this.status = status; + } + /** * Create entity object from model object * @param surveyUnit survey unit entity * @param request model object * @return entity object */ - public static CommunicationRequestDB fromModel(CommunicationRequest request, SurveyUnit surveyUnit, CommunicationTemplateDB communicationTemplate) { + public static CommunicationRequestDB fromModel(CommunicationRequest request, SurveyUnit surveyUnit, CommunicationTemplateDB communicationTemplateDB) { List status = new ArrayList<>(); - CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(request.id(), communicationTemplate, + CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(request.id(), communicationTemplateDB.getCommunicationTemplateDBId(), request.reason(), request.emitter(), surveyUnit, status); if(request.status() != null) { @@ -88,7 +109,7 @@ public static CommunicationRequest toModel(CommunicationRequestDB request) { .map(CommunicationRequestStatusDB::toModel).toList(); } - return new CommunicationRequest(request.getId(), request.getCommunicationTemplate().getId(), + return new CommunicationRequest(request.getId(), request.communicationTemplateDBId.getCampaignId(), request.communicationTemplateDBId.getMeshuggahId(), request.getReason(), request.getEmitter(), status); } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDB.java index f2138471..85d341ee 100644 --- a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDB.java +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDB.java @@ -1,5 +1,13 @@ package fr.insee.pearljam.infrastructure.surveyunit.entity; +import jakarta.persistence.EmbeddedId; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinColumns; +import jakarta.persistence.MapsId; +import jakarta.persistence.CascadeType; import java.io.Serializable; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestStatus; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationStatusType; @@ -8,9 +16,6 @@ import jakarta.persistence.EnumType; import jakarta.persistence.Enumerated; import jakarta.persistence.FetchType; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; import jakarta.persistence.Table; import lombok.AllArgsConstructor; @@ -37,14 +42,23 @@ public class CommunicationRequestStatusDB implements Serializable { @Column private CommunicationStatusType status; - @ManyToOne(fetch = FetchType.LAZY) + @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // Ensures cascading behavior private CommunicationRequestDB communicationRequest; public static CommunicationRequestStatusDB fromModel(CommunicationRequestStatus requestStatus, CommunicationRequestDB communicationRequest) { - return new CommunicationRequestStatusDB(requestStatus.id(), requestStatus.date(), requestStatus.status(), communicationRequest); + return new CommunicationRequestStatusDB( + requestStatus.id(), + requestStatus.date(), + requestStatus.status(), + communicationRequest + ); } public static CommunicationRequestStatus toModel(CommunicationRequestStatusDB requestStatus) { - return new CommunicationRequestStatus(requestStatus.getId(), requestStatus.getDate(), requestStatus.getStatus()); + return new CommunicationRequestStatus( + requestStatus.getId(), + requestStatus.getDate(), + requestStatus.getStatus() + ); } } diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/ContactOutcomeDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/ContactOutcomeDB.java new file mode 100644 index 00000000..9fefe00f --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/ContactOutcomeDB.java @@ -0,0 +1,78 @@ +package fr.insee.pearljam.infrastructure.surveyunit.entity; + + +import fr.insee.pearljam.api.domain.ContactOutcomeType; +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.domain.surveyunit.model.ContactOutcome; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.io.Serial; +import java.io.Serializable; + +@Entity +@Table(name = "contact_outcome") +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class ContactOutcomeDB implements Serializable { + + @Serial + private static final long serialVersionUID = 1056818927018376638L; + /** + * the id of ContactOutcome + */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + /** + * the date of ContactOutcome + */ + @Column + private Long date; + /** + * the OutcomeType of ContactOutcome + */ + @Enumerated(EnumType.STRING) + @Column + private ContactOutcomeType type; + /** + * the totalNumberOfContactAttempts of ContactOutcome + */ + @Column + private Integer totalNumberOfContactAttempts; + /** + * The SurveyUnit associated to ContactOutcome + */ + @OneToOne + private SurveyUnit surveyUnit; + + /** + * Create entity object from model object + * @param surveyUnit survey unit entity + * @param contactOutcome contact-outcome model object + * @return contactOutcome entity object + */ + public static ContactOutcomeDB fromModel(SurveyUnit surveyUnit, ContactOutcome contactOutcome) { + return new ContactOutcomeDB(null, contactOutcome.date(),contactOutcome.type(),contactOutcome.totalNumberOfContactAttempts(), surveyUnit); + } + + /** + * Create model object from entity + * @param contactOutcome entity object + * @return contactOutcome model object + */ + public static ContactOutcome toModel(ContactOutcomeDB contactOutcome) { + return new ContactOutcome(contactOutcome.getId(),contactOutcome.getDate(), contactOutcome.getType(),contactOutcome.getTotalNumberOfContactAttempts(),contactOutcome.getSurveyUnit().getId()); + } + + public void updateContactOutcome(ContactOutcome contactOutcome) { + setDate(contactOutcome.date()); + setType(contactOutcome.type()); + setTotalNumberOfContactAttempts(contactOutcome.totalNumberOfContactAttempts()); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/IdentificationDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/IdentificationDB.java deleted file mode 100644 index 0cfc3cae..00000000 --- a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/IdentificationDB.java +++ /dev/null @@ -1,101 +0,0 @@ -package fr.insee.pearljam.infrastructure.surveyunit.entity; - -import fr.insee.pearljam.api.domain.SurveyUnit; -import fr.insee.pearljam.domain.surveyunit.model.Identification; -import fr.insee.pearljam.domain.surveyunit.model.question.*; -import jakarta.persistence.*; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.io.Serializable; - -@Entity -@Table(name = "identification") -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -public class IdentificationDB implements Serializable { - - private static final long serialVersionUID = 1987L; - - /** - * Identification id - */ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @Column - @Enumerated(EnumType.STRING) - private IdentificationQuestionValue identification; - - @Column - @Enumerated(EnumType.STRING) - private AccessQuestionValue access; - - @Column - @Enumerated(EnumType.STRING) - private SituationQuestionValue situation; - - @Column - @Enumerated(EnumType.STRING) - private CategoryQuestionValue category; - - @Column - @Enumerated(EnumType.STRING) - private OccupantQuestionValue occupant; - - /** - * The SurveyUnit associated to Identification - */ - @OneToOne - private SurveyUnit surveyUnit; - - public IdentificationDB(Identification identification, SurveyUnit su) { - this.surveyUnit = su; - if (identification != null) { - this.identification = identification.identification(); - this.access = identification.access(); - this.situation = identification.situation(); - this.category = identification.category(); - this.occupant = identification.occupant(); - } - } - - /** - * return model of the db entity - * @param identificationDB identification DB entity - * @return the model object of the db entity - */ - public static Identification toModel(IdentificationDB identificationDB) { - if(identificationDB == null) { - return null; - } - return new Identification( - identificationDB.getIdentification(), - identificationDB.getAccess(), - identificationDB.getSituation(), - identificationDB.getCategory(), - identificationDB.getOccupant()); - } - - - /** - * update the db entity from the model object - * @param identification model object - */ - public void update(Identification identification) { - if (identification == null) { - return; - } - - this.setIdentification(identification.identification()); - this.setAccess(identification.access()); - this.setSituation(identification.situation()); - this.setCategory(identification.category()); - this.setOccupant(identification.occupant()); - } -} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/HouseF2FIdentificationDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/HouseF2FIdentificationDB.java new file mode 100644 index 00000000..89e43e63 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/HouseF2FIdentificationDB.java @@ -0,0 +1,93 @@ +package fr.insee.pearljam.infrastructure.surveyunit.entity.identification; + +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationType; +import fr.insee.pearljam.domain.surveyunit.model.question.*; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Entity +@DiscriminatorValue("HOUSEF2F") +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class HouseF2FIdentificationDB extends IdentificationDB { + + @Column + @Enumerated(EnumType.STRING) + private IdentificationQuestionValue identification; + + @Column + @Enumerated(EnumType.STRING) + private AccessQuestionValue access; + + @Column + @Enumerated(EnumType.STRING) + private SituationQuestionValue situation; + + @Column + @Enumerated(EnumType.STRING) + private CategoryQuestionValue category; + + @Column + @Enumerated(EnumType.STRING) + private OccupantQuestionValue occupant; + + @Override + protected IdentificationConfiguration getIdentificationConfiguration() { + return IdentificationConfiguration.HOUSEF2F; + } + + public HouseF2FIdentificationDB( + Long id, + SurveyUnit surveyUnit, + IdentificationQuestionValue identification, + AccessQuestionValue access, + SituationQuestionValue situation, + CategoryQuestionValue category, + OccupantQuestionValue occupant) { + super(id, IdentificationType.HOUSEF2F, surveyUnit); + this.identification = identification; + this.access = access; + this.situation = situation; + this.category = category; + this.occupant = occupant; + } + + @Override + protected Identification toModel() { + return Identification.builder() + .id(id) + .identificationType(identificationType) + .identification(identification) + .access(access) + .situation(situation) + .category(category) + .occupant(occupant) + .build(); + } + + /** + * update the db entity from the model object + * + * @param identification model object + */ + @Override + public void updateFields(Identification identification) { + if (identification == null) { + return; + } + + this.setIdentification(identification.identification()); + this.setAccess(identification.access()); + this.setSituation(identification.situation()); + this.setCategory(identification.category()); + this.setOccupant(identification.occupant()); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/HouseTelIdentificationDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/HouseTelIdentificationDB.java new file mode 100644 index 00000000..8e5b4535 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/HouseTelIdentificationDB.java @@ -0,0 +1,68 @@ +package fr.insee.pearljam.infrastructure.surveyunit.entity.identification; + +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationType; +import fr.insee.pearljam.domain.surveyunit.model.question.*; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Entity +@DiscriminatorValue("HOUSETEL") +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class HouseTelIdentificationDB extends IdentificationDB { + + @Column + @Enumerated(EnumType.STRING) + private SituationQuestionValue situation; + + @Column + @Enumerated(EnumType.STRING) + private CategoryQuestionValue category; + + @Override + protected IdentificationConfiguration getIdentificationConfiguration() { + return IdentificationConfiguration.HOUSETEL; + } + + public HouseTelIdentificationDB( + Long id, + SurveyUnit surveyUnit, + SituationQuestionValue situation, + CategoryQuestionValue category) { + super(id, IdentificationType.HOUSETEL, surveyUnit); + this.situation = situation; + this.category = category; + } + + @Override + protected Identification toModel() { + return Identification.builder() + .id(id) + .identificationType(identificationType) + .situation(situation) + .category(category) + .build(); + } + + /** + * update the db entity from the model object + * + * @param identification model object + */ + @Override + public void updateFields(Identification identification) { + if (identification == null) { + return; + } + this.setSituation(identification.situation()); + this.setCategory(identification.category()); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/IdentificationDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/IdentificationDB.java new file mode 100644 index 00000000..4bf5e65c --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/IdentificationDB.java @@ -0,0 +1,152 @@ +package fr.insee.pearljam.infrastructure.surveyunit.entity.identification; + +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationState; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationType; +import jakarta.persistence.*; +import lombok.*; + +import java.io.Serial; +import java.io.Serializable; + +@Entity +@Table(name = "identification") +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@DiscriminatorColumn(name = "identification_type", discriminatorType = DiscriminatorType.STRING) +@NoArgsConstructor +@Getter +@Setter +public abstract class IdentificationDB implements Serializable { + + @Serial + private static final long serialVersionUID = 1987L; + + /** + * Identification id + */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + protected Long id; + + @Column(name = "identification_type", insertable = false, updatable = false) + @Enumerated(EnumType.STRING) + protected IdentificationType identificationType; + + @Column(name = "identification_state", insertable = false) + @Enumerated(EnumType.STRING) + protected IdentificationState identificationState; + + protected abstract IdentificationConfiguration getIdentificationConfiguration(); + + /** + * The SurveyUnit associated to Identification + */ + @OneToOne + protected SurveyUnit surveyUnit; + + protected IdentificationDB(Long id, IdentificationType identificationType, SurveyUnit surveyUnit) { + this.id = id; + this.identificationType = identificationType; + this.surveyUnit = surveyUnit; + } + + /** + * return model of the db entity + * + * @param identificationDB identification DB entity + * @return the model object of the db entity + */ + public static Identification toModel(IdentificationDB identificationDB) { + if (identificationDB == null) { + return null; + } + return identificationDB.toModel(); + } + + protected abstract Identification toModel(); + + public void update(Identification identification) { + if (identification == null) { + return; + } + updateFields(identification); + updateIdentificationState(identification, getIdentificationConfiguration()); + } + + private void updateIdentificationState(Identification identification, IdentificationConfiguration configuration) { + if (identification != null && configuration != null) { + this.identificationState = IdentificationState.getState(identification, configuration); + } + } + + protected abstract void updateFields(Identification identification); + + public static IdentificationDB fromModel(SurveyUnit surveyUnit, + Identification identification, + IdentificationConfiguration configuration) { + if (surveyUnit == null) { + throw new IllegalArgumentException("SurveyUnit cannot be null"); + } + + if(identification == null){ + return null; + } + + + IdentificationType identificationType = switch (configuration) { + case HOUSEF2F, IASCO -> IdentificationType.HOUSEF2F; + case HOUSETEL, HOUSETELWSR -> IdentificationType.HOUSETEL; + case INDF2F, INDF2FNOR -> IdentificationType.INDF2F; + case INDTEL, INDTELNOR -> IdentificationType.INDTEL; + case SRCVREINT -> IdentificationType.SRCVREINT; + case NOIDENT -> null; + }; + if (identificationType == null) { + return null; + } + + + return switch (identificationType) { + case HOUSEF2F -> new HouseF2FIdentificationDB( + identification.id(), + surveyUnit, + identification.identification(), + identification.access(), + identification.situation(), + identification.category(), + identification.occupant()); + case HOUSETEL -> new HouseTelIdentificationDB( + identification.id(), + surveyUnit, + identification.situation(), + identification.category() + ); + case INDTEL -> new IndTelIdentificationDB( + identification.id(), + surveyUnit, + identification.individualStatus(), + identification.situation() + ); + case INDF2F -> new IndF2FIdentificationDB( + identification.id(), + surveyUnit, + identification.individualStatus(), + identification.situation(), + identification.interviewerCanProcess() + ); + case SRCVREINT -> new SrcvReintIdentificationDB( + identification.id(), + surveyUnit, + identification.numberOfRespondents(), + identification.individualStatus(), + identification.householdComposition(), + identification.presentInPreviousHome(), + identification.situation() + ); + }; + + + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/IndF2FIdentificationDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/IndF2FIdentificationDB.java new file mode 100644 index 00000000..808a3626 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/IndF2FIdentificationDB.java @@ -0,0 +1,79 @@ +package fr.insee.pearljam.infrastructure.surveyunit.entity.identification; + +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationType; +import fr.insee.pearljam.domain.surveyunit.model.question.IndividualStatusQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.InterviewerCanProcessQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.SituationQuestionValue; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Entity +@DiscriminatorValue("INDF2F") +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class IndF2FIdentificationDB extends IdentificationDB { + + @Column + @Enumerated(EnumType.STRING) + private IndividualStatusQuestionValue individualStatus; + + @Column + @Enumerated(EnumType.STRING) + private SituationQuestionValue situation; + + @Column + @Enumerated(EnumType.STRING) + private InterviewerCanProcessQuestionValue interviewerCanProcess; + + @Override + protected IdentificationConfiguration getIdentificationConfiguration() { + return IdentificationConfiguration.INDF2F; + } + + + public IndF2FIdentificationDB( + Long id, + SurveyUnit surveyUnit, + IndividualStatusQuestionValue individualStatus, + SituationQuestionValue situation, + InterviewerCanProcessQuestionValue interviewerCanProcess) { + super(id, IdentificationType.INDF2F, surveyUnit); + this.individualStatus = individualStatus; + this.situation = situation; + this.interviewerCanProcess = interviewerCanProcess; + } + + @Override + protected Identification toModel() { + return Identification.builder() + .id(id) + .identificationType(identificationType) + .individualStatus(individualStatus) + .situation(situation) + .interviewerCanProcess(interviewerCanProcess) + .build(); + } + + /** + * update the db entity from the model object + * + * @param identification model object + */ + @Override + public void updateFields(Identification identification) { + if (identification == null) { + return; + } + this.setIndividualStatus(identification.individualStatus()); + this.setInterviewerCanProcess(identification.interviewerCanProcess()); + this.setSituation(identification.situation()); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/IndTelIdentificationDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/IndTelIdentificationDB.java new file mode 100644 index 00000000..a6030fc8 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/IndTelIdentificationDB.java @@ -0,0 +1,70 @@ +package fr.insee.pearljam.infrastructure.surveyunit.entity.identification; + +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationType; +import fr.insee.pearljam.domain.surveyunit.model.question.IndividualStatusQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.SituationQuestionValue; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Entity +@DiscriminatorValue("INDTEL") +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class IndTelIdentificationDB extends IdentificationDB { + + @Column + @Enumerated(EnumType.STRING) + private IndividualStatusQuestionValue individualStatus; + + @Column + @Enumerated(EnumType.STRING) + private SituationQuestionValue situation; + + @Override + protected IdentificationConfiguration getIdentificationConfiguration() { + return IdentificationConfiguration.INDTEL; + } + + + public IndTelIdentificationDB( + Long id, + SurveyUnit surveyUnit, + IndividualStatusQuestionValue individualStatus, + SituationQuestionValue situation) { + super(id, IdentificationType.INDTEL, surveyUnit); + this.individualStatus = individualStatus; + this.situation = situation; + } + + protected Identification toModel() { + return Identification.builder() + .id(id) + .identificationType(identificationType) + .individualStatus(individualStatus) + .situation(situation) + .build(); + } + + + /** + * update the db entity from the model object + * + * @param identification model object + */ + @Override + public void updateFields(Identification identification) { + if (identification == null) { + return; + } + this.setIndividualStatus(identification.individualStatus()); + this.setSituation(identification.situation()); + } +} diff --git a/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/SrcvReintIdentificationDB.java b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/SrcvReintIdentificationDB.java new file mode 100644 index 00000000..6fb2f275 --- /dev/null +++ b/src/main/java/fr/insee/pearljam/infrastructure/surveyunit/entity/identification/SrcvReintIdentificationDB.java @@ -0,0 +1,91 @@ +package fr.insee.pearljam.infrastructure.surveyunit.entity.identification; + +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationType; +import fr.insee.pearljam.domain.surveyunit.model.question.*; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Entity +@DiscriminatorValue("SRCVREINT") +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +public class SrcvReintIdentificationDB extends IdentificationDB { + + @Column + @Enumerated(EnumType.STRING) + private NumberOfRespondentsQuestionValue numberOfRespondents; + + @Column + @Enumerated(EnumType.STRING) + private IndividualStatusQuestionValue individualStatus; + + @Column + @Enumerated(EnumType.STRING) + private HouseholdCompositionQuestionValue householdComposition; + + @Column + @Enumerated(EnumType.STRING) + private PresentInPreviousHomeQuestionValue presentInPreviousHome; + + @Column + @Enumerated(EnumType.STRING) + private SituationQuestionValue situation; + + @Override + protected IdentificationConfiguration getIdentificationConfiguration() { + return IdentificationConfiguration.SRCVREINT; + } + + public SrcvReintIdentificationDB( + Long id, + SurveyUnit surveyUnit, + NumberOfRespondentsQuestionValue numberOfRespondents, + IndividualStatusQuestionValue individualStatus, + HouseholdCompositionQuestionValue householdComposition, + PresentInPreviousHomeQuestionValue presentInPreviousHome, + SituationQuestionValue situation) { + super(id, IdentificationType.SRCVREINT, surveyUnit); + this.numberOfRespondents = numberOfRespondents; + this.individualStatus = individualStatus; + this.householdComposition = householdComposition; + this.presentInPreviousHome = presentInPreviousHome; + this.situation = situation; + } + + protected Identification toModel() { + return Identification.builder() + .id(id) + .identificationType(identificationType) + .numberOfRespondents(numberOfRespondents) + .individualStatus(individualStatus) + .householdComposition(householdComposition) + .presentInPreviousHome(presentInPreviousHome) + .situation(situation) + .build(); + } + + /** + * update the db entity from the model object + * + * @param identification model object + */ + @Override + protected void updateFields(Identification identification) { + if (identification == null) { + return; + } + this.setNumberOfRespondents(identification.numberOfRespondents()); + this.setIndividualStatus(identification.individualStatus()); + this.setHouseholdComposition(identification.householdComposition()); + this.setPresentInPreviousHome(identification.presentInPreviousHome()); + this.setSituation(identification.situation()); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 5ddfc993..0b803297 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -40,6 +40,9 @@ feature: enabled: false spring: + docker: + compose: + enabled: false datasource: url: username: diff --git a/src/main/resources/db/changelog/550_add_business_id.xml b/src/main/resources/db/changelog/550_add_business_id.xml new file mode 100644 index 00000000..6d879411 --- /dev/null +++ b/src/main/resources/db/changelog/550_add_business_id.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + diff --git a/src/main/resources/db/changelog/560_extend_identification.xml b/src/main/resources/db/changelog/560_extend_identification.xml new file mode 100644 index 00000000..0b3c49d2 --- /dev/null +++ b/src/main/resources/db/changelog/560_extend_identification.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + diff --git a/src/main/resources/db/changelog/561_identification_inheritance.xml b/src/main/resources/db/changelog/561_identification_inheritance.xml new file mode 100644 index 00000000..141a0d81 --- /dev/null +++ b/src/main/resources/db/changelog/561_identification_inheritance.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + diff --git a/src/main/resources/db/changelog/562_add_identification_state.xml b/src/main/resources/db/changelog/562_add_identification_state.xml new file mode 100644 index 00000000..06e51609 --- /dev/null +++ b/src/main/resources/db/changelog/562_add_identification_state.xml @@ -0,0 +1,12 @@ + + + + + + + + + + diff --git a/src/main/resources/db/changelog/563_init_identification_state_data.sql b/src/main/resources/db/changelog/563_init_identification_state_data.sql new file mode 100644 index 00000000..3817ee09 --- /dev/null +++ b/src/main/resources/db/changelog/563_init_identification_state_data.sql @@ -0,0 +1,13 @@ +UPDATE identification +SET identification_state = + CASE + WHEN identification IS NULL THEN 'MISSING' + WHEN identification IN ('DESTROY', 'UNIDENTIFIED') THEN 'FINISHED' + WHEN access IS NULL THEN 'ONGOING' + WHEN situation IS NULL THEN 'ONGOING' + WHEN situation IN ('ABSORBED', 'NOORDINARY') THEN 'FINISHED' + WHEN category IS NULL THEN 'ONGOING' + WHEN category IN ('VACANT', 'SECONDARY') THEN 'FINISHED' + WHEN occupant IS NULL THEN 'ONGOING' + ELSE 'FINISHED' + END; \ No newline at end of file diff --git a/src/main/resources/db/changelog/570_remove_unused_contact_outcome_entries.xml b/src/main/resources/db/changelog/570_remove_unused_contact_outcome_entries.xml new file mode 100644 index 00000000..c4a537fc --- /dev/null +++ b/src/main/resources/db/changelog/570_remove_unused_contact_outcome_entries.xml @@ -0,0 +1,17 @@ + + + + + + type = 'DCD' + + + + type = 'DUU' + + + + + diff --git a/src/main/resources/db/changelog/580_add_communication_metadata.xml b/src/main/resources/db/changelog/580_add_communication_metadata.xml new file mode 100644 index 00000000..0a7810c0 --- /dev/null +++ b/src/main/resources/db/changelog/580_add_communication_metadata.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/db/changelog/590_add_sensitivity_field.xml b/src/main/resources/db/changelog/590_add_sensitivity_field.xml new file mode 100644 index 00000000..9ae85754 --- /dev/null +++ b/src/main/resources/db/changelog/590_add_sensitivity_field.xml @@ -0,0 +1,13 @@ + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/db/changelog/600_update_communication_structure.xml b/src/main/resources/db/changelog/600_update_communication_structure.xml new file mode 100644 index 00000000..be65983a --- /dev/null +++ b/src/main/resources/db/changelog/600_update_communication_structure.xml @@ -0,0 +1,94 @@ + + + + + + + + + + + + + + communication_template_id IS NOT NULL + + + + + communication_template_id IS NOT NULL + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/db/dataset/init-demo-data.sql b/src/main/resources/db/dataset/init-demo-data.sql index 01b89489..135cd412 100644 --- a/src/main/resources/db/dataset/init-demo-data.sql +++ b/src/main/resources/db/dataset/init-demo-data.sql @@ -1,24 +1,87 @@ ---changeset davdarras:init-demo-data - -INSERT INTO public.address (dtype, l1, l2, l3, l4, l5, l6, l7, elevator, building, floor, door, staircase, city_priority_district) VALUES - ('InseeAddress', 'Ted Farmer' ,'','','1 rue de la gare' ,'','29270 Carhaix' ,'France', true, 'Bat. C', 'Etg 4', 'Porte 48', 'Escalier B', true), - ('InseeAddress', 'Cecilia Ortega' ,'','','2 place de la mairie' ,'','90000 Belfort' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Claude Watkins' ,'','','3 avenue de la République' ,'','32230 Marciac' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Veronica Gill' ,'','','4 chemin du ruisseau' ,'','44190 Clisson' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Christine Aguilar' ,'','','5 rue de l''école' ,'','59620 Aulnoye-Aimeries' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Louise Walker' ,'','','6 impasse du lac' ,'','38200 Vienne' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Anthony Bennett' ,'','','7 avenue de la Liberté' ,'','62000 Arras' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Christopher Lewis' ,'','','8 route du moulin' ,'','35000 Rennes' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Laurent Neville' ,'','','5 route du sapin' ,'','35000 Rennes' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Alain Thé' ,'','','7 rue des Infusions' ,'','75001 Paris' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Brie Savarin' ,'','','15 avenue des Fromages' ,'','69002 Lyon' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Cécile Houte' ,'','','8 impasse des Aromates' ,'','13003 Marseille' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Dan Tifrice' ,'','','12 chemin du Dentifrice' ,'','33000 Bordeaux' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Émile Pates' ,'','','3 place des Pâtes' ,'','59000 Lille' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'François Appétit' ,'','','22 rue de la Faim' ,'','67000 Strasbourg' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Gérard Dine' ,'','','9 allée des Gourmands' ,'','44000 Nantes' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Hélène Gume' ,'','','18 boulevard des Légumes' ,'','31000 Toulouse' ,'France', false, null, null, null, null, false), - ('InseeAddress', 'Jean Fromage' ,'','','5 rue des Croissants' ,'','06000 Nice' ,'France', false, null, null, null, null, false); +--changeset davdarras:init-demo-data context:demo + +TRUNCATE TABLE + public.communication_request_status, + public.communication_request, + public.communication_template, + public.communication_metadata, + public.contact_attempt, + public.oumessage_recipient, + public.referent, + public.message, + public.campaign_message_recipient, + public.message_status, + public.interviewer, + public.sample_identifier, + public.user, + public.campaign, + public.preference, + public.visibility, + public.survey_unit, + public.identification, + public.person, + public.phone_number, + public.state, + public.contact_outcome, + public.comment, + public.closing_cause, + public.organization_unit, + public.address; + +INSERT INTO public.address (id, dtype, l1, l2, l3, l4, l5, l6, l7, elevator, building, floor, door, staircase, city_priority_district) VALUES + (1, 'InseeAddress', 'Ted Farmer', '', '', '1 rue de la gare', '', '29270 Carhaix', 'France', true, 'Bat. C', 'Etg 4', 'Porte 48', 'Escalier B', true), + (2, 'InseeAddress', 'Cecilia Ortega', '', '', '2 place de la mairie', '', '90000 Belfort', 'France', false, null, null, null, null, false), + (3, 'InseeAddress', 'Claude Watkins', '', '', '3 avenue de la République', '', '32230 Marciac', 'France', false, null, null, null, null, false), + (4, 'InseeAddress', 'Veronica Baker', '', '', '4 chemin du ruisseau', '', '44190 Clisson', 'France', false, null, null, null, null, false), + (5, 'InseeAddress', 'Harriette Raymond', '', '', '5 rue de l''école', '', '59620 Aulnoye-Aimeries','France', false, null, null, null, null, false), + (6, 'InseeAddress', 'Aimée Lamothe', '', '', '6 impasse du lac', '', '38200 Vienne', 'France', false, null, null, null, null, false), + (7, 'InseeAddress', 'Perrin Blanchard', '', '', '7 avenue de la Liberté', '', '62000 Arras', 'France', false, null, null, null, null, false), + (8, 'InseeAddress', 'Artus Arnoux', '', '', '8 route du moulin', '', '35000 Rennes', 'France', false, null, null, null, null, false), + (9, 'InseeAddress', 'Isabelle Moreau', '', '', '5 route du sapin', '', '35000 Rennes', 'France', false, null, null, null, null, false), + (10, 'InseeAddress', 'Julien Dupont', '', '', '7 rue des Infusions', '', '75001 Paris', 'France', false, null, null, null, null, false), + (11, 'InseeAddress', 'Arthur Couyer', '', '', '15 avenue des Fromages', '', '69002 Lyon', 'France', false, null, null, null, null, false), + (12, 'InseeAddress', 'Marc Lefevre', '', '', '8 impasse des Aromates', '', '13003 Marseille', 'France', false, null, null, null, null, false), + (13, 'InseeAddress', 'Kaa Melott', '', '', '12 chemin du Dentifrice', '', '33000 Bordeaux', 'France', false, null, null, null, null, false), + (14, 'InseeAddress', 'Père Seval', '', '', '3 place des Pâtes', '', '59000 Lille', 'France', false, null, null, null, null, false), + (15, 'InseeAddress', 'Camille Renaud', '', '', '22 rue de la Faim', '', '67000 Strasbourg', 'France', false, null, null, null, null, false), + (16, 'InseeAddress', 'Pauline Durand', '', '', '9 allée des Gourmands', '', '44000 Nantes', 'France', false, null, null, null, null, false), + (17, 'InseeAddress', 'Antoine Morel', '', '', '18 boulevard des Légumes', '', '31000 Toulouse', 'France', false, null, null, null, null, false), + (18, 'InseeAddress', 'Marine Lambert', '', '', '5 rue des Croissants', '', '06000 Nice', 'France', false, null, null, null, null, false), + (19, 'InseeAddress', 'Alexandre Faure', '', '', '10 rue des Fleurs', '', '75002 Paris', 'France', false, null, null, null, null, false), + (20, 'InseeAddress', 'Eoldie Renault', '', '', '20 avenue Victor Hugo', '', '75008 Paris', 'France', false, null, null, null, null, false), + (21, 'InseeAddress', 'Maxime Petit', '', '', '30 boulevard Saint-Germain', '', '75005 Paris', 'France', false, null, null, null, null, false), + (22, 'InseeAddress', 'Amélie Gautier', '', '', '40 quai de Seine', '', '75007 Paris', 'France', false, null, null, null, null, false), + (23, 'InseeAddress', 'Damien Roux', '', '', '50 rue de Rivoli', '', '75004 Paris', 'France', false, null, null, null, null, false), + (24, 'InseeAddress', 'Claire Dubois', '', '', '60 rue de la Paix', '', '75002 Paris', 'France', false, null, null, null, null, false), + (25, 'InseeAddress', 'Hugo Simon', '', '', '70 rue de Belleville', '', '75020 Paris', 'France', false, null, null, null, null, false), + (26, 'InseeAddress', 'Chloé Lemoine', '', '', '80 rue de la République', '', '69001 Lyon', 'France', false, null, null, null, null, false), + (27, 'InseeAddress', 'Romain Bertrand', '', '', '90 avenue Jean Jaurès', '', '69003 Lyon', 'France', false, null, null, null, null, false), + (28, 'InseeAddress', 'Alice Renault', '', '', '100 rue Victor Hugo', '', '69002 Lyon', 'France', false, null, null, null, null, false), + (29, 'InseeAddress', 'Guillaume Faure', '', '', '110 boulevard des Capucines', '', '33000 Bordeaux', 'France', false, null, null, null, null, false), + (30, 'InseeAddress', 'Laurent Neville', '', '', '120 rue Sainte-Catherine', '', '33000 Bordeaux', 'France', false, null, null, null, null, false), + (31, 'InseeAddress', 'Harry Cover', '', '', '130 chemin de la Lune', '', '13004 Marseille', 'France', false, null, null, null, null, false), + (32, 'InseeAddress', 'Ella Gance', '', '', '140 rue du Soleil', '', '13001 Marseille', 'France', false, null, null, null, null, false), + (33, 'InseeAddress', 'Jean Neige', '', '', '150 avenue des Étoiles', '', '06000 Nice', 'France', false, null, null, null, null, false), + (34, 'InseeAddress', 'Phil Harmonie', '', '', '160 boulevard de la Mer', '', '06200 Nice', 'France', false, null, null, null, null, false), + (35, 'InseeAddress', 'Alain Thé', '', '', '170 rue de l''Industrie', '', '67000 Strasbourg', 'France', false, null, null, null, null, false), + (36, 'InseeAddress', 'Brie Savarin', '', '', '180 rue des Arts', '', '44000 Nantes', 'France', false, null, null, null, null, false), + (37, 'InseeAddress', 'Cécile Houte', '', '', '190 avenue du Général de Gaulle','', '34000 Montpellier', 'France', false, null, null, null, null, false), + (38, 'InseeAddress', 'Dan Tifrice', '', '', '200 boulevard de la Liberté', '', '34000 Montpellier', 'France', false, null, null, null, null, false), + (39, 'InseeAddress', 'Emile Pates', '', '', '210 rue des Entrepreneurs', '', '38000 Grenoble', 'France', false, null, null, null, null, false), + (40, 'InseeAddress', 'Marine Lefevre', '', '', '41 rue de la République', '', '75001 Paris', 'France', false, null, null, null, null, false), + (41, 'InseeAddress', 'Thierry Bernard', '', '', '42 avenue de la Liberté', '', '69000 Lyon', 'France', false, null, null, null, null, false), + (42, 'InseeAddress', 'Sylvie Martin', '', '', '43 boulevard Saint-Germain', '', '13000 Marseille', 'France', false, null, null, null, null, false), + (43, 'InseeAddress', 'Laurence Girard', '', '', '44 chemin du Moulin', '', '34000 Montpellier', 'France', false, null, null, null, null, false), + (44, 'InseeAddress', 'Dominique Moreau', '', '', '45 impasse du Lac', '', '31000 Toulouse', 'France', false, null, null, null, null, false), + (45, 'InseeAddress', 'Juliette Roussel', '', '', '46 route du Soleil', '', '44000 Nantes', 'France', false, null, null, null, null, false), + (46, 'InseeAddress', 'Pascal Dubois', '', '', '47 place de la Mairie', '', '67000 Strasbourg', 'France', false, null, null, null, null, false), + (47, 'InseeAddress', 'Amandine Perrin', '', '', '48 allée des Fleurs', '', '35000 Rennes', 'France', false, null, null, null, null, false), + (48, 'InseeAddress', 'Nicolas Lambert', '', '', '49 rue des Sapins', '', '29000 Quimper', 'France', false, null, null, null, null, false), + (49, 'InseeAddress', 'Bruno Simon', '', '', '50 avenue de la Gare', '', '21000 Dijon', 'France', false, null, null, null, null, false), + (50, 'InseeAddress', 'Véronique Petit', '', '', '51 rue des Ecoles', '', '14000 Caen', 'France', false, null, null, null, null, false), + (51, 'InseeAddress', 'Philippe Garnier', '', '', '52 rue de l''Industrie', '', '76000 Rouen', 'France', false, null, null, null, null, false), + (52, 'InseeAddress', 'Catherine Renault', '', '', '53 boulevard de la Mer', '', '80000 Amiens', 'France', false, null, null, null, null, false), + (53, 'InseeAddress', 'Jacques Faure', '', '', '55 boulevard de la Mer', '', '80000 Amiens', 'France', false, null, null, null, null, false); INSERT INTO public.organization_unit (id, label, type, organization_unit_parent_id) VALUES ('OU-NATIONAL', 'National organizational unit', 'NATIONAL', null); INSERT INTO public.organization_unit (id, label, type, organization_unit_parent_id) VALUES ('OU-NORTH', 'North region organizational unit', 'LOCAL', 'OU-NATIONAL'); @@ -26,54 +89,98 @@ INSERT INTO public.organization_unit (id, label, type, organization_unit_parent_ INSERT INTO public.organization_unit (id, label, type, organization_unit_parent_id) VALUES ('OU-WEST', 'West region organizational unit', 'LOCAL', 'OU-NATIONAL'); INSERT INTO public.interviewer (id, email, first_name, last_name, phone_number) VALUES - ('INTW1', 'margie.lucas@ou.com', 'Margie', 'Lucas', '+3391231231230'), - ('INTW2', 'carlton.campbell@ou.com', 'Carlton', 'Campbell', '+3391231231231'), - ('INTW3', 'gerald.edwards@ou.com', 'Gerald', 'Edwards', '+3391231231231'), - ('INTW4', 'melody.grant@ou.com', 'Melody', 'Grant', '+3391231231231'), - ('GUEST', 'guest.guest@ou.com', 'GUEST', 'GUEST', '+3391231231231'); - -INSERT INTO public.sample_identifier (dtype, autre, bs, ec, le, nograp, noi, nole, nolog, numfa, rges, ssech) VALUES - ('InseeSampleIdentifier', '11', 11, '1', 11, '11', 11, 11, 11, 11, 11, 1), - ('InseeSampleIdentifier', '12', 12, '1', 12, '12', 12, 12, 12, 12, 12, 1), - ('InseeSampleIdentifier', '13', 13, '1', 13, '13', 13, 13, 13, 13, 13, 2), - ('InseeSampleIdentifier', '14', 14, '1', 14, '14', 14, 14, 14, 14, 14, 3), - ('InseeSampleIdentifier', '20', 20, '2', 20, '20', 20, 20, 20, 20, 20, 1), - ('InseeSampleIdentifier', '21', 21, '2', 21, '21', 21, 21, 21, 21, 21, 1), - ('InseeSampleIdentifier', '22', 22, '2', 22, '22', 22, 22, 22, 22, 22, 2), - ('InseeSampleIdentifier', '23', 23, '2', 23, '23', 23, 23, 23, 23, 23, 1), - ('InseeSampleIdentifier', '24', 24, '2', 24, '24', 24, 24, 24, 24, 24, 1), - ('InseeSampleIdentifier', '25', 25, '1', 25, '25', 25, 25, 25, 25, 25, 1), - ('InseeSampleIdentifier', '26', 26, '1', 26, '26', 26, 26, 26, 26, 26, 1), - ('InseeSampleIdentifier', '27', 27, '1', 27, '27', 27, 27, 27, 27, 27, 2), - ('InseeSampleIdentifier', '28', 28, '1', 28, '28', 28, 28, 28, 28, 28, 3), - ('InseeSampleIdentifier', '29', 29, '2', 29, '29', 29, 29, 29, 29, 29, 1), - ('InseeSampleIdentifier', '30', 30, '2', 30, '30', 30, 30, 30, 30, 30, 1), - ('InseeSampleIdentifier', '31', 31, '2', 31, '31', 31, 31, 31, 31, 31, 2), - ('InseeSampleIdentifier', '32', 32, '2', 32, '32', 32, 32, 32, 32, 32, 1), - ('InseeSampleIdentifier', '33', 33, '2', 33, '33', 33, 33, 33, 33, 33, 1); + ('INTERV1', 'interviewer1@insee.fr', 'Isabelle', 'Interviewer 1', '+3391231231231'), + ('INTERV2', 'interviewer2@insee.fr', 'Ingrid', 'Interviewer 2', '+3391231231232'), + ('INTERV3', 'interviewer3@insee.fr', 'Isaac', 'Interviewer 3', '+3391231231233'), + ('INTERV4', 'interviewer4@insee.fr', 'Isidore', 'Interviewer 4', '+3391231231234'), + ('INTERV5', 'interviewer5@insee.fr', 'Irma', 'Interviewer 5', '+3391231231235'); + +INSERT INTO public.sample_identifier (id, dtype, autre, bs, ec, le, nograp, noi, nole, nolog, numfa, rges, ssech) VALUES + (1, 'InseeSampleIdentifier', '1', 1, '1', 1, '11', 1, 1, 1, 1, 1, 1), + (2, 'InseeSampleIdentifier', '2', 2, '1', 2, '12', 2, 2, 2, 2, 2, 1), + (3, 'InseeSampleIdentifier', '3', 3, '1', 3, '13', 3, 3, 3, 3, 3, 2), + (4, 'InseeSampleIdentifier', '4', 4, '1', 4, '14', 4, 4, 4, 4, 4, 3), + (5, 'InseeSampleIdentifier', '5', 5, '2', 5, '15', 5, 5, 5, 5, 5, 1), + (6, 'InseeSampleIdentifier', '6', 6, '2', 6, '16', 6, 6, 6, 6, 6, 1), + (7, 'InseeSampleIdentifier', '7', 7, '2', 7, '17', 7, 7, 7, 7, 7, 2), + (8, 'InseeSampleIdentifier', '8', 8, '2', 8, '18', 8, 8, 8, 8, 8, 1), + (9, 'InseeSampleIdentifier', '9', 9, '2', 9, '19', 9, 9, 9, 9, 9, 1), + (10, 'InseeSampleIdentifier', '10', 10, '1', 10, '20', 10, 10, 10, 10, 10, 1), + (11, 'InseeSampleIdentifier', '11', 11, '1', 11, '21', 11, 11, 11, 11, 11, 1), + (12, 'InseeSampleIdentifier', '12', 12, '1', 12, '22', 12, 12, 12, 12, 12, 2), + (13, 'InseeSampleIdentifier', '13', 13, '1', 13, '23', 13, 13, 13, 13, 13, 3), + (14, 'InseeSampleIdentifier', '14', 14, '2', 14, '24', 14, 14, 14, 14, 14, 1), + (15, 'InseeSampleIdentifier', '15', 15, '2', 15, '25', 15, 15, 15, 15, 15, 1), + (16, 'InseeSampleIdentifier', '16', 16, '2', 16, '26', 16, 16, 16, 16, 16, 2), + (17, 'InseeSampleIdentifier', '17', 17, '2', 17, '27', 17, 17, 17, 17, 17, 1), + (18, 'InseeSampleIdentifier', '18', 18, '2', 18, '28', 18, 18, 18, 18, 18, 1), + (19, 'InseeSampleIdentifier', '19', 19, '1', 19, '29', 19, 19, 19, 19, 19, 1), + (20, 'InseeSampleIdentifier', '20', 20, '1', 20, '30', 20, 20, 20, 20, 20, 1), + (21, 'InseeSampleIdentifier', '21', 21, '1', 21, '31', 21, 21, 21, 21, 21, 2), + (22, 'InseeSampleIdentifier', '22', 22, '1', 22, '32', 22, 22, 22, 22, 22, 3), + (23, 'InseeSampleIdentifier', '23', 23, '1', 23, '33', 23, 23, 23, 23, 23, 1), + (24, 'InseeSampleIdentifier', '24', 24, '1', 24, '34', 24, 24, 24, 24, 24, 1), + (25, 'InseeSampleIdentifier', '25', 25, '1', 25, '35', 25, 25, 25, 25, 25, 2), + (26, 'InseeSampleIdentifier', '26', 26, '1', 26, '36', 26, 26, 26, 26, 26, 1), + (27, 'InseeSampleIdentifier', '27', 27, '1', 27, '37', 27, 27, 27, 27, 27, 1), + (28, 'InseeSampleIdentifier', '28', 28, '1', 28, '38', 28, 28, 28, 28, 28, 1), + (29, 'InseeSampleIdentifier', '29', 29, '1', 29, '39', 29, 29, 29, 29, 29, 1), + (30, 'InseeSampleIdentifier', '30', 30, '1', 30, '40', 30, 30, 30, 30, 30, 2), + (31, 'InseeSampleIdentifier', '31', 31, '1', 31, '41', 31, 31, 31, 31, 31, 3), + (32, 'InseeSampleIdentifier', '32', 32, '1', 32, '42', 32, 32, 32, 32, 32, 1), + (33, 'InseeSampleIdentifier', '33', 33, '1', 33, '43', 33, 33, 33, 33, 33, 1), + (34, 'InseeSampleIdentifier', '34', 34, '1', 34, '44', 34, 34, 34, 34, 34, 2), + (35, 'InseeSampleIdentifier', '35', 35, '1', 35, '45', 35, 35, 35, 35, 35, 1), + (36, 'InseeSampleIdentifier', '36', 36, '1', 36, '46', 36, 36, 36, 36, 36, 1), + (37, 'InseeSampleIdentifier', '37', 37, '1', 37, '47', 37, 37, 37, 37, 37, 1), + (38, 'InseeSampleIdentifier', '38', 38, '1', 38, '48', 38, 38, 38, 38, 38, 1), + (39, 'InseeSampleIdentifier', '39', 39, '1', 39, '49', 39, 39, 39, 39, 39, 1), + (40, 'InseeSampleIdentifier', '40', 40, '1', 40, '50', 40, 40, 40, 40, 40, 1), + (41, 'InseeSampleIdentifier', '41', 41, '1', 41, '51', 41, 41, 41, 41, 41, 1), + (42, 'InseeSampleIdentifier', '42', 42, '1', 42, '52', 42, 42, 42, 42, 42, 1), + (43, 'InseeSampleIdentifier', '43', 43, '1', 43, '53', 43, 43, 43, 43, 43, 1), + (44, 'InseeSampleIdentifier', '44', 44, '1', 44, '54', 44, 44, 44, 44, 44, 1), + (45, 'InseeSampleIdentifier', '45', 45, '1', 45, '55', 45, 45, 45, 45, 45, 1), + (46, 'InseeSampleIdentifier', '46', 46, '1', 46, '56', 46, 46, 46, 46, 46, 1), + (47, 'InseeSampleIdentifier', '47', 47, '1', 47, '57', 47, 47, 47, 47, 47, 1), + (48, 'InseeSampleIdentifier', '48', 48, '1', 48, '58', 48, 48, 48, 48, 48, 1), + (49, 'InseeSampleIdentifier', '49', 49, '1', 49, '59', 49, 49, 49, 49, 49, 1), + (50, 'InseeSampleIdentifier', '50', 50, '1', 50, '60', 50, 50, 50, 50, 50, 1), + (51, 'InseeSampleIdentifier', '51', 51, '1', 51, '61', 51, 51, 51, 51, 51, 1), + (52, 'InseeSampleIdentifier', '52', 52, '1', 52, '62', 52, 52, 52, 52, 52, 1), + (53, 'InseeSampleIdentifier', '53', 53, '1', 53, '63', 53, 53, 53, 53, 53, 1); INSERT INTO public.USER (id, first_name, last_name, organization_unit_id) VALUES - ('ABC', 'Melinda', 'Webb', 'OU-NORTH'), - ('DEF', 'Everett', 'Juste', 'OU-NORTH'), - ('GHI', 'Elsie', 'Clarke', 'OU-SOUTH'), - ('JKL', 'Julius', 'Howell', 'OU-NATIONAL'), - ('MNO', 'Ted', 'Kannt', 'OU-WEST'), - ('GUEST', 'firstname', 'lastname', 'OU-NATIONAL'); - -INSERT INTO public.campaign (id, label, email, identification_configuration, contact_attempt_configuration, contact_outcome_configuration) VALUES - ('SIMPSONS2020X00', 'Survey on the Simpsons tv show 2020', 'first.email@test.com', 'IASCO', 'F2F', 'F2F'), - ('VQS2021X00', 'Everyday life and health survey 2021', 'second.email@test.com', 'IASCO', 'TEL', 'TEL'), - ('ZCLOSEDX00', 'Everyday life and health survey 2021', 'third.email@test.com', 'IASCO', 'F2F', 'F2F'), - ('XCLOSEDX00', 'Everyday life and health survey 2021', 'fourth.email@test.com', 'IASCO', 'TEL', 'TEL'); + ('GESTIO1', 'Gertrude', 'Gestionnaire1', 'OU-NATIONAL'), + ('GESTIO2', 'Gontrand', 'Gestionnaire2', 'OU-NORTH'), + ('GESTIO3', 'Gerard', 'Gestionnaire3', 'OU-SOUTH'), + ('GESTIO4', 'Gustave', 'Gestionnaire4', 'OU-WEST'); + +INSERT INTO public.campaign (id, label, email, identification_configuration, contact_attempt_configuration, contact_outcome_configuration, sensitivity) VALUES + ('SIMPSONS2020X00', 'Survey on the Simpsons tv show 2020', 'first.email@test.com', 'IASCO', 'F2F', 'F2F', false), + ('VQS2021X00', 'Everyday life and health survey 2021', 'second.email@test.com', 'IASCO', 'TEL', 'TEL', false), + ('ZCLOSEDX00', 'Everyday life and health survey 2021', 'third.email@test.com', 'IASCO', 'F2F', 'F2F', false), + ('XCLOSEDX00', 'Everyday life and health survey 2021', 'fourth.email@test.com', 'IASCO', 'TEL', 'TEL', false), + ('AQV2022X00', 'Campagne qualité volaille en 2022', 'second.email@test.com', 'IASCO', 'F2F', 'F2F', false), + ('AQV2023X00', 'Campagne qualité volaille en 2023', 'second.email@test.com', 'IASCO', 'F2F', 'F2F', true), + ('AQV2024X00', 'Campagne qualité volaille en 2024', 'second.email@test.com', 'IASCO', 'F2F', 'F2F', false), + ('INDTEL2025X00', 'INDTEL campaign', 'third.email@test.com', 'INDTEL', 'TEL', 'TEL', false), + ('IASCO2025X00', 'IASCO campaign', 'third.email@test.com', 'IASCO', 'F2F', 'F2F', false), + ('NOIDENT2025X00', 'NOIDENT campaign', 'third.email@test.com', 'NOIDENT', NULL, NULL, false), + ('HOUSEF2F2025X00', 'HOUSEF2F campaign', 'third.email@test.com', 'HOUSEF2F', 'F2F', 'F2F', false), + ('HOUSETEL2025X00', 'HOUSETEL campaign', 'third.email@test.com', 'HOUSETEL', 'TEL', 'TEL', false), + ('HOUSETELWSR2025X00', 'HOUSETELWSR campaign', 'third.email@test.com', 'HOUSETELWSR', 'TEL', 'TEL', false), + ('SRCVREINT2025X00', 'SRCVREINT campaign', 'third.email@test.com', 'SRCVREINT', NULL, NULL, false), + ('INDTELNOR2025X00', 'INDTELNOR campaign', 'third.email@test.com', 'INDTELNOR', 'TEL', 'TEL', false), + ('INDF2F2025X00', 'INDF2F campaign', 'third.email@test.com', 'INDF2F', 'F2F', 'F2F', false), + ('INDF2FNOR2025X00', 'INDF2F campaign', 'third.email@test.com', 'INDF2FNOR', 'F2F', 'F2F', false); INSERT INTO public.preference (id_user, id_campaign) VALUES - ('GHI', 'SIMPSONS2020X00'), - ('JKL', 'SIMPSONS2020X00'), - ('JKL', 'VQS2021X00'), - ('GUEST', 'SIMPSONS2020X00'), - ('GUEST', 'VQS2021X00'), - ('GUEST', 'ZCLOSEDX00'), - ('GUEST', 'XCLOSEDX00'); + ('GESTIO1', 'SIMPSONS2020X00'), + ('GESTIO1', 'AQV2023X00'), + ('GESTIO2', 'VQS2021X00'), + ('GESTIO3', 'ZCLOSEDX00'), + ('GESTIO4', 'XCLOSEDX00'); INSERT INTO visibility ( @@ -90,186 +197,727 @@ INSERT INTO visibility ( tel ) VALUES ('OU-NORTH', 'SIMPSONS2020X00', - EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, - EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, - true, 'north-simpsons@nooneknows.fr', '0321234567'), + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'north-simpsons@nooneknows.fr', '0321234567'), + ('OU-NORTH', 'VQS2021X00', - EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, - EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, - true, 'north-vqs@nooneknows.fr', ''), + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'north-vqs@nooneknows.fr', ''), ('OU-SOUTH', 'VQS2021X00', - EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, - EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, - true, 'south-vqs@nooneknows.fr', ''), + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'south-vqs@nooneknows.fr', ''), ('OU-SOUTH', 'SIMPSONS2020X00', - EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, - EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, - true, 'south-simpsons@nooneknows.fr', '0123456789'), + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'south-simpsons@nooneknows.fr', '0123456789'), ('OU-SOUTH', 'ZCLOSEDX00', - EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '5 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000, - true, 'south-zclosed@nooneknows.fr', ''), + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '5 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000, + true, 'south-zclosed@nooneknows.fr', ''), ('OU-WEST', 'ZCLOSEDX00', - EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '5 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000, - true, 'west-zclosed@nooneknows.fr', ''), + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '5 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000, + true, 'west-zclosed@nooneknows.fr', ''), ('OU-SOUTH', 'XCLOSEDX00', - EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '5 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, - EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000, - true, 'south-xclosed@nooneknows.fr', ''); - -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '11', TRUE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Ted Farmer' AND s.bs='11'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '12', TRUE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cecilia Ortega' AND s.bs='12'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '13', FALSE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Claude Watkins' AND s.bs='13'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '14', FALSE, a.id, 'SIMPSONS2020X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Veronica Gill' AND s.bs='14'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '20', FALSE, a.id, 'VQS2021X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Christine Aguilar' AND s.bs='20'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '21', FALSE, a.id, 'VQS2021X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Louise Walker' AND s.bs='21'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '22', FALSE, a.id, 'VQS2021X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Anthony Bennett' AND s.bs='22'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '23', FALSE, a.id, 'VQS2021X00', 'GUEST', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Christopher Lewis' AND s.bs='23'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '24', TRUE, a.id, 'SIMPSONS2020X00', NULL, s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Laurent Neville' AND s.bs='24'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '25', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Alain Thé' AND s.bs='25'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '26', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Brie Savarin' AND s.bs='26'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '27', FALSE, a.id, 'SIMPSONS2020X00', 'INTW2', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cécile Houte' AND s.bs='27'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '28', FALSE, a.id, 'SIMPSONS2020X00', 'INTW3', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Dan Tifrice' AND s.bs='28'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '29', FALSE, a.id, 'VQS2021X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Émile Pates' AND s.bs='29'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '30', FALSE, a.id, 'VQS2021X00', 'INTW2', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='François Appétit' AND s.bs='30'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '31', FALSE, a.id, 'VQS2021X00', 'INTW4', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Gérard Dine' AND s.bs='31'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '32', FALSE, a.id, 'VQS2021X00', 'INTW4', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Hélène Gume' AND s.bs='32'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '33', TRUE, a.id, 'SIMPSONS2020X00', NULL, s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Jean Fromage' AND s.bs='33'; - -INSERT INTO public.person (email, favorite_email, first_name, last_name, birthdate, title, privileged, survey_unit_id) VALUES - ('test@test.com',TRUE, 'Ted', 'Farmer', 11111111, 0, TRUE, '11'), - ('test@test.com', TRUE,'Cecilia', 'Ortega', 11111111, 1, TRUE, '12'), - ('test@test.com', TRUE,'Claude', 'Watkins', 11111111, 0, TRUE, '13'), - ('test@test.com', TRUE,'Veronica', 'Baker', 11111111, 1, TRUE, '14'), - ('test@test.com', TRUE,'Christine', 'Aguilar', 11111111, 1, FALSE, '11'), - ('test@test.com', TRUE,'Louise', 'Walker', 11111111, 1, FALSE, '11'), - ('test@test.com', TRUE,'Anthony', 'Bennett', 11111111, 0, FALSE, '12'), - ('test@test.com', TRUE,'Christopher', 'Lewis', 11111111, 0, FALSE, '14'), - ('test@test.com', TRUE,'Harriette', 'Raymond', 11111111, 0, TRUE, '20'), - ('test@test.com', TRUE,'Aimée', 'Lamothe', 11111111, 0, TRUE, '21'), - ('test@test.com', TRUE,'Perrin', 'Blanchard', 11111111, 0, TRUE, '22'), - ('test@test.com', TRUE,'Artus', 'Arnoux', 11111111, 0, TRUE, '23'), - ('test@test.com', TRUE,'Laurent', 'Neville', 11111111, 0, TRUE, '24'), - ('test@test.com', TRUE, 'Harry', 'Cover', 11111111, 1, FALSE, '25'), - ('test@test.com', TRUE, 'Ella', 'Gance', 11111111, 0, FALSE, '25'), - ('test@test.com', TRUE, 'Jean', 'Neige', 11111111, 0, FALSE, '26'), - ('test@test.com', TRUE, 'Phil', 'Harmonie', 11111111, 0, FALSE, '28'), - ('test@test.com', TRUE, 'Alain', 'Thé', 11111111, 0, TRUE, '25'), - ('test@test.com', TRUE, 'Brie', 'Savarin', 11111111, 1, TRUE, '26'), - ('test@test.com', TRUE, 'Cécile', 'Houte', 11111111, 0, TRUE, '27'), - ('test@test.com', TRUE, 'Dan', 'Tifrice', 11111111, 1, TRUE, '28'), - ('test@test.com', TRUE, 'Émile', 'Pates', 11111111, 1, TRUE, '29'), - ('test@test.com', TRUE, 'François', 'Appétit', 11111111, 1, TRUE, '30'), - ('test@test.com', TRUE, 'Gérard', 'Dine', 11111111, 0, TRUE, '31'), - ('test@test.com', TRUE, 'Hélène', 'Gume', 11111111, 0, TRUE, '32'), - ('test@test.com', TRUE, 'Jean', 'Fromage', 11111111, 0, TRUE, '33'); - - - -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Ted' and p.last_name='Farmer' and p.survey_unit_id='11'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT FALSE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Ted' and p.last_name='Farmer' and p.survey_unit_id='11'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Cecilia' and p.last_name='Ortega' and p.survey_unit_id='12'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Claude' and p.last_name='Watkins' and p.survey_unit_id='13'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Veronica' and p.last_name='Baker' and p.survey_unit_id='14'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Christine' and p.last_name='Aguilar' and p.survey_unit_id='11'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Louise' and p.last_name='Walker' and p.survey_unit_id='11'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Anthony' and p.last_name='Bennett' and p.survey_unit_id='12'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Christopher' and p.last_name='Lewis' and p.survey_unit_id='14'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Harriette' and p.last_name='Raymond' and p.survey_unit_id='20'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Aimée' and p.last_name='Lamothe' and p.survey_unit_id='21'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Perrin' and p.last_name='Blanchard' and p.survey_unit_id='22'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Artus' and p.last_name='Arnoux' and p.survey_unit_id='23'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Laurent' and p.last_name='Neville' and p.survey_unit_id='24'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Harry' and p.last_name='Cover' and p.survey_unit_id='25'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT FALSE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Ella' and p.last_name='Gance' and p.survey_unit_id='25'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Jean' and p.last_name='Neige' and p.survey_unit_id='26'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Phil' and p.last_name='Harmonie' and p.survey_unit_id='28'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Alain' and p.last_name='Thé' and p.survey_unit_id='25'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Brie' and p.last_name='Savarin' and p.survey_unit_id='26'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Cécile' and p.last_name='Houte' and p.survey_unit_id='27'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Dan' and p.last_name='Tifrice' and p.survey_unit_id='28'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Émile' and p.last_name='Pates' and p.survey_unit_id='29'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='François' and p.last_name='Appétit' and p.survey_unit_id='30'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Gérard' and p.last_name='Dine' and p.survey_unit_id='31'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Hélène' and p.last_name='Gume' and p.survey_unit_id='32'; -INSERT INTO public.phone_number (favorite, number, source, person_id) SELECT TRUE,'+33677542802', 0, p.id FROM person p WHERE p.first_name='Jean' and p.last_name='Fromage' and p.survey_unit_id='33'; - -INSERT INTO public.state (date, type, survey_unit_id) VALUES - (111112111,'VIN', '11'), - (110111111,'NNS', '11'), - (111111111,'TBR', '12'), - (111111111,'TBR', '13'), - (111111111,'TBR', '14'), - (101111111,'TBR', '11'), - (101111111,'TBR', '24'), - (1590504478334, 'VIC', '20'), - (1590504478334, 'VIC', '21'), - (1590504478334, 'FIN', '22'), - (1590504478334, 'VIC', '23'), - (111112111,'VIN', '25'), - (110111111,'NNS', '25'), - (111111111,'TBR', '26'), - (111111111,'TBR', '27'), - (111111111,'TBR', '28'), - (101111111,'TBR', '25'), - (101111111,'TBR', '33'), - (1590504478334, 'VIC', '29'), - (1590504478334, 'VIC', '30'), - (1590504478334, 'FIN', '31'), - (1590504478334, 'VIC', '32'); - -INSERT INTO public.contact_outcome (date, type, survey_unit_id) VALUES - (1590504478334, 'DUK', '24'), - (1590504478334, 'DUK', '33'); - -INSERT INTO public.comment (type, value, survey_unit_id) VALUES - ('INTERVIEWER', 'un commentaire', '13'), - ('INTERVIEWER', 'un commentaire', '27'); - -INSERT INTO closing_cause (date, type, survey_unit_id) VALUES - (EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, 'NPI', '11'), - (EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, 'NPI', '25'); - - -INSERT INTO public.identification (survey_unit_id, identification,access,situation,category,occupant) VALUES - ('11', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), - ('21', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), - ('25', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), - ('30', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'); + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '5 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '6 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '7 days') * 1000, + true, 'south-xclosed@nooneknows.fr', ''), + + ('OU-NORTH', 'AQV2022X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'aqv2022@nooneknows.fr', '0321234567'), + + ('OU-NORTH', 'AQV2023X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'aqv2023@nooneknows.fr', '0321234567'), + + ('OU-NORTH', 'AQV2024X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'aqv2024@nooneknows.fr', '0321234567'), + + ('OU-NORTH', 'INDF2F2025X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'indf2f@nooneknows.fr', '0321234567'), + + ('OU-NORTH', 'INDF2FNOR2025X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'indf2fnor@nooneknows.fr', '0321234567'), + + ('OU-NORTH', 'INDTELNOR2025X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'indtelnor@nooneknows.fr', '0321234567'), + + ('OU-NORTH', 'SRCVREINT2025X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'srcvreint@nooneknows.fr', '0321234567'), + + ('OU-NORTH', 'HOUSETELWSR2025X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'housetelwsr@nooneknows.fr', '0321234567'), + + ('OU-NORTH', 'HOUSETEL2025X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'housetel@nooneknows.fr', '0321234567'), + + ('OU-NORTH', 'HOUSEF2F2025X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'housef2fs@nooneknows.fr', '0321234567'), + + ('OU-NORTH', 'NOIDENT2025X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'noident@nooneknows.fr', '0321234567'), + + ('OU-NORTH', 'IASCO2025X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'iasco@nooneknows.fr', '0321234567'), + + ('OU-NORTH', 'INDTEL2025X00', + EXTRACT(EPOCH FROM NOW() + INTERVAL '1 month') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '1 day') * 1000, + EXTRACT(EPOCH FROM NOW() + INTERVAL '2 months') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '2 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, + EXTRACT(EPOCH FROM NOW() - INTERVAL '4 days') * 1000, + true, 'indtel@nooneknows.fr', '0321234567'); + +INSERT INTO public.survey_unit (id, display_name, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) VALUES + ('11', 'business-id-11', TRUE, 1, 'SIMPSONS2020X00', 'INTERV5', 1, 'OU-NORTH'), + ('12', 'business-id-12', TRUE, 2, 'SIMPSONS2020X00', 'INTERV5', 2, 'OU-NORTH'), + ('13', 'business-id-13', FALSE, 3, 'SIMPSONS2020X00', 'INTERV5', 3, 'OU-NORTH'), + ('14', 'business-id-14', FALSE, 4, 'SIMPSONS2020X00', 'INTERV5', 4, 'OU-NORTH'), + ('20', 'business-id-20', FALSE, 5, 'VQS2021X00', 'INTERV5', 5, 'OU-NORTH'), + ('21', 'business-id-21', FALSE, 6, 'VQS2021X00', 'INTERV5', 6, 'OU-NORTH'), + ('22', 'business-id-22', FALSE, 7, 'VQS2021X00', 'INTERV5', 7, 'OU-NORTH'), + ('23', 'business-id-23', FALSE, 8, 'VQS2021X00', 'INTERV5', 8, 'OU-NORTH'), + ('PROTO01', 'business-id-proto01', TRUE, 9, 'AQV2023X00', 'INTERV5', 9, 'OU-NORTH'), + ('PROTO02', 'business-id-proto02', TRUE, 10, 'AQV2023X00', 'INTERV5', 10, 'OU-NORTH'), + ('PROTO03', 'business-id-proto03', FALSE, 11, 'AQV2023X00', 'INTERV5', 11, 'OU-NORTH'), + ('PROTO04', 'business-id-proto04', FALSE, 12, 'AQV2023X00', 'INTERV5', 12, 'OU-NORTH'), + ('PROTO05', 'business-id-proto05', FALSE, 13, 'AQV2023X00', 'INTERV5', 13, 'OU-NORTH'), + ('PROTO06', 'business-id-proto06', FALSE, 14, 'AQV2023X00', 'INTERV5', 14, 'OU-NORTH'), + ('PROTO07', 'business-id-proto07', FALSE, 15, 'AQV2023X00', 'INTERV5', 15, 'OU-NORTH'), + ('PROTO08', 'business-id-proto08', FALSE, 16, 'AQV2023X00', 'INTERV5', 16, 'OU-NORTH'), + ('PROTO09', 'business-id-proto09', TRUE, 17, 'AQV2023X00', NULL, 17, 'OU-NORTH'), + ('PROTO10', 'business-id-proto10', TRUE, 18, 'AQV2023X00', 'INTERV1', 18, 'OU-NORTH'), + ('PROTO11', 'business-id-proto11', TRUE, 19, 'AQV2023X00', 'INTERV1', 19, 'OU-NORTH'), + ('PROTO12', 'business-id-proto12', FALSE, 20, 'AQV2023X00', 'INTERV2', 20, 'OU-NORTH'), + ('PROTO13', 'business-id-proto13', FALSE, 21, 'AQV2023X00', 'INTERV3', 21, 'OU-NORTH'), + ('PROTO14', 'business-id-proto14', FALSE, 22, 'AQV2023X00', 'INTERV1', 22, 'OU-NORTH'), + ('PROTO15', 'business-id-proto15', FALSE, 23, 'AQV2023X00', 'INTERV2', 23, 'OU-NORTH'), + ('PROTO16', 'business-id-proto16', FALSE, 24, 'AQV2023X00', 'INTERV4', 24, 'OU-NORTH'), + ('PROTO17', 'business-id-proto17', FALSE, 25, 'AQV2023X00', 'INTERV4', 25, 'OU-NORTH'), + ('PROTO18', 'business-id-proto18', TRUE, 26, 'AQV2023X00', NULL, 26, 'OU-NORTH'), + ('PROTO19', 'business-id-proto19', TRUE, 27, 'AQV2023X00', NULL, 27, 'OU-NORTH'), + ('PROTO20', 'business-id-proto20', TRUE, 28, 'AQV2023X00', NULL, 28, 'OU-NORTH'), + ('PROTO21', 'business-id-proto21', TRUE, 29, 'AQV2024X00', NULL, 29, 'OU-NORTH'), + ('PROTO22', 'business-id-proto22', TRUE, 30, 'AQV2024X00', 'INTERV5', 30, 'OU-NORTH'), + ('PROTO23', 'business-id-proto23', TRUE, 31, 'AQV2024X00', 'INTERV5', 31, 'OU-NORTH'), + ('PROTO24', 'business-id-proto24', FALSE, 32, 'AQV2024X00', 'INTERV5', 32, 'OU-NORTH'), + ('PROTO25', 'business-id-proto25', FALSE, 33, 'AQV2024X00', 'INTERV5', 33, 'OU-NORTH'), + ('PROTO26', 'business-id-proto26', FALSE, 34, 'AQV2024X00', 'INTERV5', 34, 'OU-NORTH'), + ('PROTO27', 'business-id-proto27', FALSE, 35, 'AQV2024X00', 'INTERV5', 35, 'OU-NORTH'), + ('PROTO28', 'business-id-proto28', FALSE, 36, 'AQV2024X00', 'INTERV5', 36, 'OU-NORTH'), + ('PROTO29', 'business-id-proto29', FALSE, 37, 'AQV2024X00', 'INTERV5', 37, 'OU-NORTH'), + ('PROTO30', 'business-id-proto30', TRUE, 38, 'AQV2024X00', 'INTERV5', 38, 'OU-NORTH'), + ('SABIANE01', 'business-id-sabiane01', TRUE, 39, 'INDTEL2025X00', 'INTERV1', 39, 'OU-NORTH'), + ('SABIANE02', 'business-id-sabiane02', TRUE, 40, 'INDTEL2025X00', 'INTERV1', 40, 'OU-NORTH'), + ('SABIANE03', 'business-id-sabiane03', TRUE, 41, 'IASCO2025X00', 'INTERV1', 41, 'OU-NORTH'), + ('SABIANE04', 'business-id-sabiane04', TRUE, 42, 'IASCO2025X00', 'INTERV1', 42, 'OU-NORTH'), + ('SABIANE05', 'business-id-sabiane05', TRUE, 43, 'NOIDENT2025X00', 'INTERV1', 43, 'OU-NORTH'), + ('SABIANE06', 'business-id-sabiane06', TRUE, 44, 'HOUSEF2F2025X00', 'INTERV1', 44, 'OU-NORTH'), + ('SABIANE07', 'business-id-sabiane07', TRUE, 45, 'HOUSETEL2025X00', 'INTERV1', 45, 'OU-NORTH'), + ('SABIANE08', 'business-id-sabiane08', TRUE, 46, 'HOUSETELWSR2025X00', 'INTERV1', 46, 'OU-NORTH'), + ('SABIANE09', 'business-id-sabiane09', TRUE, 47, 'SRCVREINT2025X00', 'INTERV1', 47, 'OU-NORTH'), + ('SABIANE10', 'business-id-sabiane10', TRUE, 48, 'INDTELNOR2025X00', 'INTERV1', 48, 'OU-NORTH'), + ('SABIANE11', 'business-id-sabiane11', TRUE, 49, 'INDF2F2025X00', 'INTERV1', 49, 'OU-NORTH'), + ('SABIANE12', 'business-id-sabiane12', TRUE, 50, 'INDF2F2025X00', 'INTERV1', 50, 'OU-NORTH'), + ('SABIANE13', 'business-id-sabiane13', TRUE, 51, 'HOUSEF2F2025X00', 'INTERV1', 51, 'OU-NORTH'), + ('SABIANE14', 'business-id-sabiane14', TRUE, 52, 'HOUSETEL2025X00', 'INTERV1', 52, 'OU-NORTH'), + ('SABIANE15', 'business-id-sabiane15', TRUE, 53, 'HOUSETELWSR2025X00', 'INTERV1', 53, 'OU-NORTH'); + +INSERT INTO public.person (id, email, favorite_email, first_name, last_name, birthdate, title, privileged, survey_unit_id) VALUES + (1, 'test@test.com', TRUE, 'Ted', 'Farmer', 315532800000, 0, TRUE, '11'), + (2, 'test@test.com', TRUE, 'Cecilia', 'Ortega', 325242830770, 1, TRUE, '12'), + (3, 'test@test.com', TRUE, 'Claude', 'Watkins', 334952861540, 0, TRUE, '13'), + (4, 'test@test.com', TRUE, 'Veronica', 'Baker', 344662892310, 1, TRUE, '14'), + (5, 'test@test.com', TRUE, 'Christine', 'Aguilar', 354372923080, 1, FALSE, '11'), + (6, 'test@test.com', TRUE, 'Louise', 'Walker', 364082953850, 1, FALSE, '11'), + (7, 'test@test.com', TRUE, 'Anthony', 'Bennett', 373792984620, 0, FALSE, '12'), + (8, 'test@test.com', TRUE, 'Christopher', 'Lewis', 383503015390, 0, FALSE, '14'), + (9, 'test@test.com', TRUE, 'Harriette', 'Raymond', 393213046160, 1, TRUE, '20'), + (10, 'test@test.com', TRUE, 'Aimée', 'Lamothe', 402923076930, 0, TRUE, '21'), + (11, 'test@test.com', TRUE, 'Perrin', 'Blanchard', 412633107700, 0, TRUE, '22'), + (12, 'test@test.com', TRUE, 'Artus', 'Arnoux', 422343138470, 0, TRUE, '23'), + (13, 'test@test.com', TRUE, 'Isabelle', 'Moreau', 567993600020, 1, TRUE, 'PROTO01'), + (14, 'test@test.com', TRUE, 'Julien', 'Dupont', 577703630790, 0, TRUE, 'PROTO02'), + (15, 'test@test.com', TRUE, 'Sophie', 'Martin', 587413661560, 1, FALSE, 'PROTO03'), + (16, 'test@test.com', TRUE, 'Marc', 'Lefevre', 597123692330, 0, TRUE, 'PROTO04'), + (17, 'test@test.com', TRUE, 'Nathalie', 'Bernard', 606833723100, 1, FALSE, 'PROTO05'), + (18, 'test@test.com', TRUE, 'Olivier', 'Girard', 616543753870, 0, FALSE, 'PROTO06'), + (19, 'test@test.com', TRUE, 'Camille', 'Renaud', 626253784640, 1, TRUE, 'PROTO07'), + (20, 'test@test.com', TRUE, 'Pauline', 'Durand', 635963815410, 1, TRUE, 'PROTO08'), + (21, 'test@test.com', TRUE, 'Antoine', 'Morel', 645673846180, 0, TRUE, 'PROTO09'), + (22, 'test@test.com', TRUE, 'Marine', 'Lambert', 655383876950, 1, TRUE, 'PROTO10'), + (23, 'test@test.com', TRUE, 'Alexandre', 'Faure', 665093907720, 0, TRUE, 'PROTO11'), + (24, 'test@test.com', TRUE, 'Elodie', 'Renault', 674803938490, 1, TRUE, 'PROTO12'), + (25, 'test@test.com', TRUE, 'Maxime', 'Petit', 684513969260, 0, TRUE, 'PROTO13'), + (26, 'test@test.com', TRUE, 'Amélie', 'Gautier', 694224000030, 1, TRUE, 'PROTO14'), + (27, 'test@test.com', TRUE, 'Damien', 'Roux', 703934030800, 0, TRUE, 'PROTO15'), + (28, 'test@test.com', TRUE, 'Claire', 'Dubois', 713644061570, 1, TRUE, 'PROTO16'), + (29, 'test@test.com', TRUE, 'Hugo', 'Simon', 723354092340, 0, TRUE, 'PROTO17'), + (30, 'test@test.com', TRUE, 'Chloé', 'Lemoine', 733064123110, 1, TRUE, 'PROTO18'), + (31, 'test@test.com', TRUE, 'Romain', 'Bertrand', 742774153880, 0, TRUE, 'PROTO19'), + (32, 'test@test.com', TRUE, 'Alice', 'Renault', 752484184650, 1, TRUE, 'PROTO20'), + (33, 'test@test.com', TRUE, 'Guillaume', 'Faure', 762194215420, 0, TRUE, 'PROTO21'), + (34, 'test@test.com', TRUE, 'Laurent', 'Neville', 674803938490, 1, TRUE, 'PROTO22'), + (35, 'test@test.com', TRUE, 'Harry', 'Cover', 684513969260, 0, TRUE, 'PROTO23'), + (36, 'test@test.com', TRUE, 'Ella', 'Gance', 694224000030, 1, TRUE, 'PROTO24'), + (37, 'test@test.com', TRUE, 'Jean', 'Neige', 703934030800, 0, TRUE, 'PROTO25'), + (38, 'test@test.com', TRUE, 'Phil', 'Harmonie', 713644061570, 1, TRUE, 'PROTO26'), + (39, 'test@test.com', TRUE, 'Alain', 'Thé', 723354092340, 0, TRUE, 'PROTO27'), + (40, 'test@test.com', TRUE, 'Brie', 'Savarin', 733064123110, 1, TRUE, 'PROTO28'), + (41, 'test@test.com', TRUE, 'Cécile', 'Houte', 742774153880, 0, TRUE, 'PROTO29'), + (42, 'test@test.com', TRUE, 'Dan', 'Tifrice', 752484184650, 1, TRUE, 'PROTO30'), + (43, 'test@test.com', TRUE, 'Emile', 'Pates', 771904246190, 0, TRUE, 'SABIANE01'), + (44, 'test@test.com', TRUE, 'Marine', 'Lefevre', 781614276960, 0, TRUE, 'SABIANE02'), + (45, 'test@test.com', TRUE, 'Thierry', 'Bernard', 791324307730, 0, TRUE, 'SABIANE03'), + (46, 'test@test.com', TRUE, 'Sylvie', 'Martin', 801034338500, 0, TRUE, 'SABIANE04'), + (47, 'test@test.com', TRUE, 'Laurence', 'Girard', 810744369270, 0, TRUE, 'SABIANE05'), + (48, 'test@test.com', TRUE, 'Dominique', 'Moreau', 820454400040, 0, TRUE, 'SABIANE06'), + (49, 'test@test.com', TRUE, 'Juliette', 'Roussel', 830164430810, 0, TRUE, 'SABIANE07'), + (50, 'test@test.com', TRUE, 'Pascal', 'Dubois', 839874461580, 0, TRUE, 'SABIANE08'), + (51, 'test@test.com', TRUE, 'Amandine', 'Perrin', 849584492350, 0, TRUE, 'SABIANE09'), + (52, 'test@test.com', TRUE, 'Nicolas', 'Lambert', 859294523120, 0, TRUE, 'SABIANE10'), + (53, 'test@test.com', TRUE, 'Bruno', 'Simon', 869004553890, 0, TRUE, 'SABIANE11'), + (54, 'test@test.com', TRUE, 'Véronique', 'Petit', 878714584660, 0, TRUE, 'SABIANE12'), + (55, 'test@test.com', TRUE, 'Philippe', 'Garnier', 888424615430, 0, TRUE, 'SABIANE13'), + (56, 'test@test.com', TRUE, 'Catherine', 'Renault', 898134646200, 0, TRUE, 'SABIANE14'), + (57, 'test@test.com', TRUE, 'Jacques', 'Faure', 907844676970, 0, TRUE, 'SABIANE15'), + (58, 'test@test.com', TRUE, 'Marion', 'Cotille', 917554707740, 1, FALSE, 'PROTO01'), + (59, 'test@test.com', TRUE, 'Arthur', 'Couyer', 927264738510, 1, TRUE, 'PROTO03'), + (60, 'test@test.com', TRUE, 'Kaa', 'Melott', 936974769280, 0, TRUE, 'PROTO05'), + (61, 'test@test.com', TRUE, 'Père', 'Seval', 946684800050, 0, TRUE, 'PROTO06'); + +INSERT INTO public.phone_number (id, favorite, number, source, person_id) VALUES + (1, TRUE, '+33677542802', 0, 1), + (2, FALSE,'+33677542803', 0, 1), + (3, TRUE, '+33677542804', 0, 2), + (4, TRUE, '+33677542805', 0, 3), + (5, TRUE, '+33677542806', 0, 4), + (6, TRUE, '+33677542807', 0, 5), + (7, TRUE, '+33677542808', 0, 6), + (8, TRUE, '+33677542809', 0, 7), + (9, TRUE, '+33677542810', 0, 8), + (10, TRUE, '+33677542811', 0, 9), + (11, TRUE, '+33677542812', 0, 10), + (12, TRUE, '+33677542813', 0, 11), + (13, TRUE, '+33677542814', 0, 12), + (28, TRUE, '+33677542829', 0, 13), + (29, TRUE, '+33677542830', 0, 14), + (30, TRUE, '+33677542831', 0, 15), + (31, TRUE, '+33677542832', 0, 16), + (32, TRUE, '+33677542833', 0, 17), + (33, TRUE, '+33677542834', 0, 18), + (34, TRUE, '+33677542835', 0, 19), + (35, TRUE, '+33677542836', 0, 20), + (36, TRUE, '+33677542837', 0, 21), + (37, TRUE, '+33677542838', 0, 22), + (38, TRUE, '+33677542839', 0, 23), + (39, TRUE, '+33677542840', 0, 24), + (40, TRUE, '+33677542841', 0, 25), + (41, TRUE, '+33677542842', 0, 26), + (42, TRUE, '+33677542843', 0, 27), + (43, TRUE, '+33677542844', 0, 28), + (44, TRUE, '+33677542845', 0, 29), + (45, TRUE, '+33677542846', 0, 30), + (46, TRUE, '+33677542847', 0, 31), + (47, TRUE, '+33677542848', 0, 32), + (48, TRUE, '+33677542849', 0, 33), + (49, TRUE, '+33677542850', 0, 34), + (50, TRUE, '+33677542851', 0, 35), + (51, TRUE, '+33677542852', 0, 36), + (52, TRUE, '+33677542853', 0, 37), + (53, TRUE, '+33677542854', 0, 38), + (54, TRUE, '+33677542855', 0, 39), + (55, TRUE, '+33677542856', 0, 40), + (56, TRUE, '+33677542857', 0, 41), + (57, TRUE, '+33677542858', 0, 42), + (58, TRUE, '+33677542859', 0, 43), + (59, TRUE, '+33677542860', 0, 44), + (60, TRUE, '+33677542861', 0, 45), + (61, TRUE, '+33677542862', 0, 46), + (62, TRUE, '+33677542863', 0, 47), + (63, TRUE, '+33677542864', 0, 48), + (64, TRUE, '+33677542865', 0, 49), + (65, TRUE, '+33677542866', 0, 50), + (66, TRUE, '+33677542867', 0, 51), + (67, TRUE, '+33677542868', 0, 52), + (68, TRUE, '+33677542860', 0, 53), + (69, TRUE, '+33677542861', 0, 54), + (70, TRUE, '+33677542862', 0, 55), + (71, TRUE, '+33677542863', 0, 56), + (72, TRUE, '+33677542864', 0, 57), + (73, TRUE, '+33677542865', 0, 58), + (74, TRUE, '+33677542866', 0, 59), + (75, TRUE, '+33677542866', 0, 60), + (76, TRUE, '+33677542866', 0, 61); + + +INSERT INTO public.comment (id, type, value, survey_unit_id) VALUES + (1, 'INTERVIEWER', 'un commentaire', '13'); + +INSERT INTO closing_cause (id, date, type, survey_unit_id) VALUES + (1, EXTRACT(EPOCH FROM NOW() - INTERVAL '3 days') * 1000, 'NPI', '11'); + + +INSERT INTO public.identification (id, survey_unit_id, identification_type, identification, access, situation, category, occupant) VALUES + (1, '11', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (2, '12', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (3, '13', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (4, '14', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (5, '20', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (6, '21', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (7, '22', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (8, '23', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (9, 'PROTO01', 'HOUSEF2F', NULL, NULL, NULL, NULL, NULL), + (10, 'PROTO02', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (11, 'PROTO03', 'HOUSEF2F', NULL, NULL, NULL, NULL, NULL), + (12, 'PROTO04', 'HOUSEF2F', 'UNIDENTIFIED', NULL, NULL, NULL, NULL), + (13, 'PROTO05', 'HOUSEF2F', 'UNIDENTIFIED', 'ACC', NULL, NULL, NULL), + (14, 'PROTO06', 'HOUSEF2F', 'UNIDENTIFIED', 'ACC', 'ORDINARY', NULL, NULL), + (15, 'PROTO07', 'HOUSEF2F', 'UNIDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', NULL), + (16, 'PROTO08', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (17, 'PROTO09', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (18, 'PROTO10', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (19, 'PROTO11', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (20, 'PROTO12', 'HOUSEF2F', 'UNIDENTIFIED', NULL, NULL, NULL, NULL), + (21, 'PROTO13', 'HOUSEF2F', 'UNIDENTIFIED', 'ACC', NULL, NULL, NULL), + (22, 'PROTO14', 'HOUSEF2F', 'UNIDENTIFIED', 'ACC', 'ORDINARY', NULL, NULL), + (23, 'PROTO15', 'HOUSEF2F', 'UNIDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', NULL), + (24, 'PROTO16', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (25, 'PROTO17', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (26, 'PROTO18', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (27, 'PROTO19', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (28, 'PROTO20', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (29, 'PROTO21', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (30, 'PROTO22', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (31, 'PROTO23', 'HOUSEF2F', NULL, NULL, NULL, NULL, NULL), + (32, 'PROTO24', 'HOUSEF2F', 'UNIDENTIFIED', NULL, NULL, NULL, NULL), + (33, 'PROTO25', 'HOUSEF2F', 'UNIDENTIFIED', 'ACC', NULL, NULL, NULL), + (34, 'PROTO26', 'HOUSEF2F', 'UNIDENTIFIED', 'ACC', 'ORDINARY', NULL, NULL), + (35, 'PROTO27', 'HOUSEF2F', 'UNIDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', NULL), + (36, 'PROTO28', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (37, 'PROTO29', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (38, 'PROTO30', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (39, 'SABIANE01', 'INDTEL', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (40, 'SABIANE02', 'INDTEL', NULL, NULL, NULL, NULL, NULL), + (41, 'SABIANE03', 'INDTEL', NULL, NULL, NULL, NULL, NULL), + (42, 'SABIANE04', 'INDTEL', 'IDENTIFIED', NULL, NULL, NULL, NULL), + (43, 'SABIANE05', 'INDTEL', NULL, NULL, NULL, NULL, NULL), + (44, 'SABIANE06', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', NULL, NULL), + (45, 'SABIANE07', 'HOUSETEL', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', NULL), + (46, 'SABIANE08', 'HOUSETEL', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), + (47, 'SABIANE09', 'SRCVREINT', NULL, NULL, NULL, NULL, NULL), + (48, 'SABIANE10', 'INDTEL', NULL, NULL, NULL, NULL, NULL), + (49, 'SABIANE11', 'INDF2F', 'IDENTIFIED', NULL, NULL, NULL, NULL), + (50, 'SABIANE12', 'INDF2F', 'IDENTIFIED', 'ACC', NULL, NULL, NULL), + (51, 'SABIANE13', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', NULL, NULL), + (52, 'SABIANE14', 'HOUSETEL', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', NULL), + (53, 'SABIANE15', 'HOUSETEL', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'); + + +INSERT INTO public.state (id, date, type, survey_unit_id) VALUES + (1, 1741521660000, 'VIN', '11'), + (2, 1741521720000, 'TBR', '11'), + (3, 1741521780000, 'TBR', '12'), + (4, 1741521840000, 'TBR', '13'), + (5, 1741521900000, 'TBR', '14'), + (6, 1741521960000, 'VIC', '20'), + (7, 1741522020000, 'VIC', '21'), + (8, 1741522080000, 'FIN', '22'), + (9, 1741522140000, 'VIC', '23'), + (10, 1741523100000, 'NVM', 'PROTO01'), + (11, 1741523112000, 'ANV', 'PROTO01'), + (12, 1741523118000, 'VIN', 'PROTO01'), + (13, 1741523124000, 'VIC', 'PROTO01'), + (14, 1741523130000, 'PRC', 'PROTO01'), + (15, 1741523100000, 'NVM', 'PROTO02'), + (16, 1741523112000, 'ANV', 'PROTO02'), + (17, 1741523118000, 'VIN', 'PROTO02'), + (18, 1741523124000, 'VIC', 'PROTO02'), + (19, 1741523130000, 'PRC', 'PROTO02'), + (20, 1741523136000, 'INS', 'PROTO02'), + (21, 1741523142000, 'WFT', 'PROTO02'), + (22, 1741523148000, 'WFS', 'PROTO02'), + (23, 1741523154000, 'FIN', 'PROTO02'), + (24, 1741523160000, 'TBR', 'PROTO02'), + (25, 1741523200000, 'NVM', 'PROTO03'), + (26, 1741523212000, 'ANV', 'PROTO03'), + (27, 1741523218000, 'VIN', 'PROTO03'), + (28, 1741523224000, 'VIC', 'PROTO03'), + (29, 1741523230000, 'PRC', 'PROTO03'), + (30, 1741523236000, 'INS', 'PROTO03'), + (31, 1741523100000, 'NVM', 'PROTO04'), + (32, 1741523112000, 'ANV', 'PROTO04'), + (33, 1741523118000, 'VIN', 'PROTO04'), + (34, 1741523124000, 'VIC', 'PROTO04'), + (35, 1741523130000, 'PRC', 'PROTO04'), + (36, 1741523400000, 'NVM', 'PROTO05'), + (37, 1741523412000, 'ANV', 'PROTO05'), + (38, 1741523418000, 'VIN', 'PROTO05'), + (39, 1741523424000, 'VIC', 'PROTO05'), + (40, 1741523430000, 'PRC', 'PROTO05'), + (41, 1741523436000, 'INS', 'PROTO05'), + (42, 1741523500000, 'NVM', 'PROTO06'), + (43, 1741523512000, 'ANV', 'PROTO06'), + (44, 1741523518000, 'VIN', 'PROTO06'), + (45, 1741523524000, 'VIC', 'PROTO06'), + (46, 1741523530000, 'PRC', 'PROTO06'), + (47, 1741523536000, 'INS', 'PROTO06'), + (48, 1741523542000, 'WFT', 'PROTO06'), + (49, 1741523548000, 'WFS', 'PROTO06'), + (50, 1741523554000, 'FIN', 'PROTO06'), + (51, 1741523560000, 'TBR', 'PROTO06'), + (52, 1741523600000, 'NVM', 'PROTO07'), + (53, 1741523612000, 'ANV', 'PROTO07'), + (54, 1741523618000, 'VIN', 'PROTO07'), + (55, 1741523624000, 'VIC', 'PROTO07'), + (56, 1741523630000, 'PRC', 'PROTO07'), + (57, 1741523636000, 'INS', 'PROTO07'), + (58, 1741523700000, 'NVM', 'PROTO08'), + (59, 1741523712000, 'ANV', 'PROTO08'), + (60, 1741523718000, 'VIN', 'PROTO08'), + (61, 1741523724000, 'VIC', 'PROTO08'), + (62, 1741523730000, 'PRC', 'PROTO08'), + (63, 1741523736000, 'INS', 'PROTO08'), + (64, 1741523742000, 'WFT', 'PROTO08'), + (65, 1741523748000, 'WFS', 'PROTO08'), + (66, 1741523754000, 'FIN', 'PROTO08'), + (67, 1741523760000, 'TBR', 'PROTO08'), + (68, 1741523800000, 'NVM', 'PROTO09'), + (69, 1741523812000, 'ANV', 'PROTO09'), + (70, 1741523818000, 'VIN', 'PROTO09'), + (71, 1741523824000, 'VIC', 'PROTO09'), + (72, 1741523830000, 'PRC', 'PROTO09'), + (73, 1741523836000, 'INS', 'PROTO09'), + (74, 1741523900000, 'NVM', 'PROTO10'), + (75, 1741523912000, 'ANV', 'PROTO10'), + (76, 1741523918000, 'VIN', 'PROTO10'), + (77, 1741523924000, 'VIC', 'PROTO10'), + (78, 1741523930000, 'PRC', 'PROTO10'), + (79, 1741523936000, 'INS', 'PROTO10'), + (80, 1741524000000, 'NVM', 'PROTO11'), + (81, 1741524012000, 'ANV', 'PROTO11'), + (82, 1741524018000, 'VIN', 'PROTO11'), + (83, 1741524024000, 'VIC', 'PROTO11'), + (84, 1741524030000, 'PRC', 'PROTO11'), + (85, 1741524036000, 'INS', 'PROTO11'), + (86, 1741524100000, 'NVM', 'PROTO12'), + (87, 1741524112000, 'ANV', 'PROTO12'), + (88, 1741524118000, 'VIN', 'PROTO12'), + (89, 1741524124000, 'VIC', 'PROTO12'), + (90, 1741524130000, 'PRC', 'PROTO12'), + (91, 1741524136000, 'INS', 'PROTO12'), + (92, 1741524200000, 'NVM', 'PROTO13'), + (93, 1741524212000, 'ANV', 'PROTO13'), + (94, 1741524218000, 'VIN', 'PROTO13'), + (95, 1741524224000, 'VIC', 'PROTO13'), + (96, 1741524230000, 'PRC', 'PROTO13'), + (97, 1741524236000, 'INS', 'PROTO13'), + (98, 1741524242000, 'WFT', 'PROTO13'), + (99, 1741524248000, 'WFS', 'PROTO13'), + (100, 1741524254000, 'FIN', 'PROTO13'), + (101, 1741524300000, 'NVM', 'PROTO14'), + (102, 1741524312000, 'ANV', 'PROTO14'), + (103, 1741524318000, 'VIN', 'PROTO14'), + (104, 1741524324000, 'VIC', 'PROTO14'), + (105, 1741524330000, 'PRC', 'PROTO14'), + (106, 1741524336000, 'INS', 'PROTO14'), + (107, 1741524400000, 'NVM', 'PROTO15'), + (108, 1741524412000, 'ANV', 'PROTO15'), + (109, 1741524418000, 'VIN', 'PROTO15'), + (110, 1741524424000, 'VIC', 'PROTO15'), + (111, 1741524430000, 'PRC', 'PROTO15'), + (112, 1741524436000, 'INS', 'PROTO15'), + (113, 1741524500000, 'NVM', 'PROTO16'), + (114, 1741524512000, 'ANV', 'PROTO16'), + (115, 1741524518000, 'VIN', 'PROTO16'), + (116, 1741524524000, 'VIC', 'PROTO16'), + (117, 1741524530000, 'PRC', 'PROTO16'), + (118, 1741524536000, 'INS', 'PROTO16'), + (119, 1741524542000, 'WFT', 'PROTO16'), + (120, 1741524548000, 'WFS', 'PROTO16'), + (121, 1741524554000, 'FIN', 'PROTO16'), + (122, 1741524560000, 'TBR', 'PROTO16'), + (123, 1741524600000, 'NVM', 'PROTO17'), + (124, 1741524612000, 'ANV', 'PROTO17'), + (125, 1741524618000, 'VIN', 'PROTO17'), + (126, 1741524624000, 'VIC', 'PROTO17'), + (127, 1741524630000, 'PRC', 'PROTO17'), + (128, 1741524636000, 'INS', 'PROTO17'), + (129, 1741524700000, 'NVM', 'PROTO18'), + (130, 1741524712000, 'ANV', 'PROTO18'), + (131, 1741524718000, 'VIN', 'PROTO18'), + (132, 1741524724000, 'VIC', 'PROTO18'), + (133, 1741524730000, 'PRC', 'PROTO18'), + (134, 1741524736000, 'INS', 'PROTO18'), + (135, 1741524800000, 'NVM', 'PROTO19'), + (136, 1741524812000, 'ANV', 'PROTO19'), + (137, 1741524818000, 'VIN', 'PROTO19'), + (138, 1741524824000, 'VIC', 'PROTO19'), + (139, 1741524830000, 'PRC', 'PROTO19'), + (140, 1741524836000, 'INS', 'PROTO19'), + (141, 1741524842000, 'WFT', 'PROTO19'), + (142, 1741524848000, 'WFS', 'PROTO19'), + (143, 1741524854000, 'FIN', 'PROTO19'), + (144, 1741524900000, 'NVM', 'PROTO20'), + (145, 1741524912000, 'ANV', 'PROTO20'), + (146, 1741524918000, 'VIN', 'PROTO20'), + (147, 1741524924000, 'VIC', 'PROTO20'), + (148, 1741524930000, 'PRC', 'PROTO20'), + (149, 1741524936000, 'INS', 'PROTO20'), + (150, 1741525000000, 'NVM', 'PROTO21'), + (151, 1741525012000, 'ANV', 'PROTO21'), + (152, 1741525018000, 'VIN', 'PROTO21'), + (153, 1741525024000, 'VIC', 'PROTO21'), + (154, 1741525030000, 'PRC', 'PROTO21'), + (155, 1741525036000, 'INS', 'PROTO21'), + (231, 1741523100000, 'NVM', 'PROTO22'), + (232, 1741523112000, 'ANV', 'PROTO22'), + (233, 1741523118000, 'VIN', 'PROTO22'), + (234, 1741523124000, 'VIC', 'PROTO22'), + (235, 1741523130000, 'PRC', 'PROTO22'), + (236, 1741523136000, 'INS', 'PROTO22'), + (237, 1741523142000, 'WFT', 'PROTO22'), + (238, 1741523148000, 'WFS', 'PROTO22'), + (239, 1741523154000, 'FIN', 'PROTO22'), + (240, 1741523160000, 'TBR', 'PROTO22'), + (241, 1741523200000, 'NVM', 'PROTO23'), + (242, 1741523212000, 'ANV', 'PROTO23'), + (243, 1741523218000, 'VIN', 'PROTO23'), + (244, 1741523224000, 'VIC', 'PROTO23'), + (245, 1741523230000, 'PRC', 'PROTO23'), + (246, 1741523236000, 'INS', 'PROTO23'), + (247, 1741523100000, 'NVM', 'PROTO24'), + (248, 1741523112000, 'ANV', 'PROTO24'), + (249, 1741523118000, 'VIN', 'PROTO24'), + (250, 1741523124000, 'VIC', 'PROTO24'), + (251, 1741523130000, 'PRC', 'PROTO24'), + (252, 1741523400000, 'NVM', 'PROTO25'), + (253, 1741523412000, 'ANV', 'PROTO25'), + (254, 1741523418000, 'VIN', 'PROTO25'), + (255, 1741523424000, 'VIC', 'PROTO25'), + (256, 1741523430000, 'PRC', 'PROTO25'), + (257, 1741523436000, 'INS', 'PROTO25'), + (258, 1741523500000, 'NVM', 'PROTO26'), + (259, 1741523512000, 'ANV', 'PROTO26'), + (260, 1741523518000, 'VIN', 'PROTO26'), + (261, 1741523524000, 'VIC', 'PROTO26'), + (262, 1741523530000, 'PRC', 'PROTO26'), + (263, 1741523536000, 'INS', 'PROTO26'), + (264, 1741523542000, 'WFT', 'PROTO26'), + (265, 1741523548000, 'WFS', 'PROTO26'), + (266, 1741523554000, 'FIN', 'PROTO26'), + (267, 1741523560000, 'TBR', 'PROTO26'), + (268, 1741523600000, 'NVM', 'PROTO27'), + (269, 1741523612000, 'ANV', 'PROTO27'), + (270, 1741523618000, 'VIN', 'PROTO27'), + (271, 1741523624000, 'VIC', 'PROTO27'), + (272, 1741523630000, 'PRC', 'PROTO27'), + (273, 1741523636000, 'INS', 'PROTO27'), + (274, 1741523700000, 'NVM', 'PROTO28'), + (275, 1741523712000, 'ANV', 'PROTO28'), + (276, 1741523718000, 'VIN', 'PROTO28'), + (277, 1741523724000, 'VIC', 'PROTO28'), + (278, 1741523730000, 'PRC', 'PROTO28'), + (279, 1741523736000, 'INS', 'PROTO28'), + (280, 1741523742000, 'WFT', 'PROTO28'), + (281, 1741523748000, 'WFS', 'PROTO28'), + (282, 1741523754000, 'FIN', 'PROTO28'), + (283, 1741523760000, 'TBR', 'PROTO28'), + (284, 1741523800000, 'NVM', 'PROTO29'), + (285, 1741523812000, 'ANV', 'PROTO29'), + (286, 1741523818000, 'VIN', 'PROTO29'), + (287, 1741523824000, 'VIC', 'PROTO29'), + (288, 1741523830000, 'PRC', 'PROTO29'), + (289, 1741523836000, 'INS', 'PROTO29'), + (290, 1741523900000, 'NVM', 'PROTO30'), + (291, 1741523912000, 'ANV', 'PROTO30'), + (292, 1741523918000, 'VIN', 'PROTO30'), + (293, 1741523924000, 'VIC', 'PROTO30'), + (294, 1741523930000, 'PRC', 'PROTO30'), + (295, 1741523936000, 'INS', 'PROTO30'), + (156, 1741524300000, 'NVM', 'SABIANE01'), + (157, 1741524312000, 'ANV', 'SABIANE01'), + (158, 1741524318000, 'VIN', 'SABIANE01'), + (159, 1741524324000, 'VIC', 'SABIANE01'), + (160, 1741524330000, 'PRC', 'SABIANE01'), + (161, 1741524360000, 'NVM', 'SABIANE02'), + (162, 1741524372000, 'ANV', 'SABIANE02'), + (163, 1741524378000, 'VIN', 'SABIANE02'), + (164, 1741524384000, 'VIC', 'SABIANE02'), + (165, 1741524390000, 'PRC', 'SABIANE02'), + (166, 1741524420000, 'NVM', 'SABIANE03'), + (167, 1741524432000, 'ANV', 'SABIANE03'), + (168, 1741524438000, 'VIN', 'SABIANE03'), + (169, 1741524444000, 'VIC', 'SABIANE03'), + (170, 1741524450000, 'PRC', 'SABIANE03'), + (171, 1741524480000, 'NVM', 'SABIANE04'), + (172, 1741524492000, 'ANV', 'SABIANE04'), + (173, 1741524498000, 'VIN', 'SABIANE04'), + (174, 1741524504000, 'VIC', 'SABIANE04'), + (175, 1741524510000, 'PRC', 'SABIANE04'), + (176, 1741524540000, 'NVM', 'SABIANE05'), + (177, 1741524552000, 'ANV', 'SABIANE05'), + (178, 1741524558000, 'VIN', 'SABIANE05'), + (179, 1741524564000, 'VIC', 'SABIANE05'), + (180, 1741524570000, 'PRC', 'SABIANE05'), + (181, 1741524600000, 'NVM', 'SABIANE06'), + (182, 1741524612000, 'ANV', 'SABIANE06'), + (183, 1741524618000, 'VIN', 'SABIANE06'), + (184, 1741524624000, 'VIC', 'SABIANE06'), + (185, 1741524630000, 'PRC', 'SABIANE06'), + (186, 1741524660000, 'NVM', 'SABIANE07'), + (187, 1741524672000, 'ANV', 'SABIANE07'), + (188, 1741524678000, 'VIN', 'SABIANE07'), + (189, 1741524684000, 'VIC', 'SABIANE07'), + (190, 1741524690000, 'PRC', 'SABIANE07'), + (191, 1741524720000, 'NVM', 'SABIANE08'), + (192, 1741524732000, 'ANV', 'SABIANE08'), + (193, 1741524738000, 'VIN', 'SABIANE08'), + (194, 1741524744000, 'VIC', 'SABIANE08'), + (195, 1741524750000, 'PRC', 'SABIANE08'), + (196, 1741524780000, 'NVM', 'SABIANE09'), + (197, 1741524792000, 'ANV', 'SABIANE09'), + (198, 1741524798000, 'VIN', 'SABIANE09'), + (199, 1741524804000, 'VIC', 'SABIANE09'), + (200, 1741524810000, 'PRC', 'SABIANE09'), + (201, 1741524840000, 'NVM', 'SABIANE10'), + (202, 1741524852000, 'ANV', 'SABIANE10'), + (203, 1741524858000, 'VIN', 'SABIANE10'), + (204, 1741524864000, 'VIC', 'SABIANE10'), + (205, 1741524870000, 'PRC', 'SABIANE10'), + (206, 1741524900000, 'NVM', 'SABIANE11'), + (207, 1741524912000, 'ANV', 'SABIANE11'), + (208, 1741524918000, 'VIN', 'SABIANE11'), + (209, 1741524924000, 'VIC', 'SABIANE11'), + (210, 1741524930000, 'PRC', 'SABIANE11'), + (211, 1741524960000, 'NVM', 'SABIANE12'), + (212, 1741524972000, 'ANV', 'SABIANE12'), + (213, 1741524978000, 'VIN', 'SABIANE12'), + (214, 1741524984000, 'VIC', 'SABIANE12'), + (215, 1741524990000, 'PRC', 'SABIANE12'), + (216, 1741525020000, 'NVM', 'SABIANE13'), + (217, 1741525032000, 'ANV', 'SABIANE13'), + (218, 1741525038000, 'VIN', 'SABIANE13'), + (219, 1741525044000, 'VIC', 'SABIANE13'), + (220, 1741525050000, 'PRC', 'SABIANE13'), + (221, 1741525080000, 'NVM', 'SABIANE14'), + (222, 1741525086000, 'ANV', 'SABIANE14'), + (223, 1741525092000, 'VIN', 'SABIANE14'), + (224, 1741525098000, 'VIC', 'SABIANE14'), + (225, 1741525110000, 'PRC', 'SABIANE14'), + (226, 1741525140000, 'NVM', 'SABIANE15'), + (227, 1741525152000, 'ANV', 'SABIANE15'), + (228, 1741525158000, 'VIN', 'SABIANE15'), + (229, 1741525164000, 'VIC', 'SABIANE15'), + (230, 1741525170000, 'PRC', 'SABIANE15'); INSERT INTO public.communication_template (meshuggah_id, medium, type, campaign_id) VALUES ('mesh1', 'EMAIL', 'REMINDER', 'SIMPSONS2020X00'), @@ -278,11 +926,11 @@ INSERT INTO public.communication_template (meshuggah_id, medium, type, campaign_ ('mesh4', 'LETTER', 'NOTICE', 'VQS2021X00'), ('mesh5', 'EMAIL', 'NOTICE', 'VQS2021X00'); -INSERT INTO public.communication_request (survey_unit_id, emitter, reason, communication_template_id) VALUES - ('11', 'INTERVIEWER', 'REFUSAL', 1), - ('11', 'INTERVIEWER', 'UNREACHABLE', 2), - ('20', 'INTERVIEWER', 'REFUSAL', 3), - ('20', 'INTERVIEWER', 'UNREACHABLE', 4); +INSERT INTO public.communication_request (id, survey_unit_id, emitter, reason, campaign_id, meshuggah_id) VALUES + (1, '11', 'INTERVIEWER', 'REFUSAL', 'SIMPSONS2020X00', 'mesh1'), + (2, '11', 'INTERVIEWER', 'UNREACHABLE', 'SIMPSONS2020X00', 'mesh2'), + (3, '20', 'INTERVIEWER', 'REFUSAL', 'VQS2021X00', 'mesh3'), + (4, '20', 'INTERVIEWER', 'UNREACHABLE', 'VQS2021X00', 'mesh4'); INSERT INTO public.communication_request_status (communication_request_id, status, date) VALUES (1, 'INITIATED', 1721903754305), @@ -291,4 +939,98 @@ INSERT INTO public.communication_request_status (communication_request_id, statu (2, 'INITIATED', 1721903754305), (2, 'READY', 1721903756310), (3, 'INITIATED', 1721903754205), - (4, 'INITIATED', 1721903754205); \ No newline at end of file + (4, 'INITIATED', 1721903754205); + +INSERT INTO public.communication_metadata (survey_unit_id, campaign_id, meshuggah_id, metadata_key, metadata_value) VALUES + ('11','SIMPSONS2020X00','mesh1','recipient_full_name', 'Albert Einstein'), + ('11', 'SIMPSONS2020X00','mesh1','recipient_address', '112 Mercer Street, Princeton, New Jersey'); + +SELECT setval( + pg_get_serial_sequence('public.communication_request_status', 'id'), + COALESCE((SELECT MAX(id) FROM public.communication_request_status), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.communication_request', 'id'), + COALESCE((SELECT MAX(id) FROM public.communication_request), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.communication_metadata', 'id'), + COALESCE((SELECT MAX(id) FROM public.communication_metadata), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.contact_attempt', 'id'), + COALESCE((SELECT MAX(id) FROM public.contact_attempt), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.referent', 'id'), + COALESCE((SELECT MAX(id) FROM public.referent), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.message', 'id'), + COALESCE((SELECT MAX(id) FROM public.message), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.sample_identifier', 'id'), + COALESCE((SELECT MAX(id) FROM public.sample_identifier), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.identification', 'id'), + COALESCE((SELECT MAX(id) FROM public.identification), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.person', 'id'), + COALESCE((SELECT MAX(id) FROM public.person), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.phone_number', 'id'), + COALESCE((SELECT MAX(id) FROM public.phone_number), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.state', 'id'), + COALESCE((SELECT MAX(id) FROM public.state), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.contact_outcome', 'id'), + COALESCE((SELECT MAX(id) FROM public.contact_outcome), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.comment', 'id'), + COALESCE((SELECT MAX(id) FROM public.comment), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.closing_cause', 'id'), + COALESCE((SELECT MAX(id) FROM public.closing_cause), 0) + 1, + false +); + +SELECT setval( + pg_get_serial_sequence('public.address', 'id'), + COALESCE((SELECT MAX(id) FROM public.address), 0) + 1, + false +); \ No newline at end of file diff --git a/src/main/resources/db/dataset/reinit-test-data.sql b/src/main/resources/db/dataset/reinit-test-data.sql index d2a0cdf5..a6cc743e 100644 --- a/src/main/resources/db/dataset/reinit-test-data.sql +++ b/src/main/resources/db/dataset/reinit-test-data.sql @@ -1,35 +1,36 @@ --changeset davdarras:reset-data context:test -SET REFERENTIAL_INTEGRITY FALSE; -TRUNCATE TABLE public.communication_request_status; -TRUNCATE TABLE public.communication_request; -TRUNCATE TABLE public.communication_template; -TRUNCATE TABLE public.campaign_message_recipient; -TRUNCATE TABLE public.contact_attempt; -TRUNCATE TABLE public.message_status; -TRUNCATE TABLE public.oumessage_recipient; -TRUNCATE TABLE public.referent; -TRUNCATE TABLE public.message; -TRUNCATE TABLE public.interviewer; -TRUNCATE TABLE public.sample_identifier; -TRUNCATE TABLE public.user; -TRUNCATE TABLE public.campaign; -TRUNCATE TABLE public.preference; -TRUNCATE TABLE public.visibility; -TRUNCATE TABLE public.survey_unit; -TRUNCATE TABLE public.identification; -TRUNCATE TABLE public.person; -TRUNCATE TABLE public.phone_number; -TRUNCATE TABLE public.state; -TRUNCATE TABLE public.contact_outcome; -TRUNCATE TABLE public.comment; -TRUNCATE TABLE public.closing_cause; -TRUNCATE TABLE public.organization_unit; -TRUNCATE TABLE public.address; +TRUNCATE TABLE + public.communication_request_status, + public.communication_request, + public.communication_template, + public.communication_metadata, + public.contact_attempt, + public.oumessage_recipient, + public.referent, + public.message, + public.campaign_message_recipient, + public.message_status, + public.interviewer, + public.sample_identifier, + public.user, + public.campaign, + public.preference, + public.visibility, + public.survey_unit, + public.identification, + public.person, + public.phone_number, + public.state, + public.contact_outcome, + public.comment, + public.closing_cause, + public.organization_unit, + public.address; ALTER TABLE public.communication_request_status ALTER COLUMN id RESTART WITH 1; ALTER TABLE public.communication_request ALTER COLUMN id RESTART WITH 1; -ALTER TABLE public.communication_template ALTER COLUMN id RESTART WITH 1; +ALTER TABLE public.communication_metadata ALTER COLUMN id RESTART WITH 1; ALTER TABLE public.contact_attempt ALTER COLUMN id RESTART WITH 1; ALTER TABLE public.referent ALTER COLUMN id RESTART WITH 1; ALTER TABLE public.message ALTER COLUMN id RESTART WITH 1; @@ -77,7 +78,8 @@ INSERT INTO public.sample_identifier (dtype, autre, bs, ec, le, nograp, noi, nol ('InseeSampleIdentifier', '21', 21, '2', 21, '21', 21, 21, 21, 21, 21, 1), ('InseeSampleIdentifier', '22', 22, '2', 22, '22', 22, 22, 22, 22, 22, 2), ('InseeSampleIdentifier', '23', 23, '2', 23, '23', 23, 23, 23, 23, 23, 1), - ('InseeSampleIdentifier', '24', 24, '2', 24, '24', 24, 24, 24, 24, 24, 1); + ('InseeSampleIdentifier', '24', 24, '2', 24, '24', 24, 24, 24, 24, 24, 1), + ('InseeSampleIdentifier', '25', 25, '2', 25, '25', 25, 25, 25, 25, 25, 1); INSERT INTO public.USER (id, first_name, last_name, organization_unit_id) VALUES ('ABC', 'Melinda', 'Webb', 'OU-NORTH'), @@ -123,16 +125,16 @@ INSERT INTO visibility ( ('OU-SOUTH', 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true, 'north-vqs@nooneknows.fr', ''), ('OU-WEST' , 'ZCLOSEDX00',1719052554308, 1718966154308, 1719225354308, 1718879754308, 1718789354308, 1718706954308, true, 'north-vqs@nooneknows.fr', ''); -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '11', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Ted Farmer' AND s.bs='11'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '12', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cecilia Ortega' AND s.bs='12'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '25', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-SOUTH' FROM address a, sample_identifier s WHERE a.l1='Mylene Mikoton' AND s.bs='25'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '13', FALSE, a.id, 'SIMPSONS2020X00', 'INTW2', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Claude Watkins' AND s.bs='13'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '14', FALSE, a.id, 'SIMPSONS2020X00', 'INTW3', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Veronica Gill' AND s.bs='14'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '20', FALSE, a.id, 'VQS2021X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Christine Aguilar' AND s.bs='20'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '21', FALSE, a.id, 'VQS2021X00', 'INTW2', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Louise Walker' AND s.bs='21'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '22', FALSE, a.id, 'VQS2021X00', 'INTW4', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Anthony Bennett' AND s.bs='22'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '23', FALSE, a.id, 'VQS2021X00', 'INTW4', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Christopher Lewis' AND s.bs='23'; -INSERT INTO public.survey_unit (id, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '24', TRUE, a.id, 'SIMPSONS2020X00', NULL, s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Laurent Neville' AND s.bs='24'; +INSERT INTO public.survey_unit (id, display_name, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '11', 'business-id-11',TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Ted Farmer' AND s.bs='11'; +INSERT INTO public.survey_unit (id, display_name, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '12', 'business-id-12', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Cecilia Ortega' AND s.bs='12'; +INSERT INTO public.survey_unit (id, display_name, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '25', 'business-id-25', TRUE, a.id, 'SIMPSONS2020X00', 'INTW1', s.id, 'OU-SOUTH' FROM address a, sample_identifier s WHERE a.l1='Mylene Mikoton' AND s.bs='25'; +INSERT INTO public.survey_unit (id, display_name, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '13', 'business-id-13', FALSE, a.id, 'SIMPSONS2020X00', 'INTW2', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Claude Watkins' AND s.bs='13'; +INSERT INTO public.survey_unit (id, display_name, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '14', 'business-id-14', FALSE, a.id, 'SIMPSONS2020X00', 'INTW3', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Veronica Gill' AND s.bs='14'; +INSERT INTO public.survey_unit (id, display_name, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '20', 'business-id-20', FALSE, a.id, 'VQS2021X00', 'INTW1', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Christine Aguilar' AND s.bs='20'; +INSERT INTO public.survey_unit (id, display_name, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '21', 'business-id-21', FALSE, a.id, 'VQS2021X00', 'INTW2', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Louise Walker' AND s.bs='21'; +INSERT INTO public.survey_unit (id, display_name, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '22', 'business-id-22', FALSE, a.id, 'VQS2021X00', 'INTW4', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Anthony Bennett' AND s.bs='22'; +INSERT INTO public.survey_unit (id, display_name, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '23', 'business-id-23', FALSE, a.id, 'VQS2021X00', 'INTW4', s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Christopher Lewis' AND s.bs='23'; +INSERT INTO public.survey_unit (id, display_name, priority, address_id, campaign_id, interviewer_id, sample_identifier_id, organization_unit_id) SELECT '24', 'business-id-24', TRUE, a.id, 'SIMPSONS2020X00', NULL, s.id, 'OU-NORTH' FROM address a, sample_identifier s WHERE a.l1='Laurent Neville' AND s.bs='24'; INSERT INTO public.person (email, favorite_email, first_name, last_name, birthdate, title, privileged, survey_unit_id) VALUES @@ -192,13 +194,17 @@ INSERT INTO public.referent (campaign_id, first_name, last_name, role, phone_num INSERT INTO public.comment (type, value, survey_unit_id) VALUES ('INTERVIEWER', 'un commentaire', '13'); -INSERT INTO closing_cause (date, type, survey_unit_id) VALUES - (DATEDIFF('SECOND', TIMESTAMP '1970-01-01 00:00:00', DATEADD('DAY', -3, CURRENT_TIMESTAMP)) * 1000, 'NPI', '11'); +INSERT INTO closing_cause ("date", type, survey_unit_id) +VALUES ( + EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - INTERVAL '3 day')) * 1000, + 'NPI', + '11' +); -INSERT INTO public.identification (survey_unit_id, identification,access,situation,category,occupant) VALUES - ('11', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'), - ('21', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED'); +INSERT INTO public.identification (survey_unit_id, identification_type, identification,access,situation,category,occupant,individual_status,interviewer_can_process,number_of_respondents,present_in_previous_home,household_composition,identification_state) VALUES + ('11', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED','SAME_ADDRESS','YES','MANY','AT_LEAST_ONE','SAME_COMPO','FINISHED'), + ('21', 'HOUSEF2F', 'IDENTIFIED', 'ACC', 'ORDINARY', 'PRIMARY', 'IDENTIFIED', null, null, null, null, null,'FINISHED'); INSERT INTO public.communication_template (meshuggah_id, medium, type, campaign_id) VALUES ('mesh1', 'EMAIL', 'REMINDER', 'SIMPSONS2020X00'), @@ -207,11 +213,11 @@ INSERT INTO public.communication_template (meshuggah_id, medium, type, campaign_ ('mesh4', 'LETTER', 'NOTICE', 'VQS2021X00'), ('mesh5', 'EMAIL', 'NOTICE', 'VQS2021X00'); -INSERT INTO public.communication_request (survey_unit_id, emitter, reason, communication_template_id) VALUES - ('11', 'INTERVIEWER', 'REFUSAL', 1), - ('11', 'INTERVIEWER', 'UNREACHABLE', 2), - ('20', 'INTERVIEWER', 'REFUSAL', 3), - ('20', 'INTERVIEWER', 'UNREACHABLE', 4); +INSERT INTO public.communication_request (survey_unit_id, emitter, reason, campaign_id, meshuggah_id) VALUES + ('11', 'INTERVIEWER', 'REFUSAL', 'SIMPSONS2020X00', 'mesh1'), + ('11', 'INTERVIEWER', 'UNREACHABLE', 'SIMPSONS2020X00', 'mesh2'), + ('20', 'INTERVIEWER', 'REFUSAL', 'VQS2021X00', 'mesh3'), + ('20', 'INTERVIEWER', 'UNREACHABLE', 'VQS2021X00', 'mesh4'); INSERT INTO public.communication_request_status (communication_request_id, status, date) VALUES (1, 'INITIATED', 1721903754305), @@ -222,4 +228,6 @@ INSERT INTO public.communication_request_status (communication_request_id, statu (3, 'INITIATED', 1721903754205), (4, 'INITIATED', 1721903754205); -SET REFERENTIAL_INTEGRITY TRUE; \ No newline at end of file +INSERT INTO public.communication_metadata (survey_unit_id, campaign_id, meshuggah_id, metadata_key, metadata_value) VALUES + ('11','SIMPSONS2020X00','mesh1','recipient_full_name', 'Albert Einstein'), + ('11', 'SIMPSONS2020X00','mesh1','recipient_address', '112 Mercer Street, Princeton, New Jersey'); diff --git a/src/main/resources/db/demo.xml b/src/main/resources/db/integration-demo.xml similarity index 100% rename from src/main/resources/db/demo.xml rename to src/main/resources/db/integration-demo.xml diff --git a/src/main/resources/db/master.xml b/src/main/resources/db/master.xml index 6d41a033..f4d1ed69 100644 --- a/src/main/resources/db/master.xml +++ b/src/main/resources/db/master.xml @@ -62,4 +62,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml index da8c9b50..9ecc136e 100644 --- a/src/main/resources/logback-spring.xml +++ b/src/main/resources/logback-spring.xml @@ -1,5 +1,5 @@ - + diff --git a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java index eff2c46b..35dee2ac 100644 --- a/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java +++ b/src/test/java/fr/insee/pearljam/api/authKeycloak/TestAuthKeyCloak.java @@ -7,6 +7,8 @@ import fr.insee.pearljam.api.controller.WsText; import fr.insee.pearljam.api.domain.*; import fr.insee.pearljam.api.dto.address.AddressDto; +import fr.insee.pearljam.api.dto.closingcause.ClosingCauseDto; +import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; import fr.insee.pearljam.api.dto.interviewer.InterviewerContextDto; import fr.insee.pearljam.api.dto.message.MessageDto; import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitContextDto; @@ -18,10 +20,10 @@ import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitInterviewerLinkDto; import fr.insee.pearljam.api.dto.user.UserContextDto; import fr.insee.pearljam.api.dto.user.UserDto; -import fr.insee.pearljam.api.exception.NotFoundException; import fr.insee.pearljam.api.repository.*; import fr.insee.pearljam.api.service.*; import fr.insee.pearljam.api.surveyunit.dto.CommentDto; +import fr.insee.pearljam.api.surveyunit.dto.ContactOutcomeDto; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; import fr.insee.pearljam.api.utils.MockMvcTestUtils; import fr.insee.pearljam.api.utils.ScriptConstants; @@ -56,6 +58,7 @@ import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.Set; import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.*; @@ -80,7 +83,6 @@ @Import(FixedDateServiceConfiguration.class) class TestAuthKeyCloak { - private final SurveyUnitService surveyUnitService; private final UserService userService; private final StateRepository stateRepository; private final UserRepository userRepository; @@ -91,7 +93,6 @@ class TestAuthKeyCloak { private final OrganizationUnitRepository organizationUnitRepository; private final InterviewerRepository interviewerRepository; private final ClosingCauseRepository closingCauseRepository; - private final ReferentService referentservice; private final MessageService messageService; private final PreferenceService preferenceService; @@ -100,17 +101,15 @@ class TestAuthKeyCloak { private MockRestServiceServer mockServer; - static Authentication LOCAL_USER = AuthenticatedUserTestHelper.AUTH_LOCAL_USER; - static Authentication INTERVIEWER = AuthenticatedUserTestHelper.AUTH_INTERVIEWER; - static Authentication ADMIN = AuthenticatedUserTestHelper.AUTH_ADMIN; + private static final Authentication LOCAL_USER = AuthenticatedUserTestHelper.AUTH_LOCAL_USER; + private static final Authentication INTERVIEWER = AuthenticatedUserTestHelper.AUTH_INTERVIEWER; + private static final Authentication ADMIN = AuthenticatedUserTestHelper.AUTH_ADMIN; /** * This method set up the dataBase content - * - * */ @BeforeEach - public void setUp() { + void setUp() { mockServer = MockRestServiceServer.createServer(restTemplate); } @@ -154,14 +153,14 @@ private ResultMatcher expectTimestampFromCurrentDate(String expression, int unit /** * Test that the GET endpoint "api/user" * return 200 - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(1) void testGetUser() throws Exception { - mockMvc.perform(get("/api/user").accept(MediaType.APPLICATION_JSON) - .with(authentication(LOCAL_USER))) + mockMvc.perform(get(Constants.API_USER).accept(MediaType.APPLICATION_JSON) + .with(authentication(LOCAL_USER))) .andDo(print()) .andExpectAll( status().isOk(), @@ -179,8 +178,8 @@ void testGetUser() throws Exception { void testGetCampaignInterviewerStateCountNotAttributed() throws Exception { mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units/not-attributed/state-count") - .accept(MediaType.APPLICATION_JSON) - .with(authentication(LOCAL_USER))) + .accept(MediaType.APPLICATION_JSON) + .with(authentication(LOCAL_USER))) .andExpectAll( status().isOk(), jsonPath("$.nvmCount").value("0"), @@ -210,9 +209,10 @@ void testGetCampaignInterviewerStateCountNotAttributed() throws Exception { @Order(1) void testGetContactOutcomeCountNotattributed() throws Exception { mockMvc.perform(get( - "https://localhost:8080/api/campaign/SIMPSONS2020X00/survey-units/not-attributed/contact-outcomes") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + "https://localhost:8080/api/campaign/SIMPSONS2020X00/survey-units/not-attributed/contact" + + "-outcomes") + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), jsonPath("$.inaCount").value("0"), @@ -221,7 +221,6 @@ void testGetContactOutcomeCountNotattributed() throws Exception { jsonPath("$.ucdCount").value("0"), jsonPath("$.utrCount").value("0"), jsonPath("$.alaCount").value("0"), - jsonPath("$.dcdCount").value("0"), jsonPath("$.nuhCount").value("0"), jsonPath("$.dukCount").value("1"), jsonPath("$.duuCount").value("0"), @@ -232,10 +231,6 @@ void testGetContactOutcomeCountNotattributed() throws Exception { /** * Test that the GET endpoint "api/user" * return null - * - * @throws InterruptedException - * @throws NotFoundException - * @throws JSONException */ @Test @Order(2) @@ -245,7 +240,7 @@ void testGetUserNotFound() { private ResultMatcher checkJsonPath(String formattablePath, String nodeAttribute, Object expectedValue) { if (expectedValue instanceof Boolean) { - return jsonPath(String.format(formattablePath, nodeAttribute)).value((Boolean) expectedValue); + return jsonPath(String.format(formattablePath, nodeAttribute)).value(expectedValue); } else if (expectedValue instanceof Long) { return jsonPath(String.format(formattablePath, nodeAttribute)).value(((Long) expectedValue).intValue()); } else { @@ -258,8 +253,8 @@ private ResultMatcher checkJsonPath(String formattablePath, String nodeAttribute /** * Test that the GET endpoint "api/campaigns" * return 200 - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(3) @@ -267,18 +262,18 @@ void testGetCampaign() throws Exception { String campaignJsonPath = "$.[?(@.id == 'SIMPSONS2020X00')].%s"; mockMvc.perform(get(Constants.API_CAMPAIGNS) - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), checkJsonPath(campaignJsonPath, "label", "Survey on the Simpsons tv show 2020"), - checkJsonPath(campaignJsonPath, "allocated", 4L), + checkJsonPath(campaignJsonPath, "allocated", 5L), checkJsonPath(campaignJsonPath, "toProcessInterviewer", 0L), checkJsonPath(campaignJsonPath, "toAffect", 0L), checkJsonPath(campaignJsonPath, "toFollowUp", 0L), checkJsonPath(campaignJsonPath, "finalized", 0L), checkJsonPath(campaignJsonPath, "email", "first.email@test.com"), - checkJsonPath(campaignJsonPath, "toReview", 3L), + checkJsonPath(campaignJsonPath, "toReview", 4L), checkJsonPath(campaignJsonPath, "preference", true), checkJsonPath(campaignJsonPath, "identificationConfiguration", IdentificationConfiguration.IASCO.name()), @@ -297,16 +292,16 @@ void testGetCampaign() throws Exception { /** * Test that the GET endpoint "api/campaign/{id}/interviewers" * return 200 - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(4) void testGetCampaignInterviewer() throws Exception { String interviewerJsonPath = "$.[?(@.id == 'INTW1')].%s"; mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/interviewers") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), checkJsonPath(interviewerJsonPath, "interviewerFirstName", "Margie"), @@ -317,23 +312,23 @@ void testGetCampaignInterviewer() throws Exception { /** * Test that the GET endpoint "api/campaign/{id}/interviewers" * return 404 when campaign Id is false - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(5) void testGetCampaignInterviewerNotFound() throws Exception { mockMvc.perform(get("/api/campaign/SIMPSONS2020X000000/interviewers") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } /** * Test that the GET endpoint "api/campaign/{id}/survey-units/state-count" * return 200 - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(6) @@ -341,8 +336,8 @@ void testGetCampaignStateCount() throws Exception { String ouJsonPath = "$.organizationUnits.[?(@.idDem == 'OU-NORTH')].%s"; mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units/state-count") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), checkJsonPath(ouJsonPath, "nvmCount", 0L), @@ -372,27 +367,27 @@ void testGetCampaignStateCount() throws Exception { void testPutClosingCauseNoPreviousClosingCause() throws Exception { mockMvc.perform(put("/api/survey-unit/11/closing-cause/NPI") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); List closingCauses = closingCauseRepository.findBySurveyUnitId("11"); - assertEquals(ClosingCauseType.NPI, closingCauses.get(0).getType()); + assertEquals(ClosingCauseType.NPI, closingCauses.getFirst().getType()); } /** * Test that the GET endpoint "api/campaign/{id}/survey-units/state-count" * return 404 when campaign Id is false - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(7) void testGetCampaignStateCountNotFound() throws Exception { mockMvc.perform(get("/api/campaign/test/survey-units/state-count") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @@ -400,12 +395,12 @@ void testGetCampaignStateCountNotFound() throws Exception { @Order(8) void testPutClosingCausePreviousClosingCause() throws Exception { mockMvc.perform(put("/api/survey-unit/11/closing-cause/NPA") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); List closingCauses = closingCauseRepository.findBySurveyUnitId("11"); - assertEquals(ClosingCauseType.NPA, closingCauses.get(0).getType()); + assertEquals(ClosingCauseType.NPA, closingCauses.getFirst().getType()); } @@ -415,19 +410,19 @@ void testPutCloseSU() throws Exception { String ouJsonPath = "$.organizationUnits.[?(@.idDem == 'OU-NORTH')].%s"; mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units/state-count") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll(status().isOk(), checkJsonPath(ouJsonPath, "tbrCount", 4L), checkJsonPath(ouJsonPath, "rowCount", 0L)); mockMvc.perform(put("/api/survey-unit/14/close/ROW") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units/state-count") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll(status().isOk(), checkJsonPath(ouJsonPath, "tbrCount", 3L), checkJsonPath(ouJsonPath, "rowCount", 1L)); @@ -437,15 +432,15 @@ void testPutCloseSU() throws Exception { * Test that the GET endpoint * "api/campaign/{id}/survey-units/interviewer/{id}/state-count" * return 200 - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(8) void testGetCampaignInterviewerStateCount() throws Exception { mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units/interviewer/INTW1/state-count") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll(status().isOk(), jsonPath("$.nvmCount").value(0L), jsonPath("$.nnsCount").value(0L), @@ -472,15 +467,15 @@ void testGetCampaignInterviewerStateCount() throws Exception { * Test that the GET endpoint * "api/campaign/{id}/survey-units/interviewer/{id}/state-count" * return 404 when campaign Id is false - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(9) void testGetCampaignInterviewerStateCountNotFoundCampaign() throws Exception { mockMvc.perform(get("/api/campaign/SIMPSONS2020X000000/survey-units/interviewer/INTW1/state-count") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @@ -488,16 +483,16 @@ void testGetCampaignInterviewerStateCountNotFoundCampaign() throws Exception { * Test that the GET endpoint * "api/campaign/{id}/survey-units/interviewer/{id}/state-count" * return 404 when interviewer Id is false - * - * @throws InterruptedException - * @throws JSONException + * + * @throws InterruptedException ie + * @throws JSONException jsone */ @Test @Order(10) void testGetCampaignInterviewerStateCountNotFoundIntw() throws Exception { mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units/interviewer/test/state-count") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @@ -508,105 +503,105 @@ void testGetCampaignInterviewerStateCountNotFoundIntw() throws Exception { * Test that the GET endpoint "api/survey-unit/{id}" * return 404 when survey-unit is false * - * @throws InterruptedException - * @throws JSONException + * @throws InterruptedException ie + * @throws JSONException jsone */ @Test @Order(13) void testGetSurveyUnitInterviewerDetailNotFound() throws Exception { mockMvc.perform(get("/api/interviewer/survey-unit/123456789") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } /** * Test that the PUT endpoint "api/survey-unit/{id}/state/{state}" * return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(15) @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) void testPutSurveyUnitState() throws Exception { mockMvc.perform(put("/api/survey-unit/12/state/WFT") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); - assertSame(StateType.WFT, stateRepository.findFirstDtoBySurveyUnitIdOrderByDateDesc("12").getType()); + assertSame(StateType.WFT, stateRepository.findFirstDtoBySurveyUnitIdOrderByDateDesc("12").type()); } /** * Test that the PUT endpoint "api/survey-unit/{id}" * return 400 with unknown state - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(16) void testPutSurveyUnitStateStateFalse() throws Exception { mockMvc.perform(put("/api/survey-unit/11/state/test") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isInternalServerError()); } /** * Test that the PUT endpoint "api/survey-unit/{id}" * return 403 when not allowed to pass to this state - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(17) void testPutSurveyUnitStateNoSu() throws Exception { mockMvc.perform(put("/api/survey-unit/11/state/AOC") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isForbidden()); } /** * Test that the PUT endpoint "api/preferences" * return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(18) void testPutPreferences() throws Exception { mockMvc.perform(put("/api/preferences") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of("SIMPSONS2020X00"))) - .contentType(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of("SIMPSONS2020X00"))) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } /** * Test that the PUT endpoint "api/preferences" * return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(19) void testPutPreferencesWrongCampaignId() throws Exception { mockMvc.perform(put("/api/preferences") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(""))) - .contentType(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(""))) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } /** * Test that the GET endpoint * "/campaign/{id}/survey-units/interviewer/{idep}/closing-causes" returns 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(19) @@ -614,8 +609,8 @@ void testGetCampaignInterviewerClosingCauseCount() throws Exception { // use a beforeEach method to run each test with a cleaned database mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units/interviewer/INTW1/closing-causes") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll(status().isOk(), jsonPath("$.npaCount").value("0"), jsonPath("$.npiCount").value("1"), @@ -626,15 +621,15 @@ void testGetCampaignInterviewerClosingCauseCount() throws Exception { /** * Test that the GET endpoint "api/campaign/{id}/survey-units/abandoned" - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(20) void testGetNbSuAbandoned() throws Exception { mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units/abandoned") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll(status().isOk(), jsonPath("$.count").value("0")); } @@ -642,8 +637,8 @@ void testGetNbSuAbandoned() throws Exception { /** * Test that the Get endpoint * "/campaign/{id}/survey-units/contact-outcomes[?date={date}]" return 200 - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(20) @@ -651,8 +646,8 @@ void testGetContactOutcomeCountByCampaign() throws Exception { String ouJsonPath = "$.organizationUnits.[?(@.idDem == 'OU-NORTH')].%s"; mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units/contact-outcomes") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll(status().isOk(), checkJsonPath(ouJsonPath, "labelDem", "North region organizational unit"), checkJsonPath(ouJsonPath, "inaCount", 0L), @@ -661,7 +656,6 @@ void testGetContactOutcomeCountByCampaign() throws Exception { checkJsonPath(ouJsonPath, "ucdCount", 0L), checkJsonPath(ouJsonPath, "utrCount", 0L), checkJsonPath(ouJsonPath, "alaCount", 0L), - checkJsonPath(ouJsonPath, "dcdCount", 0L), checkJsonPath(ouJsonPath, "nuhCount", 0L), checkJsonPath(ouJsonPath, "dukCount", 1L), checkJsonPath(ouJsonPath, "duuCount", 0L), @@ -671,8 +665,8 @@ void testGetContactOutcomeCountByCampaign() throws Exception { /** * Test that the Get endpoint * "/campaign/survey-units/contact-outcomes[?date={date}]" return 200 - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(20) @@ -680,8 +674,8 @@ void testGetContactOutcomeCountAllCampaign() throws Exception { String ouJsonPath = "$.[?(@.campaign.id == 'SIMPSONS2020X00')].%s"; mockMvc.perform(get("/api/campaigns/survey-units/contact-outcomes") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll(status().isOk(), checkJsonPath(ouJsonPath, "campaign.label", "Survey on the Simpsons tv show 2020"), checkJsonPath(ouJsonPath, "inaCount", 0L), @@ -690,7 +684,6 @@ void testGetContactOutcomeCountAllCampaign() throws Exception { checkJsonPath(ouJsonPath, "ucdCount", 0L), checkJsonPath(ouJsonPath, "utrCount", 0L), checkJsonPath(ouJsonPath, "alaCount", 0L), - checkJsonPath(ouJsonPath, "dcdCount", 0L), checkJsonPath(ouJsonPath, "nuhCount", 0L), checkJsonPath(ouJsonPath, "nuhCount", 0L), checkJsonPath(ouJsonPath, "dukCount", 1L), @@ -700,52 +693,52 @@ void testGetContactOutcomeCountAllCampaign() throws Exception { /** * Test that the GET endpoint "api/campaign/{id}/survey-units/abandoned" - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(21) void testGetNbSuAbandonedNotFound() throws Exception { mockMvc.perform(get("/api/campaign/test/survey-units/abandoned") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } /** * Test that the GET endpoint "api/campaign/{id}/survey-units/not-attributed" - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(22) void testGetNbSuNotAttributed() throws Exception { mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units/not-attributed") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll(status().isOk(), jsonPath("$.count").value("0")); } /** * Test that the GET endpoint "api/campaign/{id}/survey-units/not-attributed" - * - * @throws InterruptedException - * @throws JSONException + * + * @throws InterruptedException ie + * @throws JSONException jsone */ @Test @Order(23) void testGetNbSuNotAttributedNotFound() throws Exception { mockMvc.perform(get("/api/campaign/test/survey-units/not-attributed") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } /** * Test that the POST endpoint "api/message" return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(34) @@ -755,44 +748,44 @@ void testPostMessage() throws Exception { message.setSender("abc"); mockMvc.perform(post("/api/message") - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(message))) + .with(authentication(LOCAL_USER)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(message))) .andExpect(status().isOk()); List messages = messageRepository .findMessagesDtoByIds(messageRepository.getMessageIdsByInterviewer("INTW1")); - assertEquals("TEST", messages.get(0).getText()); + assertEquals("TEST", messages.getFirst().getText()); } /** * Test that the POST endpoint "api/message" return 400 when bad format - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(35) void testPostMessageBadFormat() throws Exception { mockMvc.perform(post("/api/message") - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(null))) + .with(authentication(LOCAL_USER)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(null))) .andExpect(status().isBadRequest()); } /** * Test that the GET endpoint * "api/messages/{id}" return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(36) void testGetMessage() throws Exception { mockMvc.perform(get("/api/messages/INTW1") - .with(authentication(INTERVIEWER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(INTERVIEWER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), jsonPath("$[?(@.text == 'TEST')]").exists()); @@ -802,15 +795,15 @@ void testGetMessage() throws Exception { /** * Test that the GET endpoint * "api/messages/{id}" return empty body with a wrong id - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(37) void testGetMessageWrongId() throws Exception { mockMvc.perform(get("/api/messages/123456789") - .with(authentication(INTERVIEWER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(INTERVIEWER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), jsonPath("$.length()").value(0)); @@ -819,16 +812,16 @@ void testGetMessageWrongId() throws Exception { /** * Test that the put endpoint "api/message/{id}/interviewer/{idep}/read" * return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(38) void testPutMessageAsRead() throws Exception { - Long messageId = messageRepository.getMessageIdsByInterviewer("INTW1").get(0); + Long messageId = messageRepository.getMessageIdsByInterviewer("INTW1").getFirst(); mockMvc.perform(put("/api/message/" + messageId + "/interviewer/INTW1/read") - .with(authentication(INTERVIEWER)) - .contentType(MediaType.APPLICATION_JSON)) + .with(authentication(INTERVIEWER)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } @@ -836,40 +829,40 @@ void testPutMessageAsRead() throws Exception { /** * Test that the put endpoint "api/message/{id}/interviewer/{idep}/delete" * return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(39) void testPutMessageAsDelete() throws Exception { - Long messageId = messageRepository.getMessageIdsByInterviewer("INTW1").get(0); + Long messageId = messageRepository.getMessageIdsByInterviewer("INTW1").getFirst(); String url = String.format("/api/message/%d/interviewer/INTW1/delete", messageId); mockMvc.perform(put(url) - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); Optional message = messageRepository.findById(messageId); - assertEquals(MessageStatusType.DEL, message.get().getMessageStatus().get(0).getStatus()); + assertEquals(MessageStatusType.DEL, message.get().getMessageStatus().getFirst().getStatus()); } /** * Test that the PUT endpoint * "/message/{id}/interviewer/{idep}/read" return 404 with a wrong Id - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(40) void testPutMessageAsReadWrongId() throws Exception { - Long messageId = messageRepository.getMessageIdsByInterviewer("INTW1").get(0); + Long messageId = messageRepository.getMessageIdsByInterviewer("INTW1").getFirst(); String url = String.format("/api/message/%d/interviewer/Test/read", messageId); mockMvc.perform(put(url) - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @@ -877,15 +870,15 @@ void testPutMessageAsReadWrongId() throws Exception { /** * Test that the GET endpoint * "/message-history" return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(41) void testGetMessageHistory() throws Exception { mockMvc.perform(get("/api/message-history") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll(status().isOk(), jsonPath("$[?(@.text == 'TEST')]").exists()); @@ -894,8 +887,8 @@ void testGetMessageHistory() throws Exception { /** * Test that the POST endpoint * "/verify-name" return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(42) @@ -903,9 +896,9 @@ void testPostVerifyName() throws Exception { WsText message = new WsText("simps"); mockMvc.perform(post("/api/verify-name") - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(message))) + .with(authentication(LOCAL_USER)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(message))) .andExpectAll(status().isOk(), jsonPath("$[?(@.id == 'SIMPSONS2020X00')]").exists()); @@ -913,17 +906,17 @@ void testPostVerifyName() throws Exception { /** * Test that the POST endpoint "api/message" return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(43) void testPostMessageSysteme() throws Exception { MessageDto message = new MessageDto("Synchronisation", List.of("SIMPSONS2020X00")); mockMvc.perform(post("/api/message") - .with(authentication(INTERVIEWER)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(message))) + .with(authentication(INTERVIEWER)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(message))) .andExpectAll(status().isOk()); List messages = messageRepository .findMessagesDtoByIds(messageRepository.getMessageIdsByInterviewer("INTW1")); @@ -933,8 +926,8 @@ void testPostMessageSysteme() throws Exception { /** * Test that the Get endpoint * "/interviewers" return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(44) @@ -942,8 +935,8 @@ void testGetInterviewer() throws Exception { String interviewerJsonPath = "$.[?(@.id == 'INTW1')].%s"; mockMvc.perform(get("/api/interviewers") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), jsonPath("$.[?(@.id == 'INTW1')]").exists(), @@ -954,19 +947,20 @@ void testGetInterviewer() throws Exception { /** * Test that the Get endpoint * "/interviewer/{id}/campaigns" return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(45) void testGetInterviewerRelatedCampaigns() throws Exception { mockMvc.perform(get("/api/interviewer/INTW1/campaigns") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), jsonPath("$.[?(@.id == 'SIMPSONS2020X00')]").exists(), - jsonPath("$.[?(@.id == 'SIMPSONS2020X00')].label").value("Survey on the Simpsons tv show 2020"), + jsonPath("$.[?(@.id == 'SIMPSONS2020X00')].label").value("Survey on the Simpsons tv show " + + "2020"), expectValidManagementStartDate(), expectValidEndDate()); } @@ -975,23 +969,23 @@ void testGetInterviewerRelatedCampaigns() throws Exception { * Test that the Get endpoint * "/interviewer/{id}/campaigns" return 404 * when interviewer not exist - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(46) void testGetInterviewerNotExistForCampaign() throws Exception { mockMvc.perform(get("/api/interviewer/INTW123/campaigns") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } /** * Test that the Get endpoint * "/survey-units/closable" return 200 - * - * @throws Exception + * + * @throws Exception e */ @Test @Order(47) @@ -1008,13 +1002,14 @@ void testGetSUClosable() throws Exception { """; mockServer.expect(ExpectedCount.once(), - requestTo(containsString(Constants.API_QUEEN_SURVEYUNITS_STATEDATA))) + requestTo(containsString(Constants.API_QUEEN_SURVEYUNITS_STATEDATA))) .andExpect(method(HttpMethod.POST)) .andRespond(withStatus(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(expectedBody)); - Optional visiOpt = visibilityRepository.findVisibilityByCampaignIdAndOuId("VQS2021X00", "OU-NORTH"); + Optional visiOpt = visibilityRepository.findVisibilityByCampaignIdAndOuId("VQS2021X00", "OU" + + "-NORTH"); if (visiOpt.isEmpty()) { fail("No visibility found for VQS2021X00 and OU-NORTH"); } @@ -1050,16 +1045,16 @@ void testGetSUClosable() throws Exception { * Test that the Get endpoint * "/campaign/{id}/survey-units/interviewer/{id}/contact-outcomes[?date={date}]" * return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(48) void testGetContactOutcomeCountByCampaignAndInterviewer() throws Exception { mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units/interviewer/INTW1/contact-outcomes") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), jsonPath("$.inaCount").value(0L), @@ -1068,7 +1063,6 @@ void testGetContactOutcomeCountByCampaignAndInterviewer() jsonPath("$.ucdCount").value(0L), jsonPath("$.utrCount").value(0L), jsonPath("$.alaCount").value(0L), - jsonPath("$.dcdCount").value(0L), jsonPath("$.nuhCount").value(0L), jsonPath("$.dukCount").value(0L), jsonPath("$.duuCount").value(0L), @@ -1079,16 +1073,16 @@ void testGetContactOutcomeCountByCampaignAndInterviewer() * Test that the Get endpoint * "/campaign/{id}/survey-units/interviewer/{id}/contact-outcomes[?date={date}]" * return 404 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(49) void testGetContactOutcomeCountByCampaignNotExistAndInterviewer() throws Exception { mockMvc.perform(get("/api/campaign/SIMPSONS2020X000000/survey-units/interviewer/INTW1/contact-outcomes") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isNotFound()); @@ -1098,16 +1092,16 @@ void testGetContactOutcomeCountByCampaignNotExistAndInterviewer() * Test that the Get endpoint * "/campaign/{id}/survey-units/interviewer/{id}/contact-outcomes[?date={date}]" * return 404 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(50) void testGetContactOutcomeCountByCampaignAndInterviewerNotExist() throws Exception { mockMvc.perform(get("/api/campaign/SIMPSONS2020X000000/survey-units/interviewer/INTW123/contact-outcomes") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isNotFound()); @@ -1116,8 +1110,8 @@ void testGetContactOutcomeCountByCampaignAndInterviewerNotExist() /** * Test that the Get endpoint * "/campaign/{id}/survey-units/contact-outcomes[?date={date}]" return 404 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(52) @@ -1125,8 +1119,8 @@ void testGetContactOutcomeCountByCampaignNotExist() throws Exception { mockMvc.perform(get("/api/campaign/SIMPSONS2020X000000/survey-units/contact-outcomes") - .with(authentication(LOCAL_USER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isNotFound()); } @@ -1134,8 +1128,8 @@ void testGetContactOutcomeCountByCampaignNotExist() /** * Test that the Put endpoint * "/survey-unit/{id}/comment" return 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(54) @@ -1143,14 +1137,14 @@ void testPutCommentOnSu() throws Exception { String comment = asJsonString(new CommentDto(CommentType.MANAGEMENT, "Test of comment")); mockMvc.perform(put("/api/survey-unit/11/comment") - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON) - .content(comment)) + .with(authentication(LOCAL_USER)) + .contentType(MediaType.APPLICATION_JSON) + .content(comment)) .andExpect(status().isOk()); mockMvc.perform(get("/api/interviewer/survey-unit/11") - .with(authentication(INTERVIEWER)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(INTERVIEWER)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), jsonPath("$.comments[0].type").value(equalTo(CommentType.MANAGEMENT.toString())), @@ -1162,8 +1156,8 @@ void testPutCommentOnSu() throws Exception { * Test that the Put endpoint * "/survey-unit/{id}/comment" return 404 * when id not exist - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(55) @@ -1171,9 +1165,9 @@ void testPutCommentSuNotExist() throws Exception { String comment = asJsonString(new CommentDto(CommentType.MANAGEMENT, "Test of comment")); mockMvc.perform(put("/api/survey-unit/11111111111/comment") - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON) - .content(comment)) + .with(authentication(LOCAL_USER)) + .contentType(MediaType.APPLICATION_JSON) + .content(comment)) .andExpect(status().isNotFound()); } @@ -1181,15 +1175,15 @@ void testPutCommentSuNotExist() throws Exception { /** * Test that the Put endpoint * "/survey-unit/{id}/viewed" return 200 and viewed attribut set to true - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(56) void testPutSuViewed() throws Exception { mockMvc.perform(put("/api/survey-unit/24/viewed") - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertEquals(true, surveyUnitRepository.findById("24").get().getViewed()); @@ -1200,31 +1194,31 @@ void testPutSuViewed() throws Exception { * Test that the Put endpoint * "/survey-unit/{id}/viewed" return 404 * when id not exist - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(57) void testPutSuViewedNotExist() throws Exception { mockMvc.perform(put("/api/survey-unit/11111111111/viewed") - .with(authentication(LOCAL_USER)) - .contentType(MediaType.APPLICATION_JSON)) + .with(authentication(LOCAL_USER)) + .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } /** * Test that the GET endpoint "api/campaigns" * return 200 - * - * @throws InterruptedException - * @throws JSONException + * + * @throws InterruptedException ie + * @throws JSONException jsone */ @Test @Order(58) void testGetOrganizationUnits() throws Exception { mockMvc.perform(get("/api/organization-units") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), jsonPath("$[?(@.id == 'OU-NORTH')].label").value("North region organizational unit"), @@ -1236,8 +1230,8 @@ void testGetOrganizationUnits() throws Exception { /** * Test that the Post endpoint * "/organization-unit/context" returns 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(103) @@ -1257,9 +1251,9 @@ void testPostOrganizationUnitContext() throws Exception { ou2.setUsers(List.of(user3, user4)); mockMvc.perform(post("/api/organization-units") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(ou1, ou2)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(ou1, ou2)))) .andExpect(status().isOk()); Optional ou1Opt = organizationUnitRepository.findById("OU-NORTH2"); @@ -1297,8 +1291,8 @@ void testPostOrganizationUnitContext() throws Exception { * Test that the Post endpoint * "/organization-unit/context" returns 400 * when there is a duplicate user - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(104) @@ -1315,9 +1309,9 @@ void testPostOrganizationUnitContextDuplicateUser() OrganizationUnitType.LOCAL, List.of(user2, user3)); mockMvc.perform(post("/api/organization-units") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(ou1, ou2)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(ou1, ou2)))) .andExpect(status().isBadRequest()); // No OU should have been added @@ -1332,8 +1326,8 @@ void testPostOrganizationUnitContextDuplicateUser() * Test that the Post endpoint * "/organization-unit/context" returns 400 * when a child organization unit does not exist - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(105) @@ -1350,9 +1344,9 @@ void testPostOrganizationUnitContextNoOU() throws Exception { OrganizationUnitType.LOCAL, List.of(user2, user3)); mockMvc.perform(post("/api/organization-units") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(ou1, ou2)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(ou1, ou2)))) .andExpect(status().isBadRequest()); // No OU should have been added @@ -1366,8 +1360,8 @@ void testPostOrganizationUnitContextNoOU() throws Exception { /** * Test that the Post endpoint * "api/interviewers" returns 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(106) @@ -1376,9 +1370,9 @@ void testPostInterviewers() throws Exception { InterviewerContextDto interv2 = generateInterviewerBContextDto("INTERV2"); mockMvc.perform(post("/api/interviewers") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(interv1, interv2)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(interv1, interv2)))) .andExpect(status().isOk()); // Interviewers should have been added @@ -1405,8 +1399,8 @@ void testPostInterviewers() throws Exception { * Test that the Post endpoint * "api/interviewers" returns 400 * when an email is missing - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(107) @@ -1416,9 +1410,9 @@ void testPostInterviewersMissingEmail() throws Exception { interv2.setEmail(null); mockMvc.perform(post("/api/interviewers") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(interv1, interv2)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(interv1, interv2)))) .andExpect(status().isBadRequest()); // Interviewers should not have been added @@ -1432,8 +1426,8 @@ void testPostInterviewersMissingEmail() throws Exception { * Test that the Post endpoint * "api/interviewers" returns 400 * when an iterviewer id is present twice - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(108) @@ -1442,9 +1436,9 @@ void testPostInterviewersDuplicateId() throws Exception { InterviewerContextDto interv2 = generateInterviewerBContextDto("INTERV3"); mockMvc.perform(post("/api/interviewers") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(interv1, interv2)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(interv1, interv2)))) .andExpect(status().isBadRequest()); // Interviewers should not have been added @@ -1457,8 +1451,8 @@ void testPostInterviewersDuplicateId() throws Exception { * Test that the Post endpoint * "api/interviewers" returns 200 * and provide default title MISTER if no title provided - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(109) @@ -1467,9 +1461,9 @@ void testPostInterviewersWithNoTitle() throws Exception { intervNoTitle.setTitle(null); mockMvc.perform(post("/api/interviewers") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(intervNoTitle)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(intervNoTitle)))) .andExpect(status().isOk()); // Interviewers should have been added @@ -1482,18 +1476,24 @@ void testPostInterviewersWithNoTitle() throws Exception { /** * Test that the POST endpoint * "/survey-units returns 200 - * - * @throws JsonProcessingException - * @throws JSONException - * @throws InterruptedException + * + * @throws JsonProcessingException jpe + * @throws JSONException json exception + * @throws InterruptedException ie */ @Test @Order(111) void testPostSurveyUnits() throws Exception { - mockMvc.perform(post("/api/survey-units") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(generateSurveyUnit("8"))))) + SurveyUnitContextDto surveyUnit = generateSurveyUnit("8"); + surveyUnit.setComments(Set.of(new CommentDto(CommentType.INTERVIEWER, "interviewer comment"))); + surveyUnit.setContactOutcome(new ContactOutcomeDto(1743078880000L,ContactOutcomeType.INA,2)); + surveyUnit.setContactAttempts(List.of(new ContactAttemptDto(1743078880000L,Status.MES,Medium.TEL),new ContactAttemptDto(1743078900000L,Status.INA,Medium.FIELD))); + surveyUnit.setClosingCause(new ClosingCauseDto(1843078880000L,ClosingCauseType.NPA)); + + mockMvc.perform(post(Constants.API_SURVEYUNITS) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(surveyUnit)))) .andExpect(status().isOk()); assertTrue(surveyUnitRepository.findById("8").isPresent()); @@ -1502,28 +1502,28 @@ void testPostSurveyUnits() throws Exception { /** * Test that the POST endpoint * "/survey-units returns 400 when id dupliate in DB - * - * @throws JsonProcessingException - * @throws JSONException - * @throws InterruptedException + * + * @throws JsonProcessingException jpe + * @throws JSONException jsone + * @throws InterruptedException ie */ @Test @Order(112) void testPostSurveyUnitsDuplicateInDB() throws Exception { mockMvc.perform(post("/api/survey-units") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(generateSurveyUnit("8"))))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(generateSurveyUnit("8"))))) .andExpect(status().isBadRequest()); } /** * Test that the POST endpoint * "/survey-units returns 400 when id dupliate in body - * - * @throws JsonProcessingException - * @throws JSONException - * @throws InterruptedException + * + * @throws JsonProcessingException jpe + * @throws JSONException jsone + * @throws InterruptedException ie */ @Test @Order(113) @@ -1531,19 +1531,19 @@ void testPostSurveyUnitsDuplicateInBody() throws Exception { SurveyUnitContextDto su = generateSurveyUnit("9"); mockMvc.perform(post("/api/survey-units") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(su, su)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(su, su)))) .andExpect(status().isBadRequest()); } /** * Test that the POST endpoint * "/survey-units returns 400 when OrganizationUnitId does not exist - * - * @throws JsonProcessingException - * @throws JSONException - * @throws InterruptedException + * + * @throws JsonProcessingException jpe + * @throws JSONException jsone + * @throws InterruptedException ie */ @Test @Order(114) @@ -1553,19 +1553,19 @@ void testPostSurveyUnitsOUNotExist() throws Exception { su.setOrganizationUnitId("OU-TEST"); mockMvc.perform(post("/api/survey-units") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(su)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(su)))) .andExpect(status().isBadRequest()); } /** * Test that the POST endpoint * "/survey-units returns 400 when campaignId does not exist - * - * @throws JsonProcessingException - * @throws JSONException - * @throws InterruptedException + * + * @throws JsonProcessingException jpe + * @throws JSONException jsone + * @throws InterruptedException ie */ @Test @Order(115) @@ -1574,9 +1574,9 @@ void testPostSurveyUnitsCampaignNotExist() throws Exception { su.setCampaign("campaignTest"); mockMvc.perform(post("/api/survey-units") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(su)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(su)))) .andExpect(status().isBadRequest()); } @@ -1584,10 +1584,10 @@ void testPostSurveyUnitsCampaignNotExist() throws Exception { /** * Test that the POST endpoint * "/survey-units returns 400 when surveyUnit body is not valid - * - * @throws JsonProcessingException - * @throws JSONException - * @throws InterruptedException + * + * @throws JsonProcessingException jpe + * @throws JSONException jsone + * @throws InterruptedException ie */ @Test @Order(117) @@ -1596,35 +1596,35 @@ void testPostSurveyUnitsSUNotValid() throws Exception { // ID null mockMvc.perform(post("/api/survey-units") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(su)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(su)))) .andExpect(status().isBadRequest()); // Campaign null su.setId("9"); su.setCampaign(""); mockMvc.perform(post("/api/survey-units") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(su)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(su)))) .andExpect(status().isBadRequest()); // Persons Null su.setPersons(Collections.emptyList()); su.setCampaign("SIMPSONS2020X00"); mockMvc.perform(post("/api/survey-units") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(su)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(su)))) .andExpect(status().isBadRequest()); } /** * Test that the Post endpoint * "/survey-units/interviewers" returns 200 - * - * @throws InterruptedException + * + * @throws InterruptedException ie */ @Test @Order(118) @@ -1639,9 +1639,9 @@ void testPostAssignements() throws Exception { SurveyUnitInterviewerLinkDto assign2 = new SurveyUnitInterviewerLinkDto("102", "INTW3"); mockMvc.perform(post(Constants.API_SURVEYUNITS_INTERVIEWERS) - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(assign1, assign2)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(assign1, assign2)))) .andDo(print()) .andExpect(status().isOk()); @@ -1660,9 +1660,9 @@ void testPostAssignements() throws Exception { /** * Test that the Post endpoint * "/survey-units/interviewers" returns 400 - * when an iterviewer is not present - * - * @throws InterruptedException + * when an interviewer is not present + * + * @throws InterruptedException ie */ @Test @Order(119) @@ -1675,9 +1675,9 @@ void testPostAssignementsNoInterviewerDoesntExist() SurveyUnitInterviewerLinkDto assign2 = new SurveyUnitInterviewerLinkDto("104", "INTWDOESNTEXIST"); mockMvc.perform(post(Constants.API_SURVEYUNITS_INTERVIEWERS) - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of(assign1, assign2)))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of(assign1, assign2)))) .andDo(print()) .andExpect(status().isBadRequest()); @@ -1696,20 +1696,20 @@ void testPostAssignementsNoInterviewerDoesntExist() /** * Test that the Post endpoint * "/orgaization-unit/id/users" returns 200 - * - * @throws JSONException - * @throws JsonProcessingException - * @throws InterruptedException + * + * @throws JSONException jsone + * @throws JsonProcessingException jpe + * @throws InterruptedException ie */ @Test @Order(120) void testPostUsersByOU() throws Exception { mockMvc.perform(post("/api/organization-unit/OU-NORTH/users") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of( - new UserContextDto("TEST", "test", "test", null, null), - new UserContextDto("TEST2", "test2", "test2", null, null))))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of( + new UserContextDto("TEST", "test", "test", null, null), + new UserContextDto("TEST2", "test2", "test2", null, null))))) .andExpect(status().isOk()); // Ensure users have been added to the organization unit @@ -1725,20 +1725,20 @@ void testPostUsersByOU() throws Exception { /** * Test that the Post endpoint * "/orgaization-unit/id/users" returns 200 - * - * @throws JSONException - * @throws JsonProcessingException - * @throws InterruptedException + * + * @throws JSONException jsone + * @throws JsonProcessingException jpe + * @throws InterruptedException ie */ @Test @Order(121) void testPostUsersByOUThatDoesNotExist() throws Exception { mockMvc.perform(post("/api/organization-unit/OU-TEST/users") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(List.of( - new UserContextDto("TEST", "test", "test", null, null), - new UserContextDto("TEST2", "test2", "test2", null, null))))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(List.of( + new UserContextDto("TEST", "test", "test", null, null), + new UserContextDto("TEST2", "test2", "test2", null, null))))) .andExpect(status().isBadRequest()); // Verify the user organization unit @@ -1755,8 +1755,8 @@ void testPostUsersByOUThatDoesNotExist() throws Exception { @Order(200) void testDeleteSurveyUnit() throws Exception { mockMvc.perform(delete("/api/survey-unit/11") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertTrue(surveyUnitRepository.findById("11").isEmpty()); @@ -1766,8 +1766,8 @@ void testDeleteSurveyUnit() throws Exception { @Order(201) void testDeleteSurveyUnitNotExist() throws Exception { mockMvc.perform(delete("/api/survey-unit/toto") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @@ -1776,25 +1776,25 @@ void testDeleteSurveyUnitNotExist() throws Exception { @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) void testDeleteCampaign() throws Exception { mockMvc.perform(delete("/api/campaign/XCLOSEDX00") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertTrue(campaignRepository.findById("XCLOSEDX00").isEmpty()); mockMvc.perform(delete("/api/campaign/SIMPSONS2020X00") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isConflict()); mockMvc.perform(delete("/api/campaign/SIMPSONS2020X00?force=false") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isConflict()); mockMvc.perform(delete("/api/campaign/SIMPSONS2020X00?force=true") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertTrue(campaignRepository.findById("SIMPSONS2020X00").isEmpty()); @@ -1804,8 +1804,8 @@ void testDeleteCampaign() throws Exception { @Order(203) void testDeleteCampaignNotExist() throws Exception { mockMvc.perform(delete("/api/campaign/SIMPSONS2020XTT") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @@ -1813,8 +1813,8 @@ void testDeleteCampaignNotExist() throws Exception { @Order(204) void testDeleteUser() throws Exception { mockMvc.perform(delete("/api/user/JKL") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertTrue(userRepository.findById("JKL").isEmpty()); @@ -1824,8 +1824,8 @@ void testDeleteUser() throws Exception { @Order(205) void testDeleteUserNotExist() throws Exception { mockMvc.perform(delete("/api/user/USER") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @@ -1835,7 +1835,7 @@ void testDeleteUserNotExist() throws Exception { void testDeleteOrganizationUnit() throws Exception { // Delete all Survey Units before deleting Organization Unit surveyUnitRepository.findByOrganizationUnitIdIn(List.of("OU-NORTH")) - .forEach(su -> surveyUnitRepository.delete(su)); + .forEach(surveyUnitRepository::delete); // Delete all Users before deleting Organization Unit userRepository.findAllByOrganizationUnitId("OU-NORTH") @@ -1846,8 +1846,8 @@ void testDeleteOrganizationUnit() throws Exception { }); mockMvc.perform(delete("/api/organization-unit/OU-NORTH") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertTrue(organizationUnitRepository.findById("OU-NORTH").isEmpty()); @@ -1857,8 +1857,8 @@ void testDeleteOrganizationUnit() throws Exception { @Order(207) void testDeleteOrganizationUnitWithUsersOrSurveyUnits() throws Exception { mockMvc.perform(delete("/api/organization-unit/OU-SOUTH") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); } @@ -1866,28 +1866,28 @@ void testDeleteOrganizationUnitWithUsersOrSurveyUnits() throws Exception { @Order(208) void testDeleteOrganizationUnitNotExist() throws Exception { mockMvc.perform(delete("/api/organization-unit/TEST") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @Test @Order(209) void testCreateValidUser() throws Exception { - mockMvc.perform(post("/api/user") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(generateValidUser()))) + mockMvc.perform(post(Constants.API_USER) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(generateValidUser()))) .andExpect(status().isCreated()); } @Test @Order(210) void testCreateAreadyPresentUser() throws Exception { - mockMvc.perform(post("/api/user") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(generateValidUser()))) + mockMvc.perform(post(Constants.API_USER) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(generateValidUser()))) .andExpect(status().isConflict()); } @@ -1895,47 +1895,47 @@ void testCreateAreadyPresentUser() throws Exception { @Order(211) void testCreateInvalidUser() throws Exception { // Null user object - mockMvc.perform(post("/api/user") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(null))) + mockMvc.perform(post(Constants.API_USER) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(null))) .andDo(print()) .andExpect(status().isBadRequest()); // User with null first name UserDto user = generateValidUser(); user.setFirstName(null); - mockMvc.perform(post("/api/user") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(user))) + mockMvc.perform(post(Constants.API_USER) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(user))) .andExpect(status().isBadRequest()); // User with null last name user = generateValidUser(); user.setLastName(null); - mockMvc.perform(post("/api/user") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(user))) + mockMvc.perform(post(Constants.API_USER) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(user))) .andExpect(status().isBadRequest()); // User with null id user = generateValidUser(); user.setId(null); - mockMvc.perform(post("/api/user") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(user))) + mockMvc.perform(post(Constants.API_USER) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(user))) .andExpect(status().isBadRequest()); // User with unknown organization unit user = generateValidUser(); user.getOrganizationUnit().setId("WHERE_IS_CHARLIE"); - mockMvc.perform(post("/api/user") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(user))) + mockMvc.perform(post(Constants.API_USER) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(user))) .andExpect(status().isBadRequest()); } @@ -1943,9 +1943,9 @@ void testCreateInvalidUser() throws Exception { @Order(212) void testUpdateMissingUser() throws Exception { mockMvc.perform(put("/api/user/TEST") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(generateValidUser()))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(generateValidUser()))) .andExpect(status().isNotFound()); } @@ -1953,9 +1953,9 @@ void testUpdateMissingUser() throws Exception { @Order(213) void testUpdateWrongUser() throws Exception { mockMvc.perform(put("/api/user/GHI") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(generateValidUser()))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(generateValidUser()))) .andExpect(status().isConflict()); } @@ -1966,9 +1966,9 @@ void testUpdateUser() throws Exception { user.setId("GHI"); mockMvc.perform(put("/api/user/GHI") - .with(authentication(ADMIN)) - .contentType(MediaType.APPLICATION_JSON) - .content(asJsonString(user))) + .with(authentication(ADMIN)) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(user))) .andExpectAll( status().isOk(), jsonPath("$.id").value("GHI"), @@ -1982,8 +1982,8 @@ void testUpdateUser() throws Exception { @Order(215) void testAssignUser() throws Exception { mockMvc.perform(put("/api/user/GHI/organization-unit/OU-SOUTH") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), jsonPath("$.id").value("GHI"), @@ -1995,8 +1995,8 @@ void testAssignUser() throws Exception { @Order(216) void testAssignUserMissingUser() throws Exception { mockMvc.perform(put("/api/user/MISSING/organization-unit/OU-SOUTH") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @@ -2004,8 +2004,8 @@ void testAssignUserMissingUser() throws Exception { @Order(217) void testAssignUserMissingOu() throws Exception { mockMvc.perform(put("/api/user/GHI/organization-unit/MISSING") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } @@ -2013,15 +2013,15 @@ void testAssignUserMissingOu() throws Exception { @Order(218) void testOngoing() throws Exception { mockMvc.perform(get("/campaigns/ZCLOSEDX00/ongoing") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), jsonPath("$.ongoing").value(false)); mockMvc.perform(get("/campaigns/VQS2021X00/ongoing") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpectAll( status().isOk(), jsonPath("$.ongoing").value(true)); @@ -2031,8 +2031,8 @@ void testOngoing() throws Exception { @Order(219) void testOngoingNotFound() throws Exception { mockMvc.perform(get("/campaigns/MISSING/ongoing") - .with(authentication(ADMIN)) - .accept(MediaType.APPLICATION_JSON)) + .with(authentication(ADMIN)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } diff --git a/src/test/java/fr/insee/pearljam/api/bussinessrules/BusinessRulesTest.java b/src/test/java/fr/insee/pearljam/api/bussinessrules/BusinessRulesTest.java new file mode 100644 index 00000000..8ebb6a0c --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/bussinessrules/BusinessRulesTest.java @@ -0,0 +1,64 @@ +package fr.insee.pearljam.api.bussinessrules; + +import fr.insee.pearljam.api.domain.StateType; +import fr.insee.pearljam.api.dto.state.StateDto; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class BusinessRulesTest { + + @Test + void stateCanBeModifiedByManager() { + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.CLO, StateType.NVA)).isTrue(); + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.NVA, StateType.NVA)).isFalse(); + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.NNS, StateType.ANV)).isTrue(); + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.FIN, StateType.ANV)).isFalse(); + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.NNS, StateType.VIN)).isTrue(); + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.ANV, StateType.VIN)).isTrue(); + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.WFT, StateType.VIN)).isFalse(); + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.TBR, StateType.FIN)).isTrue(); + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.WFT, StateType.FIN)).isFalse(); + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.FIN, StateType.WFT)).isTrue(); + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.ANV, StateType.WFT)).isFalse(); + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.ANV, StateType.CLO)).isTrue(); + assertThat(BusinessRules.stateCanBeModifiedByManager(StateType.ANV, StateType.TBR)).isFalse(); + } + + @Test + void stateCanBeSeenByInterviewerBussinessRules() { + assertThat(BusinessRules.stateCanBeSeenByInterviewerBussinessRules(StateType.VIN)).isTrue(); + assertThat(BusinessRules.stateCanBeSeenByInterviewerBussinessRules(StateType.FIN)).isTrue(); + assertThat(BusinessRules.stateCanBeSeenByInterviewerBussinessRules(StateType.CLO)).isTrue(); + assertThat(BusinessRules.stateCanBeSeenByInterviewerBussinessRules(StateType.NNS)).isFalse(); + assertThat(BusinessRules.stateCanBeSeenByInterviewerBussinessRules(StateType.NVA)).isFalse(); + } + + @Test + void shouldFallBackToTbrOrFin() { + StateDto state1 = new StateDto(1L, 1L, StateType.NVA); + StateDto state2 = new StateDto(2L, 2L, StateType.VIN); + StateDto state3 = new StateDto(3L, 3L, StateType.TBR); + List statesWithNVA = List.of(state1, state2); + List statesWithoutTBRorFIN = List.of(state2); + List statesWithTBR = List.of(state3); + + assertThat(BusinessRules.shouldFallBackToTbrOrFin(statesWithNVA)).isFalse(); + assertThat(BusinessRules.shouldFallBackToTbrOrFin(statesWithoutTBRorFIN)).isTrue(); + assertThat(BusinessRules.shouldFallBackToTbrOrFin(statesWithTBR)).isFalse(); + assertThat(BusinessRules.shouldFallBackToTbrOrFin(List.of())).isFalse(); + } + + @Test + void testBusinessRulesConstructorThrowsException() throws NoSuchMethodException { + Constructor constructor = BusinessRules.class.getDeclaredConstructor(); + constructor.setAccessible(true); + + assertThrows(InvocationTargetException.class, constructor::newInstance); + } +} \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java index b61b89c3..8c6816fc 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerCreateTest.java @@ -101,13 +101,15 @@ void testCreateCampaign04() throws Exception { ContactAttemptConfiguration.F2F, List.of(visibility), List.of(), - List.of()); + List.of(), + false); CampaignCreateDto campaign2 = generateCampaign("campId", " ", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(visibility), List.of(), - List.of()); + List.of(), + false); List campaigns = List.of(campaign1, campaign2); for(CampaignCreateDto campaign : campaigns) { mockMvc.perform(post(Constants.API_CAMPAIGN) @@ -158,7 +160,8 @@ void testCreateCampaign05() throws Exception { ContactAttemptConfiguration.F2F, invalidCampaignVisibilities, List.of(), - List.of()); + List.of(), + false); mockMvc.perform(post(Constants.API_CAMPAIGN) .contentType(MediaType.APPLICATION_JSON) .content(JsonTestHelper.toJson(campaign))) @@ -187,15 +190,16 @@ void testCreateCampaign06() throws Exception { void testCreateCampaign07() throws Exception { VisibilityCampaignCreateDto visibility = generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, 1721683254000L, 1721683255000L, true); - CommunicationTemplateCreateDto communicationTemplate = new CommunicationTemplateCreateDto("messhId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); - CommunicationTemplateCreateDto duplicatedCommunicationTemplate = new CommunicationTemplateCreateDto("messhId2", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CommunicationTemplateCreateDto communicationTemplate = new CommunicationTemplateCreateDto( "messhId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CommunicationTemplateCreateDto duplicatedCommunicationTemplate = new CommunicationTemplateCreateDto( "messhId2", CommunicationMedium.EMAIL, CommunicationType.NOTICE); CampaignCreateDto campaign = generateCampaign("campId", "label", "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(visibility), List.of(), - List.of(communicationTemplate, duplicatedCommunicationTemplate)); + List.of(communicationTemplate, duplicatedCommunicationTemplate), + false); mockMvc.perform(post(Constants.API_CAMPAIGN) .contentType(MediaType.APPLICATION_JSON) @@ -208,8 +212,8 @@ void testCreateCampaign07() throws Exception { * @return a pair of json string and dto object for the campaign */ public CampaignCreateDto generateDefaultCampaign() { - CommunicationTemplateCreateDto communicationTemplate1 = new CommunicationTemplateCreateDto("messhId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); - CommunicationTemplateCreateDto communicationTemplate2 = new CommunicationTemplateCreateDto("messhId2", CommunicationMedium.LETTER, CommunicationType.REMINDER); + CommunicationTemplateCreateDto communicationTemplate1 = new CommunicationTemplateCreateDto( "messhId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CommunicationTemplateCreateDto communicationTemplate2 = new CommunicationTemplateCreateDto( "messhId2", CommunicationMedium.LETTER, CommunicationType.REMINDER); VisibilityCampaignCreateDto firstVisibility = generateVisibility("OU-NORTH", 1721683250000L, 1721683251000L, 1721683252000L, @@ -229,7 +233,8 @@ public CampaignCreateDto generateDefaultCampaign() { ContactAttemptConfiguration.TEL, List.of(firstVisibility, secondVisibility), List.of(firstReferent, secondReferent), - List.of(communicationTemplate1, communicationTemplate2)); + List.of(communicationTemplate1, communicationTemplate2), + false); } private CampaignCreateDto generateCampaign( @@ -239,7 +244,8 @@ private CampaignCreateDto generateCampaign( ContactAttemptConfiguration contactAttemptConfiguration, List visibilities, List referents, - List communicationTemplates) { + List communicationTemplates, + boolean sensitivity) { return new CampaignCreateDto(campaignId, campaignLabel, @@ -249,7 +255,8 @@ private CampaignCreateDto generateCampaign( email, identificationConfiguration, contactOutcomeConfiguration, - contactAttemptConfiguration + contactAttemptConfiguration, + sensitivity ); } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java index 983d1d75..b1d5f603 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerTest.java @@ -53,7 +53,7 @@ void setup() { @DisplayName("Should retrieve campaign") void testGetCampaign01() throws Exception { CampaignResponseDto campaign = new CampaignResponseDto("campaign-id", "label", null, null, "email", - IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.F2F); + IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.F2F, false); campaignService.setCampaignToRetrieve(campaign); MvcResult mvcResult = mockMvc.perform(get(getPath) diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java index 8f89f971..08550c7a 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/CampaignControllerUpdateTest.java @@ -5,7 +5,6 @@ import fr.insee.pearljam.api.controller.CampaignController; import fr.insee.pearljam.api.domain.ContactAttemptConfiguration; import fr.insee.pearljam.api.domain.ContactOutcomeConfiguration; -import fr.insee.pearljam.api.domain.IdentificationConfiguration; import fr.insee.pearljam.api.campaign.controller.dummy.CampaignFakeService; import fr.insee.pearljam.api.campaign.controller.dummy.ReferentFakeService; import fr.insee.pearljam.api.dto.referent.ReferentDto; @@ -68,7 +67,7 @@ void testUpdateCampaign01() throws Exception { @DisplayName("Should return bad request when invalid campaign label") void testUpdateCampaign02() throws Exception { CampaignUpdateDto campaign = generateCampaign(" ", - "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + "test.test@sdf.com", ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(), List.of()); @@ -121,7 +120,7 @@ private void testUpdateExceptions(HttpStatus httpStatus, private void testUpdateExceptions(VisibilityCampaignUpdateDto visibility, HttpStatus httpStatus, String message) throws Exception { CampaignUpdateDto campaign = generateCampaign("campaignLabel", - "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + "test.test@sdf.com", ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(visibility), List.of()); @@ -151,14 +150,14 @@ private CampaignUpdateDto generateDefaultCampaign() { ReferentDto firstReferent = new ReferentDto("Bob", "Marley", "0123456789", "PRIMARY"); ReferentDto secondReferent = new ReferentDto("Dupont", "Jean", "1234567890", "PRIMARY"); return generateCampaign("An other campaign", - "test.test@sdf.com", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, + "test.test@sdf.com", ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, List.of(firstVisibility, secondVisibility), List.of(firstReferent, secondReferent)); } private CampaignUpdateDto generateCampaign(String campaignLabel, - String email, IdentificationConfiguration identificationConfiguration, + String email, ContactOutcomeConfiguration contactOutcomeConfiguration, ContactAttemptConfiguration contactAttemptConfiguration, List visibilities, @@ -168,7 +167,6 @@ private CampaignUpdateDto generateCampaign(String campaignLabel, visibilities, referents, email, - identificationConfiguration, contactOutcomeConfiguration, contactAttemptConfiguration ); diff --git a/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/CampaignFakeService.java b/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/CampaignFakeService.java index 510a11d2..cd6709de 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/CampaignFakeService.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/controller/dummy/CampaignFakeService.java @@ -5,6 +5,7 @@ import fr.insee.pearljam.api.campaign.dto.input.CampaignUpdateDto; import fr.insee.pearljam.api.campaign.dto.output.CampaignResponseDto; +import fr.insee.pearljam.api.dto.campaign.CampaignSensitivityDto; import fr.insee.pearljam.domain.exception.*; import lombok.RequiredArgsConstructor; @@ -147,4 +148,9 @@ public CampaignResponseDto getCampaignDtoById(String campaignId) throws Campaign } return campaignToRetrieve; } + + @Override + public List getCampaignSensitivityDto() { + return List.of(); + } } diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDtoTest.java index 9bdc8dc4..bd14ec70 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/input/CommunicationTemplateCreateDtoTest.java @@ -21,19 +21,19 @@ void testToModel() { List dtoList = List.of(dto1, dto2); // When - List modelList = CommunicationTemplateCreateDto.toModel(dtoList); + List modelList = CommunicationTemplateCreateDto.toModel(dtoList, "SIMPSONS2020X00"); // Then assertThat(modelList).hasSize(2); CommunicationTemplate firstTemplate = modelList.getFirst(); - assertThat(firstTemplate.id()).isNull(); + assertThat(firstTemplate.campaignId()).isEqualTo("SIMPSONS2020X00"); assertThat(firstTemplate.meshuggahId()).isEqualTo("msg1"); assertThat(firstTemplate.medium()).isEqualTo(CommunicationMedium.EMAIL); assertThat(firstTemplate.type()).isEqualTo(CommunicationType.NOTICE); CommunicationTemplate lastTemplate = modelList.getLast(); - assertThat(lastTemplate.id()).isNull(); + assertThat(lastTemplate.campaignId()).isEqualTo("SIMPSONS2020X00"); assertThat(lastTemplate.meshuggahId()).isEqualTo("msg2"); assertThat(lastTemplate.medium()).isEqualTo(CommunicationMedium.LETTER); assertThat(lastTemplate.type()).isEqualTo(CommunicationType.REMINDER); diff --git a/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java index 54e74b9a..35edbade 100644 --- a/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/campaign/dto/output/CommunicationTemplateResponseDtoTest.java @@ -16,8 +16,8 @@ class CommunicationTemplateResponseDtoTest { @DisplayName("Should return dto objects") void testFromModel() { // Given - CommunicationTemplate template1 = new CommunicationTemplate(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); - CommunicationTemplate template2 = new CommunicationTemplate(2L, "msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER); + CommunicationTemplate template1 = new CommunicationTemplate("SIMPSONS2020X00", "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CommunicationTemplate template2 = new CommunicationTemplate("SIMPSONS2020X00", "msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER); List communicationTemplates = List.of(template1, template2); // When @@ -26,13 +26,11 @@ void testFromModel() { // Then assertThat(communicationDtos).hasSize(2); - CommunicationTemplateResponseDto dto1 = communicationDtos.get(0); - assertThat(dto1.id()).isEqualTo(1L); + CommunicationTemplateResponseDto dto1 = communicationDtos.getFirst(); assertThat(dto1.medium()).isEqualTo(CommunicationMedium.EMAIL); assertThat(dto1.type()).isEqualTo(CommunicationType.NOTICE); CommunicationTemplateResponseDto dto2 = communicationDtos.get(1); - assertThat(dto2.id()).isEqualTo(2L); assertThat(dto2.medium()).isEqualTo(CommunicationMedium.LETTER); assertThat(dto2.type()).isEqualTo(CommunicationType.REMINDER); } diff --git a/src/test/java/fr/insee/pearljam/api/controller/StateControllerTest.java b/src/test/java/fr/insee/pearljam/api/controller/StateControllerTest.java new file mode 100644 index 00000000..fded5472 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/controller/StateControllerTest.java @@ -0,0 +1,231 @@ +package fr.insee.pearljam.api.controller; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import fr.insee.pearljam.api.dto.state.StateCountDto; +import fr.insee.pearljam.api.service.StateService; +import fr.insee.pearljam.domain.security.port.userside.AuthenticatedUserService; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +class StateControllerTest { + + @Mock + private AuthenticatedUserService authenticatedUserService; + + @Mock + private StateService stateService; + + @InjectMocks + private StateController stateController; + + @BeforeEach + void setup() { + MockitoAnnotations.openMocks(this); // Initialise les mocks + } + + @Test + @DisplayName("Test successful retrieval of interviewers' state count by campaign") + void testGetInterviewersStateCountByCampaign_Success() { + // Given + String campaignId = "SIMPSONS2020X00"; + Long date = System.currentTimeMillis(); + String userId = "user123"; + + Map stateCountMap = new HashMap<>(); + stateCountMap.put("nvmCount", 5L); + stateCountMap.put("nnsCount", 10L); + stateCountMap.put("anvCount", 3L); + + StateCountDto stateCountDto = new StateCountDto(campaignId, "Simpsons Campaign", stateCountMap); + + when(authenticatedUserService.getCurrentUserId()).thenReturn(userId); + when(stateService.getInterviewersStateCountByCampaign(userId, campaignId, date)).thenReturn(Collections.singletonList(stateCountDto)); + + // When + ResponseEntity> response = stateController.getInterviewersStateCountByCampaign(campaignId, date); + + // Then + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertNotNull(response.getBody()); + assertEquals(1, response.getBody().size()); + + StateCountDto returnedStateCountDto = response.getBody().getFirst(); + assertEquals("SIMPSONS2020X00", returnedStateCountDto.getIdDem()); + assertEquals("Simpsons Campaign", returnedStateCountDto.getLabelDem()); + assertEquals(5L, returnedStateCountDto.getNvmCount()); + assertEquals(10L, returnedStateCountDto.getNnsCount()); + assertEquals(3L, returnedStateCountDto.getAnvCount()); + + verify(authenticatedUserService).getCurrentUserId(); + verify(stateService).getInterviewersStateCountByCampaign(userId, campaignId, date); + } + + @Test + @DisplayName("Test not found scenario for interviewers' state count by campaign") + void testGetInterviewersStateCountByCampaign_NotFound() { + // Given + String campaignId = "testCampaign"; + String userId = "user123"; + Long date = 1672531200000L; + + when(authenticatedUserService.getCurrentUserId()).thenReturn(userId); + when(stateService.getInterviewersStateCountByCampaign(userId, campaignId, date)).thenReturn(null); + + // When + ResponseEntity> response = stateController.getInterviewersStateCountByCampaign(campaignId, date); + + // Then + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertNull(response.getBody()); + } + + @Test + @DisplayName("Test exception scenario when an error occurs while retrieving interviewers' state count by campaign") + void testGetInterviewersStateCountByCampaign_Exception() { + // Given + String campaignId = "testCampaign"; + String userId = "user123"; + Long date = 1672531200000L; + + when(authenticatedUserService.getCurrentUserId()).thenReturn(userId); + when(stateService.getInterviewersStateCountByCampaign(userId, campaignId, date)).thenThrow(new RuntimeException("Unexpected error")); + + // When / Then + assertThrows(RuntimeException.class, () -> stateController.getInterviewersStateCountByCampaign(campaignId, date)); + } + + @Test + @DisplayName("Test successful retrieval of survey units' state count by campaign") + void testGetCampaignsStateCount_Success() { + // Given + String userId = "user123"; + Long date = System.currentTimeMillis(); + + StateCountDto stateCountDto = new StateCountDto("SIMPSONS2020X00", "Simpsons Campaign", Collections.emptyMap()); + List stateCountCampaignsDto = Collections.singletonList(stateCountDto); + + when(authenticatedUserService.getCurrentUserId()).thenReturn(userId); + when(stateService.getStateCountByCampaigns(userId, date)).thenReturn(stateCountCampaignsDto); + + // When + ResponseEntity> response = stateController.getCampaignsStateCount(date); + + // Then + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertNotNull(response.getBody()); + assertEquals(1, response.getBody().size()); + assertEquals("SIMPSONS2020X00", response.getBody().getFirst().getIdDem()); + assertEquals("Simpsons Campaign", response.getBody().getFirst().getLabelDem()); + verify(authenticatedUserService).getCurrentUserId(); + verify(stateService).getStateCountByCampaigns(userId, date); + } + + @Test + @DisplayName("Test not found scenario for survey units' state count by campaign") + void testGetCampaignsStateCount_NotFound() { + // Given + String userId = "user123"; + Long date = 1672531200000L; + + when(authenticatedUserService.getCurrentUserId()).thenReturn(userId); + when(stateService.getStateCountByCampaigns(userId, date)).thenReturn(null); + + // When + ResponseEntity> response = stateController.getCampaignsStateCount(date); + + // Then + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertNull(response.getBody()); + } + + @Test + @DisplayName("Test exception scenario when an error occurs while retrieving survey units' state count by campaign") + void testGetCampaignsStateCount_Exception() { + // Given + String userId = "user123"; + Long date = 1672531200000L; + + when(authenticatedUserService.getCurrentUserId()).thenReturn(userId); + when(stateService.getStateCountByCampaigns(userId, date)).thenThrow(new RuntimeException("Unexpected error")); + + // When / Then + assertThrows(RuntimeException.class, () -> stateController.getCampaignsStateCount(date)); + } + + + @Test + @DisplayName("Test successful retrieval of interviewers' state count") + void testGetInterviewersStateCount_Success() { + // Given + Long date = System.currentTimeMillis(); + String userId = "user123"; + + StateCountDto stateCountDto = new StateCountDto("SIMPSONS2020X00", "Simpsons Campaign", Collections.emptyMap()); + List stateCountCampaignsDto = Collections.singletonList(stateCountDto); + + when(authenticatedUserService.getCurrentUserId()).thenReturn(userId); + when(stateService.getStateCountByInterviewer(userId, date)).thenReturn(stateCountCampaignsDto); + + // When + ResponseEntity> response = stateController.getInterviewersStateCount(date); + + // Then + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertNotNull(response.getBody()); + assertEquals(1, response.getBody().size()); + assertEquals("SIMPSONS2020X00", response.getBody().getFirst().getIdDem()); + assertEquals("Simpsons Campaign", response.getBody().getFirst().getLabelDem()); + verify(authenticatedUserService).getCurrentUserId(); + verify(stateService).getStateCountByInterviewer(userId, date); + } + + @Test + @DisplayName("Test not found scenario for interviewers' state count") + void testGetInterviewersStateCount_NotFound() { + // Given + Long date = 1672531200000L; + String userId = "user123"; + + when(authenticatedUserService.getCurrentUserId()).thenReturn(userId); + when(stateService.getStateCountByInterviewer(userId, date)).thenReturn(null); + + // When + ResponseEntity> response = stateController.getInterviewersStateCount(date); + + // Then + assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); + assertNull(response.getBody()); + } + + @Test + @DisplayName("Test exception scenario when an error occurs while retrieving interviewers' state count") + void testGetInterviewersStateCount_Exception() { + // Given + Long date = 1672531200000L; + String userId = "user123"; + + when(authenticatedUserService.getCurrentUserId()).thenReturn(userId); + when(stateService.getStateCountByInterviewer(userId, date)) + .thenThrow(new RuntimeException("Unexpected error")); + + // When / Then + assertThatThrownBy(() -> stateController.getInterviewersStateCount(date)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("Unexpected error"); + } +} diff --git a/src/test/java/fr/insee/pearljam/api/dto/campaign/CampaignSensitivityDtoTest.java b/src/test/java/fr/insee/pearljam/api/dto/campaign/CampaignSensitivityDtoTest.java new file mode 100644 index 00000000..ef2e2f5c --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/dto/campaign/CampaignSensitivityDtoTest.java @@ -0,0 +1,26 @@ +package fr.insee.pearljam.api.dto.campaign; + +import fr.insee.pearljam.api.domain.*; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; + +class CampaignSensitivityDtoTest { + + @Test + @DisplayName("Test of creating a sensitive campaign") + void testCreateCampaignSensitivity() { + // Given + Campaign campaign = new Campaign("id", "label", IdentificationConfiguration.HOUSEF2F, + ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, + "email@plop.com", false); + + // When + CampaignSensitivityDto campaignSensitivityDto = CampaignSensitivityDto.fromModel(campaign); + + // Then + assertThat(campaignSensitivityDto).isNotNull(); + assertThat(campaign.getId()).isEqualTo(campaignSensitivityDto.id()); + assertThat(campaign.getSensitivity()).isEqualTo(campaignSensitivityDto.sensitivity()); + } +} \ No newline at end of file diff --git a/src/test/java/fr/insee/pearljam/api/service/impl/StateServiceImplTest.java b/src/test/java/fr/insee/pearljam/api/service/impl/StateServiceImplTest.java new file mode 100644 index 00000000..705df8a9 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/api/service/impl/StateServiceImplTest.java @@ -0,0 +1,156 @@ +package fr.insee.pearljam.api.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyList; +import static org.mockito.Mockito.anyLong; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import fr.insee.pearljam.api.dto.campaign.CampaignDto; +import fr.insee.pearljam.api.dto.organizationunit.OrganizationUnitDto; +import fr.insee.pearljam.api.dto.state.StateCountDto; +import fr.insee.pearljam.api.repository.CampaignRepository; +import fr.insee.pearljam.api.repository.ClosingCauseRepository; +import fr.insee.pearljam.api.repository.InterviewerRepository; +import fr.insee.pearljam.api.repository.StateRepository; +import fr.insee.pearljam.api.service.UserService; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; +import fr.insee.pearljam.domain.surveyunit.port.serverside.CommunicationRequestRepository; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +class StateServiceImplTest { + + @Mock + private UserService userService; + @Mock + private InterviewerRepository interviewerRepository; + @Mock + private CampaignRepository campaignRepository; + @Mock + private StateRepository stateRepository; + @Mock + private CommunicationRequestRepository communicationRequestRepository; + @Mock + private ClosingCauseRepository closingCauseRepository; + + @InjectMocks + private StateServiceImpl stateService; + + private String userId; + private Long date; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + userId = "user1"; + date = System.currentTimeMillis(); + } + + @Test + @DisplayName("Should return empty result when no organization units are present") + void testGetStateCountByCampaigns_EmptyOrganizationUnits() { + // Given + when(userService.getUserOUs(userId, true)).thenReturn(Collections.emptyList()); + + // When + List result = stateService.getStateCountByCampaigns(userId, date); + + // Then + assertTrue(result.isEmpty(), "Expected empty result when no organization units are present"); + verify(userService).getUserOUs(userId, true); + verifyNoInteractions(campaignRepository, stateRepository, communicationRequestRepository, closingCauseRepository); + } + + @Test + @DisplayName("Should return two campaigns when organization units are present") + void testGetStateCountByCampaigns_WithOrganizationUnits() { + // Given + List organizationUnits = Arrays.asList(new OrganizationUnitDto("OU1", "Unit 1"), new OrganizationUnitDto("OU2", "Unit 2")); + when(userService.getUserOUs(userId, true)).thenReturn(organizationUnits); + when(campaignRepository.findAllCampaignIdsByOuIds(anyList())).thenReturn(Arrays.asList("campaign1", "campaign2")); + when(stateRepository.getStateCountSumByCampaign(anyString(), anyList(), anyLong())).thenReturn(new HashMap<>()); + when(communicationRequestRepository.getCommRequestCountByCampaignTypeAndOrgaUnit(anyString(), eq(CommunicationType.NOTICE), anyLong(), anyList())).thenReturn(0L); + when(communicationRequestRepository.getCommRequestCountByCampaignTypeAndOrgaUnit(anyString(), eq(CommunicationType.REMINDER), anyLong(), anyList())).thenReturn(0L); + when(campaignRepository.findDtoById(anyString())).thenReturn(new CampaignDto()); + + // When + List result = stateService.getStateCountByCampaigns(userId, date); + + // Then + assertEquals(2, result.size(), "Expected two campaigns to be returned."); + verify(userService).getUserOUs(userId, true); + verify(campaignRepository).findAllCampaignIdsByOuIds(Arrays.asList("OU1", "OU2")); + verify(stateRepository, times(2)).getStateCountSumByCampaign(anyString(), anyList(), eq(date)); + verify(communicationRequestRepository, times(4)).getCommRequestCountByCampaignTypeAndOrgaUnit(anyString(), any(), eq(date), anyList()); + } + + @Test + @DisplayName("Should return one campaign when date is null") + void testGetStateCountByCampaigns_WithNullDate() { + // Given + List organizationUnits = List.of(new OrganizationUnitDto("OU1", "Unit 1")); + when(userService.getUserOUs(userId, true)).thenReturn(organizationUnits); + when(campaignRepository.findAllCampaignIdsByOuIds(anyList())).thenReturn(List.of("campaign1")); + when(stateRepository.getStateCountSumByCampaign(anyString(), anyList(), anyLong())).thenReturn(new HashMap<>()); + when(communicationRequestRepository.getCommRequestCountByCampaignTypeAndOrgaUnit(anyString(), eq(CommunicationType.NOTICE), anyLong(), anyList())).thenReturn(0L); + when(communicationRequestRepository.getCommRequestCountByCampaignTypeAndOrgaUnit(anyString(), eq(CommunicationType.REMINDER), anyLong(), anyList())).thenReturn(0L); + when(campaignRepository.findDtoById(anyString())).thenReturn(new CampaignDto()); + + // When + List result = stateService.getStateCountByCampaigns(userId, null); + + // Then + assertEquals(1, result.size(), "Expected one campaign to be returned when date is null."); + verify(userService).getUserOUs(userId, true); + verify(campaignRepository).findAllCampaignIdsByOuIds(List.of("OU1")); + } + + @Test + @DisplayName("Should return an empty list when the user has no organizational units") + void shouldReturnEmptyListWhenUserHasNoOrganizationUnits() { + // Given + when(userService.getUserOUs(userId, true)).thenReturn(Collections.emptyList()); + when(interviewerRepository.findIdsByOrganizationUnits(anyList())).thenReturn(Collections.emptySet()); + + // When + List result = stateService.getStateCountByInterviewer(userId, date); + + // Then + assertTrue(result.isEmpty(), "The list should be empty if the user has no organizational units."); + verify(userService, times(2)).getUserOUs(userId, true); + } + + @Test + @DisplayName("Should return an empty list when the user has organizational units but no campaigns") + void shouldReturnEmptyListWhenUserHasOrganizationUnitsButNoCampaigns() { + // Given + List organizationUnits = List.of(new OrganizationUnitDto("OU1", "Unit 1")); + when(userService.getUserOUs(userId, true)).thenReturn(organizationUnits); + when(campaignRepository.findAllCampaignIdsByOuIds(List.of("OU1"))).thenReturn(Collections.emptyList()); + + // When + List result = stateService.getStateCountByInterviewer(userId, date); + + // Then + assertTrue(result.isEmpty(), "The list should be empty if the user has units but no campaigns."); + verify(userService, times(2)).getUserOUs(userId, true); + verify(campaignRepository).findAllCampaignIdsByOuIds(List.of("OU1")); + } + +} + diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java index d4c8c32b..1a7be324 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/controller/SurveyUnitControllerTest.java @@ -3,15 +3,15 @@ import fr.insee.pearljam.api.controller.SurveyUnitController; import fr.insee.pearljam.api.surveyunit.controller.dummy.SurveyUnitFakeService; import fr.insee.pearljam.api.surveyunit.dto.CommentDto; -import fr.insee.pearljam.api.surveyunit.dto.IdentificationDto; import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; +import fr.insee.pearljam.api.surveyunit.dto.identification.RawIdentificationDto; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; import fr.insee.pearljam.api.utils.MockMvcTestUtils; import fr.insee.pearljam.api.utils.dummy.AuthenticationUserFakeService; import fr.insee.pearljam.api.web.exception.ExceptionControllerAdvice; -import fr.insee.pearljam.domain.surveyunit.model.CommentType; import fr.insee.pearljam.domain.exception.PersonNotFoundException; import fr.insee.pearljam.domain.exception.SurveyUnitNotFoundException; +import fr.insee.pearljam.domain.surveyunit.model.CommentType; import fr.insee.pearljam.domain.surveyunit.model.question.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -88,11 +88,13 @@ void updateSurveyUnit01() throws Exception { SurveyUnitUpdateDto surveyUnitUpdated = surveyUnitService.getSurveyUnitUpdated(); assertThat(surveyUnitUpdated.id()).isEqualTo("su-id"); - IdentificationDto identificationExpected = new IdentificationDto(IdentificationQuestionValue.IDENTIFIED, + RawIdentificationDto identificationExpected = new RawIdentificationDto(IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ABSORBED, CategoryQuestionValue.OCCASIONAL, - OccupantQuestionValue.IDENTIFIED); + OccupantQuestionValue.IDENTIFIED + ,null, null, null, null, null + ); assertThat(surveyUnitUpdated.identification()).isEqualTo(identificationExpected); diff --git a/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java b/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java index 8f6af3a4..400d97cb 100644 --- a/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java +++ b/src/test/java/fr/insee/pearljam/api/surveyunit/dto/SurveyUnitDetailDtoTest.java @@ -1,123 +1,130 @@ package fr.insee.pearljam.api.surveyunit.dto; -import fr.insee.pearljam.api.domain.*; +import fr.insee.pearljam.api.domain.Address; +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.api.domain.InseeAddress; +import fr.insee.pearljam.api.domain.InseeSampleIdentifier; +import fr.insee.pearljam.api.domain.SampleIdentifier; +import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitDetailDto; +import fr.insee.pearljam.api.surveyunit.dto.identification.IdentificationDto; import fr.insee.pearljam.domain.surveyunit.model.CommentType; -import fr.insee.pearljam.domain.surveyunit.model.communication.*; -import fr.insee.pearljam.domain.surveyunit.model.question.*; -import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestEmitter; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestReason; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationStatusType; +import fr.insee.pearljam.domain.surveyunit.model.question.AccessQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.CategoryQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.IdentificationQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.OccupantQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.SituationQuestionValue; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDBId; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommentDB; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestStatusDB; -import fr.insee.pearljam.infrastructure.surveyunit.entity.IdentificationDB; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - +import fr.insee.pearljam.infrastructure.surveyunit.entity.identification.HouseF2FIdentificationDB; +import fr.insee.pearljam.infrastructure.surveyunit.entity.identification.IdentificationDB; import java.util.HashSet; import java.util.List; import java.util.Set; - import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; class SurveyUnitDetailDtoTest { - private SurveyUnit surveyUnit; - - @BeforeEach - void setup() { - Address address = new InseeAddress("l1", "l2", "l3", "l4", "l5", "l6", "l7", true, - "building", "floor", "door", "staircase", true); - SampleIdentifier sampleIdentifier = new InseeSampleIdentifier(1, "ec", 2, 3, 4, 5, 6, - 7, 8, "autre", "nograp"); - Campaign campaign = new Campaign("id", "label", null, - null, null, "email"); - surveyUnit = new SurveyUnit("id", true, true, address, - sampleIdentifier, campaign, null, null, new HashSet<>()); - - surveyUnit.getComments().addAll(Set.of( - new CommentDB(1L, CommentType.INTERVIEWER, "value1", surveyUnit), - new CommentDB(2L, CommentType.INTERVIEWER, "value2", surveyUnit), - new CommentDB(3L, CommentType.MANAGEMENT, "value3", surveyUnit) - )); - } - - @Test - @DisplayName("Should have identification") - void testCreateIdentification01() { - IdentificationDB identificationDB = new IdentificationDB(1L, - IdentificationQuestionValue.IDENTIFIED, - AccessQuestionValue.ACC, - SituationQuestionValue.ORDINARY, - CategoryQuestionValue.SECONDARY, - OccupantQuestionValue.IDENTIFIED, - surveyUnit); - surveyUnit.setIdentification(identificationDB); - SurveyUnitDetailDto surveyUnitDetailDto = new SurveyUnitDetailDto(surveyUnit); - IdentificationDto identificationDto = surveyUnitDetailDto.getIdentification(); - IdentificationDto identificationDtoExpected = IdentificationDto.fromModel(IdentificationDB.toModel(identificationDB)); - assertThat(identificationDto).isEqualTo(identificationDtoExpected); - } - - @Test - @DisplayName("Should have comments") - void testCreateComments01() { - SurveyUnitDetailDto surveyUnitDetailDto = new SurveyUnitDetailDto(surveyUnit); - assertThat(surveyUnitDetailDto.getComments()) - .containsExactlyInAnyOrder( - new CommentDto(CommentType.INTERVIEWER, "value1"), - new CommentDto(CommentType.INTERVIEWER, "value2"), - new CommentDto(CommentType.MANAGEMENT, "value3") - ); - } - - @Test - @DisplayName("Should have communication requests") - void testCreateCommunicationRequests01() { - - Set communicationRequestDBs = new HashSet<>(); - - List status1 = List.of( - new CommunicationRequestStatusDB(null, 1233456789L, CommunicationStatusType.INITIATED, null), - new CommunicationRequestStatusDB(2L, 123345678910L, CommunicationStatusType.FAILED, null) - ); - - List status2 = List.of( - new CommunicationRequestStatusDB(3L, 123345678911L, CommunicationStatusType.READY, null), - new CommunicationRequestStatusDB(4L, 123345678912L, CommunicationStatusType.CANCELLED, null) - ); - - CommunicationTemplateDB communicationTemplate1 = new CommunicationTemplateDB(1L, null, null, null, null); - CommunicationTemplateDB communicationTemplate2 = new CommunicationTemplateDB(2L, null, null, null, null); - - - communicationRequestDBs.add(new CommunicationRequestDB(10L, communicationTemplate1, - CommunicationRequestReason.UNREACHABLE, - CommunicationRequestEmitter.INTERVIEWER, surveyUnit, status1)); - communicationRequestDBs.add(new CommunicationRequestDB(11L, communicationTemplate2, - CommunicationRequestReason.REFUSAL, - CommunicationRequestEmitter.TOOL, surveyUnit, status2)); - surveyUnit.setCommunicationRequests(communicationRequestDBs); - - SurveyUnitDetailDto surveyUnitDetailDto = new SurveyUnitDetailDto(surveyUnit); - - List status1Expected = List.of( - new CommunicationRequestStatusDto(1233456789L, CommunicationStatusType.INITIATED), - new CommunicationRequestStatusDto(123345678910L, CommunicationStatusType.FAILED) - ); - - List status2Expected = List.of( - new CommunicationRequestStatusDto(123345678911L, CommunicationStatusType.READY), - new CommunicationRequestStatusDto(123345678912L, CommunicationStatusType.CANCELLED) - ); - - assertThat(surveyUnitDetailDto.getCommunicationRequests()) - .containsExactlyInAnyOrder( - new CommunicationRequestResponseDto(1L, - CommunicationRequestReason.UNREACHABLE, - CommunicationRequestEmitter.INTERVIEWER, status1Expected), - new CommunicationRequestResponseDto(2L, - CommunicationRequestReason.REFUSAL, - CommunicationRequestEmitter.TOOL, status2Expected) - ); - } + private SurveyUnit surveyUnit; + + @BeforeEach + void setup() { + Address address = new InseeAddress("l1", "l2", "l3", "l4", "l5", "l6", "l7", true, + "building", "floor", "door", "staircase", true); + SampleIdentifier sampleIdentifier = new InseeSampleIdentifier(1, "ec", 2, 3, 4, 5, 6, + 7, 8, "autre", "nograp"); + Campaign campaign = new Campaign("id", "label", null, + null, null, "email", false); + surveyUnit = new SurveyUnit("id", true, true, address, + sampleIdentifier, campaign, null, null, new HashSet<>()); + + surveyUnit.getComments().addAll(Set.of( + new CommentDB(1L, CommentType.INTERVIEWER, "value1", surveyUnit), + new CommentDB(2L, CommentType.INTERVIEWER, "value2", surveyUnit), + new CommentDB(3L, CommentType.MANAGEMENT, "value3", surveyUnit) + )); + } + + @Test + @DisplayName("Should have identification") + void testCreateIdentification01() { + IdentificationDB identificationDB = new HouseF2FIdentificationDB(1L, surveyUnit, + IdentificationQuestionValue.IDENTIFIED, + AccessQuestionValue.ACC, + SituationQuestionValue.ORDINARY, + CategoryQuestionValue.SECONDARY, + OccupantQuestionValue.IDENTIFIED); + surveyUnit.setIdentification(identificationDB); + SurveyUnitDetailDto surveyUnitDetailDto = new SurveyUnitDetailDto(surveyUnit); + IdentificationDto identificationDto = surveyUnitDetailDto.getIdentification(); + IdentificationDto identificationDtoExpected = + IdentificationDto.fromModel(IdentificationDB.toModel(identificationDB)); + assertThat(identificationDto).isEqualTo(identificationDtoExpected); + } + + @Test + @DisplayName("Should have comments") + void testCreateComments01() { + SurveyUnitDetailDto surveyUnitDetailDto = new SurveyUnitDetailDto(surveyUnit); + assertThat(surveyUnitDetailDto.getComments()) + .containsExactlyInAnyOrder( + new CommentDto(CommentType.INTERVIEWER, "value1"), + new CommentDto(CommentType.INTERVIEWER, "value2"), + new CommentDto(CommentType.MANAGEMENT, "value3") + ); + } + + @Test + @DisplayName("Should have communication requests") + void testCreateCommunicationRequests01() { + + Set communicationRequestDBs = new HashSet<>(); + + List status1 = List.of( + new CommunicationRequestStatusDB(null, 1233456789L, CommunicationStatusType.INITIATED, null), + new CommunicationRequestStatusDB(2L, 123345678910L, CommunicationStatusType.FAILED, null) + ); + + List status2 = List.of( + new CommunicationRequestStatusDB(3L, 123345678911L, CommunicationStatusType.READY, null), + new CommunicationRequestStatusDB(4L, 123345678912L, CommunicationStatusType.CANCELLED, null) + ); + + communicationRequestDBs.add(new CommunicationRequestDB(10L, new CommunicationTemplateDBId("mesh1","SIMPSONS2020X00"), + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, surveyUnit, status1)); + communicationRequestDBs.add(new CommunicationRequestDB(11L, new CommunicationTemplateDBId("mesh2","SIMPSONS2020X00"), + CommunicationRequestReason.REFUSAL, + CommunicationRequestEmitter.TOOL, surveyUnit, status2)); + surveyUnit.setCommunicationRequests(communicationRequestDBs); + + SurveyUnitDetailDto surveyUnitDetailDto = new SurveyUnitDetailDto(surveyUnit); + + List status1Expected = List.of( + new CommunicationRequestStatusDto(1233456789L, CommunicationStatusType.INITIATED), + new CommunicationRequestStatusDto(123345678910L, CommunicationStatusType.FAILED) + ); + + List status2Expected = List.of( + new CommunicationRequestStatusDto(123345678911L, CommunicationStatusType.READY), + new CommunicationRequestStatusDto(123345678912L, CommunicationStatusType.CANCELLED) + ); + + assertThat(surveyUnitDetailDto.getCommunicationRequests()) + .containsExactlyInAnyOrder( + new CommunicationRequestResponseDto("mesh1", "SIMPSONS2020X00", "mesh1", + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, status1Expected), + new CommunicationRequestResponseDto("mesh2", "SIMPSONS2020X00", "mesh2", + CommunicationRequestReason.REFUSAL, + CommunicationRequestEmitter.TOOL, status2Expected) + ); + } } diff --git a/src/test/java/fr/insee/pearljam/api/utils/AuthenticatedUserTestHelper.java b/src/test/java/fr/insee/pearljam/api/utils/AuthenticatedUserTestHelper.java index 0382e0ac..db3f1491 100644 --- a/src/test/java/fr/insee/pearljam/api/utils/AuthenticatedUserTestHelper.java +++ b/src/test/java/fr/insee/pearljam/api/utils/AuthenticatedUserTestHelper.java @@ -16,13 +16,13 @@ public class AuthenticatedUserTestHelper { - public final static Authentication AUTH_LOCAL_USER = getAuthenticatedUser("abc", + public static final Authentication AUTH_LOCAL_USER = getAuthenticatedUser("abc", AuthorityRole.LOCAL_USER); - public final static Authentication AUTH_INTERVIEWER = getAuthenticatedUser("INTW1", + public static final Authentication AUTH_INTERVIEWER = getAuthenticatedUser("INTW1", AuthorityRole.INTERVIEWER); - public final static Authentication AUTH_ADMIN = getAuthenticatedUser("GUEST", + public static final Authentication AUTH_ADMIN = getAuthenticatedUser("ADMIN", AuthorityRole.ADMIN); - public final static Authentication NOT_AUTHENTICATED = getNotAuthenticatedUser(); + public static final Authentication NOT_AUTHENTICATED = getNotAuthenticatedUser(); public static Authentication getAuthenticatedUser(String id, AuthorityRole... roles) { List authorities = Stream.of(roles) diff --git a/src/test/java/fr/insee/pearljam/api/utils/JsonTestHelper.java b/src/test/java/fr/insee/pearljam/api/utils/JsonTestHelper.java index e0dc952c..5f9f4438 100644 --- a/src/test/java/fr/insee/pearljam/api/utils/JsonTestHelper.java +++ b/src/test/java/fr/insee/pearljam/api/utils/JsonTestHelper.java @@ -1,16 +1,18 @@ package fr.insee.pearljam.api.utils; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; -public class JsonTestHelper { +public final class JsonTestHelper { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); public JsonTestHelper() { throw new IllegalArgumentException("Utility class"); } public static String toJson(Object object) throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - return objectMapper.writeValueAsString(object); + return OBJECT_MAPPER.writeValueAsString(object); } } diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java index a082ada3..7a367f04 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/CampaignServiceImplTest.java @@ -33,7 +33,7 @@ class CampaignServiceImplTest { private CampaignFakeRepository campaignRepository; private VisibilityFakeService visibilityService; private CampaignServiceImpl campaignService; - private CurrentDateService dateService = new CurrentDateService(); + private final CurrentDateService dateService = new CurrentDateService(); private final OrganizationUnit existingOrganizationUnit = new OrganizationUnit("OU-NORTH", "label-ou", OrganizationUnitType.LOCAL); private final Campaign existingCampaign = new Campaign( "CAMPAIGN-ID", @@ -41,7 +41,8 @@ class CampaignServiceImplTest { IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - "email@email.com"); + "email@email.com", + false); private final Visibility existingVisibility1 = new Visibility(existingCampaign.getId(), existingOrganizationUnit.getId(), 1721683250000L, @@ -92,9 +93,9 @@ void setup() { @Test @DisplayName("Should create a new campaign successfully") void shouldCreateNewCampaign() throws CampaignAlreadyExistException, OrganizationalUnitNotFoundException, VisibilityHasInvalidDatesException { - String campaignId = "CAMP1"; + String campaignId = "SIMPSONS2020X00"; - CommunicationTemplateCreateDto communicationTemplateDto = new CommunicationTemplateCreateDto("meshuggahId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CommunicationTemplateCreateDto communicationTemplateDto = new CommunicationTemplateCreateDto( "meshuggahId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); VisibilityCampaignCreateDto visibilityDto = new VisibilityCampaignCreateDto(1721683250000L, 1721683251000L, 1721683252000L, 1721683253000L, 1721683254000L, 1721683255000L, existingOrganizationUnit.getId(), true, "mail", "tel"); @@ -107,7 +108,8 @@ void shouldCreateNewCampaign() throws CampaignAlreadyExistException, Organizatio null, IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F + ContactAttemptConfiguration.F2F, + false ); campaignService.createCampaign(campaignCreateDto); @@ -127,7 +129,7 @@ void shouldCreateNewCampaign() throws CampaignAlreadyExistException, Organizatio .hasSize(1) .satisfiesExactly(communicationTemplateDB -> assertThat(CommunicationTemplateDB.toModel(communicationTemplateDB)) - .isEqualTo(CommunicationTemplateCreateDto.toModel(communicationTemplateDto))); + .isEqualTo(CommunicationTemplateCreateDto.toModel(communicationTemplateDto, campaignId))); } @Test @@ -146,7 +148,8 @@ void shouldThrowCampaignAlreadyExistExceptionWhenCreatingExistingCampaign() { null, IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, - ContactAttemptConfiguration.F2F + ContactAttemptConfiguration.F2F, + false ); assertThatThrownBy(() -> campaignService.createCampaign(existingCampaignDto)) @@ -169,7 +172,6 @@ void shouldUpdateExistingCampaign() throws CampaignNotFoundException, Visibility List.of(visibilityDto), List.of(), "emailUpdated@email.com", - IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); @@ -181,7 +183,7 @@ void shouldUpdateExistingCampaign() throws CampaignNotFoundException, Visibility assertThat(updatedCampaign.getId()).isEqualTo(campaignId); assertThat(updatedCampaign.getLabel()).isEqualTo(updateDto.campaignLabel()); assertThat(updatedCampaign.getEmail()).isEqualTo(updateDto.email()); - assertThat(updatedCampaign.getIdentificationConfiguration()).isEqualTo(updateDto.identificationConfiguration()); + assertThat(updatedCampaign.getIdentificationConfiguration()).isEqualTo(existingCampaign.getIdentificationConfiguration()); assertThat(updatedCampaign.getContactAttemptConfiguration()).isEqualTo(updateDto.contactAttemptConfiguration()); assertThat(updatedCampaign.getContactOutcomeConfiguration()).isEqualTo(updateDto.contactOutcomeConfiguration()); assertThat(updatedCampaign.getVisibilities()) @@ -205,7 +207,6 @@ void shouldNotUpdateEmailIfNull(String emailToUpdate) throws CampaignNotFoundExc null, null, emailToUpdate, - IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); @@ -228,7 +229,6 @@ void shouldNotUpdateVisibilitiesIfNull() throws CampaignNotFoundException, Visib null, null, null, - IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); @@ -250,7 +250,6 @@ void shouldNotUpdateReferentsIfNull() throws VisibilityHasInvalidDatesException, null, null, null, - IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); @@ -271,7 +270,6 @@ void shouldThrowCampaignNotFoundExceptionWhenUpdatingNonExistentCampaign() { null, null, null, - IdentificationConfiguration.NOIDENT, ContactOutcomeConfiguration.TEL, ContactAttemptConfiguration.TEL); diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CampaignFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CampaignFakeRepository.java index 3bf84ad4..f9884cbd 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CampaignFakeRepository.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/CampaignFakeRepository.java @@ -19,7 +19,7 @@ public class CampaignFakeRepository implements CampaignRepository { - private List campaigns = new ArrayList<>(); + private final List campaigns = new ArrayList<>(); @Getter private Campaign savedCampaign; @@ -31,11 +31,6 @@ public Optional findByIdIgnoreCase(String id) { .findFirst(); } - @Override - public List findAllIds() { - return List.of(); - } - @Override public List findAllIdsVisible(List ouIds, Long date) { return List.of(); diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/MessageFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/MessageFakeRepository.java index 220c4db3..25dc2097 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/MessageFakeRepository.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/MessageFakeRepository.java @@ -80,11 +80,6 @@ public void deleteOUMessageRecipientByMessageId(Long messageId) { } - @Override - public void deleteMessageStatusByMessageId(Long messageId) { - - } - @Override public List findAllBySenderId(String userId) { return List.of(); diff --git a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/SurveyUnitFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/SurveyUnitFakeRepository.java index 5357220a..a36b3db5 100644 --- a/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/SurveyUnitFakeRepository.java +++ b/src/test/java/fr/insee/pearljam/domain/campaign/service/dummy/SurveyUnitFakeRepository.java @@ -37,27 +37,37 @@ public List findAllIds() { } @Override - public List findIdsByCampaignIdAndOu(String id, String ouId) { + public List findSurveyUnitIdsOfOrganizationUnitsInProcessingPhaseByIdentificationConfiguration(Long date, List lstOuId, IdentificationConfiguration config) { return List.of(); } @Override - public List findAllSurveyUnitsInProcessingPhase(Long date) { + public List findClosableNoIdentSurveyUnitId(List ids) { return List.of(); } @Override - public List findSurveyUnitIdsOfOrganizationUnitsInProcessingPhaseByIdentificationConfiguration(Long date, List lstOuId, IdentificationConfiguration config) { + public List findClosableHousef2fSurveyUnitId(List ids) { return List.of(); } @Override - public List findClosableNoIdentSurveyUnitId(List ids) { + public List findClosableIndf2fFSurveyUnitId(List ids) { return List.of(); } @Override - public List findClosableIascoSurveyUnitId(List ids) { + public List findClosableIndf2fnorFSurveyUnitId(List ids) { + return List.of(); + } + + @Override + public List findClosableIndtelFSurveyUnitId(List ids) { + return List.of(); + } + + @Override + public List findClosableIndtelnorFSurveyUnitId(List ids) { return List.of(); } @@ -81,10 +91,6 @@ public List findByOrganizationUnitIdIn(List lstOuId) { return List.of(); } - @Override - public void updateAllinterviewersToNull() { - - } @Override public List findByIdInOrganizationalUnit(String id, List organizationalUnitIds) { @@ -108,12 +114,12 @@ public List findAllIdsByInterviewerId(String interviewerId) { @Override public void setInterviewer(List surveyUnitIds, String interviewerId) { - + //not used yet } @Override public void flush() { - + //not used yet } @Override @@ -128,17 +134,17 @@ public List saveAllAndFlush(Iterable entities) { @Override public void deleteAllInBatch(Iterable entities) { - + //not used yet } @Override public void deleteAllByIdInBatch(Iterable strings) { - + //not used yet } @Override public void deleteAllInBatch() { - + //not used yet } @Override @@ -228,27 +234,27 @@ public long count() { @Override public void deleteById(String s) { - + //not used yet } @Override public void delete(SurveyUnit entity) { - + //not used yet } @Override public void deleteAllById(Iterable strings) { - + //not used yet } @Override public void deleteAll(Iterable entities) { - + //not used yet } @Override public void deleteAll() { - + //not used yet } @Override diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java index 4a4b0ee9..bf612dcf 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/model/CommunicationRequestTest.java @@ -3,27 +3,27 @@ import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestEmitter; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestReason; -import org.junit.jupiter.api.Test; - import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.Test; class CommunicationRequestTest { @Test void testCreateCommunicationRequest() { // Given - Long communicationTemplateId = 1L; + String meshuggahId = "mesh1"; + String campaignId = "SIMPSONS2020X00"; Long creationDate = System.currentTimeMillis(); Long readyDate = System.currentTimeMillis(); CommunicationRequestReason reason = CommunicationRequestReason.REFUSAL; // When - CommunicationRequest communicationRequest = CommunicationRequest.create(communicationTemplateId, creationDate, readyDate, reason); + CommunicationRequest communicationRequest = CommunicationRequest.create(campaignId,meshuggahId, creationDate, readyDate, reason); // Then assertThat(communicationRequest).isNotNull(); - assertThat(communicationRequest.id()).isNull(); - assertThat(communicationTemplateId).isEqualTo(communicationRequest.communicationTemplateId()); + assertThat(communicationRequest.campaignId()).isEqualTo(campaignId); + assertThat(communicationRequest.meshuggahId()).isEqualTo(meshuggahId); assertThat(reason).isEqualTo(communicationRequest.reason()); assertThat(communicationRequest.emitter()).isEqualTo(CommunicationRequestEmitter.INTERVIEWER); assertThat(communicationRequest.status()).hasSize(2); diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/model/IdentificationStateTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/model/IdentificationStateTest.java index 3336900c..0428aa7a 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/model/IdentificationStateTest.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/model/IdentificationStateTest.java @@ -1,113 +1,194 @@ package fr.insee.pearljam.domain.surveyunit.model; -import fr.insee.pearljam.domain.surveyunit.model.question.*; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - import static org.assertj.core.api.Assertions.assertThat; -class IdentificationStateTest { - - @Test - @DisplayName("Should return MISSING when identification is null") - void testState01() { - Identification identification1 = new Identification( - null, - AccessQuestionValue.NACC, - SituationQuestionValue.ORDINARY, - CategoryQuestionValue.VACANT, - OccupantQuestionValue.UNIDENTIFIED); - - List identifications = new ArrayList<>(); - identifications.add(identification1); - identifications.forEach(identificationToCheck -> - assertThat(IdentificationState.getState(identificationToCheck)).isEqualTo(IdentificationState.MISSING)); - } - - @Test - @DisplayName("Should return FINISHED when identification question value is destroy or unidentified") - void testState02() { - Identification identificationDestroy = new Identification( - IdentificationQuestionValue.DESTROY, null, null, null, null); - Identification identificationUnidentified = new Identification( - IdentificationQuestionValue.UNIDENTIFIED, null, null, null, null); - - List identifications = List.of(identificationDestroy, identificationUnidentified); - identifications.forEach(identificationToCheck -> - assertThat(IdentificationState.getState(identificationToCheck)).isEqualTo(IdentificationState.FINISHED)); - } - - @Test - @DisplayName("Should return ONGOING state when access is null") - void testState03() { - Identification identificationToCheck = new Identification( - IdentificationQuestionValue.IDENTIFIED, null, null, null, null); - - assertThat(IdentificationState.getState(identificationToCheck)).isEqualTo(IdentificationState.ONGOING); - } - - @Test - @DisplayName("Should return ONGOING when situation question value is null") - void testState04() { - Identification identificationToCheck = new Identification( - IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, null, null, null); - - assertThat(IdentificationState.getState(identificationToCheck)).isEqualTo(IdentificationState.ONGOING); - } - - @Test - @DisplayName("Should return FINISHED when situation question value is absorbed or no ordinary") - void testState05() { - Identification identificationAbsorbed = new Identification( - IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ABSORBED, null, null); - Identification identificationNoOrdinary = new Identification( - IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.NACC, SituationQuestionValue.NOORDINARY, null, null); - - List identifications = List.of(identificationAbsorbed, identificationNoOrdinary); - identifications.forEach(identificationToCheck -> - assertThat(IdentificationState.getState(identificationToCheck)).isEqualTo(IdentificationState.FINISHED)); - } - - @Test - @DisplayName("Should return ONGOING when category question value is null") - void testState06() { - Identification identificationToCheck = new Identification( - IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, null, null); - - assertThat(IdentificationState.getState(identificationToCheck)).isEqualTo(IdentificationState.ONGOING); - } - - @Test - @DisplayName("Should return FINISHED when category question value is vacant or secondary") - void testState07() { - Identification identificationVacant = new Identification( - IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.VACANT, null); - Identification identificationSecondary = new Identification( - IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.NACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.SECONDARY, null); - - List identifications = List.of(identificationVacant, identificationSecondary); - identifications.forEach(identificationToCheck -> - assertThat(IdentificationState.getState(identificationToCheck)).isEqualTo(IdentificationState.FINISHED)); - } +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.domain.surveyunit.model.question.AccessQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.CategoryQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.IdentificationQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.IndividualStatusQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.InterviewerCanProcessQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.OccupantQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.SituationQuestionValue; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; - @Test - @DisplayName("Should return FINISHED when occupant is not null") - void testState08() { - Identification identificationToCheck = new Identification( - IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.OCCASIONAL, OccupantQuestionValue.IDENTIFIED); +class IdentificationStateTest { - assertThat(IdentificationState.getState(identificationToCheck)).isEqualTo(IdentificationState.FINISHED); + @TestFactory + @DisplayName("Parameterized tests for getState method") + Stream testGetState() { + return provideTestCases().map(testCase -> DynamicTest.dynamicTest( + testCase.getTestName(), + () -> { + IdentificationState result = IdentificationState.getState( + testCase.identification, testCase.configuration + ); + assertThat(testCase.expectedState).isEqualTo(result); + } + )); + } + + + /// | identification | access | situation | category | occupant | interviewer | IdentificationConfiguration | État attendu | + /// | --------------- | ---------- | --------------------- | ------------------ | --------------------- | ------------------- | ---------------------------- | ------------ | + /// | DESTROY | ACC | ORDINARY | PRIMARY | UNIDENTIFIED | --- | HOUSEF2F | FINISHED | + /// | UNIDENTIFIED | ACC | ORDINARY | PRIMARY | UNIDENTIFIED | --- | HOUSEF2F | FINISHED | + /// | IDENTIFIED | null | ORDINARY | PRIMARY | UNIDENTIFIED | --- | HOUSEF2F | ONGOING | + /// | IDENTIFIED | NACC | ORDINARY | PRIMARY | null | --- | HOUSEF2F | ONGOING | + /// | IDENTIFIED | ACC | ABSORBED | PRIMARY | UNIDENTIFIED | --- | HOUSEF2F | FINISHED | + /// | IDENTIFIED | ACC | NOORDINARY | PRIMARY | UNIDENTIFIED | --- | HOUSEF2F | FINISHED | + /// | IDENTIFIED | ACC | ORDINARY | SECONDARY | UNIDENTIFIED | --- | HOUSEF2F | FINISHED | + /// | IDENTIFIED | ACC | ORDINARY | VACANT | UNIDENTIFIED | --- | HOUSEF2F | FINISHED | + /// | IDENTIFIED | ACC | ORDINARY | PRIMARY | null | --- | HOUSEF2F | ONGOING | + /// | IDENTIFIED | ACC | ORDINARY | PRIMARY | IDENTIFIED | --- | HOUSEF2F | FINISHED | + /// | IDENTIFIED | ACC | ORDINARY | PRIMARY | UNIDENTIFIED | --- | HOUSEF2F | FINISHED | + /// | IDENTIFIED | ACC | null | null | null | --- | HOUSEF2F | ONGOING | + /// | IDENTIFIED | ACC | ORDINARY | null | null | --- | HOUSEF2F | ONGOING | + /// | --- | --- | --- | --- | --- | --- | HOUSEF2F | MISSING | + /// | --- | --- | --- | --- | --- | --- | HOUSETEL | MISSING | + /// | IDENTIFIED | ACC | ORDINARY | PRIMARY | IDENTIFIED | --- | INDTEL | FINISHED | + /// | IDENTIFIED | NACC | ABSORBED | SECONDARY | UNIDENTIFIED | --- | INDTEL | FINISHED | + /// | IDENTIFIED | ACC | NOORDINARY | VACANT | IDENTIFIED | --- | INDTEL | FINISHED | + /// | IDENTIFIED | NACC | ORDINARY | PRIMARY | UNIDENTIFIED | --- | INDTEL | FINISHED | + /// | IDENTIFIED | ACC | ORDINARY | PRIMARY | IDENTIFIED | --- | INDTEL | FINISHED | + /// | IDENTIFIED | ACC | null | VACANT | UNIDENTIFIED | --- | INDTEL | ONGOING | + /// | IDENTIFIED | NACC | ABSORBED | SECONDARY | IDENTIFIED | --- | INDTEL | ONGOING | + /// | IDENTIFIED | ACC | ORDINARY | PRIMARY | IDENTIFIED | --- | INDF2F | FINISHED | + /// | UNIDENTIFIED | NACC | NOORDINARY | SECONDARY | UNIDENTIFIED | --- | INDF2F | FINISHED | + /// | DESTROY | ACC | ABSORBED | VACANT | UNIDENTIFIED | --- | INDF2F | FINISHED | + /// | IDENTIFIED | ACC | null | PRIMARY | UNIDENTIFIED | --- | INDF2F | ONGOING | + /// | IDENTIFIED | ACC | ORDINARY | PRIMARY | IDENTIFIED | --- | INDF2F | FINISHED | + /// | IDENTIFIED | ACC | NOORDINARY | SECONDARY | null | --- | INDF2F | ONGOING | + /// | IDENTIFIED | NACC | ABSORBED | VACANT | UNIDENTIFIED | NO | INDF2F | FINISHED | + /// | IDENTIFIED | ACC | NOORDINARY | SECONDARY | UNIDENTIFIED | --- | INDF2F | FINISHED | + /// | IDENTIFIED | ACC | ORDINARY | PRIMARY | IDENTIFIED | --- | INDF2F | FINISHED | + /// | IDENTIFIED | ACC | ORDINARY | PRIMARY | UNIDENTIFIED | YES | INDF2F | ONGOING | + /// | IDENTIFIED | ACC | NOORDINARY | PRIMARY | UNIDENTIFIED | NO | INDF2F | ONGOING | + /// | IDENTIFIED | ACC | ABSORBED | PRIMARY | UNIDENTIFIED | --- | INDF2F | FINISHED | + /// | IDENTIFIED | ACC | ORDINARY | PRIMARY | UNIDENTIFIED | NO | INDF2F | ONGOING | + /// | IDENTIFIED | ACC | ABSORBED | PRIMARY | UNIDENTIFIED | --- | INDF2F | ONGOING | + /// | IDENTIFIED | ACC | ORDINARY | PRIMARY | UNIDENTIFIED | YES | INDF2F | FINISHED | + /// | IDENTIFIED | ACC | NOORDINARY | PRIMARY | UNIDENTIFIED | NO | INDF2F | FINISHED | + /// | IDENTIFIED | ACC | ORDINARY | PRIMARY | --- | NO | INDTEL | FINISHED | + + + private static Stream provideTestCases() { + return Stream.of( + new TestCase(null, IdentificationConfiguration.NOIDENT, IdentificationState.MISSING), + new TestCase(null, IdentificationConfiguration.HOUSEF2F, IdentificationState.MISSING), + new TestCase(null, IdentificationConfiguration.INDF2F, IdentificationState.MISSING), + new TestCase(null, IdentificationConfiguration.INDTEL, IdentificationState.MISSING), + new TestCase(Identification.builder().build(), IdentificationConfiguration.NOIDENT, IdentificationState.MISSING), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.DESTROY, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED), IdentificationConfiguration.HOUSEF2F, IdentificationState.FINISHED), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.UNIDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED), IdentificationConfiguration.HOUSEF2F, IdentificationState.FINISHED), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.IDENTIFIED, null, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED), IdentificationConfiguration.HOUSEF2F, IdentificationState.ONGOING), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.NACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, null), IdentificationConfiguration.HOUSEF2F, IdentificationState.ONGOING), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ABSORBED, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED), IdentificationConfiguration.HOUSEF2F, IdentificationState.FINISHED), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.NOORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED), IdentificationConfiguration.HOUSEF2F, IdentificationState.FINISHED), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.SECONDARY, OccupantQuestionValue.UNIDENTIFIED), IdentificationConfiguration.HOUSEF2F, IdentificationState.FINISHED), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.VACANT, OccupantQuestionValue.UNIDENTIFIED), IdentificationConfiguration.HOUSEF2F, IdentificationState.FINISHED), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, null), IdentificationConfiguration.HOUSEF2F, IdentificationState.ONGOING), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.IDENTIFIED), IdentificationConfiguration.HOUSEF2F, IdentificationState.FINISHED), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED), IdentificationConfiguration.HOUSEF2F, IdentificationState.FINISHED), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, null,null,null), IdentificationConfiguration.HOUSEF2F, IdentificationState.ONGOING), + new TestCase(buildHouseF2FIdentification(IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY,null,null), IdentificationConfiguration.HOUSEF2F, IdentificationState.ONGOING), + new TestCase(Identification.builder().build(), IdentificationConfiguration.HOUSEF2F, IdentificationState.MISSING), + new TestCase(Identification.builder().build(), IdentificationConfiguration.HOUSETEL, IdentificationState.MISSING), + new TestCase(buildIndividuTelIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.DCD, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.IDENTIFIED), IdentificationConfiguration.INDTEL, IdentificationState.FINISHED), + new TestCase(buildIndividuTelIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.DCD, AccessQuestionValue.NACC, SituationQuestionValue.ABSORBED, CategoryQuestionValue.SECONDARY, OccupantQuestionValue.UNIDENTIFIED), IdentificationConfiguration.INDTEL, IdentificationState.FINISHED), + new TestCase(buildIndividuTelIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.NOIDENT, AccessQuestionValue.ACC, SituationQuestionValue.NOORDINARY, CategoryQuestionValue.VACANT, OccupantQuestionValue.IDENTIFIED), IdentificationConfiguration.INDTEL, IdentificationState.FINISHED), + new TestCase(buildIndividuTelIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.NOFIELD, AccessQuestionValue.NACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED), IdentificationConfiguration.INDTEL, IdentificationState.FINISHED), + new TestCase(buildIndividuTelIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.SAME_ADDRESS, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.IDENTIFIED), IdentificationConfiguration.INDTEL, IdentificationState.FINISHED), + new TestCase(buildIndividuTelIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.SAME_ADDRESS, AccessQuestionValue.ACC, null, CategoryQuestionValue.VACANT, OccupantQuestionValue.UNIDENTIFIED), IdentificationConfiguration.INDTEL, IdentificationState.ONGOING), + new TestCase(buildIndividuTelIdentification(IdentificationQuestionValue.IDENTIFIED, null, AccessQuestionValue.NACC, SituationQuestionValue.ABSORBED, CategoryQuestionValue.SECONDARY, OccupantQuestionValue.IDENTIFIED), IdentificationConfiguration.INDTEL, IdentificationState.ONGOING), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.DCD, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.IDENTIFIED, null), IdentificationConfiguration.INDF2F, IdentificationState.FINISHED), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.UNIDENTIFIED, IndividualStatusQuestionValue.NOIDENT, AccessQuestionValue.NACC, SituationQuestionValue.NOORDINARY, CategoryQuestionValue.SECONDARY, OccupantQuestionValue.UNIDENTIFIED, null), IdentificationConfiguration.INDF2F, IdentificationState.FINISHED), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.DESTROY, IndividualStatusQuestionValue.NOFIELD, AccessQuestionValue.ACC, SituationQuestionValue.ABSORBED, CategoryQuestionValue.VACANT, OccupantQuestionValue.UNIDENTIFIED, null), IdentificationConfiguration.INDF2F, IdentificationState.FINISHED), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.SAME_ADDRESS, AccessQuestionValue.ACC, null, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED, null), IdentificationConfiguration.INDF2F, IdentificationState.ONGOING), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.SAME_ADDRESS, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.IDENTIFIED, null), IdentificationConfiguration.INDF2F, IdentificationState.FINISHED), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.OTHER_ADDRESS, AccessQuestionValue.ACC, SituationQuestionValue.NOORDINARY, CategoryQuestionValue.SECONDARY, null, null), IdentificationConfiguration.INDF2F, IdentificationState.ONGOING), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.OTHER_ADDRESS, AccessQuestionValue.NACC, SituationQuestionValue.ABSORBED, CategoryQuestionValue.VACANT, OccupantQuestionValue.UNIDENTIFIED, InterviewerCanProcessQuestionValue.NO), IdentificationConfiguration.INDF2F, IdentificationState.FINISHED), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.SAME_ADDRESS, AccessQuestionValue.ACC, SituationQuestionValue.NOORDINARY, CategoryQuestionValue.SECONDARY, OccupantQuestionValue.UNIDENTIFIED, null), IdentificationConfiguration.INDF2F, IdentificationState.FINISHED), + new TestCase(buildIndividuTelIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.OTHER_ADDRESS, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.IDENTIFIED), IdentificationConfiguration.INDTEL, IdentificationState.FINISHED), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.OTHER_ADDRESS, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED, InterviewerCanProcessQuestionValue.YES), IdentificationConfiguration.INDF2F, null), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.OTHER_ADDRESS, AccessQuestionValue.ACC, SituationQuestionValue.NOORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED, InterviewerCanProcessQuestionValue.YES), IdentificationConfiguration.INDF2F, IdentificationState.FINISHED), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.OTHER_ADDRESS, AccessQuestionValue.ACC, SituationQuestionValue.NOORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED, InterviewerCanProcessQuestionValue.NO), IdentificationConfiguration.INDF2F, IdentificationState.FINISHED), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.OTHER_ADDRESS, AccessQuestionValue.ACC, SituationQuestionValue.ABSORBED, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED, null), IdentificationConfiguration.INDF2F, IdentificationState.ONGOING), + new TestCase(buildIndividuF2FIdentification(IdentificationQuestionValue.IDENTIFIED,null, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, OccupantQuestionValue.UNIDENTIFIED, InterviewerCanProcessQuestionValue.NO), IdentificationConfiguration.INDF2F, IdentificationState.ONGOING) + + ); + } + + private static Identification buildHouseF2FIdentification( + IdentificationQuestionValue identification, + AccessQuestionValue access, + SituationQuestionValue situation, + CategoryQuestionValue category, + OccupantQuestionValue occupant) { + + return Identification.builder() + .identification(identification) + .access(access) + .situation(situation) + .category(category) + .occupant(occupant) + .build(); + } + + + private static Identification buildIndividuTelIdentification( + IdentificationQuestionValue identification, + IndividualStatusQuestionValue individualStatus, + AccessQuestionValue access, + SituationQuestionValue situation, + CategoryQuestionValue category, + OccupantQuestionValue occupant) { + + return Identification.builder() + .individualStatus(individualStatus) + .access(access) + .situation(situation) + .category(category) + .occupant(occupant) + .identification(identification) + .build(); + } + + private static Identification buildIndividuF2FIdentification( + IdentificationQuestionValue identification, + IndividualStatusQuestionValue individualStatus, + AccessQuestionValue access, + SituationQuestionValue situation, + CategoryQuestionValue category, + OccupantQuestionValue occupant, + InterviewerCanProcessQuestionValue interview) { + + return Identification.builder() + .individualStatus(individualStatus) + .access(access) + .situation(situation) + .category(category) + .occupant(occupant) + .identification(identification) + .interviewerCanProcess(interview) + .build(); + } + + + // Helper class to represent a test case + private record TestCase(Identification identification, IdentificationConfiguration configuration, + IdentificationState expectedState) { + + String getTestName() { + return String.format( + "Given configuration %s, identification %s, expect state %s", + configuration, identification, expectedState + ); } - @Test - @DisplayName("Should return ONGOING state") - void testState09() { - Identification identificationToCheck = new Identification( - IdentificationQuestionValue.IDENTIFIED, AccessQuestionValue.ACC, SituationQuestionValue.ORDINARY, CategoryQuestionValue.OCCASIONAL, null); + } - assertThat(IdentificationState.getState(identificationToCheck)).isEqualTo(IdentificationState.ONGOING); - } } diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java index 46e01280..bea204b7 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/SurveyUnitUpdateServiceImplTest.java @@ -1,293 +1,362 @@ package fr.insee.pearljam.domain.surveyunit.service; import fr.insee.pearljam.api.campaign.controller.dummy.VisibilityFakeService; -import fr.insee.pearljam.api.domain.*; +import fr.insee.pearljam.api.domain.Campaign; +import fr.insee.pearljam.api.domain.ContactOutcomeType; +import fr.insee.pearljam.api.domain.IdentificationConfiguration; +import fr.insee.pearljam.api.domain.OrganizationUnit; +import fr.insee.pearljam.api.domain.OrganizationUnitType; +import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.api.service.impl.SurveyUnitUpdateServiceImpl; -import fr.insee.pearljam.api.surveyunit.dto.*; -import fr.insee.pearljam.domain.campaign.port.userside.DateService; -import fr.insee.pearljam.domain.campaign.service.dummy.FixedDateService; +import fr.insee.pearljam.api.surveyunit.dto.CommentDto; +import fr.insee.pearljam.api.surveyunit.dto.CommunicationRequestCreateDto; +import fr.insee.pearljam.api.surveyunit.dto.ContactOutcomeDto; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; +import fr.insee.pearljam.api.surveyunit.dto.identification.RawIdentificationDto; import fr.insee.pearljam.domain.campaign.model.Visibility; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationMedium; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationTemplate; import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; +import fr.insee.pearljam.domain.campaign.port.userside.DateService; +import fr.insee.pearljam.domain.campaign.service.dummy.FixedDateService; import fr.insee.pearljam.domain.surveyunit.model.CommentType; -import fr.insee.pearljam.domain.surveyunit.model.communication.*; -import fr.insee.pearljam.domain.surveyunit.model.question.*; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestEmitter; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestReason; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationStatusType; +import fr.insee.pearljam.domain.surveyunit.model.question.AccessQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.CategoryQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.HouseholdCompositionQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.IdentificationQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.IndividualStatusQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.InterviewerCanProcessQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.NumberOfRespondentsQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.OccupantQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.PresentInPreviousHomeQuestionValue; +import fr.insee.pearljam.domain.surveyunit.model.question.SituationQuestionValue; import fr.insee.pearljam.domain.surveyunit.service.dummy.CommunicationRequestFakeRepository; import fr.insee.pearljam.domain.surveyunit.service.dummy.CommunicationTemplateFakeRepository; -import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDBId; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommentDB; import fr.insee.pearljam.infrastructure.surveyunit.entity.CommunicationRequestDB; -import fr.insee.pearljam.infrastructure.surveyunit.entity.IdentificationDB; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - +import fr.insee.pearljam.infrastructure.surveyunit.entity.ContactOutcomeDB; +import fr.insee.pearljam.infrastructure.surveyunit.entity.identification.HouseF2FIdentificationDB; +import fr.insee.pearljam.infrastructure.surveyunit.entity.identification.IdentificationDB; import java.util.HashSet; import java.util.List; import java.util.Set; - +import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; class SurveyUnitUpdateServiceImplTest { - private CommunicationRequestFakeRepository communicationRequestFakeRepository; - private VisibilityFakeService visibilityFakeService; - private SurveyUnitUpdateServiceImpl surveyUnitService; - private SurveyUnit surveyUnit; - private SurveyUnitUpdateDto surveyUnitDto; - private DateService dateService; - private CommunicationTemplateDB communicationTemplateDB; - private CommunicationTemplate communicationTemplate; - private CommunicationTemplateFakeRepository communicationTemplateFakeRepository; - private Campaign campaign; - private OrganizationUnit ou; + private CommunicationRequestFakeRepository communicationRequestFakeRepository; + private VisibilityFakeService visibilityFakeService; + private SurveyUnitUpdateServiceImpl surveyUnitService; + private SurveyUnit surveyUnit; + private SurveyUnitUpdateDto surveyUnitDto; + private DateService dateService; + private CommunicationTemplate communicationTemplate; + private CommunicationTemplateFakeRepository communicationTemplateFakeRepository; + private Campaign campaign; + private OrganizationUnit ou; + + @BeforeEach + void setup() { + visibilityFakeService = new VisibilityFakeService(); + communicationTemplateFakeRepository = new CommunicationTemplateFakeRepository(); + dateService = new FixedDateService(); + communicationRequestFakeRepository = new CommunicationRequestFakeRepository(); + surveyUnitService = new SurveyUnitUpdateServiceImpl(communicationRequestFakeRepository, + communicationTemplateFakeRepository, visibilityFakeService, dateService); + campaign = new Campaign("campaignId", "label", null, null, null, null, false); + ou = new OrganizationUnit("ouId", "label-ou", OrganizationUnitType.LOCAL); + Visibility visibility = new Visibility(campaign.getId(), ou.getId(), null, null, + null, null, null, null, true, "mail", "tel"); + visibilityFakeService.save(visibility); + surveyUnit = new SurveyUnit("id", true, true, null, + null, campaign, null, ou, null); + + communicationTemplate = new CommunicationTemplate("SIMPSONS2020X00", "messhId", CommunicationMedium.EMAIL, + CommunicationType.NOTICE); + communicationTemplateFakeRepository.save(communicationTemplate); + Set communicationRequestDBs = new HashSet<>(); + communicationRequestDBs.add(new CommunicationRequestDB(10L, new CommunicationTemplateDBId("mesh1","SIMPSONS2020X00"), + CommunicationRequestReason.REFUSAL, + CommunicationRequestEmitter.TOOL, + surveyUnit, null)); + surveyUnit.setCommunicationRequests(communicationRequestDBs); + } + + @Test + @DisplayName("Should add communication requests for survey unit") + void testUpdateCommunication01() { + List communicationRequests = List.of( + new CommunicationRequestCreateDto(communicationTemplate.meshuggahId(), 12345678910L, + CommunicationRequestReason.UNREACHABLE), + new CommunicationRequestCreateDto(communicationTemplate.meshuggahId(), 1234567891011L, + CommunicationRequestReason.REFUSAL) + ); + + surveyUnitDto = createSurveyUnitDto(null, null, communicationRequests, null); + surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); + + List communicationRequestResults = + communicationRequestFakeRepository.getCommunicationRequestsAdded(); + assertThat(communicationRequestResults) + .hasSize(2) + .extracting(CommunicationRequest::campaignId, + CommunicationRequest::meshuggahId, + CommunicationRequest::reason, + CommunicationRequest::emitter, + communicationRequest -> communicationRequest.status().stream() + .map(status -> tuple(status.id(), status.date(), status.status())) + .toList() + ) + .containsExactlyInAnyOrder( + tuple("campaignId", + communicationTemplate.meshuggahId(), + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, + List.of( + tuple(null, 12345678910L, CommunicationStatusType.INITIATED), + tuple(null, dateService.getCurrentTimestamp(), CommunicationStatusType.READY) + ) + ), + tuple("campaignId", + communicationTemplate.meshuggahId(), + CommunicationRequestReason.REFUSAL, + CommunicationRequestEmitter.INTERVIEWER, + List.of( + tuple(null, 1234567891011L, CommunicationStatusType.INITIATED), + tuple(null, dateService.getCurrentTimestamp(), CommunicationStatusType.READY) + ) + ) + ); + } - @BeforeEach - void setup() { - visibilityFakeService = new VisibilityFakeService(); - communicationTemplateFakeRepository = new CommunicationTemplateFakeRepository(); - dateService = new FixedDateService(); - communicationRequestFakeRepository = new CommunicationRequestFakeRepository(); - surveyUnitService = new SurveyUnitUpdateServiceImpl(communicationRequestFakeRepository, communicationTemplateFakeRepository, visibilityFakeService, dateService); - campaign = new Campaign("campaignId", "label", null, null, null,null); - ou = new OrganizationUnit("ouId", "label-ou", OrganizationUnitType.LOCAL); - Visibility visibility = new Visibility(campaign.getId(), ou.getId(), null, null, - null, null, null, null, true, "mail", "tel"); - visibilityFakeService.save(visibility); - surveyUnit = new SurveyUnit("id", true, true, null, - null, campaign, null, ou, null); + @Test + @DisplayName("Should add CANCELLED letter communication request if visibility doesn't allow letter communications") + void testUpdateCommunication02() { + visibilityFakeService.clearVisibilities(); + communicationTemplateFakeRepository.clearCommunicationTemplates(); + Visibility visibility = new Visibility(campaign.getId(), ou.getId(), null, null, + null, null, null, null, false, "mail", "tel"); + communicationTemplate = new CommunicationTemplate("SIMPSONS2020X00","messhId", CommunicationMedium.LETTER, + CommunicationType.NOTICE); + communicationTemplateFakeRepository.save(communicationTemplate); + visibilityFakeService.save(visibility); + List communicationRequests = List.of( + new CommunicationRequestCreateDto(communicationTemplate.meshuggahId(), 12345678910L, + CommunicationRequestReason.UNREACHABLE), + new CommunicationRequestCreateDto(communicationTemplate.meshuggahId(), 1234567891011L, + CommunicationRequestReason.REFUSAL) + ); - communicationTemplate = new CommunicationTemplate(3L, "messhId", CommunicationMedium.EMAIL, CommunicationType.NOTICE); - communicationTemplateFakeRepository.save(communicationTemplate); - communicationTemplateDB = new CommunicationTemplateDB(3L, "messhId", CommunicationMedium.EMAIL, CommunicationType.NOTICE, campaign); - Set communicationRequestDBs = new HashSet<>(); - communicationRequestDBs.add(new CommunicationRequestDB(10L, communicationTemplateDB, - CommunicationRequestReason.REFUSAL, - CommunicationRequestEmitter.TOOL, - surveyUnit, null)); - surveyUnit.setCommunicationRequests(communicationRequestDBs); - } + surveyUnitDto = createSurveyUnitDto(null, null, communicationRequests, null); + surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); - @Test - @DisplayName("Should add communication requests for survey unit") - void testUpdateCommunication01() { - List communicationRequests = List.of( - new CommunicationRequestCreateDto(communicationTemplate.id(), 12345678910L, - CommunicationRequestReason.UNREACHABLE), - new CommunicationRequestCreateDto(communicationTemplate.id(), 1234567891011L, - CommunicationRequestReason.REFUSAL) - ); + List communicationRequestResults = + communicationRequestFakeRepository.getCommunicationRequestsAdded(); + assertThat(communicationRequestResults) + .hasSize(2) + .extracting(CommunicationRequest::campaignId, + CommunicationRequest::meshuggahId, + CommunicationRequest::reason, + CommunicationRequest::emitter, + communicationRequest -> communicationRequest.status().stream() + .map(status -> tuple(status.id(), status.date(), status.status())) + .toList() + ) + .containsExactlyInAnyOrder( + tuple("campaignId", + communicationTemplate.meshuggahId(), + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, + List.of( + tuple(null, 12345678910L, CommunicationStatusType.INITIATED), + tuple(null, dateService.getCurrentTimestamp(), + CommunicationStatusType.CANCELLED)) + ), + tuple("campaignId", + communicationTemplate.meshuggahId(), + CommunicationRequestReason.REFUSAL, + CommunicationRequestEmitter.INTERVIEWER, + List.of( + tuple(null, 1234567891011L, CommunicationStatusType.INITIATED), + tuple(null, dateService.getCurrentTimestamp(), + CommunicationStatusType.CANCELLED)) + ) + ); + } - surveyUnitDto = createSurveyUnitDto(null, null, communicationRequests); - surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); + @Test + @DisplayName("Should add comments for survey unit") + void testUpdateComments01() { + List comments = List.of( + new CommentDto(CommentType.INTERVIEWER, "value1"), + new CommentDto(CommentType.MANAGEMENT, "value2") + ); - List communicationRequestResults = communicationRequestFakeRepository.getCommunicationRequestsAdded(); - assertThat(communicationRequestResults) - .hasSize(2) - .extracting(CommunicationRequest::id, - CommunicationRequest::communicationTemplateId, - CommunicationRequest::reason, - CommunicationRequest::emitter, - communicationRequest -> communicationRequest.status().stream() - .map(status -> tuple(status.id(), status.date(), status.status())) - .toList() - ) - .containsExactlyInAnyOrder( - tuple(null, - communicationTemplate.id(), - CommunicationRequestReason.UNREACHABLE, - CommunicationRequestEmitter.INTERVIEWER, - List.of( - tuple(null, 12345678910L, CommunicationStatusType.INITIATED), - tuple(null, dateService.getCurrentTimestamp(), CommunicationStatusType.READY) - ) - ), - tuple(null, - communicationTemplate.id(), - CommunicationRequestReason.REFUSAL, - CommunicationRequestEmitter.INTERVIEWER, - List.of( - tuple(null, 1234567891011L, CommunicationStatusType.INITIATED), - tuple(null, dateService.getCurrentTimestamp(), CommunicationStatusType.READY) - ) - ) - ); - } + surveyUnitDto = createSurveyUnitDto(null, comments, null, null); - @Test - @DisplayName("Should add CANCELLED letter communication request if visibility doesn't allow letter communications") - void testUpdateCommunication02() { - visibilityFakeService.clearVisibilities(); - communicationTemplateFakeRepository.clearCommunicationTemplates(); - Visibility visibility = new Visibility(campaign.getId(), ou.getId(), null, null, - null, null, null, null, false, "mail", "tel"); - communicationTemplate = new CommunicationTemplate(3L, "messhId", CommunicationMedium.LETTER, CommunicationType.NOTICE); - communicationTemplateFakeRepository.save(communicationTemplate); - visibilityFakeService.save(visibility); - List communicationRequests = List.of( - new CommunicationRequestCreateDto(communicationTemplate.id(), 12345678910L, - CommunicationRequestReason.UNREACHABLE), - new CommunicationRequestCreateDto(communicationTemplate.id(), 1234567891011L, - CommunicationRequestReason.REFUSAL) - ); + surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); + assertThat(surveyUnit.getComments()) + .hasSize(2) + .extracting(CommentDB::getId, + CommentDB::getType, + CommentDB::getValue, + CommentDB::getSurveyUnit + ).contains( + tuple(null, CommentType.INTERVIEWER, "value1", surveyUnit), + tuple(null, CommentType.MANAGEMENT, "value2", surveyUnit) + ); + } - surveyUnitDto = createSurveyUnitDto(null, null, communicationRequests); - surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); + @Test + @DisplayName("Should remove survey unit comments with same type of inputted comments") + void testUpdateComments02() { + surveyUnit.getComments().addAll(Set.of( + new CommentDB(1L, CommentType.INTERVIEWER, "value1", surveyUnit), + new CommentDB(2L, CommentType.INTERVIEWER, "value2", surveyUnit), + new CommentDB(3L, CommentType.MANAGEMENT, "value3", surveyUnit) + )); - List communicationRequestResults = communicationRequestFakeRepository.getCommunicationRequestsAdded(); - assertThat(communicationRequestResults) - .hasSize(2) - .extracting(CommunicationRequest::id, - CommunicationRequest::communicationTemplateId, - CommunicationRequest::reason, - CommunicationRequest::emitter, - communicationRequest -> communicationRequest.status().stream() - .map(status -> tuple(status.id(), status.date(), status.status())) - .toList() - ) - .containsExactlyInAnyOrder( - tuple(null, - 3L, - CommunicationRequestReason.UNREACHABLE, - CommunicationRequestEmitter.INTERVIEWER, - List.of( - tuple(null, 12345678910L, CommunicationStatusType.INITIATED), - tuple(null, dateService.getCurrentTimestamp(), CommunicationStatusType.CANCELLED)) - ), - tuple(null, - 3L, - CommunicationRequestReason.REFUSAL, - CommunicationRequestEmitter.INTERVIEWER, - List.of( - tuple(null, 1234567891011L, CommunicationStatusType.INITIATED), - tuple(null, dateService.getCurrentTimestamp(), CommunicationStatusType.CANCELLED)) - ) - ); - } + List comments = List.of( + new CommentDto(CommentType.INTERVIEWER, "value4") + ); - @Test - @DisplayName("Should add comments for survey unit") - void testUpdateComments01() { - List comments = List.of( - new CommentDto(CommentType.INTERVIEWER, "value1"), - new CommentDto(CommentType.MANAGEMENT, "value2") - ); + surveyUnitDto = createSurveyUnitDto(null, comments, null, null); - surveyUnitDto = createSurveyUnitDto(null, comments, null); + surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); + assertThat(surveyUnit.getComments()) + .hasSize(2) + .extracting(CommentDB::getId, + CommentDB::getType, + CommentDB::getValue, + CommentDB::getSurveyUnit + ).contains( + tuple(null, CommentType.INTERVIEWER, "value4", surveyUnit), + tuple(3L, CommentType.MANAGEMENT, "value3", surveyUnit) + ); + } - surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); - assertThat(surveyUnit.getComments()) - .hasSize(2) - .extracting(CommentDB::getId, - CommentDB::getType, - CommentDB::getValue, - CommentDB::getSurveyUnit - ).contains( - tuple(null, CommentType.INTERVIEWER, "value1", surveyUnit), - tuple(null, CommentType.MANAGEMENT, "value2", surveyUnit) - ); - } + @Test + @DisplayName("Should update identification") + void testUpdateIdentification01() { + // given an identification in DB + IdentificationDB identificationDB = createHouseF2FIdentificationDB(); + // and a surveyUnit in a HOUSEF2F configuration + surveyUnit.setIdentification(identificationDB); + campaign.setIdentificationConfiguration(IdentificationConfiguration.HOUSEF2F); - @Test - @DisplayName("Should remove survey unit comments with same type of inputted comments") - void testUpdateComments02() { - surveyUnit.getComments().addAll(Set.of( - new CommentDB(1L, CommentType.INTERVIEWER, "value1", surveyUnit), - new CommentDB(2L, CommentType.INTERVIEWER, "value2", surveyUnit), - new CommentDB(3L, CommentType.MANAGEMENT, "value3", surveyUnit) - )); + // When updating the survey unit + RawIdentificationDto identification = new RawIdentificationDto(IdentificationQuestionValue.UNIDENTIFIED, + AccessQuestionValue.NACC, + SituationQuestionValue.NOORDINARY, + CategoryQuestionValue.VACANT, + OccupantQuestionValue.UNIDENTIFIED, + IndividualStatusQuestionValue.OTHER_ADDRESS, + InterviewerCanProcessQuestionValue.NO, + NumberOfRespondentsQuestionValue.MANY, + PresentInPreviousHomeQuestionValue.NONE, + HouseholdCompositionQuestionValue.OTHER_COMPO + ); + surveyUnitDto = createSurveyUnitDto(identification, null, null, null); - List comments = List.of( - new CommentDto(CommentType.INTERVIEWER, "value4") - ); + surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); + HouseF2FIdentificationDB identificationResult = (HouseF2FIdentificationDB) surveyUnit.getIdentification(); + assertThat(identificationResult.getId()).isEqualTo(2L); + assertThat(identificationResult.getIdentification()).isEqualTo(IdentificationQuestionValue.UNIDENTIFIED); + assertThat(identificationResult.getAccess()).isEqualTo(AccessQuestionValue.NACC); + assertThat(identificationResult.getSituation()).isEqualTo(SituationQuestionValue.NOORDINARY); + assertThat(identificationResult.getCategory()).isEqualTo(CategoryQuestionValue.VACANT); + assertThat(identificationResult.getOccupant()).isEqualTo(OccupantQuestionValue.UNIDENTIFIED); + assertThat(identificationResult.getSurveyUnit()).isEqualTo(surveyUnit); + } - surveyUnitDto = createSurveyUnitDto(null, comments, null); + @Test + @DisplayName("Should not update identification entity when identification model is null") + void testUpdateIdentification02() { + IdentificationDB identificationDB = createHouseF2FIdentificationDB(); + surveyUnit.setIdentification(identificationDB); + surveyUnitDto = createSurveyUnitDto(null, null, null, null); + surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); + assertThat(surveyUnit.getIdentification()).isEqualTo(identificationDB); + } - surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); - assertThat(surveyUnit.getComments()) - .hasSize(2) - .extracting(CommentDB::getId, - CommentDB::getType, - CommentDB::getValue, - CommentDB::getSurveyUnit - ).contains( - tuple(null, CommentType.INTERVIEWER, "value4", surveyUnit), - tuple(3L, CommentType.MANAGEMENT, "value3", surveyUnit) - ); - } + @Test + @DisplayName("Should create identification entity when entity does not exist") + void testUpdateIdentification03() { + campaign.setIdentificationConfiguration(IdentificationConfiguration.HOUSEF2F); + surveyUnit.setIdentification(null); + RawIdentificationDto identification = new RawIdentificationDto(IdentificationQuestionValue.UNIDENTIFIED, + AccessQuestionValue.NACC, + SituationQuestionValue.NOORDINARY, + CategoryQuestionValue.VACANT, + OccupantQuestionValue.UNIDENTIFIED, + IndividualStatusQuestionValue.OTHER_ADDRESS, + InterviewerCanProcessQuestionValue.NO, + NumberOfRespondentsQuestionValue.MANY, + PresentInPreviousHomeQuestionValue.NONE, + HouseholdCompositionQuestionValue.OTHER_COMPO); + surveyUnitDto = createSurveyUnitDto(identification, null, null, null); - @Test - @DisplayName("Should update identification") - void testUpdateIdentification01() { - IdentificationDB identificationDB = new IdentificationDB(2L, - IdentificationQuestionValue.IDENTIFIED, - AccessQuestionValue.ACC, - SituationQuestionValue.ORDINARY, - CategoryQuestionValue.SECONDARY, - OccupantQuestionValue.IDENTIFIED, - surveyUnit); - surveyUnit.setIdentification(identificationDB); + surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); - IdentificationDto identification = new IdentificationDto(IdentificationQuestionValue.UNIDENTIFIED, - AccessQuestionValue.NACC, - SituationQuestionValue.NOORDINARY, - CategoryQuestionValue.VACANT, - OccupantQuestionValue.UNIDENTIFIED); - surveyUnitDto = createSurveyUnitDto(identification, null, null); + HouseF2FIdentificationDB identificationResult = (HouseF2FIdentificationDB) surveyUnit.getIdentification(); + assertThat(identificationResult.getId()).isNull(); + assertThat(identificationResult.getIdentification()).isEqualTo(IdentificationQuestionValue.UNIDENTIFIED); + assertThat(identificationResult.getAccess()).isEqualTo(AccessQuestionValue.NACC); + assertThat(identificationResult.getSituation()).isEqualTo(SituationQuestionValue.NOORDINARY); + assertThat(identificationResult.getCategory()).isEqualTo(CategoryQuestionValue.VACANT); + assertThat(identificationResult.getOccupant()).isEqualTo(OccupantQuestionValue.UNIDENTIFIED); + assertThat(identificationResult.getSurveyUnit()).isEqualTo(surveyUnit); + } - surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); - IdentificationDB identificationResult = surveyUnit.getIdentification(); - assertThat(identificationResult.getId()).isEqualTo(2L); - assertThat(identificationResult.getIdentification()).isEqualTo(IdentificationQuestionValue.UNIDENTIFIED); - assertThat(identificationResult.getAccess()).isEqualTo(AccessQuestionValue.NACC); - assertThat(identificationResult.getSituation()).isEqualTo(SituationQuestionValue.NOORDINARY); - assertThat(identificationResult.getCategory()).isEqualTo(CategoryQuestionValue.VACANT); - assertThat(identificationResult.getOccupant()).isEqualTo(OccupantQuestionValue.UNIDENTIFIED); - assertThat(identificationResult.getSurveyUnit()).isEqualTo(surveyUnit); - } + private static Stream contactAttemptConversions() { - @Test - @DisplayName("Should not update identification entity when identification model is null") - void testUpdateIdentification02() { - IdentificationDB identificationDB = new IdentificationDB(2L, - IdentificationQuestionValue.IDENTIFIED, - AccessQuestionValue.ACC, - SituationQuestionValue.ABSORBED, - CategoryQuestionValue.SECONDARY, - OccupantQuestionValue.IDENTIFIED, - surveyUnit); - surveyUnit.setIdentification(identificationDB); - surveyUnitDto = createSurveyUnitDto(null, null, null); - surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); - assertThat(surveyUnit.getIdentification()).isEqualTo(identificationDB); - } + return Stream.of( + Arguments.of(ContactOutcomeType.INA, ContactOutcomeType.INA), + Arguments.of(ContactOutcomeType.DCD, ContactOutcomeType.NOA), + Arguments.of(ContactOutcomeType.DUU, ContactOutcomeType.DUK) + ); + } - @Test - @DisplayName("Should create identification entity when entity does not exist") - void testUpdateIdentification03() { - surveyUnit.setIdentification(null); - IdentificationDto identification = new IdentificationDto(IdentificationQuestionValue.UNIDENTIFIED, - AccessQuestionValue.NACC, - SituationQuestionValue.NOORDINARY, - CategoryQuestionValue.VACANT, - OccupantQuestionValue.UNIDENTIFIED); - surveyUnitDto = createSurveyUnitDto(identification, null, null); + @ParameterizedTest + @DisplayName("Should update contactOutcome value") + @MethodSource("contactAttemptConversions") + void testUpdateContactOutcome01(ContactOutcomeType input, ContactOutcomeType expected) { + ContactOutcomeDto contactOutcome = new ContactOutcomeDto(dateService.getCurrentTimestamp(), + input, 5); + surveyUnit.setContactOutcome(new ContactOutcomeDB(5L,dateService.getCurrentTimestamp(),ContactOutcomeType.ALA, 3,surveyUnit)); + surveyUnitDto = createSurveyUnitDto(null, null, null, contactOutcome); - surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); + surveyUnitService.updateSurveyUnitInfos(surveyUnit, surveyUnitDto); + assertThat(surveyUnit.getContactOutcome().getType()).isEqualTo(expected); + } - IdentificationDB identificationResult = surveyUnit.getIdentification(); - assertThat(identificationResult.getId()).isNull(); - assertThat(identificationResult.getIdentification()).isEqualTo(IdentificationQuestionValue.UNIDENTIFIED); - assertThat(identificationResult.getAccess()).isEqualTo(AccessQuestionValue.NACC); - assertThat(identificationResult.getSituation()).isEqualTo(SituationQuestionValue.NOORDINARY); - assertThat(identificationResult.getCategory()).isEqualTo(CategoryQuestionValue.VACANT); - assertThat(identificationResult.getOccupant()).isEqualTo(OccupantQuestionValue.UNIDENTIFIED); - assertThat(identificationResult.getSurveyUnit()).isEqualTo(surveyUnit); - } + private SurveyUnitUpdateDto createSurveyUnitDto(RawIdentificationDto identification, List comments, + List communicationRequests, + ContactOutcomeDto contactOutcome) { + return new SurveyUnitUpdateDto("su-id", null, null, true, + comments, null, null, contactOutcome, identification, communicationRequests); + } - private SurveyUnitUpdateDto createSurveyUnitDto(IdentificationDto identification, List comments, List communicationRequests) { - return new SurveyUnitUpdateDto("su-id", null, null, true, - comments, null, null, null, identification, communicationRequests); - } + private IdentificationDB createHouseF2FIdentificationDB() { + return new HouseF2FIdentificationDB(2L, + surveyUnit, + IdentificationQuestionValue.IDENTIFIED, + AccessQuestionValue.ACC, + SituationQuestionValue.ORDINARY, + CategoryQuestionValue.SECONDARY, + OccupantQuestionValue.IDENTIFIED + ); + } } diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationRequestFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationRequestFakeRepository.java index cbb12925..fdaae049 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationRequestFakeRepository.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationRequestFakeRepository.java @@ -1,20 +1,45 @@ package fr.insee.pearljam.domain.surveyunit.service.dummy; import fr.insee.pearljam.api.domain.SurveyUnit; +import fr.insee.pearljam.api.dto.interviewer.InterviewerCountDto; +import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequest; import fr.insee.pearljam.domain.surveyunit.port.serverside.CommunicationRequestRepository; +import java.util.List; +import java.util.Set; import lombok.Getter; import lombok.RequiredArgsConstructor; -import java.util.List; - +@Getter @RequiredArgsConstructor public class CommunicationRequestFakeRepository implements CommunicationRequestRepository { - @Getter - private List communicationRequestsAdded; - @Override - public void addCommunicationRequests(SurveyUnit surveyUnit, List communicationRequests) { - communicationRequestsAdded = communicationRequests; - } + private List communicationRequestsAdded; + + @Override + public void addCommunicationRequests(SurveyUnit surveyUnit, + List communicationRequests) { + communicationRequestsAdded = communicationRequests; + } + + @Override + public Long getCommRequestCountByCampaignAndType(String campaignId, + CommunicationType type, Long date) { + return 0L; + } + + @Override + public Long getCommRequestCountByCampaignTypeAndOrgaUnit(String campaignId, + CommunicationType type, Long date, List ouIds) { + return 0L; + } + + @Override + public List getCommRequestCountByInterviewersAndType( + List campaignIds, Set interviewerId, CommunicationType type, + List ouIds, Long date) { + return List.of(); + } + + } diff --git a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationTemplateFakeRepository.java b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationTemplateFakeRepository.java index be6401e2..ef2315bb 100644 --- a/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationTemplateFakeRepository.java +++ b/src/test/java/fr/insee/pearljam/domain/surveyunit/service/dummy/CommunicationTemplateFakeRepository.java @@ -20,10 +20,11 @@ public void clearCommunicationTemplates() { } @Override - public Optional findCommunicationTemplate(Long communicationTemplateId, String campaignId) { + public Optional findCommunicationTemplate(String campaignId, String meshuggahId) { return communicationTemplates.stream() - .filter(communicationTemplate -> communicationTemplate.id().equals(communicationTemplateId)) - .findFirst(); + .filter(communicationTemplate -> + communicationTemplate.meshuggahId().equals(meshuggahId)) + .findFirst(); } @Override diff --git a/src/test/java/fr/insee/pearljam/features/CucumberTestRunner.java b/src/test/java/fr/insee/pearljam/features/CucumberTestRunner.java new file mode 100644 index 00000000..925f594f --- /dev/null +++ b/src/test/java/fr/insee/pearljam/features/CucumberTestRunner.java @@ -0,0 +1,27 @@ +package fr.insee.pearljam.features; + +import io.cucumber.spring.CucumberContextConfiguration; +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.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +import static io.cucumber.core.options.Constants.GLUE_PROPERTY_NAME; +import static io.cucumber.core.options.Constants.PLUGIN_PROPERTY_NAME; + +@CucumberContextConfiguration +@SpringBootTest +@ActiveProfiles(profiles = {"auth", "test"}) +@AutoConfigureMockMvc +@Suite +@IncludeEngines("cucumber") +@SelectClasspathResource("features") +@ConfigurationParameter(key = GLUE_PROPERTY_NAME, value = "fr.insee.pearljam.features") +@ConfigurationParameter(key = PLUGIN_PROPERTY_NAME, value = "pretty, json:target/cucumber.json, html:target/cucumber_report.html," + + " usage:target/usage.jsonx, junit:target/junit.xml") +public class CucumberTestRunner { +} + diff --git a/src/test/java/fr/insee/pearljam/features/IdentificationSteps.java b/src/test/java/fr/insee/pearljam/features/IdentificationSteps.java new file mode 100644 index 00000000..d4aae407 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/features/IdentificationSteps.java @@ -0,0 +1,192 @@ +package fr.insee.pearljam.features; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import fr.insee.pearljam.api.campaign.dto.input.CampaignCreateDto; +import fr.insee.pearljam.api.campaign.dto.input.VisibilityCampaignCreateDto; +import fr.insee.pearljam.api.constants.Constants; +import fr.insee.pearljam.api.domain.*; +import fr.insee.pearljam.api.dto.address.AddressDto; +import fr.insee.pearljam.api.dto.contactattempt.ContactAttemptDto; +import fr.insee.pearljam.api.dto.person.PersonDto; +import fr.insee.pearljam.api.dto.referent.ReferentDto; +import fr.insee.pearljam.api.dto.state.StateDto; +import fr.insee.pearljam.api.dto.surveyunit.SurveyUnitInterviewerLinkDto; +import fr.insee.pearljam.api.repository.InterviewerRepository; +import fr.insee.pearljam.api.repository.OrganizationUnitRepository; +import fr.insee.pearljam.api.repository.SurveyUnitRepository; +import fr.insee.pearljam.api.service.CampaignService; +import fr.insee.pearljam.api.surveyunit.dto.CommentDto; +import fr.insee.pearljam.api.surveyunit.dto.SurveyUnitUpdateDto; +import fr.insee.pearljam.api.surveyunit.dto.identification.RawIdentificationDto; +import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; +import fr.insee.pearljam.api.utils.JsonTestHelper; +import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationType; +import fr.insee.pearljam.domain.surveyunit.model.question.*; +import fr.insee.pearljam.infrastructure.surveyunit.entity.CommentDB; +import fr.insee.pearljam.infrastructure.surveyunit.entity.identification.IdentificationDB; +import io.cucumber.java.en.And; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.http.MediaType; +import org.springframework.security.core.Authentication; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.ResultActions; + +import java.io.IOException; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@AutoConfigureMockMvc +@RequiredArgsConstructor +public class IdentificationSteps { + + @Autowired + MockMvc mockMvc; + + private final SurveyUnitRepository surveyUnitRepository; + private final OrganizationUnitRepository organizationUnitRepository; + private final InterviewerRepository interviewerRepository; + private final CampaignService campaignService; + ObjectMapper objectMapper = new ObjectMapper(); + + private Authentication securityRole; + private IdentificationConfiguration identificationConfiguration; + private MvcResult createdCampaign; + private SurveyUnit surveyUnit; + private String surveyUnitId; + private String campaignId; + private ResultActions result; + + @Given("a user with {string} role") + public void a_user_with_following_role(String role) { + securityRole = switch (role.toLowerCase()) { + case "admin" -> AuthenticatedUserTestHelper.AUTH_ADMIN; + case "interviewer" -> AuthenticatedUserTestHelper.AUTH_INTERVIEWER; + default -> throw new IllegalArgumentException("Unknown role: " + role); + }; + } + + @When("the user create a campaign with identificationConfiguration equals to {string}") + public void the_user_create_a_campaign_with_identification_configuration_to(String inputIdentificationConfiguration) throws Exception { + createACampaignWithAuthenticationAndIdentificationConfiguration(securityRole, + inputIdentificationConfiguration); + + createdCampaign = + mockMvc.perform(get(String.join("/", Constants.API_CAMPAIGN, campaignId)).with(authentication(securityRole)).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andReturn(); + } + + @Then("the created campaign should have the identification configuration {string}") + public void the_created_campaign_should_have_the_identification_configuration(String expectedIdentificationType) throws IOException { + String contentResult = createdCampaign.getResponse().getContentAsString(); + + CampaignCreateDto campaignDto = objectMapper.readValue(contentResult, CampaignCreateDto.class); + + assertThat(campaignDto.identificationConfiguration()).isEqualTo(IdentificationConfiguration.fromName(expectedIdentificationType)); + } + + + @Given("a survey-unit is in a campaign with identification configuration equals to {string}") + public void a_survey_unit_is_in_a_campaign_with_identification_configuration_equals_to(String inputIdentification) throws Exception { + createACampaignWithAuthenticationAndIdentificationConfiguration(AuthenticatedUserTestHelper.AUTH_ADMIN, + inputIdentification); + } + + @And("this survey-unit is affected to this interviewer") + public void this_survey_unit_is_affected_to_this_interviewer() throws Exception { + surveyUnitId = "SURVEYUNIT_" + System.currentTimeMillis(); + + Address addressDB = new InseeAddress("l1", "l2", "l3", "l4", "l5", "l6", "l7", true, + "building", "floor", "door", "staircase", true); + Campaign campaignDB = campaignService.findById(campaignId).orElseThrow(); + Interviewer interviewerDB = interviewerRepository.findById("INTW1").orElseThrow(); + OrganizationUnit ouDB = organizationUnitRepository.findById("OU-NORTH").orElseThrow(); + Set personsDB = Set.of(new Person(Title.MISTER, "Bob", "Marley", "bob.marley@insee.fr", true, true, + 537535032000L, surveyUnit)); + Identification identificationDB = new Identification(null, IdentificationType.HOUSEF2F, null, null, null, null + , null, null, null, null, null, null); + surveyUnit = new SurveyUnit(surveyUnitId, false, false, addressDB, null, campaignDB, interviewerDB, ouDB, personsDB); + + surveyUnit.setIdentification(IdentificationDB.fromModel(surveyUnit, identificationDB, identificationConfiguration)); + surveyUnit.getStates().add(new State(System.currentTimeMillis(), surveyUnit, StateType.VIN)); + surveyUnit = surveyUnitRepository.save(surveyUnit); + + List link = List.of(new SurveyUnitInterviewerLinkDto(surveyUnitId, "INTW1")); + + mockMvc.perform(post(Constants.API_SURVEYUNITS_INTERVIEWERS).with(authentication(AuthenticatedUserTestHelper.AUTH_ADMIN)).content(JsonTestHelper.toJson(link)).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); + + + } + + + @When("the interviewer update the survey-unit with identification value") + public void the_interviewer_update_the_survey_unit_with_identification_value() throws Exception { + + SurveyUnitUpdateDto editedSurveyUnit = updateIdentification( + new RawIdentificationDto(IdentificationQuestionValue.UNIDENTIFIED, AccessQuestionValue.ACC, + SituationQuestionValue.ORDINARY, CategoryQuestionValue.PRIMARY, + OccupantQuestionValue.IDENTIFIED, IndividualStatusQuestionValue.SAME_ADDRESS, + InterviewerCanProcessQuestionValue.YES, + NumberOfRespondentsQuestionValue.ONE, PresentInPreviousHomeQuestionValue.AT_LEAST_ONE, + HouseholdCompositionQuestionValue.SAME_COMPO)); + + result = + mockMvc.perform(put(String.join("/", "/api/survey-unit", surveyUnitId)).with(authentication(securityRole)).contentType(MediaType.APPLICATION_JSON).content(JsonTestHelper.toJson(editedSurveyUnit)).accept(MediaType.APPLICATION_JSON)); + + } + + @Then("the survey-unit is updated and its identification equals:") + public void the_survey_unit_is_updated_and_its_identification_equals(String expectedValue) throws Exception { + result.andExpect(status().isOk()); + String content = result.andReturn().getResponse().getContentAsString(); + + JsonNode expectedJson = objectMapper.readTree(expectedValue); + JsonNode actualResponse = objectMapper.readTree(content); + JsonNode actualIdentification = actualResponse.get("identification"); + assertThat(actualIdentification).isEqualTo(expectedJson); + } + + + private SurveyUnitUpdateDto updateIdentification(RawIdentificationDto newIdentification) { + return new SurveyUnitUpdateDto( + surveyUnit.getId(), + surveyUnit.getPersons().stream().map(PersonDto::new).toList(), + new AddressDto(surveyUnit.getAddress()), + surveyUnit.getMove(), + CommentDto.fromModel(surveyUnit.getComments().stream().map(CommentDB::toModel).collect(Collectors.toSet())), + surveyUnit.getStates().stream().map(StateDto::new).toList(), + surveyUnit.getContactAttempts().stream().map(ContactAttemptDto::new).toList(), + null, + newIdentification, // New identification + List.of() + ); + } + + private void createACampaignWithAuthenticationAndIdentificationConfiguration(Authentication authentication, + String inputIdentificationConfiguration) throws Exception { + identificationConfiguration = + IdentificationConfiguration.fromName(inputIdentificationConfiguration); + campaignId = "CAMPAIGN_" + System.currentTimeMillis(); + CampaignCreateDto inputCampaign = new CampaignCreateDto(campaignId, "campaign_label", + List.of(new VisibilityCampaignCreateDto(1L + , 2L, 3L, 4L, 5L, 6L, "OU-NORTH", false, "mail", "tel")), List.of(), List.of(new ReferentDto( + "Bob", + "Marley" + , "0123456789", "PRIMARY")), "campaign@e.mail", identificationConfiguration, + ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, false); + mockMvc.perform(post(Constants.API_CAMPAIGN).with(authentication(authentication)).contentType(MediaType.APPLICATION_JSON).content(JsonTestHelper.toJson(inputCampaign)).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); + + } +} diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java index 4699021f..46fb9819 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/adapter/VisibilityDaoAdapterTest.java @@ -60,7 +60,7 @@ class VisibilityDaoAdapterTest { void setup() { campaign = new Campaign("id", "label", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - "email@plop.com"); + "email@plop.com", false); organizationUnit = new OrganizationUnit("OU-SOUTHWEST", "South west", OrganizationUnitType.LOCAL); organizationUnit2 = new OrganizationUnit("OU-NORTHWEST", "North west", OrganizationUnitType.NATIONAL); diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java index 311963fa..d82fea38 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/CommunicationTemplateDBTest.java @@ -22,9 +22,9 @@ void testToModel() { // Given Campaign campaign = new Campaign("id", "label", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - "email@plop.com"); - CommunicationTemplateDB templateDB1 = new CommunicationTemplateDB(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE, campaign); - CommunicationTemplateDB templateDB2 = new CommunicationTemplateDB(2L, "msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER, campaign); + "email@plop.com", false); + CommunicationTemplateDB templateDB1 = new CommunicationTemplateDB(new CommunicationTemplateDBId("mesh1", "SIMPSONS2020X00"), CommunicationMedium.EMAIL, CommunicationType.NOTICE, campaign); + CommunicationTemplateDB templateDB2 = new CommunicationTemplateDB(new CommunicationTemplateDBId("mesh2", "SIMPSONS2020X00"), CommunicationMedium.LETTER, CommunicationType.REMINDER, campaign); List dbList = List.of(templateDB1, templateDB2); // When @@ -34,13 +34,11 @@ void testToModel() { assertThat(modelList) .hasSize(2); - assertThat(modelList.getFirst().id()).isEqualTo(1L); - assertThat(modelList.getFirst().meshuggahId()).isEqualTo("msg1"); + assertThat(modelList.getFirst().meshuggahId()).isEqualTo("mesh1"); assertThat(modelList.getFirst().medium()).isEqualTo(CommunicationMedium.EMAIL); assertThat(modelList.getFirst().type()).isEqualTo(CommunicationType.NOTICE); - assertThat(modelList.getLast().id()).isEqualTo(2L); - assertThat(modelList.getLast().meshuggahId()).isEqualTo("msg2"); + assertThat(modelList.getLast().meshuggahId()).isEqualTo("mesh2"); assertThat(modelList.getLast().medium()).isEqualTo(CommunicationMedium.LETTER); assertThat(modelList.getLast().type()).isEqualTo(CommunicationType.REMINDER); } @@ -51,9 +49,9 @@ void testFromModel() { // Given Campaign campaign = new Campaign("id", "label", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - "email@plop.com"); - CommunicationTemplate template1 = new CommunicationTemplate(1L, "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); - CommunicationTemplate template2 = new CommunicationTemplate(2L, "msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER); + "email@plop.com", false); + CommunicationTemplate template1 = new CommunicationTemplate("SIMPSONS2020X00", "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE); + CommunicationTemplate template2 = new CommunicationTemplate("SIMPSONS2020X00", "msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER); List modelList = List.of(template1, template2); // When @@ -63,25 +61,25 @@ void testFromModel() { assertThat(dbList) .hasSize(2) .anySatisfy(templateDB -> { - verifyCommunicationTemplateDB(templateDB, null, + verifyCommunicationTemplateDB(templateDB, "id", "msg1", CommunicationMedium.EMAIL, CommunicationType.NOTICE, campaign); }) .anySatisfy(templateDB -> { - verifyCommunicationTemplateDB(templateDB, null, + verifyCommunicationTemplateDB(templateDB, "id", "msg2", CommunicationMedium.LETTER, CommunicationType.REMINDER, campaign); }); } private void verifyCommunicationTemplateDB( CommunicationTemplateDB templateDB, - Long expectedId, + String expectedCampaignId, String expectedMesshugahId, CommunicationMedium expectedMedium, CommunicationType expectedType, Campaign expectedCampaign ) { - assertThat(templateDB.getId()).isEqualTo(expectedId); - assertThat(templateDB.getMeshuggahId()).isEqualTo(expectedMesshugahId); + assertThat(templateDB.getCommunicationTemplateDBId().getCampaignId()).isEqualTo(expectedCampaignId); + assertThat(templateDB.getCommunicationTemplateDBId().getMeshuggahId()).isEqualTo(expectedMesshugahId); assertThat(templateDB.getMedium()).isEqualTo(expectedMedium); assertThat(templateDB.getType()).isEqualTo(expectedType); assertThat(templateDB.getCampaign()).isEqualTo(expectedCampaign); diff --git a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java index 5c55a02e..72d8225f 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/campaign/entity/VisibilityDBTest.java @@ -16,7 +16,7 @@ class VisibilityDBTest { void setup() { campaign = new Campaign("id", "label", IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.F2F, ContactAttemptConfiguration.F2F, - "email@plop.com"); + "email@plop.com", false); organizationUnit = new OrganizationUnit("OU-SOUTHWEST", "South west", OrganizationUnitType.LOCAL); } diff --git a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDBTest.java index 4faf5746..baae4c25 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestDBTest.java @@ -3,7 +3,7 @@ import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.domain.surveyunit.model.communication.*; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; -import org.junit.jupiter.api.BeforeEach; +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDBId; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -14,66 +14,65 @@ class CommunicationRequestDBTest { - private SurveyUnit surveyUnit; - private CommunicationTemplateDB communicationTemplate; + private final SurveyUnit surveyUnit = new SurveyUnit(); + private final CommunicationTemplateDB communicationTemplateDB = new CommunicationTemplateDB(); + private final CommunicationTemplateDBId communicationTemplateDBId = new CommunicationTemplateDBId("mesh1", + "SIMPSONS2020X00"); - @BeforeEach - void setup() { - surveyUnit = new SurveyUnit(); - surveyUnit.setId("su-id"); - communicationTemplate = new CommunicationTemplateDB(); - communicationTemplate.setId(1L); - } + @Test + @DisplayName("Should return model object") + void testToModel01() { + List statusDB = List.of( + new CommunicationRequestStatusDB(null, 1233456789L, CommunicationStatusType.INITIATED, null), + new CommunicationRequestStatusDB(1L, 123345678910L, CommunicationStatusType.FAILED, null) + ); + CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(1L, communicationTemplateDBId, + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, + surveyUnit, + statusDB); - @Test - @DisplayName("Should return model object") - void testToModel01() { - List statusDB = List.of( - new CommunicationRequestStatusDB(null, 1233456789L, CommunicationStatusType.INITIATED, null), - new CommunicationRequestStatusDB(communicationTemplate.getId(), 123345678910L, CommunicationStatusType.FAILED, null) - ); - CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(1L, communicationTemplate, - CommunicationRequestReason.UNREACHABLE, - CommunicationRequestEmitter.INTERVIEWER, - surveyUnit, - statusDB); + CommunicationRequest communicationRequest = CommunicationRequestDB.toModel(communicationRequestDB); + assertThat(communicationRequest.id()).isEqualTo(communicationRequestDB.getId()); + assertThat(communicationRequest.meshuggahId()).isEqualTo(communicationRequestDB.getCommunicationTemplateDBId().getMeshuggahId()); + assertThat(communicationRequest.campaignId()).isEqualTo(communicationRequestDB.getCommunicationTemplateDBId().getCampaignId()); + assertThat(communicationRequest.reason()).isEqualTo(communicationRequestDB.getReason()); + List status = statusDB.stream() + .map(CommunicationRequestStatusDB::toModel) + .toList(); + assertThat(communicationRequest.status()).containsExactlyInAnyOrderElementsOf(status); + } - CommunicationRequest communicationRequest = CommunicationRequestDB.toModel(communicationRequestDB); - assertThat(communicationRequest.id()).isEqualTo(communicationRequestDB.getId()); - assertThat(communicationRequest.communicationTemplateId()).isEqualTo(communicationRequestDB.getCommunicationTemplate().getId()); - assertThat(communicationRequest.reason()).isEqualTo(communicationRequestDB.getReason()); - List status = statusDB.stream() - .map(CommunicationRequestStatusDB::toModel) - .toList(); - assertThat(communicationRequest.status()).containsExactlyInAnyOrderElementsOf(status); - } + @Test + @DisplayName("Should return entity object") + void testFromModel01() { + List status = List.of( + new CommunicationRequestStatus(null, 1233456789L, CommunicationStatusType.INITIATED), + new CommunicationRequestStatus(2L, 123345678910L, CommunicationStatusType.FAILED) + ); - @Test - @DisplayName("Should return entity object") - void testFromModel01() { - List status = List.of( - new CommunicationRequestStatus(null, 1233456789L, CommunicationStatusType.INITIATED), - new CommunicationRequestStatus(2L, 123345678910L, CommunicationStatusType.FAILED) - ); + CommunicationRequest communicationRequest = new CommunicationRequest(1L, + communicationTemplateDBId.getCampaignId(), communicationTemplateDBId.getMeshuggahId(), + CommunicationRequestReason.UNREACHABLE, + CommunicationRequestEmitter.INTERVIEWER, + status); - CommunicationRequest communicationRequest = new CommunicationRequest(1L, - communicationTemplate.getId(), - CommunicationRequestReason.UNREACHABLE, - CommunicationRequestEmitter.INTERVIEWER, - status); + communicationTemplateDB.setCommunicationTemplateDBId(communicationTemplateDBId); - CommunicationRequestDB communicationRequestDB = CommunicationRequestDB.fromModel(communicationRequest, surveyUnit, communicationTemplate); - assertThat(communicationRequestDB.getId()).isEqualTo(communicationRequest.id()); - assertThat(communicationRequestDB.getCommunicationTemplate().getId()).isEqualTo(communicationRequest.communicationTemplateId()); - assertThat(communicationRequestDB.getReason()).isEqualTo(communicationRequest.reason()); - assertThat(communicationRequestDB.getStatus()) - .extracting(CommunicationRequestStatusDB::getId, - CommunicationRequestStatusDB::getDate, - CommunicationRequestStatusDB::getStatus, - CommunicationRequestStatusDB::getCommunicationRequest) - .containsExactlyInAnyOrder( - tuple(null, 1233456789L, CommunicationStatusType.INITIATED, communicationRequestDB), - tuple(2L, 123345678910L, CommunicationStatusType.FAILED, communicationRequestDB) - ); - } + CommunicationRequestDB communicationRequestDB = CommunicationRequestDB.fromModel(communicationRequest, + surveyUnit, communicationTemplateDB); + assertThat(communicationRequestDB.getId()).isEqualTo(communicationRequest.id()); + assertThat(communicationRequestDB.getCommunicationTemplateDBId().getCampaignId()).isEqualTo(communicationRequest.campaignId()); + assertThat(communicationRequestDB.getCommunicationTemplateDBId().getMeshuggahId()).isEqualTo(communicationRequest.meshuggahId()); + assertThat(communicationRequestDB.getReason()).isEqualTo(communicationRequest.reason()); + assertThat(communicationRequestDB.getStatus()) + .extracting(CommunicationRequestStatusDB::getId, + CommunicationRequestStatusDB::getDate, + CommunicationRequestStatusDB::getStatus, + CommunicationRequestStatusDB::getCommunicationRequest) + .containsExactlyInAnyOrder( + tuple(null, 1233456789L, CommunicationStatusType.INITIATED, communicationRequestDB), + tuple(2L, 123345678910L, CommunicationStatusType.FAILED, communicationRequestDB) + ); + } } diff --git a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDBTest.java index 848fa601..2915e678 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/CommunicationRequestStatusDBTest.java @@ -1,12 +1,15 @@ package fr.insee.pearljam.infrastructure.surveyunit.entity; -import fr.insee.pearljam.domain.surveyunit.model.communication.*; -import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestEmitter; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestReason; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationRequestStatus; +import fr.insee.pearljam.domain.surveyunit.model.communication.CommunicationStatusType; +import static org.assertj.core.api.Assertions.assertThat; + +import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDBId; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; - class CommunicationRequestStatusDBTest { @Test @DisplayName("Should return model object") @@ -14,7 +17,7 @@ void testToModel01() { CommunicationRequestStatusDB communicationRequestStatusDB = new CommunicationRequestStatusDB(1L, 123456789L, CommunicationStatusType.INITIATED, null); CommunicationRequestStatus communicationRequestStatus = CommunicationRequestStatusDB.toModel(communicationRequestStatusDB); - assertThat(communicationRequestStatus.id()).isEqualTo(communicationRequestStatusDB.getId()); + assertThat(communicationRequestStatus.date()).isEqualTo(communicationRequestStatusDB.getDate()); assertThat(communicationRequestStatus.status()).isEqualTo(communicationRequestStatusDB.getStatus()); } @@ -22,8 +25,7 @@ void testToModel01() { @Test @DisplayName("Should return entity object") void testFromModel01() { - CommunicationTemplateDB communicationTemplate = new CommunicationTemplateDB(1L, null, null, null, null); - CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(null, communicationTemplate, + CommunicationRequestDB communicationRequestDB = new CommunicationRequestDB(null, new CommunicationTemplateDBId("mesh1","SIMPSONS2020X00"), CommunicationRequestReason.UNREACHABLE, CommunicationRequestEmitter.INTERVIEWER, null, null); CommunicationRequestStatus communicationRequestStatus = new CommunicationRequestStatus(1L, 123456789L, CommunicationStatusType.INITIATED); diff --git a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/IdentificationDBTest.java b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/IdentificationDBTest.java index 41e0fcf7..57815ccd 100644 --- a/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/IdentificationDBTest.java +++ b/src/test/java/fr/insee/pearljam/infrastructure/surveyunit/entity/IdentificationDBTest.java @@ -2,7 +2,10 @@ import fr.insee.pearljam.api.domain.SurveyUnit; import fr.insee.pearljam.domain.surveyunit.model.Identification; +import fr.insee.pearljam.domain.surveyunit.model.IdentificationType; import fr.insee.pearljam.domain.surveyunit.model.question.*; +import fr.insee.pearljam.infrastructure.surveyunit.entity.identification.HouseF2FIdentificationDB; +import fr.insee.pearljam.infrastructure.surveyunit.entity.identification.IdentificationDB; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -11,69 +14,77 @@ class IdentificationDBTest { - private IdentificationDB identificationDB; - private SurveyUnit surveyUnitDB; + private IdentificationDB identificationDB; + private SurveyUnit surveyUnitDB; - private final Long identificationId = 1L; + private final Long identificationId = 1L; - @BeforeEach - void setup() { - surveyUnitDB = new SurveyUnit(); - surveyUnitDB.setId("1"); - identificationDB = new IdentificationDB(identificationId, - IdentificationQuestionValue.IDENTIFIED, - AccessQuestionValue.ACC, - SituationQuestionValue.ABSORBED, - CategoryQuestionValue.SECONDARY, - OccupantQuestionValue.IDENTIFIED, - surveyUnitDB); - } + @BeforeEach + void setup() { + surveyUnitDB = new SurveyUnit(); + surveyUnitDB.setId("1"); + identificationDB = new HouseF2FIdentificationDB(identificationId, + surveyUnitDB, + IdentificationQuestionValue.IDENTIFIED, + AccessQuestionValue.ACC, + SituationQuestionValue.ABSORBED, + CategoryQuestionValue.SECONDARY, + OccupantQuestionValue.IDENTIFIED + ); + } - @Test - @DisplayName("Should update the db entity") - void testUpdate01() { - Identification identification = new Identification(IdentificationQuestionValue.UNIDENTIFIED, - AccessQuestionValue.NACC, - SituationQuestionValue.NOORDINARY, - CategoryQuestionValue.VACANT, - OccupantQuestionValue.UNIDENTIFIED); - identificationDB.update(identification); - assertThat(identificationDB.getId()).isEqualTo(identificationId); - assertThat(identificationDB.getIdentification()).isEqualTo(identification.identification()); - assertThat(identificationDB.getOccupant()).isEqualTo(identification.occupant()); - assertThat(identificationDB.getCategory()).isEqualTo(identification.category()); - assertThat(identificationDB.getAccess()).isEqualTo(identification.access()); - assertThat(identificationDB.getSituation()).isEqualTo(identification.situation()); - assertThat(identificationDB.getSurveyUnit()).isEqualTo(surveyUnitDB); - } + @Test + @DisplayName("Should update the db entity") + void testUpdate01() { + Identification identification = new Identification( + identificationId, + IdentificationType.HOUSEF2F, + IdentificationQuestionValue.UNIDENTIFIED, + AccessQuestionValue.NACC, + SituationQuestionValue.NOORDINARY, + CategoryQuestionValue.VACANT, + OccupantQuestionValue.UNIDENTIFIED, + null, null, null, null, null); + identificationDB.update(identification); + HouseF2FIdentificationDB houseF2FIdentificationDB = (HouseF2FIdentificationDB) identificationDB; + assertThat(houseF2FIdentificationDB.getId()).isEqualTo(identificationId); + assertThat(houseF2FIdentificationDB.getIdentification()).isEqualTo(identification.identification()); + assertThat(houseF2FIdentificationDB.getOccupant()).isEqualTo(identification.occupant()); + assertThat(houseF2FIdentificationDB.getCategory()).isEqualTo(identification.category()); + assertThat(houseF2FIdentificationDB.getAccess()).isEqualTo(identification.access()); + assertThat(houseF2FIdentificationDB.getSituation()).isEqualTo(identification.situation()); + assertThat(identificationDB.getSurveyUnit()).isEqualTo(surveyUnitDB); + } - @Test - @DisplayName("Should not update db entity when identification is null") - void testUpdate02() { - identificationDB.update(null); - assertThat(identificationDB.getId()).isEqualTo(identificationId); - assertThat(identificationDB.getIdentification()).isEqualTo(IdentificationQuestionValue.IDENTIFIED); - assertThat(identificationDB.getOccupant()).isEqualTo(OccupantQuestionValue.IDENTIFIED); - assertThat(identificationDB.getCategory()).isEqualTo(CategoryQuestionValue.SECONDARY); - assertThat(identificationDB.getAccess()).isEqualTo(AccessQuestionValue.ACC); - assertThat(identificationDB.getSituation()).isEqualTo(SituationQuestionValue.ABSORBED); - assertThat(identificationDB.getSurveyUnit()).isEqualTo(surveyUnitDB); - } + @Test + @DisplayName("Should not update db entity when identification is null") + void testUpdate02() { + identificationDB.update(null); + HouseF2FIdentificationDB houseF2FIdentificationDB = (HouseF2FIdentificationDB) identificationDB; + assertThat(houseF2FIdentificationDB.getId()).isEqualTo(identificationId); + assertThat(houseF2FIdentificationDB.getIdentification()).isEqualTo(IdentificationQuestionValue.IDENTIFIED); + assertThat(houseF2FIdentificationDB.getOccupant()).isEqualTo(OccupantQuestionValue.IDENTIFIED); + assertThat(houseF2FIdentificationDB.getCategory()).isEqualTo(CategoryQuestionValue.SECONDARY); + assertThat(houseF2FIdentificationDB.getAccess()).isEqualTo(AccessQuestionValue.ACC); + assertThat(houseF2FIdentificationDB.getSituation()).isEqualTo(SituationQuestionValue.ABSORBED); + assertThat(houseF2FIdentificationDB.getSurveyUnit()).isEqualTo(surveyUnitDB); + } - @Test - @DisplayName("Should create model") - void testToModel01() { - Identification identification = IdentificationDB.toModel(identificationDB); - assertThat(identificationDB.getIdentification()).isEqualTo(identification.identification()); - assertThat(identificationDB.getOccupant()).isEqualTo(identification.occupant()); - assertThat(identificationDB.getCategory()).isEqualTo(identification.category()); - assertThat(identificationDB.getAccess()).isEqualTo(identification.access()); - assertThat(identificationDB.getSituation()).isEqualTo(identification.situation()); - } + @Test + @DisplayName("Should create model") + void testToModel01() { + Identification identification = IdentificationDB.toModel(identificationDB); + HouseF2FIdentificationDB houseF2FIdentificationDB = (HouseF2FIdentificationDB) identificationDB; + assertThat(houseF2FIdentificationDB.getIdentification()).isEqualTo(identification.identification()); + assertThat(houseF2FIdentificationDB.getOccupant()).isEqualTo(identification.occupant()); + assertThat(houseF2FIdentificationDB.getCategory()).isEqualTo(identification.category()); + assertThat(houseF2FIdentificationDB.getAccess()).isEqualTo(identification.access()); + assertThat(houseF2FIdentificationDB.getSituation()).isEqualTo(identification.situation()); + } - @Test - @DisplayName("Should return null when identification db is null") - void testToModel02() { - assertThat(IdentificationDB.toModel(null)).isNull(); - } + @Test + @DisplayName("Should return null when identification db is null") + void testToModel02() { + assertThat(IdentificationDB.toModel(null)).isNull(); + } } diff --git a/src/test/java/fr/insee/pearljam/integration/DemoDataIT.java b/src/test/java/fr/insee/pearljam/integration/DemoDataIT.java new file mode 100644 index 00000000..206773b0 --- /dev/null +++ b/src/test/java/fr/insee/pearljam/integration/DemoDataIT.java @@ -0,0 +1,23 @@ +package fr.insee.pearljam.integration; + +import fr.insee.pearljam.api.utils.ScriptConstants; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.transaction.annotation.Transactional; + +import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_CLASS; + +@ActiveProfiles(profiles = {"demo"}) +@ContextConfiguration +@SpringBootTest +@Transactional +@Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_CLASS) +class DemoDataIT { + @Test + void contextLoads() { + // verifying demo data is loaded + } +} diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java index 671726d4..9ba7f7b5 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CampaignIT.java @@ -9,6 +9,8 @@ import fr.insee.pearljam.domain.campaign.model.communication.CommunicationType; import fr.insee.pearljam.infrastructure.campaign.entity.CommunicationTemplateDB; import fr.insee.pearljam.infrastructure.campaign.entity.VisibilityDB; +import org.json.JSONArray; +import org.json.JSONObject; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; @@ -27,6 +29,7 @@ import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication; import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; @@ -45,6 +48,24 @@ class CampaignIT { @Autowired private CampaignRepository campaignRepository; + @Test + @DisplayName("Should retrieve campaign") + void testGetSensitiveCampaign() throws Exception { + MvcResult mvcResult = mockMvc.perform(get(Constants.API_CAMPAIGNS_ON_GOING) + .with(authentication(AuthenticatedUserTestHelper.AUTH_ADMIN)) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn(); + + String contentResult = mvcResult.getResponse().getContentAsString(); + JSONArray jsonArray = new JSONArray(contentResult); + + JSONObject expectedCampaign = new JSONObject(); + expectedCampaign.put("id", "SIMPSONS2020X00"); + expectedCampaign.put("sensitivity", false); + assertEquals(expectedCampaign.toString(), jsonArray.getJSONObject(0).toString(), "Unexpected campaign content"); + } + @Test @DisplayName("Should retrieve campaign") void testGetCampaign() throws Exception { @@ -96,7 +117,8 @@ void testGetCampaign() throws Exception { "email":"first.email@test.com", "identificationConfiguration":"IASCO", "contactOutcomeConfiguration":"F2F", - "contactAttemptConfiguration":"F2F" + "contactAttemptConfiguration":"F2F", + "sensitivity": false } """; JSONAssert.assertEquals(contentResult, expectedResult, JSONCompareMode.NON_EXTENSIBLE); @@ -153,16 +175,19 @@ void testCreateCampaign() throws Exception { ], "communicationTemplates": [ { + "campaignId": "SIMPSONS2020X00", "meshuggahId": "meshId1", "medium": "LETTER", "type": "REMINDER" }, { + "campaignId": "SIMPSONS2020X00", "meshuggahId": "meshId2", "medium": "EMAIL", "type": "NOTICE" }, { + "campaignId": "SIMPSONS2020X00", "meshuggahId": "meshId3", "medium": "LETTER", "type": "NOTICE" @@ -171,7 +196,8 @@ void testCreateCampaign() throws Exception { "email": "test.email@plop.com", "identificationConfiguration":"IASCO", "contactOutcomeConfiguration":"F2F", - "contactAttemptConfiguration":"F2F" + "contactAttemptConfiguration":"F2F", + "sensitivity": false } """; mockMvc.perform(post(Constants.API_CAMPAIGN) @@ -216,7 +242,8 @@ void testCreateCampaign() throws Exception { private void assertCommunicationTemplate(CommunicationTemplateDB communicationTemplateToCheck, String campaignId, String meshuggahId, CommunicationMedium medium, CommunicationType type) { - assertThat(communicationTemplateToCheck.getMeshuggahId()).isEqualTo(meshuggahId); + assertThat(communicationTemplateToCheck.getCommunicationTemplateDBId().getMeshuggahId()).isEqualTo(meshuggahId); + assertThat(communicationTemplateToCheck.getCommunicationTemplateDBId().getCampaignId()).isEqualTo(campaignId); assertThat(communicationTemplateToCheck.getCampaign().getId()).isEqualTo(campaignId); assertThat(communicationTemplateToCheck.getType()).isEqualTo(type); assertThat(communicationTemplateToCheck.getMedium()).isEqualTo(medium); @@ -288,7 +315,7 @@ void testUpdateCampaign() throws Exception { assertThat(campaignOptional).isPresent(); Campaign campaignUpdated = campaignOptional.get(); assertCampaignInfos(campaignUpdated, campaignId, "An other campaign", "test.test@sdf.com", - ContactAttemptConfiguration.F2F, IdentificationConfiguration.NOIDENT, + ContactAttemptConfiguration.F2F, IdentificationConfiguration.IASCO, ContactOutcomeConfiguration.TEL); assertThat(campaignUpdated.getVisibilities()).hasSize(2); assertThat(campaignUpdated.getVisibilities()) diff --git a/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationTemplateIT.java b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationTemplateIT.java index 973a110f..334853ab 100644 --- a/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationTemplateIT.java +++ b/src/test/java/fr/insee/pearljam/integration/campaign/CommunicationTemplateIT.java @@ -37,12 +37,16 @@ void testGetCommunicationTemplates() throws Exception { String expectedResult = """ [ { - "id":1, + "id": "mesh1", + "campaignId": "SIMPSONS2020X00", + "meshuggahId":"mesh1", "medium":"EMAIL", "type":"REMINDER" }, { - "id":2, + "id": "mesh2", + "campaignId": "SIMPSONS2020X00", + "meshuggahId":"mesh2", "medium":"LETTER", "type":"NOTICE" } diff --git a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java index 3bf45240..932a00e5 100644 --- a/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java +++ b/src/test/java/fr/insee/pearljam/integration/surveyunit/SurveyUnitIT.java @@ -1,12 +1,11 @@ package fr.insee.pearljam.integration.surveyunit; -import fr.insee.pearljam.api.service.SurveyUnitService; import fr.insee.pearljam.api.utils.AuthenticatedUserTestHelper; import fr.insee.pearljam.api.utils.MockMvcTestUtils; import fr.insee.pearljam.api.utils.ScriptConstants; -import fr.insee.pearljam.domain.exception.CommunicationTemplateNotFoundException; import fr.insee.pearljam.config.FixedDateServiceConfiguration; import fr.insee.pearljam.domain.campaign.port.userside.DateService; +import fr.insee.pearljam.domain.exception.CommunicationTemplateNotFoundException; import org.json.JSONException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -39,486 +38,503 @@ @Transactional class SurveyUnitIT { - @Autowired - private MockMvc mockMvc; - - @Autowired - private SurveyUnitService surveyUnitService; + @Autowired + private MockMvc mockMvc; - @Autowired - private DateService dateService; + @Autowired + private DateService dateService; - @Test - void testGetAllSurveyUnits() throws Exception { - MvcResult mvcResult = mockMvc.perform(get("/api/survey-units") - .with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)) - .accept(MediaType.APPLICATION_JSON)) - .andReturn(); + @Test + @DisplayName("Should return survey units associated to the interviewer") + void testGetSurveyUnits() throws Exception { + MvcResult mvcResult = + mockMvc.perform(get("/api/survey-units").with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)).accept(MediaType.APPLICATION_JSON)).andReturn(); - String contentResult = mvcResult.getResponse().getContentAsString(); - String expectedResult = """ - [ - { - "id":"11", - "campaign":"SIMPSONS2020X00", - "campaignLabel":"Survey on the Simpsons tv show 2020", - "managementStartDate":1718966154301, - "interviewerStartDate":1719052554302, - "identificationPhaseStartDate":1719138954303, - "collectionStartDate":1719225354304, - "collectionEndDate":1721903754305, - "endDate":1724582154306, - "identificationConfiguration":"IASCO", - "contactOutcomeConfiguration":"F2F", - "contactAttemptConfiguration":"F2F", - "useLetterCommunication": true - }, - { - "id":"12", - "campaign":"SIMPSONS2020X00", - "campaignLabel":"Survey on the Simpsons tv show 2020", - "managementStartDate":1718966154301, - "interviewerStartDate":1719052554302, - "identificationPhaseStartDate":1719138954303, - "collectionStartDate":1719225354304, - "collectionEndDate":1721903754305, - "endDate":1724582154306, - "identificationConfiguration":"IASCO", - "contactOutcomeConfiguration":"F2F", - "contactAttemptConfiguration":"F2F", - "useLetterCommunication": true - }, - { - "id":"20", - "campaign":"VQS2021X00", - "campaignLabel":"Everyday life and health survey 2021", - "managementStartDate":1718966154308, - "interviewerStartDate":1719052554308, - "identificationPhaseStartDate":1719138954308, - "collectionStartDate":1719225354308, - "collectionEndDate":1721903754308, - "endDate":1724582154308, - "identificationConfiguration":"IASCO", - "contactOutcomeConfiguration":"TEL", - "contactAttemptConfiguration":"TEL", - "useLetterCommunication": false - } - ] - """; - JSONAssert.assertEquals(expectedResult, contentResult, JSONCompareMode.NON_EXTENSIBLE); - } + String contentResult = mvcResult.getResponse().getContentAsString(); + String expectedResult = """ + [ + { + "id":"11", + "campaign":"SIMPSONS2020X00", + "campaignLabel":"Survey on the Simpsons tv show 2020", + "managementStartDate":1718966154301, + "interviewerStartDate":1719052554302, + "identificationPhaseStartDate":1719138954303, + "collectionStartDate":1719225354304, + "collectionEndDate":1721903754305, + "endDate":1724582154306, + "identificationConfiguration":"IASCO", + "contactOutcomeConfiguration":"F2F", + "contactAttemptConfiguration":"F2F", + "useLetterCommunication": true + }, + { + "id":"12", + "campaign":"SIMPSONS2020X00", + "campaignLabel":"Survey on the Simpsons tv show 2020", + "managementStartDate":1718966154301, + "interviewerStartDate":1719052554302, + "identificationPhaseStartDate":1719138954303, + "collectionStartDate":1719225354304, + "collectionEndDate":1721903754305, + "endDate":1724582154306, + "identificationConfiguration":"IASCO", + "contactOutcomeConfiguration":"F2F", + "contactAttemptConfiguration":"F2F", + "useLetterCommunication": true + }, + { + "id":"25", + "campaign":"SIMPSONS2020X00", + "campaignLabel":"Survey on the Simpsons tv show 2020", + "managementStartDate":1718966154308, + "interviewerStartDate":1719052554309, + "identificationPhaseStartDate":1719138954310, + "collectionStartDate":1719225354314, + "collectionEndDate":1721903754315, + "endDate":1724582154316, + "identificationConfiguration":"IASCO", + "contactOutcomeConfiguration":"F2F", + "contactAttemptConfiguration":"F2F", + "useLetterCommunication":false + }, + { + "id":"20", + "campaign":"VQS2021X00", + "campaignLabel":"Everyday life and health survey 2021", + "managementStartDate":1718966154308, + "interviewerStartDate":1719052554308, + "identificationPhaseStartDate":1719138954308, + "collectionStartDate":1719225354308, + "collectionEndDate":1721903754308, + "endDate":1724582154308, + "identificationConfiguration":"IASCO", + "contactOutcomeConfiguration":"TEL", + "contactAttemptConfiguration":"TEL", + "useLetterCommunication": false + } + ] + """; + JSONAssert.assertEquals(expectedResult, contentResult, JSONCompareMode.NON_EXTENSIBLE); + } - /** - * Test that the GET endpoint "api/survey-unit/{id}" - * return 200. - * - * @throws InterruptedException - * @throws JSONException - */ - @Test - void testGetSurveyUnitDetail() throws Exception { - MvcResult result = mockMvc.perform(get("/api/interviewer/survey-unit/11") - .with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)) - .accept(MediaType.APPLICATION_JSON)) - .andExpectAll(status().isOk()) - .andReturn(); + /** + * Test that the GET endpoint "api/survey-unit/{id}" + * return 200. + * + * @throws InterruptedException ie + * @throws JSONException jse + */ + @Test + void testGetSurveyUnitDetail() throws Exception { + MvcResult result = + mockMvc.perform(get("/api/interviewer/survey-unit/11").with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)).accept(MediaType.APPLICATION_JSON)).andExpectAll(status().isOk()).andReturn(); - String resultJson = result.getResponse().getContentAsString(); - String expectedJson = """ - { - "id":"11", - "persons":[ - { - "id":1, - "title":"MISTER", - "firstName":"Ted", - "lastName":"Farmer", - "email":"test@test.com", - "birthdate":11111111, - "favoriteEmail":true, - "privileged":true, - "phoneNumbers":[ - { - "source":"FISCAL", - "favorite":false, - "number":"+33677542802" - }, - { - "source":"FISCAL", - "favorite":true, - "number":"+33677542802" - } - ] - }, - { - "id":6, - "title":"MISS", - "firstName":"Christine", - "lastName":"Aguilar", - "email":"test@test.com", - "birthdate":11111111, - "favoriteEmail":true, - "privileged":false, - "phoneNumbers":[ - { - "source":"FISCAL", - "favorite":true, - "number":"+33677542802" - } - ] - }, - { - "id":7, - "title":"MISS", - "firstName":"Louise", - "lastName":"Walker", - "email":"test@test.com", - "birthdate":11111111, - "favoriteEmail":true, - "privileged":false, - "phoneNumbers":[ - { - "source":"FISCAL", - "favorite":true, - "number":"+33677542802" - } - ] - } - ], - "address":{ - "l1":"Ted Farmer", - "l2":"", - "l3":"", - "l4":"1 rue de la gare", - "l5":"", - "l6":"29270 Carhaix", - "l7":"France", - "elevator":true, - "building":"Bat. C", - "floor":"Etg 4", - "door":"Porte 48", - "staircase":"Escalier B", - "cityPriorityDistrict":true - }, - "priority":true, - "campaign":"SIMPSONS2020X00", - "comments":[], - "sampleIdentifiers":{ - "bs":11, - "ec":"1", - "le":11, - "noi":11, - "numfa":11, - "rges":11, - "ssech":1, - "nolog":11, - "nole":11, - "autre":"11", - "nograp":"11" - }, - "states":[ - { - "id":1, - "date":111112111, - "type":"VIN" - }, - { - "id":7, - "date":101111111, - "type":"TBR" - } - ], - "contactAttempts":[], - "identification":{ - "identification":"IDENTIFIED", - "access":"ACC", - "situation":"ORDINARY", - "category":"PRIMARY", - "occupant":"IDENTIFIED" - }, - "communicationTemplates":[ - { - "id":1, - "medium":"EMAIL", - "type":"REMINDER" - }, - { - "id":2, - "medium":"LETTER", - "type":"NOTICE" - } - ], - "communicationRequests":[ - { - "communicationTemplateId":1, - "reason":"REFUSAL", - "emitter":"INTERVIEWER", - "status":[ - { - "date":1721903754305, - "status":"INITIATED" - }, - { - "date":1721903755305, - "status":"READY" - }, - { - "date":1721903756305, - "status":"SUBMITTED" - } - ] - }, - { - "communicationTemplateId":2, - "reason":"UNREACHABLE", - "emitter":"INTERVIEWER", - "status":[ - { - "date":1721903754305, - "status":"INITIATED" - }, - { - "date":1721903756310, - "status":"READY" - } - ] - } - ] - }"""; - JSONAssert.assertEquals(expectedJson, resultJson, JSONCompareMode.NON_EXTENSIBLE); - } + String resultJson = result.getResponse().getContentAsString(); + String expectedJson = """ + { + "id":"11", + "displayName":"business-id-11", + "persons":[ + { + "id":1, + "title":"MISTER", + "firstName":"Ted", + "lastName":"Farmer", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":true, + "phoneNumbers":[ + { + "source":"FISCAL", + "favorite":false, + "number":"+33677542802" + }, + { + "source":"FISCAL", + "favorite":true, + "number":"+33677542802" + } + ] + }, + { + "id":6, + "title":"MISS", + "firstName":"Christine", + "lastName":"Aguilar", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":false, + "phoneNumbers":[ + { + "source":"FISCAL", + "favorite":true, + "number":"+33677542802" + } + ] + }, + { + "id":7, + "title":"MISS", + "firstName":"Louise", + "lastName":"Walker", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":false, + "phoneNumbers":[ + { + "source":"FISCAL", + "favorite":true, + "number":"+33677542802" + } + ] + } + ], + "address":{ + "l1":"Ted Farmer", + "l2":"", + "l3":"", + "l4":"1 rue de la gare", + "l5":"", + "l6":"29270 Carhaix", + "l7":"France", + "elevator":true, + "building":"Bat. C", + "floor":"Etg 4", + "door":"Porte 48", + "staircase":"Escalier B", + "cityPriorityDistrict":true + }, + "priority":true, + "campaign":"SIMPSONS2020X00", + "comments":[], + "sampleIdentifiers":{ + "bs":11, + "ec":"1", + "le":11, + "noi":11, + "numfa":11, + "rges":11, + "ssech":1, + "nolog":11, + "nole":11, + "autre":"11", + "nograp":"11" + }, + "states":[ + { + "id":1, + "date":111112111, + "type":"VIN" + }, + { + "id":7, + "date":101111111, + "type":"TBR" + } + ], + "contactAttempts":[], + "identification":{ + "identification":"IDENTIFIED", + "access":"ACC", + "situation":"ORDINARY", + "category":"PRIMARY", + "occupant":"IDENTIFIED" + }, + "communicationTemplates":[ + { + "id": "mesh1", + "campaignId": "SIMPSONS2020X00", + "meshuggahId":"mesh1", + "medium":"EMAIL", + "type":"REMINDER" + }, + { + "id": "mesh2", + "campaignId": "SIMPSONS2020X00", + "meshuggahId":"mesh2", + "medium":"LETTER", + "type":"NOTICE" + } + ], + "communicationRequests":[ + { + "communicationTemplateId":"mesh1", + "campaignId":"SIMPSONS2020X00", + "meshuggahId": "mesh1", + "reason":"REFUSAL", + "emitter":"INTERVIEWER", + "status":[ + { + "date":1721903754305, + "status":"INITIATED" + }, + { + "date":1721903755305, + "status":"READY" + }, + { + "date":1721903756305, + "status":"SUBMITTED" + } + ] + }, + { + "communicationTemplateId": "mesh2", + "campaignId":"SIMPSONS2020X00", + "meshuggahId": "mesh2", + "reason":"UNREACHABLE", + "emitter":"INTERVIEWER", + "status":[ + { + "date":1721903754305, + "status":"INITIATED" + }, + { + "date":1721903756310, + "status":"READY" + } + ] + } + ] + }"""; + JSONAssert.assertEquals(expectedJson, resultJson, JSONCompareMode.NON_EXTENSIBLE); + } - /** - * Test that the PUT endpoint "api/survey-unit/{id}" - * return 200 - * - * @throws Exception - */ - @Test - @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) - void testPutSurveyUnitDetail() throws Exception { - long currentTimestamp = dateService.getCurrentTimestamp(); - String updateJson = """ - { - "id":"20", - "persons":[ - { - "id":10, - "title":"MISTER", - "firstName":"Harriette", - "lastName":"Raymond", - "email":"test@test.com", - "birthdate":11111111, - "favoriteEmail":true, - "privileged":true, - "phoneNumbers":[ - { - "source":"FISCAL", - "favorite":true, - "number":"test" - } - ] - } - ], - "address":{ - "l1":"test1", - "l2":"test2", - "l3":"test3", - "l4":"test4", - "l5":"test5", - "l6":"test6", - "l7":"test7", - "elevator":true, - "building":"testBuilding", - "floor":"testFloor", - "door":"testDoor", - "staircase":"testStaircase", - "cityPriorityDistrict":true - }, - "priority":false, - "campaign":"VQS2021X00", - "comments":[ - { - "type":"INTERVIEWER", - "value":"test-interviewer-comment" - }, - { - "type":"MANAGEMENT", - "value":"test-management-comment" - } - ], - "sampleIdentifiers":{ - "bs":20, - "ec":"2", - "le":20, - "noi":20, - "numfa":20, - "rges":20, - "ssech":1, - "nolog":20, - "nole":20, - "autre":"20", - "nograp":"20" - }, - "states":[ - { - "date":1590504459838, - "type":"AOC" - }, - { - "id":9, - "date":1590504478334, - "type":"VIC" - } - ], - "contactAttempts":[ - { - "date":1589268626000, - "status":"NOC", - "medium":"TEL" - }, - { - "date":1589268800000, - "status":"INA", - "medium":"TEL" - } - ], - "contactOutcome":{ - "date":1589268626000, - "type":"IMP", - "totalNumberOfContactAttempts":2 - }, - "communicationRequests":[ - { - "communicationTemplateId":5, - "reason":"REFUSAL", - "creationTimestamp": 1721903754305 - }, - { - "communicationTemplateId":5, - "reason":"UNREACHABLE", - "creationTimestamp": 1721903754405 - } - ] - }"""; - MvcResult result = mockMvc.perform(put("/api/survey-unit/20") - .with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)) - .accept(MediaType.APPLICATION_JSON) - .content(updateJson) - .contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + /** + * Test that the PUT endpoint "api/survey-unit/{id}" + * return 200 + * + * @throws Exception e + */ + @Test + @Sql(value = ScriptConstants.REINIT_SQL_SCRIPT, executionPhase = AFTER_TEST_METHOD) + void testPutSurveyUnitDetail() throws Exception { + long currentTimestamp = dateService.getCurrentTimestamp(); + String updateJson = """ + { + "id":"20", + "persons":[ + { + "id":10, + "title":"MISTER", + "firstName":"Harriette", + "lastName":"Raymond", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":true, + "phoneNumbers":[ + { + "source":"FISCAL", + "favorite":true, + "number":"test" + } + ] + } + ], + "address":{ + "l1":"test1", + "l2":"test2", + "l3":"test3", + "l4":"test4", + "l5":"test5", + "l6":"test6", + "l7":"test7", + "elevator":true, + "building":"testBuilding", + "floor":"testFloor", + "door":"testDoor", + "staircase":"testStaircase", + "cityPriorityDistrict":true + }, + "priority":false, + "campaign":"VQS2021X00", + "comments":[ + { + "type":"INTERVIEWER", + "value":"test-interviewer-comment" + }, + { + "type":"MANAGEMENT", + "value":"test-management-comment" + } + ], + "sampleIdentifiers":{ + "bs":20, + "ec":"2", + "le":20, + "noi":20, + "numfa":20, + "rges":20, + "ssech":1, + "nolog":20, + "nole":20, + "autre":"20", + "nograp":"20" + }, + "states":[ + { + "date":1590504459838, + "type":"AOC" + }, + { + "id":9, + "date":1590504478334, + "type":"VIC" + } + ], + "contactAttempts":[ + { + "date":1589268626000, + "status":"NOC", + "medium":"TEL" + }, + { + "date":1589268800000, + "status":"INA", + "medium":"TEL" + } + ], + "contactOutcome":{ + "date":1589268626000, + "type":"IMP", + "totalNumberOfContactAttempts":2 + }, + "communicationRequests":[ + { + "communicationTemplateId":"mesh3", + "reason":"REFUSAL", + "creationTimestamp": 1721903754305 + }, + { + "communicationTemplateId":"mesh4", + "reason":"UNREACHABLE", + "creationTimestamp": 1721903754405 + } + ] + }"""; + MvcResult result = + mockMvc.perform(put("/api/survey-unit/20").with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)).accept(MediaType.APPLICATION_JSON).content(updateJson).contentType(MediaType.APPLICATION_JSON)).andReturn(); - String resultJson = result.getResponse().getContentAsString(); - String expectedJson = """ - { - "id":"20", - "persons":[ - { - "id":10, - "title":"MISTER", - "firstName":"Harriette", - "lastName":"Raymond", - "email":"test@test.com", - "birthdate":11111111, - "favoriteEmail":true, - "privileged":true, - "phoneNumbers":[ - { - "source":"FISCAL", - "favorite":true, - "number":"test" - } - ] - } - ], - "address":{ - "l1":"test1", - "l2":"test2", - "l3":"test3", - "l4":"test4", - "l5":"test5", - "l6":"test6", - "l7":"test7", - "elevator":true, - "building":"testBuilding", - "floor":"testFloor", - "door":"testDoor", - "staircase":"testStaircase", - "cityPriorityDistrict":true - }, - "priority":false, - "campaign":"VQS2021X00", - "comments":[ - { - "type":"INTERVIEWER", - "value":"test-interviewer-comment" - }, - { - "type":"MANAGEMENT", - "value":"test-management-comment" - } - ], - "sampleIdentifiers":{ - "bs":20, - "ec":"2", - "le":20, - "noi":20, - "numfa":20, - "rges":20, - "ssech":1, - "nolog":20, - "nole":20, - "autre":"20", - "nograp":"20" - }, - "states":[ - { - "id":9, - "date":1590504478334, - "type":"VIC" - }, - { - "id":14, - "date":1590504459838, - "type":"AOC" - } - ], - "contactAttempts":[ - { - "date":1589268626000, - "status":"NOC", - "medium":"TEL" - }, - { - "date":1589268800000, - "status":"INA", - "medium":"TEL" - } - ], - "contactOutcome":{ - "date":1589268626000, - "type":"IMP", - "totalNumberOfContactAttempts":2 - }, - "communicationRequests":[ - { - "communicationTemplateId":5, - "reason":"REFUSAL", - "emitter":"INTERVIEWER", - "status":[ - { - "date":1721903754305, - "status":"INITIATED" - }, - { - "date":""" + currentTimestamp + """ + String resultJson = result.getResponse().getContentAsString(); + String expectedJson = """ + { + "id":"20", + "persons":[ + { + "id":10, + "title":"MISTER", + "firstName":"Harriette", + "lastName":"Raymond", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":true, + "phoneNumbers":[ + { + "source":"FISCAL", + "favorite":true, + "number":"test" + } + ] + } + ], + "address":{ + "l1":"test1", + "l2":"test2", + "l3":"test3", + "l4":"test4", + "l5":"test5", + "l6":"test6", + "l7":"test7", + "elevator":true, + "building":"testBuilding", + "floor":"testFloor", + "door":"testDoor", + "staircase":"testStaircase", + "cityPriorityDistrict":true + }, + "priority":false, + "campaign":"VQS2021X00", + "comments":[ + { + "type":"INTERVIEWER", + "value":"test-interviewer-comment" + }, + { + "type":"MANAGEMENT", + "value":"test-management-comment" + } + ], + "sampleIdentifiers":{ + "bs":20, + "ec":"2", + "le":20, + "noi":20, + "numfa":20, + "rges":20, + "ssech":1, + "nolog":20, + "nole":20, + "autre":"20", + "nograp":"20" + }, + "states":[ + { + "id":9, + "date":1590504478334, + "type":"VIC" + }, + { + "id":14, + "date":1590504459838, + "type":"AOC" + } + ], + "contactAttempts":[ + { + "date":1589268626000, + "status":"NOC", + "medium":"TEL" + }, + { + "date":1589268800000, + "status":"INA", + "medium":"TEL" + } + ], + "contactOutcome":{ + "date":1589268626000, + "type":"IMP", + "totalNumberOfContactAttempts":2 + }, + "communicationRequests":[ + { + "communicationTemplateId": "mesh3", + "campaignId":"VQS2021X00", + "meshuggahId": "mesh3", + "reason":"REFUSAL", + "emitter":"INTERVIEWER", + "status":[ + { + "date":1721903754305, + "status":"INITIATED" + }, + { + "date":""" + currentTimestamp + """ , "status":"READY" } - ] - }, + ] + }, { - "communicationTemplateId":4, + "communicationTemplateId": "mesh4", + "campaignId":"VQS2021X00", + "meshuggahId": "mesh4", "reason":"UNREACHABLE", "emitter":"INTERVIEWER", "status":[ @@ -529,7 +545,9 @@ void testPutSurveyUnitDetail() throws Exception { ] }, { - "communicationTemplateId":5, + "communicationTemplateId": "mesh4", + "campaignId":"VQS2021X00", + "meshuggahId": "mesh4", "reason":"UNREACHABLE", "emitter":"INTERVIEWER", "status":[ @@ -538,105 +556,238 @@ void testPutSurveyUnitDetail() throws Exception { "status":"INITIATED" }, { - "date":""" + currentTimestamp + """ - , - "status":"READY" - } + "date": 1719324512000, + "status": "CANCELLED" + } ] }, - { - "communicationTemplateId":3, - "reason":"REFUSAL", - "emitter":"INTERVIEWER", - "status":[ - { - "date":1721903754205, - "status":"INITIATED" - } - ] - } - ] - }"""; - JSONAssert.assertEquals(expectedJson, resultJson, JSONCompareMode.NON_EXTENSIBLE); - } + { + "communicationTemplateId": "mesh3", + "campaignId":"VQS2021X00", + "meshuggahId": "mesh3", + "reason":"REFUSAL", + "emitter":"INTERVIEWER", + "status":[ + { + "date":1721903754205, + "status":"INITIATED" + } + ] + } + ] + }"""; + JSONAssert.assertEquals(expectedJson, resultJson, JSONCompareMode.NON_EXTENSIBLE); + } + + @Test + @DisplayName("Should throw exception when communication template not found") + void testPutSurveyUnitDetailException() throws Exception { + String updateJson = """ + { + "id":"20", + "persons":[ + { + "id":10, + "title":"MISTER", + "firstName":"Harriette", + "lastName":"Raymond", + "email":"test@test.com", + "birthdate":11111111, + "favoriteEmail":true, + "privileged":true, + "phoneNumbers":[ + ] + } + ], + "address":{ + "l1":"test1", + "l2":"test2", + "l3":"test3", + "l4":"test4", + "l5":"test5", + "l6":"test6", + "l7":"test7", + "elevator":true, + "building":"testBuilding", + "floor":"testFloor", + "door":"testDoor", + "staircase":"testStaircase", + "cityPriorityDistrict":true + }, + "priority":false, + "campaign":"VQS2021X00", + "comments":[], + "sampleIdentifiers":{ + "bs":20, + "ec":"2", + "le":20, + "noi":20, + "numfa":20, + "rges":20, + "ssech":1, + "nolog":20, + "nole":20, + "autre":"20", + "nograp":"20" + }, + "states":[ + { + "date":1590504459838, + "type":"AOC" + } + ], + "contactAttempts":[], + "contactOutcome":{ + "date":1589268626000, + "type":"IMP", + "totalNumberOfContactAttempts":2 + }, + "communicationRequests":[ + { + "communicationTemplateId":"NOT_EXIST", + "reason":"UNREACHABLE", + "creationTimestamp": 1721903754405 + } + ] + }"""; + String putUrl = "/api/survey-unit/20"; + mockMvc.perform(put(putUrl).with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)).accept(MediaType.APPLICATION_JSON).content(updateJson).contentType(MediaType.APPLICATION_JSON)).andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, putUrl, CommunicationTemplateNotFoundException.MESSAGE)); + } + + @Test + @DisplayName("Should return all survey-units for a campaign") + void testGetAllSurveyUnitsByCampaign() throws Exception { + MvcResult mvcResult = + mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units").with(authentication(AuthenticatedUserTestHelper.AUTH_LOCAL_USER)).accept(MediaType.APPLICATION_JSON)).andReturn(); + + String contentResult = mvcResult.getResponse().getContentAsString(); + String expectedResult = """ + [ + { + "id":"12", + "displayName":"business-id-12", + "ssech":1, + "location":"90000", + "city":"Belfort", + "campaign":"Survey on the Simpsons tv show 2020", + "state":"TBR", + "reading":true, + "viewed":false, + "comments":[], + "interviewer":{ + "id":"INTW1", + "interviewerFirstName":"Margie", + "interviewerLastName":"Lucas" + } + }, + { + "id":"13", + "displayName":"business-id-13", + "ssech":2, + "location":"32230", + "city":"Marciac", + "campaign":"Survey on the Simpsons tv show 2020", + "state":"TBR", + "reading":true, + "viewed":false, + "comments":[ + { + "type":"INTERVIEWER", + "value":"un commentaire" + } + ], + "interviewer":{ + "id":"INTW2", + "interviewerFirstName":"Carlton", + "interviewerLastName":"Campbell" + } + }, + { + "id":"24", + "displayName":"business-id-24", + "ssech":1, + "location":"35000", + "city":"Rennes", + "campaign":"Survey on the Simpsons tv show 2020", + "state":"TBR", + "reading":true, + "viewed":false, + "contactOutcome":{ + "date":1590504478334, + "type":"DUK", + "totalNumberOfContactAttempts":null + }, + "comments":[] + }, + { + "id":"14", + "displayName":"business-id-14", + "ssech":3, + "location":"44190", + "city":"Clisson", + "campaign":"Survey on the Simpsons tv show 2020", + "state":"TBR", + "reading":true, + "viewed":false, + "comments":[], + "interviewer":{ + "id":"INTW3", + "interviewerFirstName":"Gerald", + "interviewerLastName":"Edwards" + } + }, + { + "id":"11", + "displayName":"business-id-11", + "ssech":1, + "location":"29270", + "city":"Carhaix", + "campaign":"Survey on the Simpsons tv show 2020", + "closingCause":"NPI", + "state":"VIN", + "reading":true, + "viewed":false, + "comments":[], + "interviewer":{ + "id":"INTW1", + "interviewerFirstName":"Margie", + "interviewerLastName":"Lucas" + } + } + ] + """; + JSONAssert.assertEquals(expectedResult, contentResult, JSONCompareMode.NON_EXTENSIBLE); + } + + @Test + @DisplayName("Should return survey units for a campaign filtered by state") + void testGetSurveyUnitsByCampaign02() throws Exception { + MvcResult mvcResult = + mockMvc.perform(get("/api/campaign/SIMPSONS2020X00/survey-units?state=VIN").with(authentication(AuthenticatedUserTestHelper.AUTH_LOCAL_USER)).accept(MediaType.APPLICATION_JSON)).andReturn(); - @Test - @DisplayName("Should throw exception when communication template not found") - void testPutSurveyUnitDetailException() throws Exception { - String updateJson = """ - { - "id":"20", - "persons":[ - { - "id":10, - "title":"MISTER", - "firstName":"Harriette", - "lastName":"Raymond", - "email":"test@test.com", - "birthdate":11111111, - "favoriteEmail":true, - "privileged":true, - "phoneNumbers":[ - ] - } - ], - "address":{ - "l1":"test1", - "l2":"test2", - "l3":"test3", - "l4":"test4", - "l5":"test5", - "l6":"test6", - "l7":"test7", - "elevator":true, - "building":"testBuilding", - "floor":"testFloor", - "door":"testDoor", - "staircase":"testStaircase", - "cityPriorityDistrict":true - }, - "priority":false, - "campaign":"VQS2021X00", - "comments":[], - "sampleIdentifiers":{ - "bs":20, - "ec":"2", - "le":20, - "noi":20, - "numfa":20, - "rges":20, - "ssech":1, - "nolog":20, - "nole":20, - "autre":"20", - "nograp":"20" - }, - "states":[ - { - "date":1590504459838, - "type":"AOC" - } - ], - "contactAttempts":[], - "contactOutcome":{ - "date":1589268626000, - "type":"IMP", - "totalNumberOfContactAttempts":2 - }, - "communicationRequests":[ - { - "communicationTemplateId":6, - "reason":"UNREACHABLE", - "creationTimestamp": 1721903754405 - } - ] - }"""; - String putUrl = "/api/survey-unit/20"; - mockMvc.perform(put(putUrl) - .with(authentication(AuthenticatedUserTestHelper.AUTH_INTERVIEWER)) - .accept(MediaType.APPLICATION_JSON) - .content(updateJson) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcTestUtils.apiErrorMatches(HttpStatus.NOT_FOUND, putUrl, CommunicationTemplateNotFoundException.MESSAGE)); - } + String contentResult = mvcResult.getResponse().getContentAsString(); + String expectedResult = """ + [ + { + "id":"11", + "displayName":"business-id-11", + "ssech":1, + "location":"29270", + "city":"Carhaix", + "campaign":"Survey on the Simpsons tv show 2020", + "closingCause":"NPI", + "state":"VIN", + "reading":true, + "viewed":false, + "comments":[], + "interviewer":{ + "id":"INTW1", + "interviewerFirstName":"Margie", + "interviewerLastName":"Lucas" + } + } + ] + """; + JSONAssert.assertEquals(expectedResult, contentResult, JSONCompareMode.NON_EXTENSIBLE); + } } diff --git a/src/test/resources/application-auth.yml b/src/test/resources/application-auth.yml index a225656e..2d3ded1d 100644 --- a/src/test/resources/application-auth.yml +++ b/src/test/resources/application-auth.yml @@ -15,11 +15,27 @@ spring: contexts: test defaultSchema: public change-log: classpath:db/integration-test.xml + docker: + compose: + enabled: true + file: compose.yml + lifecycle-management: start-and-stop + start: + command: up + stop: + command: down + timeout: 1m + arguments: -v + skip: + in-tests: false datasource: - url: jdbc:h2:mem:testauthdb;NON_KEYWORDS=user,value;DATABASE_TO_UPPER=TRUE;DEFAULT_NULL_ORDERING=HIGH;INIT=create domain if not exists jsonb as json;MODE=PostgreSQL - driverClassName: org.h2.Driver - username: sa - password: password + url: jdbc:postgresql://localhost:5434/pearl + username: mypostgresuser + password: mypostgrespassword + driver-class-name: org.postgresql.Driver + hikari: + minimum-idle: 1 + maximum-pool-size: 1 logging: level: root: INFO diff --git a/src/test/resources/application-demo.yml b/src/test/resources/application-demo.yml new file mode 100644 index 00000000..5030cfb8 --- /dev/null +++ b/src/test/resources/application-demo.yml @@ -0,0 +1,61 @@ +application: + corsOrigins: '*' + roles: + interviewer: interviewer_access + local_user: local_manager_access + national_user: national_manager_access + admin: admin_access + webclient: webclient_access + +spring: + application: + name: api + liquibase: + enabled: true + contexts: demo + defaultSchema: public + change-log: classpath:db/integration-demo.xml + docker: + compose: + enabled: true + file: compose.yml + lifecycle-management: start-and-stop + start: + command: up + stop: + command: down + timeout: 1m + arguments: -v + skip: + in-tests: false + datasource: + url: jdbc:postgresql://localhost:5434/pearl + username: mypostgresuser + password: mypostgrespassword + driver-class-name: org.postgresql.Driver + hikari: + minimum-idle: 1 + maximum-pool-size: 1 + +logging: + level: + root: INFO + +feature: + oidc: + enabled: false + +fr: + insee: + pearljam: + #Datacollection config + datacollection: + service: + url: + scheme: http + host: localhost + port: 8081 + #Mail service config + mail: + service: + enabled: false \ No newline at end of file diff --git a/src/test/resources/application-noauth.yml b/src/test/resources/application-noauth.yml index 866b0b94..870131a4 100644 --- a/src/test/resources/application-noauth.yml +++ b/src/test/resources/application-noauth.yml @@ -15,11 +15,27 @@ spring: contexts: test defaultSchema: public change-log: classpath:db/integration-test.xml + docker: + compose: + enabled: true + file: compose.yml + lifecycle-management: start-and-stop + start: + command: up + stop: + command: down + timeout: 1m + arguments: -v + skip: + in-tests: false datasource: - url: jdbc:h2:mem:testnoauthdb;NON_KEYWORDS=user,value;DATABASE_TO_UPPER=TRUE;DEFAULT_NULL_ORDERING=HIGH;INIT=create domain if not exists jsonb as json;MODE=PostgreSQL - driverClassName: org.h2.Driver - username: sa - password: password + url: jdbc:postgresql://localhost:5434/pearl + username: mypostgresuser + password: mypostgrespassword + driver-class-name: org.postgresql.Driver + hikari: + minimum-idle: 1 + maximum-pool-size: 1 logging: level: diff --git a/src/test/resources/features/identification.feature b/src/test/resources/features/identification.feature new file mode 100644 index 00000000..79949d22 --- /dev/null +++ b/src/test/resources/features/identification.feature @@ -0,0 +1,42 @@ +Feature: Identification + + Scenario Outline: Configure a campaign identification behavior + Given a user with "admin" role + When the user create a campaign with identificationConfiguration equals to "" + Then the created campaign should have the identification configuration "" + + Examples: + | identificationConfiguration | + | IASCO | + | HOUSEF2F | + | HOUSETEL | + | HOUSETELWSR | + | INDF2F | + | INDF2FNOR | + | INDTEL | + | INDTELNOR | + | SRCVREINT | + | NOIDENT | + + + Scenario Outline: Persist a survey unit identification + Given a user with "interviewer" role + And a survey-unit is in a campaign with identification configuration equals to "" + And this survey-unit is affected to this interviewer + When the interviewer update the survey-unit with identification value + Then the survey-unit is updated and its identification equals: + """ + + """ + + Examples: + | identificationConfiguration | expectedValue | + | IASCO | {"identification":"UNIDENTIFIED","access":"ACC","situation":"ORDINARY","category":"PRIMARY","occupant":"IDENTIFIED"} | + | HOUSEF2F | {"identification":"UNIDENTIFIED","access":"ACC","situation":"ORDINARY","category":"PRIMARY","occupant":"IDENTIFIED"} | + | HOUSETEL | {"situation":"ORDINARY","category":"PRIMARY"} | + | HOUSETELWSR | {"situation":"ORDINARY","category":"PRIMARY"} | + | INDF2F | {"individualStatus":"SAME_ADDRESS","interviewerCanProcess":"YES","situation":"ORDINARY"} | + | INDF2FNOR | {"individualStatus":"SAME_ADDRESS","interviewerCanProcess":"YES","situation":"ORDINARY"} | + | INDTEL | {"individualStatus":"SAME_ADDRESS","situation":"ORDINARY"} | + | INDTELNOR | {"individualStatus":"SAME_ADDRESS","situation":"ORDINARY"} | + | SRCVREINT | {"numberOfRespondents":"ONE","individualStatus":"SAME_ADDRESS","householdComposition":"SAME_COMPO","presentInPreviousHome":"AT_LEAST_ONE","situation":"ORDINARY"} |