From 43168ef02adb8e45ec3ed2f95762d6539bf45700 Mon Sep 17 00:00:00 2001
From: "florian.azizian" <florian.azizian@maarch.org>
Date: Wed, 17 Apr 2019 09:38:36 +0100
Subject: [PATCH] FEAT #8391 continue link with xParaph

---
 .../batch/process_mailsFromSignatoryBook.php  |  14 +-
 modules/visa/xml/remoteSignatoryBooks.xml     |   6 +-
 package.json                                  |  26 +-
 rest/index.php                                |   2 +
 .../ExternalSignatoryBookTrait.php            |  16 +-
 .../PreProcessActionController.php            |  67 ++++-
 .../controllers/XParaphController.php         | 257 +++++++++++++++---
 ...ernal-signatory-book-action.component.html |  21 +-
 ...xternal-signatory-book-action.component.ts |   2 +-
 9 files changed, 334 insertions(+), 77 deletions(-)

diff --git a/modules/visa/batch/process_mailsFromSignatoryBook.php b/modules/visa/batch/process_mailsFromSignatoryBook.php
index 6e904a4dd32..d20f00d2697 100755
--- a/modules/visa/batch/process_mailsFromSignatoryBook.php
+++ b/modules/visa/batch/process_mailsFromSignatoryBook.php
@@ -184,8 +184,6 @@ try {
             $signatoryBook = "/modules/visa/class/IParapheurController.php";
         } elseif ($configRemoteSignatoryBook['id'] == 'fastParapheur') {
             $signatoryBook = "/modules/visa/class/FastParapheurController.php";
-        } elseif ($configRemoteSignatoryBook['id'] == 'maarchParapheur') {
-            $signatoryBook = "/modules/visa/class/MaarchParapheurController.php";
         }
     } else {
         $GLOBALS['logger']->write('no signatory book enabled', 'ERROR', 102);
@@ -194,16 +192,18 @@ try {
     }
 
     // On inclut la classe du parapheur activé
-    if (file_exists($GLOBALS['MaarchDirectory'] . 'custom/' . $GLOBALS['CustomId'] . $signatoryBook)) {
+    if (is_file($GLOBALS['MaarchDirectory'] . 'custom/' . $GLOBALS['CustomId'] . $signatoryBook)) {
         $classToInclude = $GLOBALS['MaarchDirectory'] . 'custom/' . $GLOBALS['CustomId'] . $signatoryBook;
-    } elseif (file_exists($GLOBALS['MaarchDirectory'] . $signatoryBook)) {
+        Bt_myInclude($classToInclude);
+    } elseif (is_file($GLOBALS['MaarchDirectory'] . $signatoryBook)) {
         $classToInclude = $GLOBALS['MaarchDirectory'] . $signatoryBook;
-    } else {
+        Bt_myInclude($classToInclude);
+    } elseif (!in_array($configRemoteSignatoryBook['id'], ['maarchParapheur', 'xParaph'])) {
         $GLOBALS['logger']->write('No class detected', 'ERROR', 102);
         echo "\nNo class detected ! \nThe batch cannot be launched !\n\n";
         exit(102);
     }
-    Bt_myInclude($classToInclude);
+
 } catch (IncludeFileError $e) {
     $GLOBALS['logger']->write(
         'Problem with the php include path:' .$e .' '. get_include_path(),
@@ -263,6 +263,8 @@ if ($configRemoteSignatoryBook['id'] == 'ixbus') {
     $retrievedMails = FastParapheurController::retrieveSignedMails(['config' => $configRemoteSignatoryBook, 'idsToRetrieve' => $idsToRetrieve]);
 } elseif ($configRemoteSignatoryBook['id'] == 'maarchParapheur') {
     $retrievedMails = \ExternalSignatoryBook\controllers\MaarchParapheurController::retrieveSignedMails(['config' => $configRemoteSignatoryBook, 'idsToRetrieve' => $idsToRetrieve]);
+} elseif ($configRemoteSignatoryBook['id'] == 'xParaph') {
+    $retrievedMails = \ExternalSignatoryBook\controllers\XParaphController::retrieveSignedMails(['config' => $configRemoteSignatoryBook, 'idsToRetrieve' => $idsToRetrieve]);
 }
 
 if (!empty($retrievedMails['error'])) {
diff --git a/modules/visa/xml/remoteSignatoryBooks.xml b/modules/visa/xml/remoteSignatoryBooks.xml
index 3783ef80776..0efdf033c72 100755
--- a/modules/visa/xml/remoteSignatoryBooks.xml
+++ b/modules/visa/xml/remoteSignatoryBooks.xml
@@ -48,12 +48,10 @@
     <signatoryBook>
         <id>xParaph</id>
         <url>https://preprodssl.ssl.spl-xdemat.fr/Xparaph/wsdl/wsdl.php</url>
-        <login></login>
-        <password></password>
-        <siret></siret>
         <docutype>101</docutype>
         <docustype>9</docustype>
-        <validatedState>VAL</validatedState>
+        <validatedStateSignature>VAL</validatedStateSignature>
+        <validatedStateNoSignature>VAL</validatedStateNoSignature>
         <refusedState>REF</refusedState>
     </signatoryBook>
 </root>
diff --git a/package.json b/package.json
index 05af0b18076..64a2157c864 100755
--- a/package.json
+++ b/package.json
@@ -17,7 +17,7 @@
     "chart.js": "1.1.1",
     "chosen-js": "^1.8.7",
     "core-js": "^2.6.5",
-    "jquery": "^3.3.1",
+    "jquery": "^3.4.0",
     "jquery-typeahead": "^2.10.6",
     "jquery.nicescroll": "~3.6.8",
     "jstree-bootstrap-theme": "^1.0.1",
@@ -34,20 +34,20 @@
   },
   "devDependencies": {
     "@angular-devkit/build-angular": "^0.12.2",
-    "@angular/animations": "^7.2.11",
+    "@angular/animations": "^7.2.13",
     "@angular/cdk": "^7.3.6",
     "@angular/cli": "^7.3.7",
-    "@angular/common": "^7.2.11",
-    "@angular/compiler": "^7.2.11",
-    "@angular/compiler-cli": "^7.2.11",
-    "@angular/core": "^7.2.11",
-    "@angular/forms": "^7.2.11",
-    "@angular/http": "^7.2.11",
+    "@angular/common": "^7.2.13",
+    "@angular/compiler": "^7.2.13",
+    "@angular/compiler-cli": "^7.2.13",
+    "@angular/core": "^7.2.13",
+    "@angular/forms": "^7.2.13",
+    "@angular/http": "^7.2.13",
     "@angular/material": "^7.3.6",
-    "@angular/platform-browser": "^7.2.11",
-    "@angular/platform-browser-dynamic": "^7.2.11",
-    "@angular/platform-server": "^7.2.11",
-    "@angular/router": "^7.2.11",
+    "@angular/platform-browser": "^7.2.13",
+    "@angular/platform-browser-dynamic": "^7.2.13",
+    "@angular/platform-server": "^7.2.13",
+    "@angular/router": "^7.2.13",
     "@types/datatables.net": "^1.10.17",
     "@types/jquery": "^2.0.51",
     "@types/node": "^7.10.1",
@@ -61,7 +61,7 @@
     "tslib": "^1.9.0",
     "typescript": "3.2.4",
     "url-loader": "^1.1.2",
-    "webpack": "^4.29.5"
+    "webpack": "^4.30.0"
   },
   "repository": {}
 }
diff --git a/rest/index.php b/rest/index.php
index dd7a57fce3c..5f24564e346 100755
--- a/rest/index.php
+++ b/rest/index.php
@@ -377,4 +377,6 @@ $app->post('/saveNumericPackage', \Sendmail\Controllers\ReceiveMessageExchangeCo
 $app->post('/saveMessageExchangeReturn', \Sendmail\Controllers\ReceiveMessageExchangeController::class . ':saveMessageExchangeReturn');
 $app->post('/saveMessageExchangeReview', \Sendmail\Controllers\MessageExchangeReviewController::class . ':saveMessageExchangeReview');
 
+$app->get('/xParaphWorkflow', \ExternalSignatoryBook\controllers\XParaphController::class . ':getWorkflow');
+
 $app->run();
diff --git a/src/app/action/controllers/ExternalSignatoryBookTrait.php b/src/app/action/controllers/ExternalSignatoryBookTrait.php
index d07bc20aaae..ecf2023c79f 100644
--- a/src/app/action/controllers/ExternalSignatoryBookTrait.php
+++ b/src/app/action/controllers/ExternalSignatoryBookTrait.php
@@ -75,9 +75,23 @@ trait ExternalSignatoryBookTrait
 
                 $historyInfo = ' (à ' . $processingUserInfo['firstname'] . ' ' . $processingUserInfo['lastname'] . ')';
             } elseif ($config['id'] == 'xParaph') {
+                $attachments = AttachmentModel::getOnView([
+                    'select'    => [
+                        'count(1) as nb'
+                    ],
+                    'where'     => ["res_id_master = ?", "attachment_type not in (?)", "status not in ('DEL', 'OBS', 'FRZ', 'TMP', 'SEND_MASS')", "in_signature_book = 'true'"],
+                    'data'      => [$args['resId'], ['converted_pdf', 'incoming_mail_attachment', 'print_folder', 'signed_response']]
+                ]);
+                if ($attachments[0]['nb'] == 0) {
+                    $noAttachmentsResource = ResModel::getExtById(['resId' => $args['resId'], 'select' => ['alt_identifier']]);
+                    return ['errors' => ['No attachment for this mail : ' . $noAttachmentsResource['alt_identifier']]];
+                }
+
                 $attachmentToFreeze = XParaphController::sendDatas([
                     'config'      => $config,
-                    'resIdMaster' => $args['resId']
+                    'resIdMaster' => $args['resId'],
+                    'info'        => $args['data']['info'],
+                    'steps'       => $args['data']['steps'],
                 ]);
             }
         }
diff --git a/src/app/action/controllers/PreProcessActionController.php b/src/app/action/controllers/PreProcessActionController.php
index 359b993b1f8..9187c270800 100644
--- a/src/app/action/controllers/PreProcessActionController.php
+++ b/src/app/action/controllers/PreProcessActionController.php
@@ -384,6 +384,12 @@ class PreProcessActionController
             }
 
             $signatureBookEnabled = $config['id'];
