From 9f35f768416e28655a803c8d01818f3cea766c11 Mon Sep 17 00:00:00 2001
From: "florian.azizian" <florian.azizian@maarch.org>
Date: Mon, 25 Mar 2019 11:53:02 +0100
Subject: [PATCH] FEAT #9107 preprocess action shipping

---
 rest/index.php                                |  2 +-
 sql/develop.sql                               |  2 +-
 sql/structure.sql                             |  2 +-
 .../PreProcessActionController.php            | 85 +++++++++++++++++++
 .../models/AttachmentModelAbstract.php        | 17 ++++
 .../models/ShippingTemplateModelAbstract.php  | 15 ++++
 6 files changed, 120 insertions(+), 3 deletions(-)

diff --git a/rest/index.php b/rest/index.php
index e34f6af20e3..d14d23f8229 100755
--- a/rest/index.php
+++ b/rest/index.php
@@ -279,7 +279,7 @@ $app->post('/acknowledgementReceipt', \AcknowledgementReceipt\controllers\Acknow
 //PreProcess
 $app->post('/resourcesList/users/{userId}/groups/{groupId}/baskets/{basketId}/checkAcknowledgementReceipt', \Action\controllers\PreProcessActionController::class . ':checkAcknowledgementReceipt');
 $app->get('/resourcesList/users/{userId}/groups/{groupId}/baskets/{basketId}/actions/{actionId}/getRedirect', \Action\controllers\PreProcessActionController::class . ':getRedirectInformations');
-//$app->post('/resourcesList/users/{userId}/groups/{groupId}/baskets/{basketId}/actions/{actionId}/checkShippings', \Action\controllers\PreProcessActionController::class . ':checkShippings');
+$app->post('/resourcesList/users/{userId}/groups/{groupId}/baskets/{basketId}/actions/{actionId}/checkShippings', \Action\controllers\PreProcessActionController::class . ':checkShippings');
 $app->get('/resources/{resId}/users/{userId}/isDestinationChanging', \Action\controllers\PreProcessActionController::class . ':isDestinationChanging');
 
 //shipping
diff --git a/sql/develop.sql b/sql/develop.sql
index f58a3a7ea28..7b30b8ec1f4 100755
--- a/sql/develop.sql
+++ b/sql/develop.sql
@@ -90,7 +90,7 @@ label character varying(64) NOT NULL,
 description character varying(255) NOT NULL,
 options json DEFAULT '{}',
 fee json DEFAULT '{}',
-entities json DEFAULT '{}',
+entities jsonb DEFAULT '{}',
 account json DEFAULT '{}',
 CONSTRAINT shipping_templates_pkey PRIMARY KEY (id)
 )
diff --git a/sql/structure.sql b/sql/structure.sql
index 84e2d3267fe..e66891d4ec1 100755
--- a/sql/structure.sql
+++ b/sql/structure.sql
@@ -1576,7 +1576,7 @@ label character varying(64) NOT NULL,
 description character varying(255) NOT NULL,
 options json DEFAULT '{}',
 fee json DEFAULT '{}',
-entities json DEFAULT '{}',
+entities jsonb DEFAULT '{}',
 account json DEFAULT '{}',
 CONSTRAINT shipping_templates_pkey PRIMARY KEY (id)
 )
diff --git a/src/app/action/controllers/PreProcessActionController.php b/src/app/action/controllers/PreProcessActionController.php
index 3f9c6fa5588..54bc4f59d89 100644
--- a/src/app/action/controllers/PreProcessActionController.php
+++ b/src/app/action/controllers/PreProcessActionController.php
@@ -13,6 +13,7 @@
 namespace Action\controllers;
 
 use AcknowledgementReceipt\models\AcknowledgementReceiptModel;
+use Attachment\models\AttachmentModel;
 use Basket\models\BasketModel;
 use Basket\models\GroupBasketRedirectModel;
 use Contact\models\ContactModel;
@@ -25,6 +26,7 @@ use Resource\controllers\ResController;
 use Resource\controllers\ResourceListController;
 use Resource\models\ResModel;
 use Respect\Validation\Validator;
+use Shipping\models\ShippingTemplateModel;
 use Slim\Http\Request;
 use Slim\Http\Response;
 use SrcCore\controllers\PreparedClauseController;
@@ -328,6 +330,89 @@ class PreProcessActionController
         return $response->withJson(['sendEmail' => $sendEmail, 'sendPaper' => $sendPaper, 'sendList' => $sendList,  'noSendAR' => $noSendAR, 'alreadySend' => $alreadySend, 'alreadyGenerated' => $alreadyGenerated]);
     }
 
