shop.balmet.com

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

econt_delivery.php (16760B)


      1 <?php
      2 
      3 /** @noinspection PhpUndefinedClassInspection */
      4 
      5 /**
      6  * @property Request $request
      7  * @property Response $response
      8  * @property Session $session
      9  * @property \Cart\Cart $cart
     10  * @property ModelCheckoutOrder $model_checkout_order
     11  * @property ControllerApiExtensionEcontDelivery
     12  * @property Loader $load
     13  * @property Language $language
     14  * @property ModelCatalogProduct $model_catalog_product
     15  * @property Url $url
     16  * @property ModelSettingSetting $model_setting_setting
     17  * @property ModelExtensionShippingEcontDelivery $model_extension_shipping_econt_delivery
     18  * @property DB $db
     19  */
     20 class ControllerExtensionShippingEcontDelivery extends Controller {
     21 
     22     public function afterModelCheckoutOrderAddHistory(/** @noinspection PhpUnusedParameterInspection */ $eventRoute, &$data) {
     23         $orderId = @intval($this->request->get['order_id']);
     24         if ($orderId <= 0) {
     25             if ($this->request->get['route'] === 'api/order/add') {
     26                 $orderId = intval(reset($data));
     27                 if ($orderId <= 0) return;
     28 
     29                 if (!empty($this->session->data['econt_delivery']['customer_info'])) $this->db->query(sprintf("
     30                     INSERT INTO `%s`.`%secont_delivery_customer_info`
     31                     SET id_order = {$orderId},
     32                         customer_info = '%s'
     33                     ON DUPLICATE KEY UPDATE
     34                         customer_info = VALUES(customer_info)
     35                 ",
     36                     DB_DATABASE,
     37                     DB_PREFIX,
     38                     json_encode($this->session->data['econt_delivery']['customer_info'])
     39                 ));
     40             } else {
     41                 if (!($orderId = intval($this->session->data['order_id']))) return;
     42             }
     43         }
     44 
     45         $orderData = $this->model_checkout_order->getOrder($orderId);
     46         if (empty($orderData) || $orderData['shipping_code'] !== 'econt_delivery.econt_delivery') return;
     47 
     48         $this->load->model('extension/shipping/econt_delivery');
     49         $customerInfo = $this->session->data['econt_delivery']['customer_info'];
     50         if (empty($customerInfo)) {
     51             $customerInfo = $this->db->query(sprintf("
     52                 SELECT
     53                     ci.customer_info AS customerInfo
     54                 FROM `%s`.`%secont_delivery_customer_info` AS ci
     55                 WHERE TRUE
     56                     AND ci.id_order = {$orderId}
     57                 LIMIT 1
     58             ",
     59                 DB_DATABASE,
     60                 DB_PREFIX
     61             ));
     62             $customerInfo = json_decode($customerInfo->row['customerInfo'], true);
     63         }
     64         if (!$customerInfo || empty($customerInfo['id'])) return;
     65 
     66         $this->load->language('extension/shipping/econt_delivery');
     67         $order = array(
     68             'customerInfo' => array(
     69                 'id' => $customerInfo['id']
     70             ),
     71             'orderNumber' => $orderData['order_id'],
     72             'shipmentDescription' => sprintf("%s #{$orderData['order_id']}", $this->language->get('text_econt_delivery_order')),
     73             'status' => $orderData['order_status'],
     74             'orderTime' => $orderData['date_added'],
     75             'currency' => $orderData['currency_code'],
     76             'cod' => ($orderData['payment_code'] === 'cod'),
     77             'partialDelivery' => 1,
     78             'items' => array()
     79         );
     80 
     81         $productTotal = 0;
     82 
     83         $orderProducts = $this->model_checkout_order->getOrderProducts($orderId);
     84         if (!empty($orderProducts)) {
     85             if (count($orderProducts) <= 1) {
     86                 $orderProduct = reset($orderProducts);
     87                 $order['shipmentDescription'] = $orderProduct['name'];
     88             }
     89             $this->load->model('catalog/product');
     90             foreach ($orderProducts as $orderProduct) {
     91                 $productData = $this->model_catalog_product->getProduct($orderProduct['product_id']);
     92                 if (empty($productData)) continue;
     93 
     94                 $orderItemPrice = floatval($orderProduct['total']) + (floatval($orderProduct['tax']) * intval($orderProduct['quantity']));
     95                 $order['items'][] = array(
     96                     'name' => $productData['name'],
     97                     'SKU' => $productData['sku'],
     98                     'URL' => $this->url->link('product/product', http_build_query(array(
     99                         'product_id' => $productData['product_id']
    100                     )), true),
    101                     'count' => $orderProduct['quantity'],
    102                     'totalPrice' => $orderItemPrice,
    103                     'totalWeight' => floatval($productData['weight'] * $orderProduct['quantity'])
    104                 );
    105                 $productTotal += $orderItemPrice;
    106             }
    107         }
    108 
    109         $orderTotals = $this->model_checkout_order->getOrderTotals($orderData['order_id']);
    110         if (!empty($orderTotals)) {
    111             $orderTotal = array_reduce($orderTotals, function($total, $currentRow) {
    112                 if (!in_array($currentRow['code'], array('shipping', 'total'))) $total += $currentRow['value'];
    113                 return $total;
    114             }, 0);
    115             $discount = $orderTotal - $productTotal;
    116             if ($discount != 0) {
    117                 $order['partialDelivery'] = 0;
    118                 $order['items'][] = array(
    119                     'name' => $this->language->get('text_econt_delivery_order_discount'),
    120                     'count' => 1,
    121                     'totalPrice' => $discount
    122                 );
    123             }
    124         }
    125 
    126         $this->load->model('setting/setting');
    127         $settings = $this->model_setting_setting->getSetting('shipping_econt_delivery');
    128         if (empty($settings['shipping_econt_delivery_system_url']) || empty($settings['shipping_econt_delivery_private_key'])) return;
    129 
    130         $response = [];
    131         try {
    132             $curl = curl_init();
    133             curl_setopt($curl, CURLOPT_URL, "{$settings['shipping_econt_delivery_system_url']}/services/OrdersService.updateOrder.json");
    134             curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    135             curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    136             curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    137             curl_setopt($curl, CURLOPT_HTTPHEADER, [
    138                 'Content-Type: application/json',
    139                 "Authorization: {$settings['shipping_econt_delivery_private_key']}"
    140             ]);
    141             curl_setopt($curl, CURLOPT_POST, true);
    142             curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($order));
    143             curl_setopt($curl, CURLOPT_TIMEOUT, 6);
    144             $response = curl_exec($curl);
    145             curl_close($curl);
    146         } catch (Exception $exception) {
    147             $logger = new Log('econt_delivery.log');
    148             $logger->write(sprintf('Curl failed with error [%d] %s', $exception->getCode(), $exception->getMessage()));
    149         }
    150 
    151         return json_decode($response, true);
    152     }
    153 
    154     public function afterViewCheckoutBilling($route,$templateParams,$html) {
    155         return preg_replace("#<div (class=\"checkbox\">\\s+<label>\\s+<input\\s+type=\"checkbox\"\\s+name=\"shipping_address\")#i",'<div style="display:none !important;" \1',$html);
    156     }
    157     public function beforeCartSaveShipping() {
    158         if($this->request->request['shipping_method'] == 'econt_delivery.econt_delivery') {
    159             $this->session->data['econt_delivery']['customer_info'] = json_decode(html_entity_decode($this->request->request['econt_delivery_shipping_info']),true);
    160             if(!$this->session->data['econt_delivery']['customer_info']) {
    161                 $this->load->language('extension/shipping/econt_delivery');
    162                 $this->response->addHeader('Content-Type: application/json');
    163                 $this->response->setOutput(json_encode(array('error' => array('warning' => $this->language->get('err_missing_customer_info')))));
    164                 return false;
    165             }
    166             $this->session->data['shipping_address']['firstname'] = $this->session->data['econt_delivery']['customer_info']['name'];
    167             $this->session->data['shipping_address']['lastname'] = '';
    168             $this->session->data['shipping_address']['iso_code_3'] = $this->session->data['econt_delivery']['customer_info']['country_code'];
    169             $this->session->data['shipping_address']['city'] = $this->session->data['econt_delivery']['customer_info']['city_name'];
    170             $this->session->data['shipping_address']['postcode'] = $this->session->data['econt_delivery']['customer_info']['post_code'];
    171             if($this->session->data['econt_delivery']['customer_info']['office_code']) {
    172                 $this->session->data['shipping_address']['address_1'] = 'Econt office: '.$this->session->data['econt_delivery']['customer_info']['office_code'];
    173                 $this->session->data['shipping_address']['address_2'] = $this->session->data['econt_delivery']['customer_info']['address'];
    174             } else {
    175                 $this->session->data['shipping_address']['address_1'] = $this->session->data['econt_delivery']['customer_info']['address'];
    176             }
    177         }
    178     }
    179 
    180     public function afterCheckoutConfirm() {
    181         if($this->session->data['shipping_method']['code'] == 'econt_delivery.econt_delivery') {
    182             if(empty($this->session->data['econt_delivery']['customer_info'])) throw new Exception;
    183             if (($orderId = @intval($this->session->data['order_id'])) > 0) {
    184                 $this->db->query(sprintf("
    185                     INSERT INTO `%s`.`%secont_delivery_customer_info`
    186                     SET id_order = {$orderId},
    187                         customer_info = '%s'
    188                     ON DUPLICATE KEY UPDATE
    189                         customer_info = VALUES(customer_info)
    190                 ",
    191                     DB_DATABASE,
    192                     DB_PREFIX,
    193                     $this->db->escape(json_encode($this->session->data['econt_delivery']['customer_info']))
    194                 ));
    195             }
    196         }
    197     }
    198 
    199     public function beforeCartSavePayment() {
    200         if($this->session->data['shipping_method']['code'] == 'econt_delivery.econt_delivery') {
    201             $cod = @$this->request->request['payment_method'] == 'cod' ? '_cod' : '';
    202             $this->session->data['shipping_method']['cost'] = $this->session->data['econt_delivery']['customer_info']['shipping_price'.$cod];
    203         }
    204     }
    205 
    206     public function getCustomerInfoParams() {
    207         $response = array();
    208         try {
    209             $this->load->language('extension/shipping/econt_delivery');
    210 
    211             if (!isset($this->session->data['api_id'])) throw new Exception($this->language->get('text_catalog_controller_api_extension_econt_delivery_permission_error'));
    212 
    213             $this->load->model('setting/setting');
    214             $econtDeliverySettings = $this->model_setting_setting->getSetting('shipping_econt_delivery');
    215 
    216             $separatorPos = strpos($econtDeliverySettings['shipping_econt_delivery_private_key'], '@');
    217             if ($separatorPos === false) throw new Exception($this->language->get('text_catalog_controller_api_extension_econt_delivery_shop_id_error'));
    218             $shopId = substr($econtDeliverySettings['shipping_econt_delivery_private_key'], 0, $separatorPos);
    219             if (intval($shopId) <= 0) throw new Exception($this->language->get('text_catalog_controller_api_extension_econt_delivery_shop_id_error'));
    220 
    221             $this->load->model('extension/shipping/econt_delivery');
    222             $response['customer_info'] = array(
    223                 'id_shop' => $shopId,
    224                 'order_total' => $this->model_extension_shipping_econt_delivery->getOrderTotal(),
    225                 'order_weight' => $this->cart->getWeight(),
    226                 'order_currency' => @$this->session->data['currency'],
    227                 'customer_company' => @$this->session->data['shipping_address']['company'],
    228                 'customer_name' => @$this->session->data['shipping_address']['firstname'] . ' ' . @$this->session->data['shipping_address']['lastname'],
    229                 'customer_phone' => @$this->session->data['customer']['telephone'],
    230                 'customer_email' => @$this->session->data['customer']['email'],
    231                 'customer_country' => @$this->session->data['shipping_address']['iso_code_3'],
    232                 'customer_city_name' => @$this->session->data['shipping_address']['city'],
    233                 'customer_post_code' => @$this->session->data['shipping_address']['postcode'],
    234                 'customer_address' => @$this->session->data['shipping_address']['address_1'] . ' ' . @$this->session->data['shipping_address']['address_2'],
    235                 'ignore_history' => true,
    236                 'default_css' => true
    237             );
    238             $officeCode = trim(@$this->session->data['econt_delivery']['customer_info']['office_code']);
    239             if (!empty($officeCode)) $response['customer_info']['customer_office_code'] = $officeCode;
    240             $zip = trim(@$this->session->data['econt_delivery']['customer_info']['zip']);
    241             if (!empty($zip)) $response['customer_info']['customer_zip'] = $zip;
    242             $response['customer_info_url'] = $econtDeliverySettings['shipping_econt_delivery_system_url'] . '/customer_info.php?' . http_build_query($response['customer_info'], null, '&');
    243         } catch (Exception $exception) {
    244             $response = array('error' => $exception->getMessage());
    245         }
    246         $this->response->addHeader('Content-Type: application/json');
    247         $this->response->setOutput(json_encode($response));
    248 
    249         return false;
    250     }
    251 
    252     public function beforeApi() {
    253         $this->loadEcontDeliveryData();
    254         return false;
    255     }
    256     public function loadEcontDeliveryData() {
    257         $orderId = @intval($this->request->get['order_id']);
    258         if (@$this->request->get['action'] === 'updateCustomerInfo') {
    259             if ($orderId > 0) {
    260                 $this->db->query(sprintf("
    261                     INSERT INTO `%s`.`%secont_delivery_customer_info`
    262                     SET id_order = {$orderId},
    263                         customer_info = '%s'
    264                     ON DUPLICATE KEY UPDATE
    265                         customer_info = VALUES(customer_info)
    266                 ",
    267                     DB_DATABASE,
    268                     DB_PREFIX,
    269                     json_encode($this->request->post)
    270                 ));
    271             }
    272             $this->session->data['econt_delivery']['customer_info'] = $this->request->post;
    273         } else {
    274             if (empty($this->session->data['econt_delivery']['customer_info']) && $orderId > 0) {
    275                 $customerInfo = $this->db->query(sprintf("
    276                     SELECT
    277                         ci.customer_info AS customerInfo
    278                     FROM `%s`.`%secont_delivery_customer_info` AS ci
    279                     WHERE TRUE
    280                         AND ci.id_order = {$orderId}
    281                     LIMIT 1
    282                 ",
    283                     DB_DATABASE,
    284                     DB_PREFIX
    285                 ));
    286                 $customerInfo = json_decode($customerInfo->row['customerInfo'], true);
    287                 if ($customerInfo) $this->session->data['econt_delivery']['customer_info'] = $customerInfo;
    288             }
    289         }
    290 
    291         if (!@$this->session->data['payment_method'] && is_array(@$this->session->data['payment_methods']) && in_array(@$this->request->post['payment_method'], @$this->session->data['payment_methods'])) $this->session->data['payment_method'] = $this->session->data['payment_methods'][$this->request->post['payment_method']];
    292         if (!@$this->session->data['shipping_method'] && is_array(@$this->session->data['shipping_methods']) && in_array(@$this->request->post['shipping_method'], @$this->session->data['shipping_methods'])) $this->session->data['shipping_method'] = $this->session->data['shipping_methods'][$this->request->post['shipping_method']];
    293 
    294         if (isset($this->session->data['payment_method']['code']) && $this->session->data['payment_method']['code'] === 'cod') $shippingCost = $this->session->data['econt_delivery']['customer_info']['shipping_price_cod'];
    295         else $shippingCost = @$this->session->data['econt_delivery']['customer_info']['shipping_price'];
    296         $shippingCost = floatval($shippingCost);
    297 
    298         if (isset($this->session->data['shipping_methods']['econt_delivery'])) $this->session->data['shipping_methods']['econt_delivery']['quote']['econt_delivery']['cost'] = $shippingCost;
    299         if (isset($this->session->data['shipping_method']) && $this->session->data['shipping_method']['code'] === 'econt_delivery.econt_delivery') $this->session->data['shipping_method']['cost'] = floatval($shippingCost);
    300 
    301         $this->response->addHeader('Content-Type: application/json');
    302         $this->response->setOutput(json_encode(@$this->session->data['econt_delivery']['customer_info']));
    303     }
    304 
    305 }