From f187e0cb14a6c1fdd958eee0a9bb0a8f3ed723c6 Mon Sep 17 00:00:00 2001
From: "florian.azizian" <florian.azizian@maarch.org>
Date: Thu, 15 Oct 2020 12:30:02 +0200
Subject: [PATCH] FEAT #15049 TIME 2:40 WIP Export seda action

---
 package.json                                  |  2 +-
 .../controllers/ExportSEDATrait.php           | 68 +++++++++++++-
 .../exportSeda/controllers/SedaController.php | 90 ++++++++++---------
 src/lang/lang-fr.json                         |  4 +-
 4 files changed, 119 insertions(+), 45 deletions(-)

diff --git a/package.json b/package.json
index 5494a139803..3f3c3e90195 100755
--- a/package.json
+++ b/package.json
@@ -66,7 +66,7 @@
     "ngx-cookie-service": "^10.0.1",
     "ngx-pipes": "^2.7.5",
     "node-sass": "^4.14.1",
-    "nodemon": "^2.0.4",
+    "nodemon": "^2.0.5",
     "npm-check-updates": "^9.0.4",
     "pdfjs-dist": "2.5.207",
     "photoswipe": "^4.1.3",
diff --git a/src/app/external/exportSeda/controllers/ExportSEDATrait.php b/src/app/external/exportSeda/controllers/ExportSEDATrait.php
index fa5a1089077..c78ae82f789 100644
--- a/src/app/external/exportSeda/controllers/ExportSEDATrait.php
+++ b/src/app/external/exportSeda/controllers/ExportSEDATrait.php
@@ -15,8 +15,14 @@ namespace ExportSeda\controllers;
 use Attachment\models\AttachmentModel;
 use Docserver\models\DocserverModel;
 use Docserver\models\DocserverTypeModel;
+use Doctype\models\DoctypeModel;
+use Entity\models\EntityModel;
+use ExportSeda\controllers\ExportSEDATrait;
+use ExportSeda\controllers\SedaController;
 use MessageExchange\models\MessageExchangeModel;
 use Resource\controllers\StoreController;
+use Resource\models\ResModel;
+use SrcCore\models\CoreConfigModel;
 use SrcCore\models\ValidatorModel;
 
 trait ExportSEDATrait
@@ -26,8 +32,66 @@ trait ExportSEDATrait
         ValidatorModel::notEmpty($args, ['resId']);
         ValidatorModel::intVal($args, ['resId']);
 