+            $additionalsInfos = [
+                'attachments'   => [],
+                'noAttachment'  => [],
+                'mails'         => [],
+                'noMail'        => []
+            ];
             if ($signatureBookEnabled == 'ixbus') {
                 // TODO
             } elseif ($signatureBookEnabled == 'iParapheur') {
@@ -391,12 +397,6 @@ class PreProcessActionController
             } elseif ($signatureBookEnabled == 'fastParapheur') {
                 // TODO
             } elseif ($signatureBookEnabled == 'maarchParapheur') {
-                $additionalsInfos = [
-                    'attachments'    => [],
-                    'noAttachment'   => [],
-                    'mails'          => [],
-                    'noMail'         => []
-                ];
                 $userList = MaarchParapheurController::getInitializeDatas(['config' => $config]);
                 if (!empty($userList['users'])) {
                     $additionalsInfos['users'] = $userList['users'];
@@ -476,7 +476,60 @@ class PreProcessActionController
                     }
                 }
             } elseif ($signatureBookEnabled == 'xParaph') {
-                // TODO
+                $userInfos  = UserModel::getByLogin(['login' => $GLOBALS['userId'], 'select' => ['external_id']]);
+                $externalId = json_decode($userInfos['external_id'], true);
+                $additionalsInfos['accounts'] = $externalId['xParaph'];
+
+                foreach ($data['resources'] as $resId) {
+                    $noAttachmentsResource = ResModel::getExtById(['resId' => $resId, 'select' => ['alt_identifier']]);
+                    if (empty($noAttachmentsResource['alt_identifier'])) {
+                        $noAttachmentsResource['alt_identifier'] = _UNDEFINED;
+                    }
+
+                    // Check attachments
+                    $attachments = AttachmentModel::getOnView([
+                        'select'    => [
+                            'res_id', 'res_id_version', 'title', 'identifier', 'attachment_type',
+                            'status', 'typist', 'docserver_id', 'path', 'filename', 'creation_date',
+                            'validation_date', 'relation', 'attachment_id_master'
+                        ],
+                        'where'     => ["res_id_master = ?", "attachment_type not in (?)", "status not in ('DEL', 'OBS', 'FRZ', 'TMP', 'SEND_MASS')", "in_signature_book = 'true'"],
+                        'data'      => [$resId, ['converted_pdf', 'incoming_mail_attachment', 'print_folder', 'signed_response']]
+                    ]);
+                    
+                    if (empty($attachments)) {
+                        $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resId, 'reason' => 'noAttachmentInSignatoryBook'];
+                    } else {
+                        foreach ($attachments as $value) {
+                            if (!empty($value['res_id'])) {
+                                $resIdAttachment = $value['res_id'];
+                                $collId          = 'attachments_coll';
+                                $is_version      = false;
+                            } else {
+                                $resIdAttachment = $value['res_id_version'];
+                                $collId          = 'attachments_version_coll';
+                                $is_version      = true;
+                            }
+                            
+                            $adrInfo = ConvertPdfController::getConvertedPdfById(['resId' => $resIdAttachment, 'collId' => $collId, 'isVersion' => $is_version]);
+                            if (empty($adrInfo['docserver_id'])) {
+                                $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resIdAttachment, 'reason' => 'noAttachmentConversion'];
+                                break;
+                            }
+                            $docserverInfo = DocserverModel::getByDocserverId(['docserverId' => $adrInfo['docserver_id']]);
+                            if (empty($docserverInfo['path_template'])) {
+                                $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resIdAttachment, 'reason' => 'docserverDoesNotExists'];
+                                break;
+                            }
+                            $filePath = $docserverInfo['path_template'] . str_replace('#', '/', $adrInfo['path']) . $adrInfo['filename'];
+                            if (!is_file($filePath)) {
+                                $additionalsInfos['noAttachment'][] = ['alt_identifier' => $noAttachmentsResource['alt_identifier'], 'res_id' => $resIdAttachment, 'reason' => 'fileDoesNotExists'];
+                                break;
+                            }
+                        }
+                        $additionalsInfos['attachments'][] = ['res_id' => $resId];
+                    }
+                }
             }
         }
 
