1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 
<?php
/* --------------------------------------------------------------
   ShipcloudWebhookController.inc.php 2018-01-29
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2017 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

class ShipcloudWebhookController extends HttpViewController
{
    /**
     * @var \LanguageTextManager
     */
    protected $text;
    
    /**
     * @var \ShipcloudLogger
     */
    protected $logger;
    
    protected function init()
    {
        $this->text = MainFactory::create('LanguageTextManager', 'shipcloud', $_SESSION['language_id']);
        $this->logger = MainFactory::create('ShipcloudLogger');
    }
    
    public function actionDefault()
    {
        try
        {
            $rawInput = file_get_contents('php://input');
            $this->logger->debug_notice(
                sprintf(
                    "WEBHOOK called from %s, body:\n%s",
                    $_SERVER['REMOTE_ADDR'],
                    $rawInput
                )
            );
            $webhookData = json_decode($rawInput, true);
            if(json_last_error()  !== JSON_ERROR_NONE)
            {
                throw new ShipcloudWebhookException('invalid input');
            }
            
            if(isset($webhookData['data']['object_type']) && $webhookData['data']['object_type'] === 'shipment')
            {
                $shipmentId = $webhookData['data']['id'];
                $shipmentUrl = $webhookData['data']['url'];
            }
            else
            {
                throw new ShipcloudWebhookException('unsupported object_type');
            }
            
            try
            {
                $shipmentsRequest = MainFactory::create('ShipcloudRestRequest', 'GET', $shipmentUrl);
                $restService      = MainFactory::create('ShipcloudRestService');
                $result           = $restService->performRequest($shipmentsRequest);
            }
            catch (RestException $e)
            {
                throw new ShipcloudWebhookException($e->getMessage());
            }
            
            $shipmentData     = json_decode($result->getResponseBody(), true);
            if(json_last_error() !== JSON_ERROR_NONE)
            {
                throw new ShipcloudWebhookException('could not retrieve shipment data');
            }
            
            if($result->getResponseCode() !== 200)
            {
                throw new ShipcloudWebhookException('Error retrieving shipment data - ' . $result->getResponseCode());
            }

            if(empty($shipmentData['reference_number']))
            {
                throw new ShipcloudWebhookException('Shipment referenced in webhook notification does not have a reference_number');
            }
            $orderId = new IdType((int)$shipmentData['reference_number']);
            
            $this->logger->notice(
                sprintf(
                    'WEBHOOK %s/%s for order %s',
                        $webhookData['id'],
                        $webhookData['type'],
                        (string)$orderId->asInt()
                )
            );
            
            $this->processWebhookEvent($orderId, new StringType($webhookData['type']));
            
            $responseData  = [
                'result' => 'OK',
            ];
        }
        catch (ShipcloudWebhookException $e)
        {
            $this->logger->notice('ERROR handling webhook event: ' . $e->getMessage());
            $responseData = [
                'result' => 'ERROR',
                'errors' => [
                    $e->getMessage(),
                ]
            ];
            
        }
        catch (UnexpectedValueException $e)
        {
            $this->logger->notice('ERROR handling webhook event: ' . $e->getMessage());
            $responseData = [
                'result' => 'ERROR',
                'errors' => [
                    $e->getMessage(),
                ]
            ];
        }
        
        $response = MainFactory::create('JsonHttpControllerResponse', $responseData, ['Content-Type: application/json']);
        return $response;
    }
    
    protected function processWebhookEvent(IdType $orderId, StringType $eventType)
    {
        $knownTypes = [
            'shipment.tracking.label_created',
            'shipment.tracking.picked_up',
            'shipment.tracking.transit',
            'shipment.tracking.out_for_delivery',
            'shipment.tracking.delivered',
            'shipment.tracking.awaits_pickup_by_receiver',
            'shipment.tracking.canceled',
            'shipment.tracking.delayed',
            'shipment.tracking.exception',
            'shipment.tracking.not_delivered',
            'shipment.tracking.destroyed',
            'shipment.tracking.notification',
            'shipment.tracking.unknown',
        ];
        /** @var \OrderWriteService $orderWrite */
        $orderWrite = StaticGXCoreLoader::getService('OrderWrite');
        /** @var \OrderReadService $orderRead */
        $orderRead  = StaticGXCoreLoader::getService('OrderRead');
        $oldOrderStatusId = new IdType($orderRead->getOrderById($orderId)->getStatusId());
        
        if(in_array($eventType->asString(), $knownTypes, true))
        {
            /** @var \ShipcloudConfigurationStorage $configuration */
            $configuration = MainFactory::create('ShipcloudConfigurationStorage');
            $orderStatusConfigurationKey = str_replace('.', '_', $eventType->asString());
            $orderStatusConfigurationKey = str_replace('shipment_', '', $orderStatusConfigurationKey);
            $orderStatusId = (int)$configuration->get('webhook/order_status_' . $orderStatusConfigurationKey);
            $historyComment = $this->text->get_text('webhook_event_' .
                                                    str_replace('.', '_', $eventType->asString()));
        }
        else
        {
            $orderStatusId = -1; // do not change
            $historyComment = $this->text->get_text('webhook_event_eventtype_unsupported') . ': ' . $eventType->asString();
        }
        if($orderStatusId >= 0) {
            $newOrderStatusId = new IdType($orderStatusId);
        }
        else
        {
            $newOrderStatusId = $oldOrderStatusId;
        }
        $orderWrite->updateOrderStatus($orderId, $newOrderStatusId, new StringType($historyComment), new BoolType(false));
    }
}

class ShipcloudWebhookException extends RuntimeException {}