+    public function checkShippings(Request $request, Response $response, array $aArgs)
+    {
+        $currentUser = UserModel::getByLogin(['login' => $GLOBALS['userId'], 'select' => ['id']]);
+
+        // $errors = ResourceListController::listControl(['groupId' => $aArgs['groupId'], 'userId' => $aArgs['userId'], 'basketId' => $aArgs['basketId'], 'currentUserId' => $currentUser['id']]);
+        // if (!empty($errors['errors'])) {
+        //     return $response->withStatus($errors['code'])->withJson(['errors' => $errors['errors']]);
+        // }
+
+        $data = $request->getParsedBody();
+
+        if (!Validator::arrayType()->notEmpty()->validate($data['resources'])) {
+            return $response->withStatus(400)->withJson(['errors' => 'Data resources is empty or not an array']);
+        }
+
+        $data['resources'] = array_slice($data['resources'], 0, 500);
+        if (!ResController::hasRightByResId(['resId' => $data['resources'], 'userId' => $GLOBALS['userId']])) {
+            return $response->withStatus(403)->withJson(['errors' => 'Almost one resource is out of perimeter']);
+        }
+
+        $aDestination = ResModel::get([
+            'select' => ['destination'],
+            'where'  => ['res_id in (?)'],
+            'data'   => [$data['resources']]
+        ]);
+
+        $entities = [];
+        foreach ($aDestination as $values) {
+            $entities[] = $values['destination'];
+        }
+
+        $aTemplates = [];
+        if (!empty($entities)) {
+            $aEntities = EntityModel::get(['select' => ['id'], 'where' => ['entity_id in (?)'], 'data' => $entities]);
+
+            $entitiesId = [];
+            foreach ($aEntities as $value) {
+                if (!empty($value['id'])) {
+                    $entitiesId[] = (string)$value['id'];
+                }
+            }
+
+            $aTemplates = ShippingTemplateModel::getByEntities([
+                'select'   => ['id', 'label', 'description', 'options', 'fee'],
+                'entities' => $entitiesId
+            ]);
+    
+            foreach ($aTemplates as $key => $value) {
+                $aTemplates[$key]['options']  = json_decode($value['options'], true);
+                $aTemplates[$key]['fee']      = json_decode($value['fee'], true);
+            }
+        }
+
+        $aAttachments = AttachmentModel::getAttachmentToSend(['ids' => $data['resources']]);
+
+        $resources = [];
+        $canNotSend = [];
+
+        foreach ($data['resources'] as $valueResId) {
+            $resIdFound = false;
+            foreach ($aAttachments as $key => $attachment) {
+                if ($attachment['res_id_master'] == $valueResId) {
+                    // TODO Check Contact;
+                    $resources[$valueResId][] = $attachment;
+                    $resIdFound = true;
+                    unset($aAttachments[$key]);
+                    break;
+                }
+            }
+            if (!$resIdFound) {
+                $resInfo = ResModel::getExtById(['select' => ['alt_identifier'], 'resId' => $valueResId]);
+                $canNotSend[$valueResId] = [$resInfo, 'Not attachment to send'];
+            }
+        }
+
+        return $response->withJson([
+            'shippingTemplates' => $aTemplates,
+            'entities'          => $entities,
+            'resources'         => $resources,
+            'canNotSend'        => $canNotSend
+        ]);
+    }
+
     public function isDestinationChanging(Request $request, Response $response, array $args)
     {
         if (!ResController::hasRightByResId(['resId' => [$args['resId']], 'userId' => $GLOBALS['userId']])) {
diff --git a/src/app/attachment/models/AttachmentModelAbstract.php b/src/app/attachment/models/AttachmentModelAbstract.php
index 1dd8ea05dd4..b8d56c4008e 100755
--- a/src/app/attachment/models/AttachmentModelAbstract.php
+++ b/src/app/attachment/models/AttachmentModelAbstract.php
@@ -66,6 +66,23 @@ abstract class AttachmentModelAbstract
         return $aAttachment[0];
     }
 
+    public static function getAttachmentToSend(array $aArgs)
+    {
+        ValidatorModel::notEmpty($aArgs, ['ids']);
+        ValidatorModel::arrayType($aArgs, ['select', 'orderBy', 'ids']);
+
+        $aAttachments = DatabaseModel::select([
+            'select'    => empty($aArgs['select']) ? ['max(relation) as relation', 'res_id_master', 'title', 'res_id', 'res_id_version', 'identifier'] : $aArgs['select'],
+            'table'     => ['res_view_attachments'],
+            'where'     => ['res_id_master in (?)', 'status not in (?, ?)', 'attachment_type not in (?, ?)', 'in_send_attach = TRUE'],
+            'data'      => [$aArgs['ids'], 'OBS', 'DEL', 'converted_pdf', 'printed_folder'],
+            'groupBy'   => ['res_id_master', 'title', 'res_id', 'res_id_version', 'identifier'],
+            'order_by'  => empty($aArgs['orderBy']) ? [] : $aArgs['orderBy']
+        ]);
+
+        return $aAttachments;
+    }
+
     public static function getListByResIdMaster(array $aArgs)
     {
         ValidatorModel::notEmpty($aArgs, ['id']);
diff --git a/src/app/shipping/models/ShippingTemplateModelAbstract.php b/src/app/shipping/models/ShippingTemplateModelAbstract.php
index 26b965e30e2..2fab8ce05be 100755
--- a/src/app/shipping/models/ShippingTemplateModelAbstract.php
+++ b/src/app/shipping/models/ShippingTemplateModelAbstract.php
@@ -56,6 +56,21 @@ abstract class ShippingTemplateModelAbstract
         return $shipping[0];
     }
 
+    public static function getByEntities(array $aArgs)
+    {
+        ValidatorModel::notEmpty($aArgs, ['entities']);
+        ValidatorModel::arrayType($aArgs, ['select', 'entities']);
+
+        $shippings = DatabaseModel::select([
+            'select' => empty($aArgs['select']) ? ['*'] : $aArgs['select'],
+            'table'  => ['shipping_templates'],
+            'where'  => ['entities @> ?'],
+            'data'   => [json_encode($aArgs['entities'])]
+        ]);
+
+        return $shippings;
+    }
+
     public static function create(array $aArgs)
     {
         ValidatorModel::notEmpty($aArgs, ['label', 'description']);
-- 
GitLab