diff --git a/src/app/external/externalSignatoryBook/controllers/XParaphController.php b/src/app/external/externalSignatoryBook/controllers/XParaphController.php
index af4081eb665..89df3f097be 100755
--- a/src/app/external/externalSignatoryBook/controllers/XParaphController.php
+++ b/src/app/external/externalSignatoryBook/controllers/XParaphController.php
@@ -17,6 +17,9 @@ namespace ExternalSignatoryBook\controllers;
 use Attachment\models\AttachmentModel;
 use Convert\controllers\ConvertPdfController;
 use Docserver\models\DocserverModel;
+use Slim\Http\Request;
+use Slim\Http\Response;
+use SrcCore\models\CoreConfigModel;
 use SrcCore\models\CurlModel;
 
 class XParaphController
@@ -25,10 +28,7 @@ class XParaphController
     {
         $attachments = AttachmentModel::getOnView([
             'select'    => [
-                'res_id', 'res_id_version', 'title', 'identifier', 'attachment_type',
-                'status', 'typist', 'docserver_id', 'path', 'filename', 'creation_date',
-                'validation_date', 'relation', 'attachment_id_master', 'filesize'
-            ],
+                'res_id', 'res_id_version', 'title'],
             'where'     => ["res_id_master = ?", "attachment_type not in (?)", "status not in ('DEL', 'OBS', 'FRZ', 'TMP')", "in_signature_book = 'true'"],
             'data'      => [$aArgs['resIdMaster'], ['converted_pdf', 'incoming_mail_attachment', 'print_folder', 'signed_response']]
         ]);