-        // TODO : CONTROL + GET DATAS
-        $data = [];
+        $resource = ResModel::getById(['resId' => $args['resId'], 'select' => ['res_id', 'destination', 'type_id', 'subject', 'linked_resources']]);
+        if (empty($resource)) {
+            return ['errors' => ['resource does not exists']];
+        } elseif (empty($resource['destination'])) {
+            return ['errors' => ['resource has no destination']];
+        }
+
+        $doctype = DoctypeModel::getById(['id' => $resource['type_id'], 'select' => ['description', 'retention_rule', 'retention_final_disposition']]);
+        if (empty($doctype['retention_rule']) || empty($doctype['retention_final_disposition'])) {
+            return ['errors' => ['retention_rule or retention_final_disposition is empty for doctype']];
+        }
+        $entity = EntityModel::getByEntityId(['entityId' => $resource['destination'], 'select' => ['producer_service', 'entity_label']]);
+        if (empty($entity['producer_service'])) {
+            return ['errors' => ['producer_service is empty for this entity']];
+        }
+
+        $config = CoreConfigModel::getJsonLoaded(['path' => 'apps/maarch_entreprise/xml/config.json']);
+        if (empty($config['exportSeda']['senderOrgRegNumber'])) {
+            return ['errors' => ['No senderOrgRegNumber found in config.json']];
+        }
+
+        if (empty($args['data']['packageName'])) {
+            return ['errors' => ['packageName is empty']];
+        }
+        if (empty($args['data']['archivalAgreement'])) {
+            return ['errors' => ['archivalAgreement is empty']];
+        }
+        if (empty($args['data']['slipId'])) {
+            return ['errors' => ['slipId is empty']];
+        }
+        if (empty($args['data']['entityArchiveRecipient'])) {
+            return ['errors' => ['entityArchiveRecipient is empty']];
+        }
+        if (empty($args['data']['archiveDescriptionLevel'])) {
+            return ['errors' => ['archiveDescriptionLevel is empty']];
+        }
+
+        foreach ($args['data']['archives'] as $archiveUnit) {
+            if (empty($archiveUnit['id']) or empty($archiveUnit['descriptionLevel'])) {
+                return ['errors' => ['Missing id or descriptionLevel for an archiveUnit']];
+            }
+        }
+
+        $initData = SedaController::initArchivalData([
+            'resource'           => $resource,
+            'senderOrgRegNumber' => $config['exportSeda']['senderOrgRegNumber'],
+            'entity'             => $entity,
+            'doctype'            => $doctype
+        ])['archivalData'];
+
+        $data = [
+            'type' => 'ArchiveTransfer',
+            'messageObject' => [
+                'messageIdentifier'  => $initData['data']['slipInfo']['slipId'],
+                'archivalAgreement'  => $args['data']['archivalAgreement'],
+                'dataObjectPackage'  => [],
+                'archivalAgency'     => $args['data']['entityArchiveRecipient'],
+                'transferringAgency' => $initData['data']['entity']['senderArchiveEntity']
+            ]
+        ];
 
         $controller = ExportSEDATrait::generateSEDAPackage(['data' => $data]);
         if (!empty($controller['errors'])) {
diff --git a/src/app/external/exportSeda/controllers/SedaController.php b/src/app/external/exportSeda/controllers/SedaController.php
index 86a353c2a8b..8719c370045 100755
--- a/src/app/external/exportSeda/controllers/SedaController.php
+++ b/src/app/external/exportSeda/controllers/SedaController.php
@@ -53,7 +53,7 @@ class SedaController
 
         $firstResource = $body['resources'][0];
 
-        $resource = ResModel::getById(['resId' => $firstResource, 'select' => ['destination', 'type_id', 'subject', 'linked_resources']]);
+        $resource = ResModel::getById(['resId' => $firstResource, 'select' => ['res_id', 'destination', 'type_id', 'subject', 'linked_resources']]);
         if (empty($resource)) {
             return $response->withStatus(400)->withJson(['errors' => 'resource does not exists']);
         } elseif (empty($resource['destination'])) {
@@ -74,29 +74,57 @@ class SedaController
             return $response->withStatus(400)->withJson(['errors' => 'No senderOrgRegNumber found in config.json', 'lang' => 'noSenderOrgRegNumber']);
         }
 
+        $return = SedaController::initArchivalData([
+            'resource'           => $resource,
+            'senderOrgRegNumber' => $config['exportSeda']['senderOrgRegNumber'],
+            'entity'             => $entity,
+            'doctype'            => $doctype
+        ])['archivalData'];
+
+        $archivalAgreements = SedaController::getArchivalAgreements([
+            'config'              => $config,
+            'senderArchiveEntity' => $config['exportSeda']['senderOrgRegNumber'],
+            'producerService'     => $entity['producer_service']
+        ]);
+        if (!empty($archivalAgreements['errors'])) {
+            return $response->withStatus(400)->withJson($archivalAgreements);
+        }
+        $recipientArchiveEntities = SedaController::getRecipientArchiveEntities(['config' => $config, 'archivalAgreements' => $archivalAgreements['archivalAgreements']]);
+        if (!empty($recipientArchiveEntities['errors'])) {
+            return $response->withStatus(400)->withJson($recipientArchiveEntities);
+        }
+
+        $return['archivalAgreements']       = $archivalAgreements['archivalAgreements'];
+        $return['recipientArchiveEntities'] = $recipientArchiveEntities['archiveEntities'];
+        
+        return $response->withJson($return);
+    }
+
+    public function initArchivalData($args = [])
+    {
         $date = new \DateTime();
 
         $return = [
             'data' => [
                 'entity' => [
-                    'label'               => $entity['entity_label'],
-                    'producerService'     => $entity['producer_service'],
-                    'senderArchiveEntity' => $config['exportSeda']['senderOrgRegNumber']
+                    'label'               => $args['entity']['entity_label'],
+                    'producerService'     => $args['entity']['producer_service'],
+                    'senderArchiveEntity' => $args['senderOrgRegNumber'],
                 ],
                 'doctype' => [
-                    'label'                     => $doctype['description'],
-                    'retentionRule'             => $doctype['retention_rule'],
-                    'retentionFinalDisposition' => $doctype['retention_final_disposition']
+                    'label'                     => $args['doctype']['description'],
+                    'retentionRule'             => $args['doctype']['retention_rule'],
+                    'retentionFinalDisposition' => $args['doctype']['retention_final_disposition']
                 ],
                 'slipInfo' => [
                     'slipId'    => $GLOBALS['login'] . '-' . $date->format('Ymd-His'),
-                    'archiveId' => 'archive_' . $firstResource
+                    'archiveId' => 'archive_' . $args['resource']['res_id']
                 ]
             ],
             'archiveUnits' => [
                 [
-                    'id'               => 'letterbox_' . $firstResource,
-                    'label'            => $resource['subject'],
+                    'id'               => 'letterbox_' . $args['resource']['res_id'],
+                    'label'            => $args['resource']['subject'],
                     'type'             => 'mainDocument',
                     'descriptionLevel' => 'Item'
                 ]
@@ -106,7 +134,7 @@ class SedaController
         $attachments = AttachmentModel::get([
             'select'  => ['res_id', 'title'],
             'where'   => ['res_id_master = ?', 'status not in (?)', 'attachment_type not in (?)'],
-            'data'    => [$firstResource, ['DEL', 'OBS', 'TMP'], ['signed_response']],
+            'data'    => [$args['resource']['res_id'], ['DEL', 'OBS', 'TMP'], ['signed_response']],
             'orderBy' => ['modification_date DESC']
         ]);
         foreach ($attachments as $attachment) {
@@ -118,7 +146,7 @@ class SedaController
             ];
         }
 
-        $notes = NoteModel::get(['select' => ['note_text', 'id'], 'where' => ['identifier = ?'], 'data' => [$firstResource]]);
+        $notes = NoteModel::get(['select' => ['note_text', 'id'], 'where' => ['identifier = ?'], 'data' => [$args['resource']['res_id']]]);
         foreach ($notes as $note) {
             $return['archiveUnits'][] = [
                 'id'               => 'note_' . $note['id'],
@@ -131,7 +159,7 @@ class SedaController
         $emails = EmailModel::get([
             'select'  => ['object', 'id'],
             'where'   => ['document->>\'id\' = ?', 'status = ?'],
-            'data'    => [$firstResource, 'SENT'],
+            'data'    => [$args['resource']['res_id'], 'SENT'],
             'orderBy' => ['send_date desc']
         ]);
         foreach ($emails as $email) {
@@ -144,24 +172,24 @@ class SedaController
         }
 
         $return['archiveUnits'][] = [
-            'id'               => 'summarySheet_' . $firstResource,
+            'id'               => 'summarySheet_' . $args['resource']['res_id'],
             'label'            => 'Fiche de liaison',
             'type'             => 'summarySheet',
             'descriptionLevel' => 'Item'
         ];
 
-        $linkedResourcesIds = json_decode($resource['linked_resources'], true);
+        $linkedResourcesIds = json_decode($args['resource']['linked_resources'], true);
         if (!empty($linkedResourcesIds)) {
             $linkedResources = [];
             $linkedResources = ResModel::get([
-                'select' => ['res_id', 'alt_identifier'],
+                'select' => ['subject', 'alt_identifier'],
                 'where'  => ['res_id in (?)'],
                 'data'   => [$linkedResourcesIds]
             ]);
-            $return['additionalData']['linkedResources'] = array_column($linkedResources, 'alt_identifier');
+            $return['additionalData']['linkedResources'] = array_column($linkedResources, 'subject', 'alt_identifier');
         }
 
-        $entities = UserModel::getEntitiesById(['id' => $aArgs['userId'], 'select' => ['entities.id']]);
+        $entities = UserModel::getEntitiesById(['id' => $GLOBALS['id'], 'select' => ['entities.id']]);
         $entities = array_column($entities, 'id');
 
         if (empty($entities)) {
@@ -171,34 +199,16 @@ class SedaController
         $folders = FolderModel::getWithEntitiesAndResources([
             'select' => ['DISTINCT(folders.id)', 'folders.label'],
             'where'  => ['res_id = ?', '(entity_id in (?) OR keyword = ?)', 'folders.public = TRUE'],
-            'data'   => [$firstResource, $entities, 'ALL_ENTITIES']
+            'data'   => [$args['resource']['res_id'], $entities, 'ALL_ENTITIES']
         ]);
         foreach ($folders as $folder) {
             $return['additionalData']['folders'][] = [
-                'id'               => 'folder_' . $folder['id'],
-                'label'            => $folder['label'],
-                'type'             => 'folder',
-                'descriptionLevel' => 'Item'
+                'id'    => 'folder_' . $folder['id'],
+                'label' => $folder['label']
             ];
         }
 
-        $archivalAgreements = SedaController::getArchivalAgreements([
-            'config'              => $config,
-            'senderArchiveEntity' => $config['exportSeda']['senderOrgRegNumber'],
-            'producerService'     => $entity['producer_service']
-        ]);
-        if (!empty($archivalAgreements['errors'])) {
-            return $response->withStatus(400)->withJson($archivalAgreements);
-        }
-        $recipientArchiveEntities = SedaController::getRecipientArchiveEntities(['config' => $config, 'archivalAgreements' => $archivalAgreements['archivalAgreements']]);
-        if (!empty($recipientArchiveEntities['errors'])) {
-            return $response->withStatus(400)->withJson($recipientArchiveEntities);
-        }
-
-        $return['archivalAgreements']       = $archivalAgreements['archivalAgreements'];
-        $return['recipientArchiveEntities'] = $recipientArchiveEntities['archiveEntities'];
-        
-        return $response->withJson($return);
+        return ['archivalData' => $return];
     }
 
     public function getRecipientArchiveEntities($args = [])
diff --git a/src/lang/lang-fr.json b/src/lang/lang-fr.json
index 67294078b27..c56548bb304 100644
--- a/src/lang/lang-fr.json
+++ b/src/lang/lang-fr.json
@@ -2076,8 +2076,8 @@
     "recordManagement_wrongAcknowledgement": "L'accusé de réception n'est pas lié au bon courrier",
     "recordManagement_noReply": "Aucune réponse de transfert trouvé pour ce courrier",
     "recordManagement_replyNotReadable": "La réponse de transfert de ce courrier n'est pas correctement structurée",
-    "recordManagement_noReplyReference": "Aucun bordereau correspond à la réponse de transfert",
-    "recordManagement_wrongReply": "La réponse de transfert n'est pas lié au bon courrier",
+    "recordManagement_noReplyReference": "Aucun bordereau ne correspond à la réponse de transfert",
+    "recordManagement_wrongReply": "La réponse de transfert n'est pas liée au bon courrier",
     "noDestination": "Le courrier n'a pas d'entité traitante",
     "noRetentionInfo": "Le type de courrier n'a pas de règle de conservation ou de sort final",
     "noProducerService": "L'entité traitante n'a pas d'identifiant de service producteur",
-- 
GitLab