From acdbf261f084f845d11debcdae5c6b7c43ead2c7 Mon Sep 17 00:00:00 2001
From: Guillaume Heurtier <guillaume.heurtier@maarch.org>
Date: Fri, 31 Jan 2020 11:23:17 +0100
Subject: [PATCH] FEAT #12346 TIME 2:30 action send resource to maileva

---
 src/app/action/controllers/ShippingTrait.php | 135 ++++++++++++++-----
 src/app/shipping/models/ShippingModel.php    |  21 +--
 2 files changed, 115 insertions(+), 41 deletions(-)

diff --git a/src/app/action/controllers/ShippingTrait.php b/src/app/action/controllers/ShippingTrait.php
index 01839cc28c6..b54273b8433 100644
--- a/src/app/action/controllers/ShippingTrait.php
+++ b/src/app/action/controllers/ShippingTrait.php
@@ -20,6 +20,7 @@ use Convert\models\AdrModel;
 use Docserver\models\DocserverModel;
 use Entity\models\EntityModel;
 use Resource\models\ResModel;
+use Resource\models\ResourceContactModel;
 use Shipping\controllers\ShippingTemplateController;
 use Shipping\models\ShippingModel;
 use Shipping\models\ShippingTemplateModel;
@@ -39,7 +40,10 @@ trait ShippingTrait
         ValidatorModel::arrayType($args, ['data']);
 
         $currentUser = UserModel::getByLogin(['login' => $GLOBALS['userId'], 'select' => ['id']]);
-        $resource = ResModel::getById(['select' => ['destination'], 'resId' => $args['resId']]);
+
+        $resource = ResModel::getById(['select' => ['destination', 'integrations', 'subject as title', 'external_id', 'res_id'], 'resId' => $args['resId']]);
+        $integrations = json_decode($resource['integrations'], true);
+
         $recipientEntity = EntityModel::getByEntityId(['select' => ['id'], 'entityId' => $resource['destination']]);
 
         $mailevaConfig = CoreConfigModel::getMailevaConfiguration();
@@ -59,10 +63,13 @@ trait ShippingTrait
             'where'     => ['res_id_master = ?', 'in_send_attach = ?', 'status not in (?)', 'attachment_type not in (?)'],
             'data'      => [$args['resId'], true, ['OBS', 'DEL', 'TMP', 'FRZ'], ['print_folder']]
         ]);
