Plugin Directory

Changeset 3339535


Ignore:
Timestamp:
08/05/2025 09:43:26 AM (8 months ago)
Author:
eshoplogistic
Message:

Добавлено отслеживание статусов в заказе

Location:
eshoplogisticru/trunk
Files:
8 edited

Legend:

Unmodified
Added
Removed
  • eshoplogisticru/trunk/Classes/Shipping/ExportFileds.php

    r3315219 r3339535  
    512512                ),
    513513                'order[combine_places]' => array(
    514                     'apply||checkbox||Объединить все грузовые места в одно' => ($exportFormSettings['combine-places-apply'] == 'on')?'checked':'',
    515                     'dimensions||text||Габариты итогового грузового места (Д*Ш*В)' => ($exportFormSettings['combine-places-dimensions'])??'',
    516                     'weight||text||Вес итогового грузового места в кг' => ($exportFormSettings['combine-places-weight'])??''
     514                    'apply||checkbox||Объединить все грузовые места в одно' => (isset($exportFormSettings['combine-places-apply']) && $exportFormSettings['combine-places-apply'] == 'on')?'checked':'',
     515                    'dimensions||text||Габариты итогового грузового места (Д*Ш*В)' => (isset($exportFormSettings['combine-places-dimensions']) && $exportFormSettings['combine-places-dimensions'])??'',
     516                    'weight||text||Вес итогового грузового места в кг' => (isset($exportFormSettings['combine-places-weight']) && $exportFormSettings['combine-places-weight'])??''
    517517                ),
    518518                'delivery' => array(
  • eshoplogisticru/trunk/Cron/UnloadingCron.php

    r3186394 r3339535  
    7171                continue;
    7272
     73            $orderShippings = $order->get_shipping_methods();
     74            $shippingMethod = array();
     75            $shippingId = false;
     76            foreach ($orderShippings as $key=>$item){
     77                $shippingId = $item->get_id();
     78                $shippingMethod = wc_get_order_item_meta( $shippingId , 'esl_shipping_methods', $single = true );
     79                $shippingMethod = json_decode($shippingMethod, true);
     80            }
     81
     82            $tracking = false;
     83            if(isset($shippingMethod['answer']['state']['number'])){
     84                $trackId = $shippingMethod['answer']['state']['number'];
     85                $tracking = $unloading->infoOrder($orderId, $checkName['name'], 'tracking', ['track' => $trackId]);
     86            }
     87
    7388            $status = $unloading->infoOrder($orderId, $checkName['name']);
     89
    7490            if(isset($status['success']) && $status['success'] === false){
    7591                $result = $status['data']['messages'] ?? 'Ошибка при получении данных';
     
    7793                $result = $unloading->updateStatusById($status, $orderId);
    7894            }
     95            if(isset($tracking['success']) && $tracking['success'] === false){
     96                $resultTrack = $tracking['data']['messages'] ?? 'Ошибка при получении данных';
     97            }else{
     98                if(isset($tracking['status']['name']) && $shippingId){
     99                    wc_update_order_item_meta($shippingId, 'Статус заказа', $tracking['status']['name']);
     100                    if($shippingMethod){
     101                        $shippingMethod['tracking'] = $tracking;
     102                        $jsonArr = json_encode($shippingMethod, JSON_UNESCAPED_UNICODE);
     103                        wc_update_order_item_meta($shippingId, 'esl_shipping_methods', $jsonArr);
     104                    }
     105                }
     106            }
    79107
    80108            $logger = wc_get_logger();
     
    90118            $timeMin = (int)$this->addForm['cronStatusTime'];
    91119        }
     120        if($timeMin < 60)
     121            $timeMin = 60;
    92122
    93123        $schedules['esl_custom_min'] = array(
  • eshoplogisticru/trunk/Modules/Footer.php

    r3154034 r3339535  
    1818        add_shortcode('shortcode_widget_static', 'shortcode_widget_static_handler');
    1919        add_shortcode('shortcode_email_time_delivery', 'shortcode_widget_email_time_delivery');
     20        add_shortcode('shortcode_email_status_delivery', 'shortcode_widget_email_status_delivery');
    2021        update_option( 'use_smilies', false );
    2122        //add_action('wp_footer', [$this, 'addWidgetScript']);
  • eshoplogisticru/trunk/Modules/Unloading.php

    r3276976 r3339535  
    1313
    1414
    15 if ( ! defined( 'ABSPATH' ) ) {
    16     exit;
     15if (!defined('ABSPATH')) {
     16    exit;
    1717}
    1818
    19 class Unloading implements ModuleInterface {
    20 
    21     private $deliveryEsl = false;
    22     private $shippingMethods = [];
    23 
    24     public $defaultFields = array(
    25         'key'      => '', //Ключ доступа
    26         'action'   => '', //Значение: create
    27         'cms'      => '',
    28         'service'  => '',
    29         'order'    => array(
    30             'id'      => '', //Идентификатор заказа на сайте.
    31             'comment' => '',
    32         ),
    33         'places'   => array(
    34             'article'    => '',
    35             'name'       => '',
    36             'count'      => '',
    37             'price'      => '',
    38             'weight'     => '', //Вес, в кг.
    39             'dimensions' => '', //Габариты. Формат: строка вида «Д*Ш*В», в сантиметрах. Например: 15*25*10
    40             'vat_rate'   => '' //Значение ставки НДС Возможные варианты:0, 10, 20, -1 (без НДС)
    41         ),
    42         'receiver' => array( //Данные получателя
    43             'name'  => '',
    44             'phone' => '',
    45             'email' => ''
    46         ),
    47         'sender'   => array(
    48             'name'  => '',
    49             'phone' => '',
    50             'company' => '',
    51             'email' => '',
    52         ),
    53         'delivery' => array(
    54             'type'          => '',
    55             'location_from' => array( //Адрес отправителя (при заборе груза от отправителя)
    56                 'pick_up'  => '',
    57                 //Забор груза от отправителя
    58                 'terminal' => '',
    59                 //Идентификатор пункта приёма груза Обязательно, если delivery.location_from.pick_up === false
    60                 'address'  => array( //Адрес забора груза Обязательно, если delivery.location_from.pick_up === true
    61                     'region' => '', //Регион. Например: Московская область
    62                     'city'   => '', //Населённый пункт
    63                     'street' => '', //Улица
    64                     'house'  => '', //Номер строения
    65                     'room'   => '' //Квартира / офис / помещение
    66                 ),
    67             ),
    68             'payment'       => '',
    69             'cost'          => '', //Стоимость доставки, рубли.
    70             'location_to'   => array(
    71                 'terminal' => '',
    72                 'address'  => array(
    73                     'region' => '',
    74                     'city'   => '',
    75                     'street' => '',
    76                     'house'  => '',
    77                     'room'   => '',
    78                 ),
    79             ),
    80         ),
    81     );
    82 
    83     public function init() {
    84 
    85         $optionsRepository = new OptionsRepository();
    86         $moduleVersion     = $optionsRepository->getOption( 'wc_esl_shipping_plugin_enable_api_v2' );
    87         if ( $moduleVersion ) {
    88             add_action( 'admin_head', [ $this, 'esl_form_in_admin_bar' ] );
    89             add_action( 'add_meta_boxes', [ $this, 'esl_button_start_meta_boxes' ] );
    90             add_action( 'add_meta_boxes', [ $this, 'esl_button_start_meta_boxes_HPOS' ] );
    91         }
    92     }
    93 
    94     public function esl_button_start_meta_boxes_HPOS() {
    95         $shippingHelper = new ShippingHelper();
    96         if ( ! $shippingHelper->HPOS_is_enabled() ) {
    97             return false;
    98         }
    99 
    100         global $post;
    101 
    102         $pageType = $shippingHelper->admin_post_type();
    103         $postId   = false;
    104         if ( isset( $post->ID ) ) {
    105             $postId = $post->ID;
    106         }
    107         if ( isset( $_GET['id'] ) ) {
    108             $postId = $_GET['id'];
    109         }
    110         if ( ! $postId ) {
    111             return false;
    112         }
    113 
    114         if ( $pageType == 'shop_order' ) {
    115             $order          = wc_get_order( $postId );
    116             $orderShippings = $order->get_shipping_methods();
    117             $orderShipping  = array();
    118 
    119             foreach ( $orderShippings as $key => $item ) {
    120                 $orderShipping = array(
    121                     'id'   => $item->get_method_id(),
    122                     'name' => $item->get_method_title(),
    123                 );
    124             }
    125             $checkDelivery = stripos( $orderShipping['id'], WC_ESL_PREFIX );
    126             if ( $checkDelivery === false ) {
    127                 return false;
    128             }
    129 
    130             $checkName = $this->getMethodByName( $orderShipping['name'] );
    131             if ( ! $checkName['name'] ) {
    132                 return false;
    133             }
    134 
    135             $screen = wc_get_container()->get( CustomOrdersTableController::class )->custom_orders_table_usage_is_enabled()
    136                 ? wc_get_page_screen_id( 'shop-order' )
    137                 : 'shop_order';
    138 
    139             add_meta_box(
    140                 'woocommerce-order-esl-unloading',
    141                 __( 'Параметры выгрузки' ),
    142                 [ $this, 'order_meta_box_start_button' ],
    143                 $screen,
    144                 'side',
    145                 'high'
    146             );
    147         }
    148     }
    149 
    150     public function esl_button_start_meta_boxes() {
    151         global $post;
    152 
    153         $shippingHelper = new ShippingHelper();
    154         $pageType       = $shippingHelper->admin_post_type();
    155         $postId         = false;
    156         if ( isset( $post->ID ) ) {
    157             $postId = $post->ID;
    158         }
    159         if ( isset( $_GET['id'] ) ) {
    160             $postId = $_GET['id'];
    161         }
    162         if ( ! $postId ) {
    163             return false;
    164         }
    165 
    166         if ( $pageType == 'shop_order' ) {
    167 
    168             $order          = wc_get_order( $postId );
    169             $orderShippings = $order->get_shipping_methods();
    170             $orderShipping  = array();
    171 
    172             foreach ( $orderShippings as $key => $item ) {
    173                 $orderShipping = array(
    174                     'id'   => $item->get_method_id(),
    175                     'name' => $item->get_method_title(),
    176                 );
    177             }
    178             $checkDelivery = stripos( $orderShipping['id'], WC_ESL_PREFIX );
    179             if ( $checkDelivery === false ) {
    180                 return false;
    181             }
    182 
    183             $checkName = $this->getMethodByName( $orderShipping['name'] );
    184             if ( ! $checkName['name'] ) {
    185                 return false;
    186             }
    187 
    188             add_meta_box(
    189                 'woocommerce-order-esl-unloading',
    190                 __( 'Параметры выгрузки' ),
    191                 [ $this, 'order_meta_box_start_button' ],
    192                 'shop_order',
    193                 'side',
    194                 'default'
    195             );
    196         }
    197     }
    198 
    199     public function esl_form_in_admin_bar() {
    200         global $post, $pagenow;
    201 
    202         $shippingHelper = new ShippingHelper();
    203         $pageType       = $shippingHelper->admin_post_type();
    204         $postId         = false;
    205         if ( isset( $post->ID ) ) {
    206             $postId = $post->ID;
    207         }
    208         if ( isset( $_GET['id'] ) ) {
    209             $postId = $_GET['id'];
    210         }
    211         if ( ! $postId ) {
    212             return false;
    213         }
    214 
    215         if ( ( $pageType == 'shop_order' && $pagenow == 'post.php' ) || ( $pageType == 'shop_order' && $pagenow == 'admin.php' ) ) {
    216             $order          = wc_get_order( $postId );
    217             $orderShippings = $order->get_shipping_methods();
    218             $orderShipping  = array();
    219 
    220             foreach ( $orderShippings as $key => $item ) {
    221                 $orderShipping = array(
    222                     'id'   => $item->get_method_id(),
    223                     'name' => $item->get_method_title(),
    224                 );
    225             }
    226             $checkDelivery = stripos( $orderShipping['id'], WC_ESL_PREFIX );
    227             if ( $checkDelivery === false ) {
    228                 return false;
    229             }
    230 
    231             $checkName = $this->getMethodByName( $orderShipping['name'] );
    232             if ( ! $checkName['name'] ) {
    233                 return false;
    234             }
    235 
    236             $order = wc_get_order( $postId );
    237             if ( $order !== false ) {
    238                 $orderData          = $order->get_data();
    239                 $orderItems         = $order->get_items();
    240                 $orderShippings     = $order->get_shipping_methods();
    241                 $address            = $order->get_address();
    242                 $addressShipping    = $order->get_shipping_address_1();
    243                 $orderShipping      = array();
    244                 $optionsRepository  = new OptionsRepository();
    245                 $apiKey             = $optionsRepository->getOption( 'wc_esl_shipping_api_key' );
    246                 $exportFormSettings = $optionsRepository->getOption( 'wc_esl_shipping_export_form' );
    247 
    248                 foreach ( $orderShippings as $key => $item ) {
    249                     $shippingMethod = wc_get_order_item_meta( $item->get_id(), 'esl_shipping_methods', $single = true );
    250                     if ( $shippingMethod ) {
    251                         $this->shippingMethods = json_decode( $shippingMethod, true );
    252                     }
    253 
    254                     $orderShipping = array(
    255                         'id'    => $item->get_method_id(),
    256                         'name'  => $item->get_name(),
    257                         'title' => $item->get_method_title(),
    258                         'total' => $item->get_total(),
    259                         'tax'   => $item->get_total_tax(),
    260                     );
    261 
    262                 }
    263 
    264                 $checkDelivery = stripos( $orderShipping['id'], WC_ESL_PREFIX );
    265                 if ( $checkDelivery === false ) {
    266                     return false;
    267                 }
    268 
    269 
    270                 if ( $orderShipping['id'] === 'wc_esl_frame_mixed' ) {
    271                     $typeMethod = $this->getMethodByName( $orderShipping['name'] );
    272                 } else {
    273                     $shippingHelper      = new ShippingHelper();
    274                     $options             = $this->getOptionMethod( $shippingHelper->getSlugMethod( $orderShipping['id'] ) );
    275                     $nameCurrectDelivery = $options['name'];
    276                     $typeMethodTitle     = $shippingHelper->getTypeMethod( $orderShipping['id'] );
    277                     $idWithoutPrefix     = explode( WC_ESL_PREFIX, $orderShipping['id'] )[1];
    278                     $idWithoutPrefix     = explode( '_', $idWithoutPrefix )[0];
    279                     if ( $idWithoutPrefix ) {
    280                         $nameCurrectDelivery = $idWithoutPrefix;
    281                     }
    282 
    283                     $typeMethod = array(
    284                         'name' => $nameCurrectDelivery,
    285                         'type' => $typeMethodTitle
    286                     );
    287                 }
    288 
    289                 $cutAddressShipping = array(
    290                     'terminal'         => '',
    291                     'terminal_address' => ''
    292                 );
    293                 if ( $typeMethod['type'] === 'door' ) {
    294                     $cutAddressShipping = $this->getPartAddressNameDoor( $addressShipping );
    295                 }
    296 
    297                 if ( $typeMethod['type'] === 'terminal' ) {
    298                     $cutAddressShipping = $this->getPartAddressNameTerminal( $addressShipping );
    299                 }
    300 
    301                 $additional = array(
    302                     'key'     => $apiKey,
    303                     'service' => mb_strtolower( $typeMethod['name'] ),
    304                     'detail'  => true
    305                 );
    306 
    307                 $methodDelivery = new ExportFileds();
    308                 $fieldDelivery  = $methodDelivery->exportFields( mb_strtolower( $typeMethod['name'] ), $this->shippingMethods, $order );
    309 
    310                 $eshopLogisticApi = new EshopLogisticApi( new WpHttpClient() );
    311                 $additionalFields = $eshopLogisticApi->apiExportAdditional( $additional );
    312                 if ( $additionalFields->hasErrors() ) {
    313                     $additionalFields = [];
    314                 } else {
    315                     $additionalFields = $additionalFields->data();
    316                 }
    317                 $orderShippingId = reset( $orderData['shipping_lines'] );
    318                 $orderShippingId = $orderShippingId->get_id();
    319                 $infoApi         = $eshopLogisticApi->infoAccount();
    320                 if ( $infoApi->hasErrors() ) {
    321                     $infoApi = [];
    322                 } else {
    323                     $infoApi = $infoApi->data();
    324                 }
    325 
    326                 $optionsRepository = new OptionsRepository();
    327                 $addFieldSaved = $optionsRepository->getOption('wc_esl_shipping_add_field_form');
    328 
    329                 $street = get_post_meta( $order->get_id(), 'esl_billing_field_street', true );
    330                 $building = get_post_meta( $order->get_id(), 'esl_billing_field_building', true );
    331                 $room = get_post_meta( $order->get_id(), 'esl_billing_field_room', true );
    332 
    333                 if(!$street)
    334                     $street = get_post_meta( $order->get_id(), 'esl_shipping_field_street', true );
    335 
    336                 if(!$building)
    337                     $building = get_post_meta( $order->get_id(), 'esl_shipping_field_building', true );
    338 
    339                 if(!$room)
    340                     $room = get_post_meta( $order->get_id(), 'esl_shipping_field_room', true );
    341 
    342                 echo View::render( 'unloading-form', [
    343                     'orderData'          => $orderData,
    344                     'orderItems'         => $orderItems,
    345                     'orderShipping'      => $orderShipping,
    346                     'address'            => $address,
    347                     'addressShipping'    => $cutAddressShipping,
    348                     'typeMethod'         => $typeMethod,
    349                     'additionalFields'   => $additionalFields,
    350                     'exportFormSettings' => $exportFormSettings,
    351                     'shippingMethods'    => $this->shippingMethods,
    352                     'fieldDelivery'      => $fieldDelivery,
    353                     'orderShippingId'    => $orderShippingId,
    354                     'infoApi'            => $infoApi,
    355                     'addFieldSaved'      => $addFieldSaved,
    356                     'street'             => $street,
    357                     'building'           => $building,
    358                     'room'               => $room
    359                 ] );
    360             }
    361         }
    362 
    363     }
    364 
    365     protected function getOptionMethod( $slug ) {
    366         if ( empty( $slug ) ) {
    367             return null;
    368         }
    369 
    370         $optionsRepository = new OptionsRepository();
    371         $services          = $optionsRepository->getOption( 'wc_esl_shipping_account_services' );
    372 
    373         if ( ! isset( $services[ $slug ] ) ) {
    374             return null;
    375         }
    376 
    377         return $services[ $slug ];
    378     }
    379 
    380     public function order_meta_box_start_button() {
    381         echo View::render( 'unloading-button', [
    382             'shippingMethods' => $this->shippingMethods,
    383         ] );
    384     }
    385 
    386     public function params_delivery_init( $data ) {
    387         $data                = json_decode( stripslashes( $data ), true );
    388         $defaultParamsCreate = $this->defaultFieldApiCreate( $data );
    389 
    390         $eshopLogisticApi = new EshopLogisticApi( new WpHttpClient() );
    391         $result           = $eshopLogisticApi->apiExportCreate( $defaultParamsCreate );
    392 
    393         if ( ! $result->hasErrors() ) {
    394             $shippingMethod = wc_get_order_item_meta( $data['order_shipping_id'], 'esl_shipping_methods', $single = true );
    395             if ( $shippingMethod ) {
    396                 $shippingMethods = json_decode( $shippingMethod, true );
    397             }
    398 
    399             $shippingMethods['answer'] = $result->data();
    400 
    401             $jsonArr = json_encode( $shippingMethods, JSON_UNESCAPED_UNICODE );
    402             wc_update_order_item_meta( $data['order_shipping_id'], 'esl_shipping_methods', $jsonArr );
    403 
    404             if ( $data['delivery_id'] == 'sdek' && isset( $shippingMethods['answer']['order']['id'] ) ) {
    405                 sleep( 3 );
    406                 $optionsRepository = new OptionsRepository();
    407                 $apiKey            = $optionsRepository->getOption( 'wc_esl_shipping_api_key' );
    408 
    409                 $data             = array(
    410                     'key'      => $apiKey,
    411                     'action'   => 'get',
    412                     'order_id' => $shippingMethods['answer']['order']['id'],
    413                     'service'  => $data['delivery_id']
    414                 );
    415                 $eshopLogisticApi = new EshopLogisticApi( new WpHttpClient() );
    416                 $resultGet        = $eshopLogisticApi->apiExportCreateSdek( $data );
    417                 if ( $resultGet->hasErrors() ) {
    418                     return $resultGet;
    419                 }
    420             }
    421         }
    422 
    423 
    424         return $result;
    425     }
    426 
    427     public function getMethodByName( $name ) {
    428         $result = array(
    429             'name' => '',
    430             'type' => ''
    431         );
    432 
    433         $nameList = array(
    434             'СберЛогистика'   => 'sberlogistics',
    435             '5POST'           => 'fivepost',
    436             'Boxberry'        => 'boxberry',
    437             'Яндекс.Доставка' => 'yandex',
    438             'СДЭК'            => 'sdek',
    439             'Деловые линии'   => 'delline',
    440             'Халва'           => 'halva',
    441             'Kit'             => 'kit',
    442             'Почта России'    => 'postrf',
    443             'ПЭК'             => 'pecom',
    444             'Магнит Пост'     => 'magnit',
    445             'Байкал Сервис'   => 'baikal',
    446             'DPD'   => 'dpd',
    447             'Фулфилмент-оператор «Почтальон»'   => 'pochtalion',
    448         );
    449 
    450         $typeList = array(
    451             'пункт выдачи заказа'       => 'terminal',
    452             'доставка до пункта выдачи' => 'terminal',
    453             'курьер'                    => 'door',
    454         );
    455 
    456         foreach ( $nameList as $key => $value ) {
    457             if ( strpos( mb_strtolower( $name ), mb_strtolower( $key ) ) !== false ) {
    458                 $result['name'] = $value;
    459             }
    460         }
    461 
    462         foreach ( $typeList as $key => $value ) {
    463             if ( strpos( mb_strtolower( $name ), mb_strtolower( $key ) ) !== false ) {
    464                 $result['type'] = $value;
    465             }
    466         }
    467 
    468         return $result;
    469     }
    470 
    471     private function defaultFieldApiCreate( $data ) {
    472         if ( ! isset( $data['delivery_id'] ) && ! $data['delivery_id'] ) {
    473             return false;
    474         }
    475 
    476         $shippingHelper    = new ShippingHelper();
    477         $optionsRepository = new OptionsRepository();
    478         $apiKey            = $optionsRepository->getOption( 'wc_esl_shipping_api_key' );
    479 
    480         if ( ! isset( $apiKey ) && ! $apiKey ) {
    481             return false;
    482         }
    483 
    484         $deliveryId = $data['delivery_id'];
    485         if ( isset( $data['fulfillment'] ) ) {
    486             $deliveryId = 'pochtalion';
    487         }
    488 
    489 
    490         $defaultFields = array(
    491             'key'      => $apiKey, //Ключ доступа
    492             'action'   => 'create', //Значение: create
    493             'cms'      => 'wordpress',
    494             'service'  => $deliveryId,
    495             'order'    => array(
    496                 'id'      => $data['order_id'], //Идентификатор заказа на сайте.
    497                 'comment' => $data['comment'],
    498             ),
    499             'receiver' => array( //Данные получателя
    500                 'name'  => $data['receiver-name'],
    501                 'phone' => $data['receiver-phone'],
    502                 'email' => $data['receiver-email'],
    503             ),
    504             'sender'   => array(
    505                 'name'  => $data['sender-name'],
    506                 'phone' => $data['sender-phone'],
    507                 'company' => $data['sender-company'],
    508                 'email' => $data['sender-email'],
    509             ),
    510             'delivery' => array(
    511                 'type'          => $data['delivery_type'],
    512                 'location_from' => array( //Адрес отправителя (при заборе груза от отправителя)
    513                     'pick_up' => $data['pick_up'] == '1', //Забор груза от отправителя
    514                 ),
    515                 'payment'       => $data['payment_type'],
    516                 'cost'          => $data['esl-unload-price'], //Стоимость доставки, рубли.
    517                 'location_to'   => array(),
    518             ),
    519         );
    520 
    521         if ( $data['pick_up'] == '1' ) {
    522             $defaultFields['delivery']['location_from']['address'] = array( //Адрес забора груза Обязательно, если delivery.location_from.pick_up === true
    523                 'region' => $data['sender-region'], //Регион. Например: Московская область
    524                 'city'   => $data['sender-city'],
    525                 'street' => $data['sender-street'],
    526                 'house'  => $data['sender-house'],
    527                 'room'   => $data['sender-room'],
    528             );
    529         }
    530         if ( $data['pick_up'] == '0' ) {
    531             $defaultFields['delivery']['location_from']['terminal'] = $data['sender-terminal'];//Идентификатор пункта приёма груза Обязательно, если delivery.location_from.pick_up === false
    532         }
    533 
    534         $defaultFields['delivery']['location_to'] = array(
    535             'address' => array(
    536                 'region' => $data['receiver-region'],
    537                 'city'   => $data['receiver-city'],
    538                 'street' => $data['receiver-street'],
    539                 'house'  => $data['receiver-house'],
    540                 'room'   => $data['receiver-room'],
    541             ),
    542         );
    543 
    544         if ( $data['delivery_type'] === 'terminal' ) {
    545             $defaultFields['delivery']['location_to']['terminal'] = $data['terminal-code'];
    546         }
    547 
    548         if ( isset( $data['products'] ) ) {
    549             foreach ( $data['products'] as $item ) {
    550                 if ( empty( $item['product_id'] ) ) {
    551                     continue;
    552                 }
    553 
    554                 $defaultFields['places'][] = array(
    555                     'article'    => $item['product_id'],
    556                     'name'       => $item['name'],
    557                     'count'      => $item['quantity'],
    558                     'price'      => $item['price'],
    559                     'weight'     => $shippingHelper->weightOption( $item['weight'] ),
    560                     //Вес, в кг.
    561                     'dimensions' => $shippingHelper->dimensionsOption( $item['width'] ) . '*' . $shippingHelper->dimensionsOption( $item['length'] ) . '*' . $shippingHelper->dimensionsOption( $item['height'] ),
    562                     //Габариты. Формат: строка вида «Д*Ш*В», в сантиметрах. Например: 15*25*10
    563                     'vat_rate'   => 0,
    564                     //Значение ставки НДС Возможные варианты:0, 10, 20, -1 (без НДС)
    565                 );
    566             }
    567         }
    568 
    569         //if(isset($data['order']) && $data['order']){
    570         //foreach ($data['order'] as $key=>$value)
    571         //$defaultFields['order'][$key] = $value;
    572         //}
    573 
    574         $exportFields = new ExportFileds();
    575         $exportFields = $exportFields->sendExportFields( $data['delivery_id'] );
    576         foreach ( $exportFields as $key => $value ) {
    577             if ( isset( $data[ $key ] ) ) {
    578                 //$defaultFields[$key] = $defaultFields[$key] + $data[$key];
    579                 $defaultFields[ $key ] = array_merge_recursive( $defaultFields[ $key ], $data[ $key ] );
    580             }
    581         }
    582 
    583         if ( isset( $data['fulfillment'] ) ) {
    584             $defaultFields['delivery']['variant'] = $data['delivery_id'];
    585         }
    586 
    587 
    588         return $defaultFields;
    589     }
    590 
    591     public function getPartAddressNameDoor( $name ) {
    592         if ( ! $name ) {
    593             return '';
    594         }
    595 
    596         $result = array(
    597             'region' => '',
    598             'city'   => '',
    599             'street' => '',
    600             'house'  => '',
    601             'room'   => '',
    602         );
    603 
    604         $partExplode = explode( ',', $name );
    605 
    606         if ( isset( $partExplode[0] ) ) {
    607             $result['region'] = $partExplode[0];
    608         }
    609         if ( isset( $partExplode[1] ) ) {
    610             $result['city'] = $partExplode[1];
    611         }
    612         if ( isset( $partExplode[2] ) ) {
    613             $result['street'] = $partExplode[2];
    614         }
    615         if ( isset( $partExplode[3] ) ) {
    616             $result['house'] = $partExplode[3];
    617         }
    618         if ( isset( $partExplode[4] ) ) {
    619             $result['room'] = $partExplode[4];
    620         }
    621     }
    622 
    623     public function getPartAddressNameTerminal( $name ) {
    624         if ( ! $name ) {
    625             return '';
    626         }
    627 
    628         $result = array(
    629             'terminal' => '',
    630         );
    631 
    632         $partExplode = explode( ',', $name );
    633 
    634         foreach ( $partExplode as $value ) {
    635             if ( str_contains( $value, 'Код пункта' ) ) {
    636                 $codePart = explode( 'Код пункта:', $value );
    637                 if ( isset( $codePart[1] ) ) {
    638                     $result['terminal'] = trim( $codePart[1] );
    639                 }
    640                 $result['terminal_address'] = trim( $name );
    641             }
    642         }
    643 
    644         return $result;
    645     }
    646 
    647     public function infoOrder( $id, $type, $action = 'get' ) {
    648 
    649         $optionsRepository = new OptionsRepository();
    650         $apiKey            = $optionsRepository->getOption( 'wc_esl_shipping_api_key' );
    651 
    652         $order           = wc_get_order( $id );
    653         $orderData       = $order->get_data();
    654         $orderShippingId = reset( $orderData['shipping_lines'] );
    655         $orderShippingId = $orderShippingId->get_id();
    656         $shippingMethod  = wc_get_order_item_meta( $orderShippingId, 'esl_shipping_methods', $single = true );
    657         if ( $shippingMethod ) {
    658             $shippingMethods = json_decode( $shippingMethod, true );
    659             if ( isset( $shippingMethods['answer']['order']['id'] ) ) {
    660                 $id = $shippingMethods['answer']['order']['id'];
    661             }
    662         }
    663 
    664         $data             = array(
    665             'key'      => $apiKey,
    666             'action'   => $action,
    667             'order_id' => $id,
    668             'service'  => $type
    669         );
    670         $eshopLogisticApi = new EshopLogisticApi( new WpHttpClient() );
    671         $result           = $eshopLogisticApi->apiExportCreate( $data );
    672         if ( $result->hasErrors() ) {
    673             return $result->jsonSerialize();
    674         }
    675 
    676         return $result->data();
    677     }
    678 
    679     public function getStatusWp() {
    680         return wc_get_order_statuses();
    681     }
    682 
    683     public function updateStatusById( $id, $order_id ) {
    684         if ( ! isset( $id['state']['number'] ) && ! isset( $id['state']['status']['code'] ) ) {
    685             return false;
    686         }
    687 
    688         $optionsRepository = new OptionsRepository();
    689         $settingsStatus    = $optionsRepository->getOption( 'wc_esl_shipping_plugin_status_form' );
    690 
    691         $order            = wc_get_order( $order_id );
    692         $orderStatus      = $order->get_status();
    693         $resultNameStatus = '';
    694 
    695         if ( isset( $settingsStatus[ $id['state']['status']['code'] ] ) ) {
    696             $resultNameStatus = $settingsStatus[ $id['state']['status']['code'] ][0]['name'];
    697         }
    698 
    699 
    700         if ( $resultNameStatus ) {
    701             if ( $orderStatus == $resultNameStatus || 'wc-' . $orderStatus == $resultNameStatus ) {
    702                 return 'Статус не изменился';
    703             }
    704 
    705             $result = $order->update_status( $resultNameStatus );
    706             if ( $result ) {
    707                 return 'Статус обновлен';
    708             }
    709         }
    710 
    711         return 'Ошибка при обновлении';
    712 
    713     }
     19class Unloading implements ModuleInterface
     20{
     21
     22    private $deliveryEsl = false;
     23    private $shippingMethods = [];
     24
     25    public $defaultFields = array(
     26        'key' => '', //Ключ доступа
     27        'action' => '', //Значение: create
     28        'cms' => '',
     29        'service' => '',
     30        'order' => array(
     31            'id' => '', //Идентификатор заказа на сайте.
     32            'comment' => '',
     33        ),
     34        'places' => array(
     35            'article' => '',
     36            'name' => '',
     37            'count' => '',
     38            'price' => '',
     39            'weight' => '', //Вес, в кг.
     40            'dimensions' => '', //Габариты. Формат: строка вида «Д*Ш*В», в сантиметрах. Например: 15*25*10
     41            'vat_rate' => '' //Значение ставки НДС Возможные варианты:0, 10, 20, -1 (без НДС)
     42        ),
     43        'receiver' => array( //Данные получателя
     44            'name' => '',
     45            'phone' => '',
     46            'email' => ''
     47        ),
     48        'sender' => array(
     49            'name' => '',
     50            'phone' => '',
     51            'company' => '',
     52            'email' => '',
     53        ),
     54        'delivery' => array(
     55            'type' => '',
     56            'location_from' => array( //Адрес отправителя (при заборе груза от отправителя)
     57                'pick_up' => '',
     58                //Забор груза от отправителя
     59                'terminal' => '',
     60                //Идентификатор пункта приёма груза Обязательно, если delivery.location_from.pick_up === false
     61                'address' => array( //Адрес забора груза Обязательно, если delivery.location_from.pick_up === true
     62                    'region' => '', //Регион. Например: Московская область
     63                    'city' => '', //Населённый пункт
     64                    'street' => '', //Улица
     65                    'house' => '', //Номер строения
     66                    'room' => '' //Квартира / офис / помещение
     67                ),
     68            ),
     69            'payment' => '',
     70            'cost' => '', //Стоимость доставки, рубли.
     71            'location_to' => array(
     72                'terminal' => '',
     73                'address' => array(
     74                    'region' => '',
     75                    'city' => '',
     76                    'street' => '',
     77                    'house' => '',
     78                    'room' => '',
     79                ),
     80            ),
     81        ),
     82    );
     83
     84    public function init()
     85    {
     86
     87        $optionsRepository = new OptionsRepository();
     88        $moduleVersion = $optionsRepository->getOption('wc_esl_shipping_plugin_enable_api_v2');
     89        if ($moduleVersion) {
     90            add_action('admin_head', [$this, 'esl_form_in_admin_bar']);
     91            add_action('add_meta_boxes', [$this, 'esl_button_start_meta_boxes']);
     92            add_action('add_meta_boxes', [$this, 'esl_button_start_meta_boxes_HPOS']);
     93        }
     94    }
     95
     96    public function esl_button_start_meta_boxes_HPOS()
     97    {
     98        $shippingHelper = new ShippingHelper();
     99        if (!$shippingHelper->HPOS_is_enabled()) {
     100            return false;
     101        }
     102
     103        global $post;
     104
     105        $pageType = $shippingHelper->admin_post_type();
     106        $postId = false;
     107        if (isset($post->ID)) {
     108            $postId = $post->ID;
     109        }
     110        if (isset($_GET['id'])) {
     111            $postId = $_GET['id'];
     112        }
     113        if (!$postId) {
     114            return false;
     115        }
     116
     117        if ($pageType == 'shop_order') {
     118            $order = wc_get_order($postId);
     119            $orderShippings = $order->get_shipping_methods();
     120            $orderShipping = array();
     121
     122            foreach ($orderShippings as $key => $item) {
     123                $orderShipping = array(
     124                    'id' => $item->get_method_id(),
     125                    'name' => $item->get_method_title(),
     126                );
     127            }
     128            $checkDelivery = stripos($orderShipping['id'], WC_ESL_PREFIX);
     129            if ($checkDelivery === false) {
     130                return false;
     131            }
     132
     133            $checkName = $this->getMethodByName($orderShipping['name']);
     134            if (!$checkName['name']) {
     135                return false;
     136            }
     137
     138            $screen = wc_get_container()->get(CustomOrdersTableController::class)->custom_orders_table_usage_is_enabled()
     139                ? wc_get_page_screen_id('shop-order')
     140                : 'shop_order';
     141
     142            add_meta_box(
     143                'woocommerce-order-esl-unloading',
     144                __('Параметры выгрузки'),
     145                [$this, 'order_meta_box_start_button'],
     146                $screen,
     147                'side',
     148                'high'
     149            );
     150        }
     151    }
     152
     153    public function esl_button_start_meta_boxes()
     154    {
     155        global $post;
     156
     157        $shippingHelper = new ShippingHelper();
     158        $pageType = $shippingHelper->admin_post_type();
     159        $postId = false;
     160        if (isset($post->ID)) {
     161            $postId = $post->ID;
     162        }
     163        if (isset($_GET['id'])) {
     164            $postId = $_GET['id'];
     165        }
     166        if (!$postId) {
     167            return false;
     168        }
     169
     170        if ($pageType == 'shop_order') {
     171
     172            $order = wc_get_order($postId);
     173            $orderShippings = $order->get_shipping_methods();
     174            $orderShipping = array();
     175
     176            foreach ($orderShippings as $key => $item) {
     177                $orderShipping = array(
     178                    'id' => $item->get_method_id(),
     179                    'name' => $item->get_method_title(),
     180                );
     181            }
     182            $checkDelivery = stripos($orderShipping['id'], WC_ESL_PREFIX);
     183            if ($checkDelivery === false) {
     184                return false;
     185            }
     186
     187            $checkName = $this->getMethodByName($orderShipping['name']);
     188            if (!$checkName['name']) {
     189                return false;
     190            }
     191
     192            add_meta_box(
     193                'woocommerce-order-esl-unloading',
     194                __('Параметры выгрузки'),
     195                [$this, 'order_meta_box_start_button'],
     196                'shop_order',
     197                'side',
     198                'default'
     199            );
     200        }
     201    }
     202
     203    public function esl_form_in_admin_bar()
     204    {
     205        global $post, $pagenow;
     206
     207        $shippingHelper = new ShippingHelper();
     208        $pageType = $shippingHelper->admin_post_type();
     209        $postId = false;
     210        if (isset($post->ID)) {
     211            $postId = $post->ID;
     212        }
     213        if (isset($_GET['id'])) {
     214            $postId = $_GET['id'];
     215        }
     216        if (!$postId) {
     217            return false;
     218        }
     219
     220        if (($pageType == 'shop_order' && $pagenow == 'post.php') || ($pageType == 'shop_order' && $pagenow == 'admin.php')) {
     221            $order = wc_get_order($postId);
     222            $orderShippings = $order->get_shipping_methods();
     223            $orderShipping = array();
     224
     225            foreach ($orderShippings as $key => $item) {
     226                $orderShipping = array(
     227                    'id' => $item->get_method_id(),
     228                    'name' => $item->get_method_title(),
     229                );
     230            }
     231            $checkDelivery = stripos($orderShipping['id'], WC_ESL_PREFIX);
     232            if ($checkDelivery === false) {
     233                return false;
     234            }
     235
     236            $checkName = $this->getMethodByName($orderShipping['name']);
     237            if (!$checkName['name']) {
     238                return false;
     239            }
     240
     241            $order = wc_get_order($postId);
     242            if ($order !== false) {
     243                $orderData = $order->get_data();
     244                $orderItems = $order->get_items();
     245                $orderShippings = $order->get_shipping_methods();
     246                $address = $order->get_address();
     247                $addressShipping = $order->get_shipping_address_1();
     248                $orderShipping = array();
     249                $optionsRepository = new OptionsRepository();
     250                $apiKey = $optionsRepository->getOption('wc_esl_shipping_api_key');
     251                $exportFormSettings = $optionsRepository->getOption('wc_esl_shipping_export_form');
     252
     253                foreach ($orderShippings as $key => $item) {
     254                    $shippingMethod = wc_get_order_item_meta($item->get_id(), 'esl_shipping_methods', $single = true);
     255                    if ($shippingMethod) {
     256                        $this->shippingMethods = json_decode($shippingMethod, true);
     257                    }
     258
     259                    $orderShipping = array(
     260                        'id' => $item->get_method_id(),
     261                        'name' => $item->get_name(),
     262                        'title' => $item->get_method_title(),
     263                        'total' => $item->get_total(),
     264                        'tax' => $item->get_total_tax(),
     265                    );
     266
     267                }
     268
     269                $checkDelivery = stripos($orderShipping['id'], WC_ESL_PREFIX);
     270                if ($checkDelivery === false) {
     271                    return false;
     272                }
     273
     274
     275                if ($orderShipping['id'] === 'wc_esl_frame_mixed') {
     276                    $typeMethod = $this->getMethodByName($orderShipping['name']);
     277                } else {
     278                    $shippingHelper = new ShippingHelper();
     279                    $options = $this->getOptionMethod($shippingHelper->getSlugMethod($orderShipping['id']));
     280                    $nameCurrectDelivery = $options['name'];
     281                    $typeMethodTitle = $shippingHelper->getTypeMethod($orderShipping['id']);
     282                    $idWithoutPrefix = explode(WC_ESL_PREFIX, $orderShipping['id'])[1];
     283                    $idWithoutPrefix = explode('_', $idWithoutPrefix)[0];
     284                    if ($idWithoutPrefix) {
     285                        $nameCurrectDelivery = $idWithoutPrefix;
     286                    }
     287
     288                    $typeMethod = array(
     289                        'name' => $nameCurrectDelivery,
     290                        'type' => $typeMethodTitle
     291                    );
     292                }
     293
     294                $cutAddressShipping = array(
     295                    'terminal' => '',
     296                    'terminal_address' => ''
     297                );
     298                if ($typeMethod['type'] === 'door') {
     299                    $cutAddressShipping = $this->getPartAddressNameDoor($addressShipping);
     300                }
     301
     302                if ($typeMethod['type'] === 'terminal') {
     303                    $cutAddressShipping = $this->getPartAddressNameTerminal($addressShipping);
     304                }
     305
     306                $additional = array(
     307                    'key' => $apiKey,
     308                    'service' => mb_strtolower($typeMethod['name']),
     309                    'detail' => true
     310                );
     311
     312                $methodDelivery = new ExportFileds();
     313                $fieldDelivery = $methodDelivery->exportFields(mb_strtolower($typeMethod['name']), $this->shippingMethods, $order);
     314
     315                $eshopLogisticApi = new EshopLogisticApi(new WpHttpClient());
     316                $additionalFields = $eshopLogisticApi->apiExportAdditional($additional);
     317                if ($additionalFields->hasErrors()) {
     318                    $additionalFields = [];
     319                } else {
     320                    $additionalFields = $additionalFields->data();
     321                }
     322                $orderShippingId = reset($orderData['shipping_lines']);
     323                $orderShippingId = $orderShippingId->get_id();
     324                $infoApi = $eshopLogisticApi->infoAccount();
     325                if ($infoApi->hasErrors()) {
     326                    $infoApi = [];
     327                } else {
     328                    $infoApi = $infoApi->data();
     329                }
     330
     331                $optionsRepository = new OptionsRepository();
     332                $addFieldSaved = $optionsRepository->getOption('wc_esl_shipping_add_field_form');
     333
     334                $street = get_post_meta($order->get_id(), 'esl_billing_field_street', true);
     335                $building = get_post_meta($order->get_id(), 'esl_billing_field_building', true);
     336                $room = get_post_meta($order->get_id(), 'esl_billing_field_room', true);
     337
     338                if (!$street)
     339                    $street = get_post_meta($order->get_id(), 'esl_shipping_field_street', true);
     340
     341                if (!$building)
     342                    $building = get_post_meta($order->get_id(), 'esl_shipping_field_building', true);
     343
     344                if (!$room)
     345                    $room = get_post_meta($order->get_id(), 'esl_shipping_field_room', true);
     346
     347                echo View::render('unloading-form', [
     348                    'orderData' => $orderData,
     349                    'orderItems' => $orderItems,
     350                    'orderShipping' => $orderShipping,
     351                    'address' => $address,
     352                    'addressShipping' => $cutAddressShipping,
     353                    'typeMethod' => $typeMethod,
     354                    'additionalFields' => $additionalFields,
     355                    'exportFormSettings' => $exportFormSettings,
     356                    'shippingMethods' => $this->shippingMethods,
     357                    'fieldDelivery' => $fieldDelivery,
     358                    'orderShippingId' => $orderShippingId,
     359                    'infoApi' => $infoApi,
     360                    'addFieldSaved' => $addFieldSaved,
     361                    'street' => $street,
     362                    'building' => $building,
     363                    'room' => $room
     364                ]);
     365            }
     366        }
     367
     368    }
     369
     370    protected function getOptionMethod($slug)
     371    {
     372        if (empty($slug)) {
     373            return null;
     374        }
     375
     376        $optionsRepository = new OptionsRepository();
     377        $services = $optionsRepository->getOption('wc_esl_shipping_account_services');
     378
     379        if (!isset($services[$slug])) {
     380            return null;
     381        }
     382
     383        return $services[$slug];
     384    }
     385
     386    public function order_meta_box_start_button()
     387    {
     388        echo View::render('unloading-button', [
     389            'shippingMethods' => $this->shippingMethods,
     390        ]);
     391    }
     392
     393    public function params_delivery_init($data)
     394    {
     395        $data = json_decode(stripslashes($data), true);
     396        $defaultParamsCreate = $this->defaultFieldApiCreate($data);
     397
     398        $eshopLogisticApi = new EshopLogisticApi(new WpHttpClient());
     399        $result = $eshopLogisticApi->apiExportCreate($defaultParamsCreate);
     400
     401        if (!$result->hasErrors()) {
     402            $shippingMethod = wc_get_order_item_meta($data['order_shipping_id'], 'esl_shipping_methods', $single = true);
     403            if ($shippingMethod) {
     404                $shippingMethods = json_decode($shippingMethod, true);
     405            }else{
     406                $shippingMethods = [];
     407            }
     408
     409            sleep(3);
     410            $optionsRepository = new OptionsRepository();
     411            $apiKey = $optionsRepository->getOption('wc_esl_shipping_api_key');
     412            $shippingMethods['answer'] = $result->data();
     413
     414            $dataGet = array(
     415                'key' => $apiKey,
     416                'action' => 'get',
     417                'order_id' => $shippingMethods['answer']['order']['id'],
     418                'service' => $data['delivery_id'],
     419            );
     420            $eshopLogisticApi = new EshopLogisticApi(new WpHttpClient());
     421            $resultGet = $eshopLogisticApi->apiExportCreateSdek($dataGet);
     422
     423            if(!$resultGet->hasErrors()){
     424                $resultTracking = $resultGet->data();
     425                if(isset($resultTracking['state']['tracking'])){
     426                    $shippingMethods['tracking'] = $resultTracking['state']['tracking'];
     427                    wc_update_order_item_meta($data['order_shipping_id'], 'Трек-код', $resultTracking['state']['tracking']);
     428                }
     429
     430                $jsonArr = json_encode($shippingMethods, JSON_UNESCAPED_UNICODE);
     431                wc_update_order_item_meta($data['order_shipping_id'], 'esl_shipping_methods', $jsonArr);
     432
     433                if ($data['delivery_id'] == 'sdek' && isset($shippingMethods['answer']['order']['id'])) {
     434                    return $resultGet;
     435                }
     436            }
     437        }
     438
     439        return $result;
     440    }
     441
     442    public function getMethodByName($name)
     443    {
     444        $result = array(
     445            'name' => '',
     446            'type' => ''
     447        );
     448
     449        $nameList = array(
     450            'СберЛогистика' => 'sberlogistics',
     451            '5POST' => 'fivepost',
     452            'Boxberry' => 'boxberry',
     453            'Яндекс.Доставка' => 'yandex',
     454            'СДЭК' => 'sdek',
     455            'Деловые линии' => 'delline',
     456            'Халва' => 'halva',
     457            'Kit' => 'kit',
     458            'Почта России' => 'postrf',
     459            'ПЭК' => 'pecom',
     460            'Магнит Пост' => 'magnit',
     461            'Байкал Сервис' => 'baikal',
     462            'DPD' => 'dpd',
     463            'Фулфилмент-оператор «Почтальон»' => 'pochtalion',
     464        );
     465
     466        $typeList = array(
     467            'пункт выдачи заказа' => 'terminal',
     468            'доставка до пункта выдачи' => 'terminal',
     469            'курьер' => 'door',
     470        );
     471
     472        foreach ($nameList as $key => $value) {
     473            if (strpos(mb_strtolower($name), mb_strtolower($key)) !== false) {
     474                $result['name'] = $value;
     475            }
     476        }
     477
     478        foreach ($typeList as $key => $value) {
     479            if (strpos(mb_strtolower($name), mb_strtolower($key)) !== false) {
     480                $result['type'] = $value;
     481            }
     482        }
     483
     484        return $result;
     485    }
     486
     487    private function defaultFieldApiCreate($data)
     488    {
     489        if (!isset($data['delivery_id']) && !$data['delivery_id']) {
     490            return false;
     491        }
     492
     493        $shippingHelper = new ShippingHelper();
     494        $optionsRepository = new OptionsRepository();
     495        $apiKey = $optionsRepository->getOption('wc_esl_shipping_api_key');
     496
     497        if (!isset($apiKey) && !$apiKey) {
     498            return false;
     499        }
     500
     501        $deliveryId = $data['delivery_id'];
     502        if (isset($data['fulfillment'])) {
     503            $deliveryId = 'pochtalion';
     504        }
     505
     506        $defaultFields = array(
     507            'key' => $apiKey, //Ключ доступа
     508            'action' => 'create', //Значение: create
     509            'cms' => 'wordpress',
     510            'service' => $deliveryId,
     511            'order' => array(
     512                'id' => $data['order_id'], //Идентификатор заказа на сайте.
     513                'comment' => $data['comment'],
     514            ),
     515            'receiver' => array( //Данные получателя
     516                'name' => $data['receiver-name'],
     517                'phone' => $data['receiver-phone'],
     518                'email' => $data['receiver-email'],
     519            ),
     520            'sender' => array(
     521                'name' => $data['sender-name'],
     522                'phone' => $data['sender-phone'],
     523                'company' => $data['sender-company'],
     524                'email' => $data['sender-email'],
     525            ),
     526            'delivery' => array(
     527                'type' => $data['delivery_type'],
     528                'location_from' => array( //Адрес отправителя (при заборе груза от отправителя)
     529                    'pick_up' => $data['pick_up'] == '1', //Забор груза от отправителя
     530                ),
     531                'payment' => $data['payment_type'],
     532                'cost' => $data['esl-unload-price'], //Стоимость доставки, рубли.
     533                'location_to' => array(),
     534            ),
     535        );
     536
     537        if ($data['pick_up'] == '1') {
     538            $defaultFields['delivery']['location_from']['address'] = array( //Адрес забора груза Обязательно, если delivery.location_from.pick_up === true
     539                'region' => $data['sender-region'], //Регион. Например: Московская область
     540                'city' => $data['sender-city'],
     541                'street' => $data['sender-street'],
     542                'house' => $data['sender-house'],
     543                'room' => $data['sender-room'],
     544            );
     545        }
     546        if ($data['pick_up'] == '0') {
     547            $defaultFields['delivery']['location_from']['terminal'] = $data['sender-terminal'];//Идентификатор пункта приёма груза Обязательно, если delivery.location_from.pick_up === false
     548        }
     549
     550        $defaultFields['delivery']['location_to'] = array(
     551            'address' => array(
     552                'region' => $data['receiver-region'],
     553                'city' => $data['receiver-city'],
     554                'street' => $data['receiver-street'],
     555                'house' => $data['receiver-house'],
     556                'room' => $data['receiver-room'],
     557            ),
     558        );
     559
     560        if ($data['delivery_type'] === 'terminal') {
     561            $defaultFields['delivery']['location_to']['terminal'] = $data['terminal-code'];
     562        }
     563
     564        if (isset($data['products'])) {
     565            foreach ($data['products'] as $item) {
     566                if (empty($item['product_id'])) {
     567                    continue;
     568                }
     569
     570                $defaultFields['places'][] = array(
     571                    'article' => $item['product_id'],
     572                    'name' => $item['name'],
     573                    'count' => $item['quantity'],
     574                    'price' => $item['price'],
     575                    'weight' => $shippingHelper->weightOption($item['weight']),
     576                    //Вес, в кг.
     577                    'dimensions' => $shippingHelper->dimensionsOption($item['width']) . '*' . $shippingHelper->dimensionsOption($item['length']) . '*' . $shippingHelper->dimensionsOption($item['height']),
     578                    //Габариты. Формат: строка вида «Д*Ш*В», в сантиметрах. Например: 15*25*10
     579                    'vat_rate' => 0,
     580                    //Значение ставки НДС Возможные варианты:0, 10, 20, -1 (без НДС)
     581                );
     582            }
     583        }
     584
     585        //if(isset($data['order']) && $data['order']){
     586        //foreach ($data['order'] as $key=>$value)
     587        //$defaultFields['order'][$key] = $value;
     588        //}
     589
     590        $exportFields = new ExportFileds();
     591        $exportFields = $exportFields->sendExportFields($data['delivery_id']);
     592        foreach ($exportFields as $key => $value) {
     593            if (isset($data[$key])) {
     594                //$defaultFields[$key] = $defaultFields[$key] + $data[$key];
     595                $defaultFields[$key] = array_merge_recursive($defaultFields[$key], $data[$key]);
     596            }
     597        }
     598
     599        if (isset($data['fulfillment'])) {
     600            $defaultFields['delivery']['variant'] = $data['delivery_id'];
     601        }
     602
     603        //FAKE
     604        //$defaultFields['fake'] = 1;
     605
     606        return $defaultFields;
     607    }
     608
     609    public function getPartAddressNameDoor($name)
     610    {
     611        if (!$name) {
     612            return '';
     613        }
     614
     615        $result = array(
     616            'region' => '',
     617            'city' => '',
     618            'street' => '',
     619            'house' => '',
     620            'room' => '',
     621        );
     622
     623        $partExplode = explode(',', $name);
     624
     625        if (isset($partExplode[0])) {
     626            $result['region'] = $partExplode[0];
     627        }
     628        if (isset($partExplode[1])) {
     629            $result['city'] = $partExplode[1];
     630        }
     631        if (isset($partExplode[2])) {
     632            $result['street'] = $partExplode[2];
     633        }
     634        if (isset($partExplode[3])) {
     635            $result['house'] = $partExplode[3];
     636        }
     637        if (isset($partExplode[4])) {
     638            $result['room'] = $partExplode[4];
     639        }
     640    }
     641
     642    public function getPartAddressNameTerminal($name)
     643    {
     644        if (!$name) {
     645            return '';
     646        }
     647
     648        $result = array(
     649            'terminal' => '',
     650        );
     651
     652        $partExplode = explode(',', $name);
     653
     654        foreach ($partExplode as $value) {
     655            if (str_contains($value, 'Код пункта')) {
     656                $codePart = explode('Код пункта:', $value);
     657                if (isset($codePart[1])) {
     658                    $result['terminal'] = trim($codePart[1]);
     659                }
     660                $result['terminal_address'] = trim($name);
     661            }
     662        }
     663
     664        return $result;
     665    }
     666
     667    public function infoOrder($id, $type, $action = 'get', $dataAdd = [])
     668    {
     669
     670        $optionsRepository = new OptionsRepository();
     671        $apiKey = $optionsRepository->getOption('wc_esl_shipping_api_key');
     672
     673        $order = wc_get_order($id);
     674        $orderData = $order->get_data();
     675        $orderShippingId = reset($orderData['shipping_lines']);
     676        $orderShippingId = $orderShippingId->get_id();
     677        $shippingMethod = wc_get_order_item_meta($orderShippingId, 'esl_shipping_methods', $single = true);
     678        if ($shippingMethod) {
     679            $shippingMethods = json_decode($shippingMethod, true);
     680            if (isset($shippingMethods['answer']['order']['id'])) {
     681                $id = $shippingMethods['answer']['order']['id'];
     682            }
     683        }
     684
     685        $data = array(
     686            'key' => $apiKey,
     687            'action' => $action,
     688            'order_id' => $id,
     689            'service' => $type,
     690        );
     691
     692        if($dataAdd){
     693            $data = array_merge($data, $dataAdd);
     694        }
     695
     696        $eshopLogisticApi = new EshopLogisticApi(new WpHttpClient());
     697        $result = $eshopLogisticApi->apiExportCreate($data);
     698        if ($result->hasErrors()) {
     699            return $result->jsonSerialize();
     700        }
     701
     702        return $result->data();
     703    }
     704
     705    public function getStatusWp()
     706    {
     707        return wc_get_order_statuses();
     708    }
     709
     710    public function updateStatusById($id, $order_id)
     711    {
     712        if (!isset($id['state']['number']) && !isset($id['state']['status']['code'])) {
     713            return false;
     714        }
     715
     716        $optionsRepository = new OptionsRepository();
     717        $settingsStatus = $optionsRepository->getOption('wc_esl_shipping_plugin_status_form');
     718
     719        $order = wc_get_order($order_id);
     720        $orderStatus = $order->get_status();
     721        $resultNameStatus = '';
     722
     723        if (isset($settingsStatus[$id['state']['status']['code']])) {
     724            $resultNameStatus = $settingsStatus[$id['state']['status']['code']][0]['name'];
     725        }
     726
     727
     728        if ($resultNameStatus) {
     729            if ($orderStatus == $resultNameStatus || 'wc-' . $orderStatus == $resultNameStatus) {
     730                return 'Статус не изменился';
     731            }
     732
     733            $result = $order->update_status($resultNameStatus);
     734            if ($result) {
     735                return 'Статус обновлен';
     736            }
     737        }
     738
     739        return 'Ошибка при обновлении';
     740
     741    }
    714742
    715743}
  • eshoplogisticru/trunk/globals.php

    r3150055 r3339535  
    371371    }
    372372}
     373
     374if ( ! function_exists( 'shortcode_widget_email_status_delivery' ) ) {
     375    function shortcode_widget_email_status_delivery( $atts, $content = null, $code = "" ) {
     376        if(!isset($atts['id']))
     377            return false;
     378
     379        $order = wc_get_order( $atts['id'] );
     380        if($order){
     381            $orderShippings = $order->get_shipping_methods();
     382            foreach ($orderShippings as $key=>$item){
     383                $shippingMethod = wc_get_order_item_meta( $item->get_id() , 'esl_shipping_methods', $single = true );
     384            }
     385            $shippingMethods = json_decode($shippingMethod, true);
     386            if(isset($shippingMethods['tracking']['status']['name'])){
     387                echo $shippingMethods['tracking']['status']['name'];
     388            }
     389        }
     390    }
     391}
  • eshoplogisticru/trunk/readme.txt

    r3315219 r3339535  
    33Tags: доставка, eshoplogisticru, woocommerce, цена доставки, срок доставки, стоимость доставки, сдэк, пэк, dostavista, picpoint, деловые линии, iml, boxberry, gtd, байкалсервис, сберлогистика, delivery, яндекс доставка
    44Tested up to: 6.71
    5 Stable tag: 2.1.59
     5Stable tag: 2.1.60
    66License: GPLv2
    77License URI: http://www.gnu.org/licenses/gpl-2.0.html
  • eshoplogisticru/trunk/views/settings.php

    r3276976 r3339535  
    748748                                            if ( isset( $add_form['cronStatusTime'] ) ) {
    749749                                                $cronStatusTime = $add_form['cronStatusTime'];
     750                                                if($cronStatusTime < 60)
     751                                                    $cronStatusTime = 60;
    750752                                            }
    751753                                            ?>
     
    755757                                                    name="cronStatusTime"
    756758                                                    class="col-sm-8 form-control"
     759                                                    min="60"
    757760                                                    value="<?php echo esc_attr( $cronStatusTime ) ?>"
    758761                                            />
  • eshoplogisticru/trunk/wc-eshop-logistic.php

    r3315219 r3339535  
    66 *
    77 * @link              https://wp.eshoplogistic.ru/
    8  * @since             2.1.59
     8 * @since             2.1.60
    99 * @package           WC_Eshop_Logistic
    1010 *
     
    1313 * Plugin URI:        https://wp.eshoplogistic.ru/
    1414 * Description:       Несколько служб доставки в одной интеграции: CDEK, DPD, Boxberry, IML, Почта России, Деловые Линии, ПЭК, Dostavista, GTD, Байкал Сервис и др.
    15  * Version:           2.1.59
     15 * Version:           2.1.60
    1616 * Author:            eShopLogistic
    1717 * Author URI:        https://eshoplogistic.ru/p747575
     
    4242define( 'WC_ESL_PLUGIN_DIR', plugin_dir_path(__FILE__) );
    4343
    44 define( 'WC_ESL_VERSION', '2.1.59' );
     44define( 'WC_ESL_VERSION', '2.1.60' );
    4545
    4646define( 'WC_ESL_DOMAIN', 'wc-esl' );
Note: See TracChangeset for help on using the changeset viewer.