@@ -37,38 +37,54 @@ class XParaphController
 
         foreach ($attachments as $value) {
             if (!empty($value['res_id'])) {
-                $resId  = $value['res_id'];
-                $collId = 'attachments_coll';
+                $resId      = $value['res_id'];
+                $collId     = 'attachments_coll';
                 $is_version = false;
             } else {
-                $resId  = $value['res_id_version'];
-                $collId = 'attachments_version_coll';
+                $resId      = $value['res_id_version'];
+                $collId     = 'attachments_version_coll';
                 $is_version = true;
             }
+
             $adrInfo       = ConvertPdfController::getConvertedPdfById(['resId' => $resId, 'collId' => $collId, 'isVersion' => $is_version]);
             $docserverInfo = DocserverModel::getByDocserverId(['docserverId' => $adrInfo['docserver_id']]);
             $filePath      = $docserverInfo['path_template'] . str_replace('#', '/', $adrInfo['path']) . $adrInfo['filename'];
-            $fileContent = file_get_contents($filePath);
-
-            $aInfos = [];
-            $aInfos['typeDepot']   = $aArgs['config']['data']['docutype'] . '-' . $aArgs['config']['data']['docustype'];
-            $aInfos['fileName']    = $value['title'];
-            $aInfos['fileContent'] = base64_encode($fileContent);
-            $aInfos['objet']       = $value['title'];
-            $aInfos['ref']         = $value['identifier'];
+            $filesize      = filesize($filePath);
+            $fileContent   = file_get_contents($filePath);
+            
+            $xmlStep = '';
+            foreach ($aArgs['steps'] as $key => $step) {
+                $xmlStep .= '<EtapeDepot>
+                                <user_siret xsi:type="xsd:string">'.$aArgs['info']['siret'].'</user_siret>
+                                <user_login xsi:type="xsd:string">'.$step['login'].'</user_login>
+                                <action xsi:type="xsd:string">'.$step['action'].'</action>
+                                <contexte xsi:type="xsd:string">'.$step['contexte'].'</contexte>
+                                <norejet xsi:type="xsd:string">0</norejet>
+                                <ordre xsi:type="xsd:int">'.$key.'</ordre>
+                            </EtapeDepot>';
+            }
 
             $xmlPostString = '<?xml version="1.0" encoding="utf-8"?>
-            <soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:parafwsdl">
+            <soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:parafwsdl" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
                 <soapenv:Header/>
                 <soapenv:Body>
-                <urn:XPRF_preDepot soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
-                    <params xsi:type="urn:XPRF_preDepot_Param">
-                        <siret xsi:type="xsd:string">'.$aArgs['config']['data']['siret'].'</siret>
-                        <login xsi:type="xsd:string">'.$aArgs['config']['data']['login'].'</login>
-                        <password xsi:type="xsd:string">'.$aArgs['config']['data']['password'].'</password>
-                        <infos xsi:type="xsd:string">'.json_encode($aInfos).'</infos>
+                <urn:XPRF_Deposer soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
+                    <params xsi:type="urn:XPRF_Deposer_Param">
+                        <reponse xsi:type="xsd:string">SOAP</reponse>
+                        <siret xsi:type="xsd:string">'.$aArgs['info']['siret'].'</siret>
+                        <login xsi:type="xsd:string">'.$aArgs['info']['login'].'</login>
+                        <password xsi:type="xsd:string">'.$aArgs['info']['password'].'</password>
+                        <docutype xsi:type="xsd:string">'.$aArgs['config']['data']['docutype'].'</docutype>
+                        <docustype xsi:type="xsd:string">'.$aArgs['config']['data']['docustype'].'</docustype>
+                        <objet xsi:type="xsd:string">'.$value['title'].'</objet>
+                        <contenu xsi:type="xsd:base64Binary">'.base64_encode($fileContent).'</contenu>
+                        <nom xsi:type="xsd:string">'.$value['title'].'</nom>
+                        <taille xsi:type="xsd:int">'.$filesize.'</taille>
+                        <pml xsi:type="xsd:string">1</pml>
+                        <avertir xsi:type="xsd:string">1</avertir>
+                        <etapes xsi:type="urn:EtapeDepot" soapenc:arrayType="urn:EtapeDepotItem[]">'.$xmlStep.'</etapes>
                     </params>
-                </urn:XPRF_preDepot>
+                </urn:XPRF_Deposer>
                 </soapenv:Body>
             </soapenv:Envelope>';
 
@@ -82,24 +98,189 @@ class XParaphController
             $isError = $response['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body;
             if (!empty($isError->Fault[0])) {
                 $error = $response['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->Fault[0]->children()->detail;
-                return $error;
+                return ['error' => $error];
             } else {
-                $url = $response['response']->children('SOAP-ENV', true)->Body->children('ns1', true)->XPRF_preDepotResponse->children()->return;
-                $test = $url;
-                // $response = $response['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children('http://sei.ws.fast.cdc.com/')->downloadResponse->children()->return;
-                // $returnedDocumentId = (string) $response->documentId;
-                // if ($aArgs['documentId'] !== $returnedDocumentId) {
-                //     // TODO gestion d'une potentiel erreur
-                //     return false;
-                // } else {
-                //     $b64FileContent = $response->content;
-                //     return ['b64FileContent' => (string)$b64FileContent, 'documentId' => $returnedDocumentId];
-                // }
+                $depotId = $response['response']->children('SOAP-ENV', true)->Body->children('ns1', true)->XPRF_DeposerResponse->children()->return->children()->depotid;
+                $attachmentToFreeze[$collId][$resId] = (string)$depotId;
             }
-
-            // $attachmentToFreeze[$collId][$resId] = (string)$response;
         }
 
         return $attachmentToFreeze;
     }
+
+    public static function getWorkflow(Request $request, Response $response, array $aArgs)
+    {
+        $data = $request->getQueryParams();
+        foreach (['login', 'siret', 'password'] as $value) {
+            if (empty($data[$value])) {
+                return $response->withStatus(400)->withJson(['errors' => $value . ' is empty']);
+            }
+        }
+
+        $loadedXml = CoreConfigModel::getXmlLoaded(['path' => 'modules/visa/xml/remoteSignatoryBooks.xml']);
+        $config = [];
+
+        if (!empty($loadedXml)) {
+            foreach ($loadedXml->signatoryBook as $value) {
+                if ($value->id == "xParaph") {
+                    $config['data'] = (array)$value;
+                    break;
+                }
+            }
+        } else {
+            return $response->withStatus(403)->withJson(['errors' => 'xParaph is not enabled']);
+        }
+
+        $xmlPostString = '<?xml version="1.0" encoding="utf-8"?>
+        <soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:parafwsdl">
+            <soapenv:Header/>
+            <soapenv:Body>
+                <urn:XPRF_Initialisation_Deposer soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
+                    <params xsi:type="urn:XPRF_Initialisation_Deposer_Param">
+                        <siret xsi:type="xsd:string">'.$data['siret'].'</siret>
+                        <login xsi:type="xsd:string">'.$data['login'].'</login>
+                        <password xsi:type="xsd:string">'.$data['password'].'</password>
+                        <action xsi:type="xsd:string">DETAIL</action>
+                        <scenario xsi:type="xsd:string">' . $config['data']['docutype'] . '-' . $config['data']['docustype'].'</scenario>
+                    </params>
+                </urn:XPRF_Initialisation_Deposer>
+            </soapenv:Body>
+        </soapenv:Envelope>';
+
+        $curlResponse = CurlModel::execSOAP([
+            'soapAction'    => 'urn:parafwsdl#paraf',
+            'url'           => $config['data']['url'],
+            'xmlPostString' => $xmlPostString,
+            'options'       => [CURLOPT_SSL_VERIFYPEER => false]
+        ]);
+
+        $isError = $curlResponse['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body;
+        if (!empty($isError->Fault[0])) {
+            $error = $curlResponse['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->Fault[0]->children()->detail;
+            return $response->withStatus(403)->withJson(['errors' => $error]);
+        } else {
+            $details = $curlResponse['response']->children('SOAP-ENV', true)->Body->children('ns1', true)->XPRF_Initialisation_DeposerResponse->children()->return->children()->Retour_XML;
+            $xmlData = simplexml_load_string($details);
+    
+            $visa = [];
+            $sign = [];
+    
+            foreach ($xmlData->SCENARIO->AUTORISATIONS->VISEURS->VISEUR as $value) {
+                $visa[] = (string)$value;
+            }
+            foreach ($xmlData->SCENARIO->AUTORISATIONS->SIGNATAIRES->SIGNATAIRE as $value) {
+                $sign[] = (string)$value;
+            }
+    
+            return $response->withJson(['visa' => $visa, 'sign' => $sign]);
+        }
+    }
+    public static function retrieveSignedMails($aArgs)
+    {
+        $validatedSignature   = $aArgs['config']['data']['validatedStateSignature'];
+        $validatedNoSignature = $aArgs['config']['data']['validatedStateNoSignature'];
+        $refused              = $aArgs['config']['data']['refusedState'];
+
+        foreach (['noVersion', 'isVersion'] as $version) {
+            $depotids = [];
+            foreach ($aArgs['idsToRetrieve'][$version] as $resId => $value) {
+                $depotids[$value->external_id] = $resId;
+            }
+            if (!empty($depotids)) {
+                $avancement = XParaphController::getAvancement(['config' => $aArgs['config'], 'depotsIds' => $depotids]);
+            }
+
+            //     $etatDossier = IxbusController::getEtatDossier(['config' => $aArgs['config'], 'sessionId' => $sessionId['cookie'], 'dossier_id' => $value->external_id]);
+    
+            //     // Refused
+            //     if ((string)$etatDossier == $aArgs['config']['data']['ixbusIdEtatRefused']) {
+            //         $aArgs['idsToRetrieve'][$version][$resId]->status = 'refused';
+            //         $notes = IxbusController::getDossier(['config' => $aArgs['config'], 'sessionId' => $sessionId['cookie'], 'dossier_id' => $value->external_id]);
+            //         $aArgs['idsToRetrieve'][$version][$resId]->noteContent = (string)$notes->MotifRefus;
+            //     // Validated
+            //     } elseif ((string)$etatDossier == $aArgs['config']['data']['ixbusIdEtatValidated']) {
+            //         $aArgs['idsToRetrieve'][$version][$resId]->status = 'validated';
+            //         $signedDocument = IxbusController::getAnnexes(['config' => $aArgs['config'], 'sessionId' => $sessionId['cookie'], 'dossier_id' => $value->external_id]);
+            //         $aArgs['idsToRetrieve'][$version][$resId]->format = 'pdf'; // format du fichier récupéré
+            //         $aArgs['idsToRetrieve'][$version][$resId]->encodedFile = (string)$signedDocument->Fichier;
+
+            //         $notes = IxbusController::getAnnotations(['config' => $aArgs['config'], 'sessionId' => $sessionId['cookie'], 'dossier_id' => $value->external_id]);
+            //         $aArgs['idsToRetrieve'][$version][$resId]->noteContent = (string)$notes->Annotation->Texte;
+            //     } else {
+            //         unset($aArgs['idsToRetrieve'][$version][$resId]);
+            //     }
+            // }
+        }
+
+        // retourner seulement les mails récupérés (validés ou signés)
+        return $aArgs['idsToRetrieve'];
+    }
+
+    public static function getAvancement($aArgs)
+    {
+        $depotIds = '';
+        $aArgs['depotsIds'] = ["20190416_145636_1" => 1993];
+        foreach ($aArgs['depotsIds'] as $key => $step) {
+            $depotIds .= '<listDepotIds>'.$key.'</listDepotIds>';
+        }
+
+        $xmlPostString = '<?xml version="1.0" encoding="utf-8"?>
+        <soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:parafwsdl" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
+            <soapenv:Header/>
+            <soapenv:Body>
+                <urn:XPRF_AvancementDepot soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
+                    <params xsi:type="urn:XPRF_AvancementDepot_Param">
+                        <siret xsi:type="xsd:string">?</siret>
+                        <login xsi:type="xsd:string">?</login>
+                        <password xsi:type="xsd:string">?</password>
+                        <depotids xsi:type="urn:listDepotIds" soapenc:arrayType="xsd:string[]">' . $depotIds . '</depotids>
+                        <withNote xsi:type="xsd:string">1</withNote>
+                    </params>
+                </urn:XPRF_AvancementDepot>
+            </soapenv:Body>
+        </soapenv:Envelope>';
+
+        $curlResponse = CurlModel::execSOAP([
+            'soapAction'    => 'urn:parafwsdl#paraf',
+            'url'           => $aArgs['config']['data']['url'],
+            'xmlPostString' => $xmlPostString,
+            'options'       => [CURLOPT_SSL_VERIFYPEER => false]
+        ]);
+
+        $isError = $curlResponse['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body;
+        if (!empty($isError->Fault[0])) {
+            $error = $curlResponse['response']->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->Fault[0]->children()->detail;
+            return ['errors' => $error];
+        } else {
+            $details = $curlResponse['response']->children('SOAP-ENV', true)->Body->children('ns1', true)->XPRF_AvancementDepotResponse->children()->return;
+            return json_decode($details, true);
+        }
+    }
+
+    public static function getFile($aArgs)
+    {
+        $xmlPostString = '<?xml version="1.0" encoding="utf-8"?>
+        <soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:parafwsdl">
+            <soapenv:Header/>
+            <soapenv:Body>
+                <urn:XPRF_getFiles soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
+                    <params xsi:type="urn:XPRF_getFiles_Param">
+                        <siret xsi:type="xsd:string">?</siret>
+                        <login xsi:type="xsd:string">?</login>
+                        <password xsi:type="xsd:string">?</password>
+                        <depotid xsi:type="xsd:string">1</depotid>
+                    </params>
+                </urn:XPRF_getFiles>
+            </soapenv:Body>
+        </soapenv:Envelope>';
+
+        $response = CurlModel::execSOAP([
+            'soapAction'    => 'urn:parafwsdl#paraf',
+            'url'           => $aArgs['config']['data']['url'],
+            'xmlPostString' => $xmlPostString,
+            'options'       => [CURLOPT_SSL_VERIFYPEER => false]
+        ]);
+
+        return $response;
+    }
 }
diff --git a/src/frontend/app/actions/send-external-signatory-book-action/send-external-signatory-book-action.component.html b/src/frontend/app/actions/send-external-signatory-book-action/send-external-signatory-book-action.component.html
index d5bcfc3983d..9b061a2bb3e 100644
--- a/src/frontend/app/actions/send-external-signatory-book-action/send-external-signatory-book-action.component.html
+++ b/src/frontend/app/actions/send-external-signatory-book-action/send-external-signatory-book-action.component.html
@@ -12,8 +12,8 @@
                     <b *ngIf="!data.contextMode" color="primary" class="highlight">{{data.selectedRes.length}}
                         {{lang.elements}}</b> ?
                 </div>
-                <div *ngIf="signatoryBookEnabled == 'maarchParapheur'">
-                    <div class="col-md-12" style="padding-top: 10px;" *ngIf="additionalsInfos.users.length != 0">
+                <div>
+                    <div class="col-md-12" style="padding-top: 10px;" *ngIf="signatoryBookEnabled == 'maarchParapheur' && additionalsInfos.users.length != 0">
                         <mat-form-field>
                             <mat-label>{{lang.userMaarchParapheur}}</mat-label>
                             <mat-select name="processingUser" [(ngModel)]="externalSignatoryBookDatas.processingUser" required>
@@ -23,16 +23,16 @@
                             </mat-select>
                         </mat-form-field>
                     </div>
-                    <div class="col-md-12" *ngIf="additionalsInfos.users.length == 0">
+                    <div class="col-md-12" *ngIf="signatoryBookEnabled == 'maarchParapheur' && additionalsInfos.users.length == 0">
                         {{lang.noUserDefinedInMaarchParapheur}}
                     </div>
-                    <div class="col-sm-12" *ngIf="additionalsInfos.users.length != 0">
+                    <div class="col-sm-12" *ngIf="signatoryBookEnabled == 'maarchParapheur' && additionalsInfos.users.length != 0">
                         <mat-radio-group required name="objectSent" [(ngModel)]="externalSignatoryBookDatas.objectSent">
                             <mat-radio-button color="primary" name="objectSent" checked value="mail">{{lang.mailNote}}</mat-radio-button>
                             <mat-radio-button color="primary" name="objectSent" value="attachment">{{lang.attachmentSignature}}</mat-radio-button><br><br>
                         </mat-radio-group>
                     </div>
-                    <div class="col-md-12" *ngIf="additionalsInfos.noAttachment.length != 0 && externalSignatoryBookDatas.objectSent == 'attachment'">
+                    <div class="col-md-12" *ngIf="additionalsInfos.noAttachment.length != 0 && (signatoryBookEnabled != 'maarchParapheur' || (signatoryBookEnabled == 'maarchParapheur' && externalSignatoryBookDatas.objectSent == 'attachment'))">
                         <div>
                             <div class="alert-message alert-message-danger mailList" role="alert">
                                 <p>
@@ -46,7 +46,7 @@
                             </div>
                         </div>
                     </div>
-                    <div class="col-md-12" *ngIf="additionalsInfos.noMail.length != 0 && externalSignatoryBookDatas.objectSent == 'mail'">
+                    <div class="col-md-12" *ngIf="signatoryBookEnabled == 'maarchParapheur' && additionalsInfos.noMail.length != 0 && externalSignatoryBookDatas.objectSent == 'mail'">
                         <div>
                             <div class="alert-message alert-message-danger mailList" role="alert">
                                 <p>
@@ -70,7 +70,14 @@
 </div>
 <div mat-dialog-actions class="actions">
     <button mat-raised-button mat-button color="primary" 
-        [disabled]="loading || !externalSignatoryBookDatas.processingUser || (signatoryBookEnabled == 'maarchParapheur' && (additionalsInfos.users.length == 0 || (externalSignatoryBookDatas.objectSent == 'attachment' && additionalsInfos.attachments.length == 0) || (externalSignatoryBookDatas.objectSent == 'mail' && additionalsInfos.mails.length == 0)))"
+        [disabled]="loading || (signatoryBookEnabled != 'maarchParapheur' && additionalsInfos.attachments.length == 0) ||
+        (signatoryBookEnabled == 'maarchParapheur' && (
+            !externalSignatoryBookDatas.processingUser || 
+            additionalsInfos.users.length == 0 || 
+            (externalSignatoryBookDatas.objectSent == 'attachment' && additionalsInfos.attachments.length == 0) || 
+            (externalSignatoryBookDatas.objectSent == 'mail' && additionalsInfos.mails.length == 0)
+            )
+        )"
         (click)="onSubmit()">{{lang.validate}}</button>
     <button mat-raised-button mat-button [disabled]="loading" [mat-dialog-close]="">{{lang.cancel}}</button>
 </div>
\ No newline at end of file
diff --git a/src/frontend/app/actions/send-external-signatory-book-action/send-external-signatory-book-action.component.ts b/src/frontend/app/actions/send-external-signatory-book-action/send-external-signatory-book-action.component.ts
index b3b67282c09..56f53ac14c9 100644
--- a/src/frontend/app/actions/send-external-signatory-book-action/send-external-signatory-book-action.component.ts
+++ b/src/frontend/app/actions/send-external-signatory-book-action/send-external-signatory-book-action.component.ts
@@ -51,7 +51,7 @@ export class sendExternalSignatoryBookActionComponent implements OnInit {
         this.loading = true;
 
         let realResSelected: string[];
-        if(this.signatoryBookEnabled == 'maarchParapheur' && this.externalSignatoryBookDatas.objectSent == 'attachment'){
+        if (this.signatoryBookEnabled != 'maarchParapheur' || (this.signatoryBookEnabled == 'maarchParapheur' && this.externalSignatoryBookDatas.objectSent == 'attachment')) {
             realResSelected = this.additionalsInfos.attachments.map((e: any) => { return e.res_id; });
         } else if (this.signatoryBookEnabled == 'maarchParapheur' && this.externalSignatoryBookDatas.objectSent == 'mail') {
             realResSelected = this.additionalsInfos.mails.map((e: any) => { return e.res_id; });
-- 
GitLab