-        if (empty($attachments)) {
+
+        if (empty($attachments) && empty($integrations['inShipping'])) {
             return true;
         }
 
+        $resourcesList = [];
+
         $contacts = [];
         foreach ($attachments as $attachment) {
             $attachmentId = $attachment['res_id'];
@@ -91,6 +98,46 @@ trait ShippingTrait
                 return ['errors' => ['Contact is not fill enough for attachment']];
             }
             $contacts[] = $afnorAddress;
+
+            $attachment['collId'] = 'attachments_coll';
+            $resourcesList[] = $attachment;
+        }
+
+        $contactsResource = [];
+        if (!empty($integrations['inShipping'])) {
+            $convertedDocument = AdrModel::getConvertedDocumentById([
+                'select'    => ['docserver_id','path', 'filename', 'fingerprint'],
+                'resId'     => $args['resId'],
+                'collId'    => 'letterbox_coll',
+                'type'      => 'PDF'
+            ]);
+            if (empty($convertedDocument)) {
+                return ['errors' => ['No conversion for resource']];
+            }
+            $resourceContacts = ResourceContactModel::get([
+                'where' => ['res_id = ?', 'mode = ?', 'type = ?'],
+                'data'  => [$args['resId'], 'recipient', 'contact']
+            ]);
+            if (empty($resourceContacts)) {
+                return ['errors' => ['No contact found for resource']];
+            }
+
+            foreach ($resourceContacts as $resourceContact) {
+                $contact = ContactModel::getById(['select' => ['*'], 'id' => $resourceContact['item_id']]);
+                if (empty($contact)) {
+                    return ['errors' => ['Contact does not exist for resource']];
+                }
+                if (!empty($contact['address_country']) && strtoupper(trim($contact['address_country'])) != 'FRANCE') {
+                    return ['errors' => ['Contact country is not France']];
+                }
+                $afnorAddress = ContactController::getContactAfnor($contact);
+                if ((empty($afnorAddress[1]) && empty($afnorAddress[2])) || empty($afnorAddress[6]) || !preg_match("/^\d{5}\s/", $afnorAddress[6])) {
+                    return ['errors' => ['Contact is not filled enough for resource']];
+                }
+                $contactsResource[] = $afnorAddress;
+            }
+            $resource['collId'] = 'letterbox_coll';
+            $resourcesList[] = $resource;
         }
 
         $curlAuth = CurlModel::execSimple([
@@ -110,9 +157,9 @@ trait ShippingTrait
         $token = $curlAuth['response']['access_token'];
 
         $errors = [];
-        foreach ($attachments as $key => $attachment) {
+        foreach ($resourcesList as $key => $resource) {
             $sendingName = CoreConfigModel::uniqueId();
-            $attachmentId = $attachment['res_id'];
+            $resId = $resource['res_id'];
 
             $createSending = CurlModel::execSimple([
                 'url'           => $mailevaConfig['uri'] . '/mail/v1/sendings',
@@ -137,15 +184,15 @@ trait ShippingTrait
                 continue;
             }
 
-            $convertedDocument = ConvertPdfController::getConvertedPdfById(['resId' => $attachmentId, 'collId' => 'attachments_coll']);
+            $convertedDocument = ConvertPdfController::getConvertedPdfById(['resId' => $resId, 'collId' => $resource['collId']]);
             $docserver = DocserverModel::getByDocserverId(['docserverId' => $convertedDocument['docserver_id'], 'select' => ['path_template']]);
             if (empty($docserver['path_template']) || !file_exists($docserver['path_template'])) {
-                $errors[] = "Docserver does not exist for attachment {$attachmentId}";
+                $errors[] = "Docserver does not exist for resource {$resId}";
                 continue;
             }
             $pathToDocument = $docserver['path_template'] . str_replace('#', DIRECTORY_SEPARATOR, $convertedDocument['path']) . $convertedDocument['filename'];
             if (!file_exists($pathToDocument) || !is_file($pathToDocument)) {
-                $errors[] = "Document not found on docserver for attachment {$attachmentId}";
+                $errors[] = "Document not found on docserver for resource {$resId}";
                 continue;
             }
 
@@ -153,31 +200,55 @@ trait ShippingTrait
                 'url'           => $mailevaConfig['uri'] . "/mail/v1/sendings/{$sendingId}/documents",
                 'bearerAuth'    => ['token' => $token],
                 'method'        => 'POST',
-                'multipartBody' => ['document' => file_get_contents($pathToDocument), 'metadata' => json_encode(['priority' => 0, 'name' => $attachment['title']])]
+                'multipartBody' => ['document' => file_get_contents($pathToDocument), 'metadata' => json_encode(['priority' => 0, 'name' => $resource['title']])]
             ]);
             if ($createDocument['code'] != 201) {
-                $errors[] = "Maileva document creation failed for attachment {$attachmentId}";
+                $errors[] = "Maileva document creation failed for resource {$resId}";
                 continue;
             }
 
-            $createRecipient = CurlModel::execSimple([
-                'url'           => $mailevaConfig['uri'] . "/mail/v1/sendings/{$sendingId}/recipients",
-                'bearerAuth'    => ['token' => $token],
-                'headers'       => ['Content-Type: application/json'],
-                'method'        => 'POST',
-                'body'          => json_encode([
-                    "address_line_1"    => $contacts[$key][1],
-                    "address_line_2"    => $contacts[$key][2],
-                    "address_line_3"    => $contacts[$key][3],
-                    "address_line_4"    => $contacts[$key][4],
-                    "address_line_5"    => $contacts[$key][5],
-                    "address_line_6"    => $contacts[$key][6],
-                    "country_code"      => 'FR'
-                ]),
-            ]);
-            if ($createRecipient['code'] != 201) {
-                $errors[] = "Maileva recipient creation failed for attachment {$attachmentId}";
-                continue;
+            if ($resource['collId'] == 'attachments_coll') {
+                $createRecipient = CurlModel::execSimple([
+                    'url'           => $mailevaConfig['uri'] . "/mail/v1/sendings/{$sendingId}/recipients",
+                    'bearerAuth'    => ['token' => $token],
+                    'headers'       => ['Content-Type: application/json'],
+                    'method'        => 'POST',
+                    'body'          => json_encode([
+                        "address_line_1"    => $contacts[$key][1],
+                        "address_line_2"    => $contacts[$key][2],
+                        "address_line_3"    => $contacts[$key][3],
+                        "address_line_4"    => $contacts[$key][4],
+                        "address_line_5"    => $contacts[$key][5],
+                        "address_line_6"    => $contacts[$key][6],
+                        "country_code"      => 'FR'
+                    ]),
+                ]);
+                if ($createRecipient['code'] != 201) {
+                    $errors[] = "Maileva recipient creation failed for resource {$resId}";
+                    continue;
+                }
+            } else {
+                foreach ($contactsResource as $contact) {
+                    $createRecipient = CurlModel::execSimple([
+                        'url'           => $mailevaConfig['uri'] . "/mail/v1/sendings/{$sendingId}/recipients",
+                        'bearerAuth'    => ['token' => $token],
+                        'headers'       => ['Content-Type: application/json'],
+                        'method'        => 'POST',
+                        'body'          => json_encode([
+                            "address_line_1"    => $contact[1],
+                            "address_line_2"    => $contact[2],
+                            "address_line_3"    => $contact[3],
+                            "address_line_4"    => $contact[4],
+                            "address_line_5"    => $contact[5],
+                            "address_line_6"    => $contact[6],
+                            "country_code"      => 'FR'
+                        ]),
+                    ]);
+                    if ($createRecipient['code'] != 201) {
+                        $errors[] = "Maileva recipient creation failed for resource {$resId}";
+                        continue 2;
+                    }
+                }
             }
 
             $setOptions = CurlModel::execSimple([
@@ -208,18 +279,20 @@ trait ShippingTrait
                 continue;
             }
 
-            $externalId = json_decode($attachment['external_id'], true);
+            $externalId = json_decode($resource['external_id'], true);
             $externalId['mailevaSendingId'] = $sendingId;
-            AttachmentModel::update(['set' => ['external_id' => json_encode($externalId)], 'where' => ['res_id = ?'], 'data' => [$attachmentId]]);
+            AttachmentModel::update(['set' => ['external_id' => json_encode($externalId)], 'where' => ['res_id = ?'], 'data' => [$resId]]);
 
             $fee = ShippingTemplateController::calculShippingFee([
                 'fee'       => $shippingTemplate['fee'],
-                'resources' => [$attachment]
+                'resources' => [$resource]
             ]);
 
+            $documentType = $resource['collId'] == 'attachments_coll' ? 'attachment' : 'resource';
             ShippingModel::create([
                 'userId'            => $currentUser['id'],
-                'attachmentId'      => $attachmentId,
+                'documentId'        => $resId,
+                'documentType'      => $documentType,
                 'options'           => json_encode($shippingTemplate['options']),
                 'fee'               => $fee,
                 'recipientEntityId' => $recipientEntity['id'],
diff --git a/src/app/shipping/models/ShippingModel.php b/src/app/shipping/models/ShippingModel.php
index 38bf95224c1..b0436705452 100644
--- a/src/app/shipping/models/ShippingModel.php
+++ b/src/app/shipping/models/ShippingModel.php
@@ -21,20 +21,21 @@ class ShippingModel
 {
     public static function create(array $args)
     {
-        ValidatorModel::notEmpty($args, ['userId', 'attachmentId', 'accountId']);
-        ValidatorModel::intVal($args, ['userId', 'attachmentId', 'recipientEntityId']);
-        ValidatorModel::stringType($args, ['accountId']);
+        ValidatorModel::notEmpty($args, ['userId', 'documentId', 'documentType', 'accountId']);
+        ValidatorModel::intVal($args, ['userId', 'documentId', 'recipientEntityId']);
+        ValidatorModel::stringType($args, ['accountId', 'documentType']);
 
         DatabaseModel::insert([
             'table'         => 'shippings',
             'columnsValues' => [
-                'user_id'               => $args['userId'],
-                'attachment_id'         => $args['attachmentId'],
-                'options'               => $args['options'],
-                'fee'                   => $args['fee'],
-                'recipient_entity_id'   => $args['recipientEntityId'],
-                'account_id'            => $args['accountId'],
-                'creation_date'         => 'CURRENT_TIMESTAMP'
+                'user_id'             => $args['userId'],
+                'document_id'         => $args['documentId'],
+                'document_type'       => $args['documentType'],
+                'options'             => $args['options'],
+                'fee'                 => $args['fee'],
+                'recipient_entity_id' => $args['recipientEntityId'],
+                'account_id'          => $args['accountId'],
+                'creation_date'       => 'CURRENT_TIMESTAMP'
             ]
         ]);
 
-- 
GitLab