Plugin Directory

Changeset 3210380


Ignore:
Timestamp:
12/19/2024 10:26:33 AM (13 months ago)
Author:
suhaimihz
Message:

v1.1.58

Location:
delyvax/trunk
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • delyvax/trunk/delyvax.php

    r3184993 r3210380  
    44    Plugin URI: https://delyva.com
    55    description: The official Delyva plugin helps store owners to integrate WooCommerce with [Delyva](https://delyva.com) for seamless service comparison and order processing.
    6     Version: 1.1.57
     6    Version: 1.1.58
    77    Author: Delyva
    88    Author URI: https://delyva.com
     
    1313    defined( 'ABSPATH' ) or die( 'No script kiddies please!' );
    1414    define('DELYVAX_API_ENDPOINT', 'https://api.delyva.app/');
    15     define('DELYVAX_PLUGIN_VERSION', '1.1.57');
     15    define('DELYVAX_PLUGIN_VERSION', '1.1.58');
    1616
    1717    require_once plugin_dir_path(__FILE__) . 'functions.php';
  • delyvax/trunk/functions.php

    r3184993 r3210380  
    218218function delyvax_set_pickup_delivery_time($order)
    219219{
    220     $settings = get_option( 'woocommerce_delyvax_settings' );
    221 
     220    $settings = get_option('woocommerce_delyvax_settings');
    222221    $processing_days = $settings['processing_days'];
    223222    $processing_hours = $settings['processing_hours'];
    224223    $processing_time = $settings['processing_time'];
    225224
    226     $gmtoffset = get_option('gmt_offset');
    227     $stimezone = get_option('timezone_string');
    228 
    229     $dtimezone = new DateTimeZone($stimezone);
    230 
    231     //initialise
    232     $pickup_date = new DateTime();
    233     $pickup_date->setTimezone($dtimezone);
    234 
    235     $pickup_time = new DateTime();
    236     // $pickup_time->setTimezone($dtimezone);
    237 
    238     $delivery_date = new DateTime();
    239     $delivery_date->setTimezone($dtimezone);
    240 
    241     $delivery_time = new DateTime();
    242     $delivery_time->setTimezone($dtimezone);
    243 
    244     $dx_delivery_date = null;
    245     $dx_delivery_time = null;
    246     $dx_delivery_date_format = null;
    247 
    248     $dx_pickup_date = null;
    249     $dx_pickup_time = null;
    250     $dx_pickup_date_format = null;
    251 
    252     $delivery_type = null;
    253     //
     225    // Fetch WordPress timezone setting
     226    $timezone_string = get_option('timezone_string') ?: 'UTC';
     227    $wp_timezone = new DateTimeZone($timezone_string);
    254228
    255229    try {
    256         //pickup / delivery
    257         $delivery_type = $order->get_meta( 'delivery_type');
    258         //if = pickup, take dx_delivery_date from pickup_date //WooDelivery
    259 
    260         //set delivery_date
    261         if($order->get_meta( 'dx_delivery_date' ) != null)
    262         {
    263             $dx_delivery_date = $order->get_meta( 'dx_delivery_date' );
    264 
    265             $delivery_date = new DateTime( '@'.(int)$order->get_meta( 'dx_delivery_date' ));
    266             $delivery_date->setTimezone($dtimezone);
    267             $dx_delivery_date_format = $delivery_date->format('d-M-Y');
    268         }else if($order->get_meta( 'delivery_date' ) != null)
    269         {
    270             $delivery_date = new DateTime($order->get_meta( 'delivery_date' ));
    271             $delivery_date->setTimezone($dtimezone);
    272 
    273             $dx_delivery_date = $delivery_date->getTimestamp();
    274 
    275             $dx_delivery_date_format = $delivery_date->format('d-M-Y');
    276         }else if($processing_days > 0)
    277         {
    278             $delivery_date->modify('+'.$processing_days.' day');
    279 
    280             $dx_delivery_date = $delivery_date->getTimestamp();
    281 
    282             $dx_delivery_date_format = $delivery_date->format('d-M-Y');
    283         }else {
    284             // $delivery_date->modify('+0 day');
    285 
    286             $dx_delivery_date = $delivery_date->getTimestamp();
    287 
    288             $dx_delivery_date_format = $delivery_date->format('d-M-Y');
    289         }
    290 
    291         //set delivery time
    292         if($order->get_meta( 'dx_delivery_time' ) != null)
    293         {
    294             $dx_delivery_time = $order->get_meta( 'dx_delivery_time' );
    295 
    296         }else if($order->get_meta( 'delivery_time' ) != null)
    297         {
    298             $w_delivery_time = $order->get_meta( 'delivery_time'); //1440 minutes / 24
    299             $a_delivery_time = explode(",",$w_delivery_time);
    300 
    301             $timeslot_from_hour = 0;
    302             $timeslot_from_min = 0;
    303 
    304             if(sizeof($a_delivery_time) > 0)
    305             {
    306                 $timeslot_from = $a_delivery_time[0]/60; //e.g. 675/60 = 11.25 =  11.15am
    307 
    308                 $timeslot_from_hour = floor($timeslot_from);
    309                 $timeslot_from_min = fmod($timeslot_from, 1) * 60;
    310             }else {
    311                 //set current time add 1 hour
    312                 $delivery_time->add(new DateInterval("PT5M"));
    313 
    314                 $timeslot_from_hour = $delivery_time->format('H');
    315                 $timeslot_from_min = $delivery_time->format('i');
    316             }
    317 
    318             $delivery_time = $delivery_date;
    319             $delivery_time->setTime($timeslot_from_hour,$timeslot_from_min,00);
    320 
    321             $dx_delivery_time = $delivery_time->format('H:i');
    322         }else if($processing_days > 0 && $processing_time != '')
    323         {
    324             $processing_time = str_replace(":00","",$processing_time);
    325 
    326             $delivery_time = $delivery_date;
    327             $delivery_time->setTime($processing_time,00,00);
    328 
    329             $dx_delivery_time = $delivery_time->format('H:i');
    330         }else if($processing_days > 0 && $processing_time == '')
    331         {
    332             $delivery_time = $delivery_date;
    333             $delivery_time->setTime('11',00,00);
    334 
    335             $dx_delivery_time = $delivery_time->format('H:i');
    336         }else if($processing_days == 0 && $processing_hours > 0)
    337         {
    338             $delivery_time->add(new DateInterval("PT".$processing_hours."H"));
    339 
    340             $dx_delivery_time = $delivery_time->format('H:i');
    341         }else {
    342             $delivery_time->add(new DateInterval("PT5M"));
    343 
    344             $dx_delivery_time = $delivery_time->format('H:i');
    345         }
    346 
    347         //set pick up date
    348         if($order->get_meta( 'dx_pickup_date' ) != null)
    349         {
    350             $dx_pickup_date = $order->get_meta( 'dx_pickup_date' );
    351 
    352             $pickup_date = new DateTime( '@'.(int)$order->get_meta( 'dx_pickup_date' ));
    353             $pickup_date->setTimezone($dtimezone);
    354             $dx_pickup_date_format = $pickup_date->format('d-M-Y');
    355         }else if($order->get_meta( 'pickup_date' ) != null)
    356         {
    357             $pickup_date = new DateTime( $order->get_meta( 'pickup_date' ));
    358             $pickup_date->setTimezone($dtimezone);
    359 
    360             $dx_pickup_date = $pickup_date->getTimestamp();
    361 
    362             $dx_pickup_date_format = $pickup_date->format('d-M-Y');
    363         }else if($processing_days > 0)
    364         {
    365             $pickup_date = $delivery_date;
    366             $dx_pickup_date = $pickup_date->getTimestamp();
    367 
    368             $dx_pickup_date_format = $pickup_date->format('d-M-Y');
    369         }else {
    370             $dx_pickup_date = $dx_delivery_date;
    371 
    372             $dx_pickup_date_format = $dx_delivery_date_format;
    373         }
    374     } catch(Exception $e) {
    375           echo 'Message: ' .$e->getMessage();
    376 
    377           $dx_delivery_date = $delivery_date->getTimestamp();
    378           $dx_delivery_time = $delivery_time->format('H:i');
    379           $dx_delivery_date_format = $delivery_date->format('d-M-Y');
    380 
    381           $dx_pickup_date = $dx_delivery_date;
    382           $dx_pickup_time = $dx_delivery_time;
    383           $dx_pickup_date_format = $dx_delivery_date_format;
    384     }
    385 
    386     $order->update_meta_data( 'dx_delivery_date', $dx_delivery_date );
    387     $order->update_meta_data( 'dx_delivery_time', $dx_delivery_time );
    388     $order->update_meta_data( 'dx_delivery_date_format', $dx_delivery_date_format );
    389 
    390     $order->update_meta_data( 'dx_pickup_date', $dx_pickup_date );
    391     $order->update_meta_data( 'dx_pickup_time', $dx_pickup_time );
    392     $order->update_meta_data( 'dx_pickup_date_format', $dx_pickup_date_format );
    393 
    394     $order->save();
    395 }
    396 
     230        $delivery_date = new DateTime('now', $wp_timezone);
     231
     232        // Processing days
     233        if ($processing_days > 0) {
     234            $delivery_date->modify("+{$processing_days} day");
     235        }
     236
     237        // Processing hours if no days
     238        if ($processing_days == 0 && $processing_hours > 0) {
     239            $delivery_date->add(new DateInterval("PT{$processing_hours}H"));
     240        }
     241
     242        // Set delivery time
     243        if (!empty($processing_time)) {
     244            [$hours, $minutes] = explode(':', $processing_time);
     245            $delivery_date->setTime($hours, $minutes, 0);
     246        }
     247
     248        $order->update_meta_data('dx_delivery_datetime', $delivery_date->format('Y-m-d H:i:s'));
     249        $order->save();
     250
     251    } catch (Exception $e) {
     252        echo 'Message: ' . $e->getMessage();
     253        $now = new DateTime();
     254        $order->update_meta_data('dx_delivery_datetime', $now->format('Y-m-d H:i:s'));
     255        $order->save();
     256    }
     257}
    397258
    398259function delyvax_create_order($order, $user, $process=false) {
     
    417278        if(!$DelyvaXTrackingCode)
    418279        {
    419             $resultCreate = delyvax_post_create_order($order, $user, $process);
     280            $resultCreate = delyvax_post_create_order($order, $process);
    420281        }
    421282    } catch (Exception $e) {
     
    424285}
    425286
    426 //rewire logic here, API is only for post
    427 function delyvax_post_create_order($order, $user, $process=false) {
    428       $settings = get_option( 'woocommerce_delyvax_settings' );
    429 
    430       $company_id = $settings['company_id'];
    431       $company_code = $settings['company_code'];
    432       $user_id = $settings['user_id'];
    433       $customer_id = $settings['customer_id'];
    434       $api_token = $settings['api_token'];
    435       $processing_days = $settings['processing_days'];
    436       $processing_hours = $settings['processing_hours'];
    437       $item_type = ($settings['item_type']) ? $settings['item_type'] : "PARCEL" ;
    438 
    439       $include_order_note = $settings['include_order_note'];
    440 
    441       $multivendor_option = $settings['multivendor'];
    442 
    443       $insurance_premium = $settings['insurance_premium'] ?? '';
    444 
    445       //----delivery date & time (pull from meta data), if not available, set to +next day 8am.
    446       $gmtoffset = get_option('gmt_offset');
    447 
    448       $stimezone = get_option('timezone_string');
    449 
    450       $dtimezone = new DateTimeZone($stimezone);
    451 
    452       $timeslot_hour = 0;
    453       $timeslot_min = 0;
    454 
    455       $delivery_date = new DateTime();
    456       $delivery_date->setTimezone($dtimezone);
    457 
    458       $delivery_time = new DateTime();
    459       $delivery_time->setTimezone($dtimezone);
    460 
    461       $delivery_type = 'delivery';
    462 
    463       if($order->get_meta( 'delivery_type' ) != null)
    464       {
    465           $delivery_type = $order->get_meta( 'delivery_type'); //pickup / delivery
    466       }
    467 
    468       $delivery_date = new DateTime('@'.(int)$order->get_meta( 'dx_delivery_date' ));
    469       $delivery_date->setTimezone($dtimezone);
    470 
    471       $dx_delivery_time = $order->get_meta( 'dx_delivery_time' );
    472       $split_dx_delivery_time = explode( ":", $dx_delivery_time );
    473       $delivery_time->setTime($split_dx_delivery_time[0],$split_dx_delivery_time[1],00);
    474 
    475       $timeslot_hour = $delivery_time->format('H');
    476       $timeslot_min = $delivery_time->format('i');
    477 
    478       $scheduledAt = $delivery_date;
    479       $scheduledAt->setTime($timeslot_hour,$timeslot_min,00);
    480 
    481       //service     
    482       $serviceCode = "";
    483 
    484       $main_order = $order;
    485 
    486       if($order->parent_id)
    487       {
    488           $main_order = wc_get_order($order->parent_id);
    489       }
    490 
    491       // Iterating through order shipping items
    492       $DelyvaXServiceCode = $main_order->get_meta( 'DelyvaXServiceCode');
    493 
    494       if($DelyvaXServiceCode)
    495       {
    496             $serviceCode = $DelyvaXServiceCode;
    497       }else {
    498             foreach( $main_order->get_items( 'shipping' ) as $item_id => $shipping_item_obj )
    499             {
    500                 $serviceobject = $shipping_item_obj->get_meta_data();
    501    
    502                 for($i=0; $i < sizeof($serviceobject); $i++)
    503                 {
    504                     if($serviceobject[$i]->key == "service_code")
    505                     {
    506                         $serviceCode = $serviceobject[0]->value;
    507                        
    508                         $main_order->update_meta_data( 'DelyvaXServiceCode', $serviceCode );
    509                         $main_order->save();
     287/**
     288 * Optimize box dimensions based on total volume and maximum item dimensions for multiple items
     289 */
     290function optimize_box_dimensions($total_volume, $max_length, $max_width, $max_height) {
     291    // Ensure box is at least as large as the biggest item
     292    $box_length = $max_length;
     293    $box_width = $max_width;
     294    $box_height = $max_height;
     295   
     296    // Adjust dimensions to accommodate total volume while maintaining proportions
     297    $current_volume = $box_length * $box_width * $box_height;
     298    if ($current_volume < $total_volume) {
     299        $scale_factor = pow($total_volume / $current_volume, 1/3);
     300        $box_length *= $scale_factor;
     301        $box_width *= $scale_factor;
     302        $box_height *= $scale_factor;
     303    }
     304   
     305    return [
     306        'length' => ceil($box_length),
     307        'width' => ceil($box_width),
     308        'height' => ceil($box_height),
     309        'volume' => ceil($box_length * $box_width * $box_height)
     310    ];
     311}
     312
     313function process_delivery_pricing($main_order, $deliveryPrice, $total_quantity, $total_price)
     314{
     315    $settings = get_option('woocommerce_delyvax_settings');
     316    $deliveryMarkup = 0;
     317    $deliveryDiscount = 0;
     318
     319    //store price discount or markup
     320    if ($deliveryPrice && $deliveryPrice > 0) {
     321        $rate_adjustment_type = $settings['rate_adjustment_type'] ?? 'discount';
     322
     323        $ra_percentage = $settings['rate_adjustment_percentage'] ?? 1;
     324        $percentRate = $ra_percentage / 100 * $deliveryPrice;
     325
     326        $flatRate = $settings['rate_adjustment_flat'] ?? 0;
     327
     328        if ($rate_adjustment_type == 'markup') {
     329            $deliveryMarkup = round($percentRate + $flatRate, 2);
     330        } else {
     331            $deliveryDiscount = round($percentRate + $flatRate, 2);
     332        }
     333
     334        //handle free shipping
     335        $free_shipping_type = $settings['free_shipping_type'] ?? '';
     336        $free_shipping_condition = $settings['free_shipping_condition'] ?? '';
     337        $free_shipping_value = $settings['free_shipping_value'] ?? '0';
     338
     339        if ($free_shipping_type == 'total_quantity') {
     340            if ($free_shipping_condition == '>') {
     341                if ($total_quantity > $free_shipping_value) {
     342                    $deliveryDiscount = $deliveryPrice;
     343                }
     344            } else if ($free_shipping_condition == '>=') {
     345                if ($total_quantity >= $free_shipping_value) {
     346                    $deliveryDiscount = $deliveryPrice;
     347                }
     348            } else if ($free_shipping_condition == '==') {
     349                if ($total_quantity == $free_shipping_value) {
     350                    $deliveryDiscount = $deliveryPrice;
     351                }
     352            } else if ($free_shipping_condition == '<=') {
     353                if ($total_quantity <= $free_shipping_value) {
     354                    $deliveryDiscount = $deliveryPrice;
     355                }
     356            } else if ($free_shipping_condition == '<') {
     357                if ($total_quantity < $free_shipping_value) {
     358                    $deliveryDiscount = $deliveryPrice;
     359                }
     360            }
     361        } else if ($free_shipping_type == 'total_amount') {
     362            if ($free_shipping_condition == '>') {
     363                if ($total_price > $free_shipping_value) {
     364                    $deliveryDiscount = $deliveryPrice;
     365                }
     366            } else if ($free_shipping_condition == '>=') {
     367                if ($total_price >= $free_shipping_value) {
     368                    $deliveryDiscount = $deliveryPrice;
     369                }
     370            } else if ($free_shipping_condition == '==') {
     371                if ($total_price == $free_shipping_value) {
     372                    $deliveryDiscount = $deliveryPrice;
     373                }
     374            } else if ($free_shipping_condition == '<=') {
     375                if ($total_price <= $free_shipping_value) {
     376                    $deliveryDiscount = $deliveryPrice;
     377                }
     378            } else if ($free_shipping_condition == '<') {
     379                if ($total_price < $free_shipping_value) {
     380                    $deliveryDiscount = $deliveryPrice;
     381                }
     382            }
     383        }
     384    }
     385
     386    return array(
     387        'deliveryMarkup' => $deliveryMarkup,
     388        'deliveryDiscount' => $deliveryDiscount
     389    );
     390}
     391
     392function get_product_dimensions($product) {
     393    return array(
     394        'weight' => delyvax_default_weight(delyvaX_weight_to_kg($product->get_weight())),
     395        'length' => delyvax_default_dimension(delyvax_dimension_to_cm($product->get_length())),
     396        'width' => delyvax_default_dimension(delyvax_dimension_to_cm($product->get_width())),
     397        'height' => delyvax_default_dimension(delyvax_dimension_to_cm($product->get_height()))
     398    );
     399}
     400
     401function get_receiver_address($order) {
     402    $r_shipping_phone = $order->get_shipping_phone();
     403   
     404    if ($order->get_shipping_address_1() || $order->get_shipping_address_2()) {
     405        return [
     406            'contactName' => $order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name(),
     407            'contactEmail' => $order->get_billing_email(),
     408            'contactNumber' => $r_shipping_phone ?: $order->get_billing_phone(),
     409            'location' => [
     410                'address' => $order->get_shipping_address_1(),
     411                'address2' => $order->get_shipping_address_2(),
     412                'city' => $order->get_shipping_city(),
     413                'state' => $order->get_shipping_state(),
     414                'country' => $order->get_shipping_country(),
     415                'postcode' => $order->get_shipping_postcode(),
     416            ]
     417        ];
     418    }
     419   
     420    return [
     421        'contactName' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
     422        'contactEmail' => $order->get_billing_email(),
     423        'contactNumber' => $order->get_billing_phone(),
     424        'location' => [
     425            "address" => $order->get_billing_address_1(),
     426            "address2" => $order->get_billing_address_2(),
     427            "city" => $order->get_billing_city(),
     428            "state" => $order->get_billing_state(),
     429            "postcode" => $order->get_billing_postcode(),
     430            "country" => $order->get_billing_country(),
     431        ]
     432    ];
     433}
     434
     435function delyvax_post_create_order($order, $process = false)
     436{
     437    if (!$order) return false;
     438    $settings = get_option('woocommerce_delyvax_settings');
     439    $multivendor_option = $settings['multivendor'];
     440    $customer_id = $settings['customer_id'];
     441    $company_id = $settings['company_id'];
     442    $company_code = $settings['company_code'];
     443
     444    $DelyvaXOrderID = $order->get_meta('DelyvaXOrderID');
     445    $store_name = get_bloginfo('name');
     446
     447    $delivery_datetime = $order->get_meta('dx_delivery_datetime');
     448    $wp_timezone = new DateTimeZone(get_option('timezone_string') ?: 'UTC');
     449
     450    if ($delivery_datetime) {
     451        $scheduledAt = DateTime::createFromFormat('Y-m-d H:i:s', $delivery_datetime, $wp_timezone);
     452        $scheduledAt->setTimezone($wp_timezone);
     453    } else {
     454        $scheduledAt = new DateTime('now', $wp_timezone);
     455    }
     456
     457    $main_order = $order;
     458
     459    // Don't create shipment for parent order
     460    if ($multivendor_option == 'DOKAN') {
     461        $has_sub_order = $order->get_meta('has_sub_order');
     462        if ($has_sub_order == '1') return;
     463    } else if ($order->get_parent_id()) {
     464        $main_order = wc_get_order($order->get_parent_id());
     465    }
     466
     467    // Iterating through order shipping items
     468    $DelyvaXServiceCode = $main_order->get_meta('DelyvaXServiceCode');
     469    $include_order_note = $settings['include_order_note'] ?? '';
     470    $insurance_premium = $settings['insurance_premium'] ?? '';
     471    $total_weight = 0;
     472    $total_volume = 0;
     473    $max_length = 0;
     474    $max_width = 0;
     475    $max_height = 0;
     476    $order_notes = '';
     477    $product_id = null;
     478
     479    if ($DelyvaXServiceCode) {
     480        $serviceCode = $DelyvaXServiceCode;
     481    } else {
     482        foreach ($main_order->get_items('shipping') as $item_id => $shipping_item_obj) {
     483            $serviceobject = $shipping_item_obj->get_meta_data();
     484
     485            for ($i = 0; $i < sizeof($serviceobject); $i++) {
     486                if ($serviceobject[$i]->key == "service_code") {
     487                    $serviceCode = $serviceobject[0]->value;
     488
     489                    $main_order->update_meta_data('DelyvaXServiceCode', $serviceCode);
     490                    $main_order->save();
     491                }
     492            }
     493        }
     494    }
     495
     496    $count = 0;
     497    $total_quantity = 0;
     498    $total_price = 0;
     499    $inventories = [];
     500
     501    foreach ($main_order->get_items() as $item) {
     502        $product_id = $item->get_product_id();
     503        $product_variation_id = $item->get_variation_id();
     504        $product = $item->get_product();
     505        $product_name = $item->get_name();
     506        $quantity = $item->get_quantity();
     507        $subtotal = $item->get_subtotal();
     508        $total = $item->get_total();
     509        $tax = $item->get_subtotal_tax();
     510        $taxclass = $item->get_tax_class();
     511        $taxstat = $item->get_tax_status();
     512        $allmeta = $item->get_meta_data();
     513        // $somemeta = $item->get_meta( '_whatever', true );
     514        $type = $item->get_type();
     515
     516        //get seller info
     517        $product_store_name = get_bloginfo('name');
     518
     519        $_pf = new WC_Product_Factory();
     520
     521        $product = $_pf->get_product($product_id);
     522       
     523        $weightDimension = [
     524            'weight' => 0,
     525            'length' => 0,
     526            'width' => 0,
     527            'height' => 0,
     528        ];
     529
     530        if ($product->is_type('variable')) {
     531            $variation = $_pf->get_product($product_variation_id);
     532
     533            if ($variation) {
     534                $product_name = $variation->get_name();
     535                $weightDimension = get_product_dimensions($variation);
     536            }
     537        } else {
     538            $weightDimension = get_product_dimensions($product);
     539        }
     540
     541        $product_weight = $weightDimension['weight'];
     542        $product_length = $weightDimension['length'];
     543        $product_width = $weightDimension['width'];
     544        $product_height = $weightDimension['height'];
     545
     546        // Calculate volume for this product considering quantity
     547        $item_volume = $product_length * $product_width * $product_height * $quantity;
     548        $total_volume += $item_volume;
     549
     550        // Track maximum dimensions
     551        $max_length = max($max_length, $product_length);
     552        $max_width = max($max_width, $product_width);
     553        $max_height = max($max_height, $product_height);
     554
     555        $product_description = '[' . $product_store_name . '] ' . $product_name . ' - Order ID #' . $main_order->get_id();
     556
     557        $inventories[] = [
     558            "name" => $product_name,
     559            "value" => array(
     560                "amount" => $total,
     561                "currency" => $main_order->get_currency(),
     562            ),
     563            "weight" => array(
     564                "value" => $product_weight,
     565                "unit" => 'kg'
     566            ),
     567            "quantity" => $quantity,
     568            "description" => $product_description
     569        ];
     570
     571        $total_weight = $total_weight + ($product_weight * $quantity);
     572        $total_price = $total_price + $subtotal;
     573        $total_quantity = $total_quantity + $quantity;
     574
     575        if ($include_order_note == 'ordernproduct') {
     576            $order_notes = $order_notes . '#' . ($count + 1) . '. [' . $store_name . '] ' . $product_name . ' X ' . $quantity . 'pcs. ';
     577        }
     578        $count++;
     579    }
     580
     581    if ($DelyvaXOrderID && $process == true) {
     582        $resultProcess = delyvax_post_process_order($order, $DelyvaXOrderID);
     583
     584        $trackingNo = $resultProcess["consignmentNo"];
     585        $nanoId = $resultProcess["nanoId"];
     586
     587        $main_order->update_meta_data('DelyvaXTrackingCode', $trackingNo);
     588        $main_order->update_meta_data('DelyvaXTrackingShort', $nanoId);
     589
     590        $main_order->update_status('wc-ready-to-collect', 'Delivery order number: ' . $trackingNo . ' - <a href="https://api.delyva.app/v1.0/order/' . $DelyvaXOrderID . '/label?companyId=' . $company_id . '" target="_blank">Print label</a> - <a href="https://' . $company_code . '.delyva.app/customer/strack?trackingNo=' . $trackingNo . '" target="_blank">Track</a>.', false);
     591
     592        $pricing = process_delivery_pricing($main_order, $resultProcess['price']['amount'], $total_quantity, $total_price);
     593
     594        $main_order->update_meta_data('DelyvaXDeliveryPrice', $resultProcess['price']['amount']);
     595        $main_order->update_meta_data('DelyvaXMarkup', $pricing['deliveryMarkup']);
     596        $main_order->update_meta_data('DelyvaXDiscount', $pricing['deliveryDiscount']);
     597        $main_order->save();
     598    } else {
     599        $main_order = $order;
     600        $store_raw_country = get_option('woocommerce_default_country');
     601
     602        // Split the country/state
     603        $split_country = explode(":", $store_raw_country);
     604
     605        // Country and state separated:
     606        $store_country = $split_country[0];
     607        $store_state = $split_country[1];
     608
     609        if ($include_order_note != 'empty')
     610            $order_notes = 'Order No: #' . $main_order->get_id() . ': ';
     611
     612        $box_dimensions = optimize_box_dimensions($total_volume, $max_length, $max_width, $max_height);
     613
     614        $receiver = get_receiver_address($order);
     615        $sender = [
     616            'contactName' => $settings['shop_name'],
     617            'contactEmail' => $settings['shop_email'],
     618            'contactNumber' => $settings['shop_mobile'],
     619            'location' => [
     620                'address' => get_option('woocommerce_store_address'),
     621                'address2' => get_option('woocommerce_store_address_2'),
     622                'city' => get_option('woocommerce_store_city'),
     623                'state' => $store_state,
     624                'country' => $store_country,
     625                'postcode' => get_option('woocommerce_store_postcode'),
     626            ]
     627        ];
     628
     629        if ($multivendor_option == 'DOKAN') {
     630            if (function_exists('dokan_get_seller_id_by_order') && function_exists('dokan_get_store_info')) {
     631                $seller_id = dokan_get_seller_id_by_order($main_order->get_id());
     632                $store_info = dokan_get_store_info($seller_id);
     633                $user_info = get_userdata($seller_id);
     634                $store_info['email'] = $user_info->user_email;
     635
     636                $product_store_name = $store_info['store_name'];
     637
     638                if ($store_info['store_name'])
     639                    $sender['contactName'] = $store_info['store_name'];
     640                // if ($store_info['first_name'])
     641                //     $store_first_name = $store_info['first_name'];
     642                // if ($store_info['last_name'])
     643                //     $store_last_name = $store_info['last_name'];
     644                if ($store_info['phone'])
     645                    $sender['contactNumber'] = $store_info['phone'];
     646                if ($store_info['email'])
     647                    $sender['contactEmail'] = $store_info['email'];
     648                $sender['location']['address'] = $store_info['address']['street_1'];
     649                $sender['location']['address2'] = $store_info['address']['street_2'];
     650                $sender['location']['city'] = $store_info['address']['city'];
     651                $sender['location']['state'] = $store_info['address']['state'];
     652                $sender['location']['postcode'] = $store_info['address']['zip'];
     653                $sender['location']['country'] = $store_info['address']['country'];
     654
     655                $origin_lat = isset($store_info['address']['lat']) ? $store_info['address']['lat'] : null;
     656                $origin_lon = isset($store_info['address']['lon']) ? $store_info['address']['lon'] : null;
     657
     658                if ($origin_lat && $origin_lon) {
     659                    $sender['location']['coordinates'] = [
     660                        'lat' => $origin_lat,
     661                        'lom' => $origin_lon,
     662                    ];
     663                }
     664            }
     665        } else if ($multivendor_option == 'WCFM') {
     666            if (function_exists('wcfm_get_vendor_id_by_post')) {
     667                $vendor_id = $order->get_meta('_vendor_id');
     668                if (!$vendor_id && function_exists('wcfm_get_vendor_id_by_post')) {
     669                    $vendor_id = wcfm_get_vendor_id_by_post($product_id);
     670                }           
     671
     672                $store_info = get_user_meta($vendor_id, 'wcfmmp_profile_settings', true);
     673
     674                if ($store_info) {
     675                    $sender['contactName'] = $store_name = $store_info['store_name'];
     676                    // $store_first_name = $store_info['store_name'];
     677                    // $store_last_name = $store_info['store_name'];
     678                    $sender['contactNumber'] = $store_info['phone'];
     679                    $sender['contactEmail'] = $store_info['store_email'] ? $store_info['store_email'] : $store_info['customer_support']['email'];
     680                    $sender['location']['address'] = isset($store_info['address']['street_1']) ? $store_info['address']['street_1'] : '';
     681                    $sender['location']['address2'] = isset($store_info['address']['street_2']) ? $store_info['address']['street_2'] : '';
     682                    $sender['location']['city'] = isset($store_info['address']['city']) ? $store_info['address']['city'] : '';
     683                    $sender['location']['state'] = isset($store_info['address']['state']) ? $store_info['address']['state'] : '';
     684                    $sender['location']['postcode'] = isset($store_info['address']['zip']) ? $store_info['address']['zip'] : '';
     685                    $sender['location']['country'] = isset($store_info['address']['country']) ? $store_info['address']['country'] : '';
     686
     687                    $origin_lat = isset($store_info['address']['lat']) ? $store_info['address']['lat'] : null;
     688                    $origin_lon = isset($store_info['address']['lon']) ? $store_info['address']['lon'] : null;
     689
     690                    if ($origin_lat && $origin_lon) {
     691                        $sender['location']['coordinates'] = [
     692                            'lat' => $origin_lat,
     693                            'lom' => $origin_lon,
     694                        ];
    510695                    }
    511696                }
    512697            }
    513       }         
    514 
    515       //inventory / items
    516       $count = 0;
    517       $inventories = array();
    518       $total_weight = 0;
    519       $total_dimension = 0;
    520       $total_price = 0;
    521       $order_notes = '';
    522       $total_quantity = 0;
    523 
    524       $store_name = get_bloginfo( 'name' );
    525       $store_phone = null;
    526       $store_email = null;
    527       $store_address_1 = null;
    528       $store_address_2 = null;
    529       $store_city = null;
    530       $store_postcode = null;
    531       $store_country = null;
    532       $store_country = null;
    533 
    534       $product_id = null;
    535 
    536       //store info
    537       $store_name = $settings['shop_name'];
    538       $store_email = $settings['shop_email'];
    539       $store_phone = $settings['shop_mobile'];
    540 
    541       $store_address_1 = get_option( 'woocommerce_store_address');
    542       $store_address_2 = get_option( 'woocommerce_store_address_2');
    543       $store_city = get_option( 'woocommerce_store_city');
    544       $store_postcode = get_option( 'woocommerce_store_postcode');
    545 
    546       $origin_lat = null;
    547       $origin_lon = null;
    548 
    549       // The country/state
    550       if($store_country == null)
    551       {
    552           $store_raw_country = get_option( 'woocommerce_default_country');
    553 
    554           // Split the country/state
    555           $split_country = explode( ":", $store_raw_country );
    556 
    557           // Country and state separated:
    558           $store_country = $split_country[0];
    559           $store_state   = $split_country[1];
    560       }
    561 
    562       $main_order = $order;
    563 
    564       if($include_order_note != 'empty') $order_notes = 'Order No: #'.$main_order->get_id().': ';
    565 
    566       $product_store_name = get_bloginfo( 'name' );
    567 
    568       foreach ( $main_order->get_items() as $item )
    569       {
    570           $product_id = $item->get_product_id();
    571       }
    572 
    573       if($multivendor_option == 'DOKAN')
    574       {
    575           if(function_exists('dokan_get_seller_id_by_order') && function_exists('dokan_get_store_info'))
    576           {
    577               $seller_id = dokan_get_seller_id_by_order($main_order->get_id());
    578               $store_info = dokan_get_store_info( $seller_id );
    579                   $user_info = get_userdata($seller_id);
    580                   $store_info['email'] = $user_info->user_email;
    581 
    582               $product_store_name = $store_info['store_name'];
    583 
    584               if($store_info['store_name']) $store_name = $store_info['store_name'];
    585               if($store_info['first_name']) $store_first_name = $store_info['first_name'];
    586               if($store_info['last_name']) $store_last_name = $store_info['last_name'];
    587               if($store_info['phone']) $store_phone = $store_info['phone'];
    588               if($store_info['email']) $store_email = $store_info['email'];
    589               $store_address_1 = $store_info['address']['street_1'];
    590               $store_address_2 = $store_info['address']['street_2'];
    591               $store_city = $store_info['address']['city'];
    592               $store_state = $store_info['address']['state'];
    593               $store_postcode = $store_info['address']['zip'];
    594               $store_country = $store_info['address']['country'];
    595 
    596               $origin_lat = isset($store_info['address']['lat']) ? $store_info['address']['lat'] : null;
    597               $origin_lon = isset($store_info['address']['lon']) ? $store_info['address']['lon'] : null;
    598           }
    599       }else if($multivendor_option == 'WCFM')
    600       {
    601           if(function_exists('wcfm_get_vendor_id_by_post'))
    602           {
    603               $vendor_id = wcfm_get_vendor_id_by_post( $product_id );
    604 
    605               $store_info = get_user_meta( $vendor_id, 'wcfmmp_profile_settings', true );
    606 
    607               if($store_info)
    608               {
    609                   $product_store_name = $store_name = $store_info['store_name'];
    610                   $store_first_name = $store_info['store_name'];
    611                   $store_last_name = $store_info['store_name'];
    612                   $store_phone = $store_info['phone'];
    613                   $store_email = $store_info['store_email'] ? $store_info['store_email'] : $store_info['customer_support']['email'];
    614                   $store_address_1 = isset( $store_info['address']['street_1'] ) ? $store_info['address']['street_1'] : '';
    615                   $store_address_2 = isset( $store_info['address']['street_2'] ) ? $store_info['address']['street_2'] : '';
    616                   $store_city     = isset( $store_info['address']['city'] ) ? $store_info['address']['city'] : '';
    617                   $store_state    = isset( $store_info['address']['state'] ) ? $store_info['address']['state'] : '';
    618                   $store_postcode      = isset( $store_info['address']['zip'] ) ? $store_info['address']['zip'] : '';
    619                   $store_country  = isset( $store_info['address']['country'] ) ? $store_info['address']['country'] : '';
    620 
    621                   $origin_lat = isset($store_info['address']['lat']) ? $store_info['address']['lat'] : null;
    622                   $origin_lon = isset($store_info['address']['lon']) ? $store_info['address']['lon'] : null;
    623               }
    624           }
    625         }else if($multivendor_option == 'MKING')
    626         {
    627             $vendor_id = marketking()->get_product_vendor( $product_id );
     698        } else if ($multivendor_option == 'MKING') {
     699            $vendor_id = marketking()->get_product_vendor($product_id);
    628700
    629701            // $company = get_user_meta($vendor_id, 'billing_company', true);     
    630             $store_name = marketking()->get_store_name_display($vendor_id);             
     702            $sender['contactName'] = marketking()->get_store_name_display($vendor_id);
    631703            // $store_name = get_user_meta($vendor_id, 'marketking_store_name', true);
    632             $store_first_name = get_user_meta($vendor_id, 'billing_first_name', true);
    633             $store_last_name = get_user_meta($vendor_id, 'billing_last_name', true);
    634             $store_phone = get_user_meta($vendor_id, 'billing_phone', true);
    635             $store_email = marketking()->get_vendor_email($vendor_id);
     704            // $store_first_name = get_user_meta($vendor_id, 'billing_first_name', true);
     705            // $store_last_name = get_user_meta($vendor_id, 'billing_last_name', true);
     706            $sender['contactNumber'] = get_user_meta($vendor_id, 'billing_phone', true);
     707            $sender['contactEmail'] = marketking()->get_vendor_email($vendor_id);
    636708            // $store_email = get_user_meta($vendor_id, 'billing_email', true);
    637709
    638             $store_address_1 = get_user_meta($vendor_id, 'billing_address_1', true);
    639             $store_address_2 = get_user_meta($vendor_id, 'billing_address_2', true);
    640             $store_city = get_user_meta($vendor_id, 'billing_city', true);
    641             $store_state = get_user_meta($vendor_id, 'billing_postcode', true);
    642             $store_postcode = get_user_meta($vendor_id, 'billing_state', true);
    643             $store_country = get_user_meta($vendor_id, 'billing_country', true);
    644            
     710            $sender['location']['address'] = get_user_meta($vendor_id, 'billing_address_1', true);
     711            $sender['location']['address2'] = get_user_meta($vendor_id, 'billing_address_2', true);
     712            $sender['location']['city'] = get_user_meta($vendor_id, 'billing_city', true);
     713            $sender['location']['state'] = get_user_meta($vendor_id, 'billing_postcode', true);
     714            $sender['location']['postcode'] = get_user_meta($vendor_id, 'billing_state', true);
     715            $sender['location']['country'] = get_user_meta($vendor_id, 'billing_country', true);
     716
    645717            // $origin_lat = isset($store_info['address']['lat']) ? $store_info['address']['lat'] : null;
    646718            // $origin_lon = isset($store_info['address']['lon']) ? $store_info['address']['lon'] : null;
    647       }else {
    648           // echo 'no multivendor';
    649       }
    650 
    651       foreach ( $main_order->get_items() as $item )
    652       {
    653           $product_id = $item->get_product_id();
    654           $product_variation_id = $item->get_variation_id();
    655           $product = $item->get_product();
    656           $product_name = $item->get_name();
    657           $quantity = $item->get_quantity();
    658           $subtotal = $item->get_subtotal();
    659           $total = $item->get_total();
    660           $tax = $item->get_subtotal_tax();
    661           $taxclass = $item->get_tax_class();
    662           $taxstat = $item->get_tax_status();
    663           $allmeta = $item->get_meta_data();
    664           // $somemeta = $item->get_meta( '_whatever', true );
    665           $type = $item->get_type();
    666 
    667           $product_weight = 0;
    668           $product_length = 0;
    669           $product_width = 0;
    670           $product_height = 0;
    671 
    672           //get seller info
    673           $product_store_name = get_bloginfo( 'name' );
    674 
    675           $_pf = new WC_Product_Factory();
    676 
    677           $product = $_pf->get_product($product_id);
    678 
    679           if( $product->is_type( 'variable' ) ){
    680               $variation = $_pf->get_product( $product_variation_id );
    681 
    682               if($variation)
    683               {
    684                   $product_name = $variation->get_name();
    685                   $product_weight = delyvax_default_weight(delyvaX_weight_to_kg($variation->get_weight()));
    686                   $product_length = delyvax_default_dimension(delyvax_dimension_to_cm($variation->get_length()));
    687                   $product_width = delyvax_default_dimension(delyvax_dimension_to_cm($variation->get_width()));
    688                   $product_height = delyvax_default_dimension(delyvax_dimension_to_cm($variation->get_height()));
    689               }else {
    690                   $product_weight = delyvax_default_weight(delyvaX_weight_to_kg($product->get_weight()));
    691                   $product_length = delyvax_default_dimension(delyvax_dimension_to_cm($product->get_length()));
    692                   $product_width = delyvax_default_dimension(delyvax_dimension_to_cm($product->get_width()));
    693                   $product_height = delyvax_default_dimension(delyvax_dimension_to_cm($product->get_height()));
    694               }
    695           }else{
    696                 $product_weight = delyvax_default_weight(delyvaX_weight_to_kg($product->get_weight()));
    697                 $product_length = delyvax_default_dimension(delyvax_dimension_to_cm($product->get_length()));
    698                 $product_width = delyvax_default_dimension(delyvax_dimension_to_cm($product->get_width()));
    699                 $product_height = delyvax_default_dimension(delyvax_dimension_to_cm($product->get_height()));
    700           }
    701 
    702           $product_description = '['.$product_store_name.'] '.$product_name.' - Order ID #'.$main_order->get_id();
    703 
    704           $inventories[$count] = array(
    705               "name" => $product_name,
    706               "type" => $item_type, //$type PARCEL / FOOD
    707               "price" => array(
    708                   "amount" => $total,
    709                   "currency" => $main_order->get_currency(),
    710               ),
    711               "weight" => array(
    712                   "value" => $product_weight,
    713                   "unit" => 'kg'
    714               ),
    715               "dimension" => array(
    716                   "unit" => 'cm',
    717                   "width" => $product_width,
    718                   "length" => $product_length,
    719                   "height" => $product_height
    720               ),
    721               "quantity" => $quantity,
    722               "description" => $product_description
    723           );
    724 
    725           $total_weight = $total_weight + ($product_weight*$quantity);
    726 
    727           $total_dimension = $total_dimension + $product_width
    728                 * $product_length
    729                 * $product_height;
    730 
    731           $total_price = $total_price + $subtotal;
    732 
    733           $total_quantity = $total_quantity + $quantity;
    734 
    735           if($include_order_note == 'ordernproduct') $order_notes = $order_notes.'#'.($count+1).'. ['.$store_name.'] '.$product_name.' X '.$quantity.'pcs. ';
    736 
    737           $count++;
    738       }
    739 
    740       $origin = array(
    741           "scheduledAt" => $scheduledAt->format('c'), //"2019-11-15T12:00:00+0800",
    742           "inventory" => $inventories,
    743           "contact" => array(
    744               "name" => $store_name,
    745               "email" => $store_email,
    746               "phone" => $store_phone,
    747               "mobile" => $store_phone,
    748               "address1" => $store_address_1,
    749               "address2" => $store_address_2,
    750               "city" => $store_city,
    751               "state" => $store_state,
    752               "postcode" => $store_postcode,
    753               "country" => $store_country
    754               // "coord" => array(
    755               //     "lat" => "",
    756               //     "lon" => ""
    757               // )
    758           ),
    759           "note"=> $order_notes
    760       );
    761 
    762       if($origin_lat && $origin_lon)
    763       {
    764           $origin['contact']['coord']['lat'] = $origin_lat;
    765           $origin['contact']['coord']['lon'] = $origin_lon;
    766       }
    767       //
    768 
    769       //destination
    770       $r_shipping_phone = $order->get_meta( 'shipping_phone' ) ? $order->get_meta( 'shipping_phone' ) : $order->get_meta( '_shipping_phone' );
    771 
    772       $destination_lat = $order->get_meta( 'shipping_lat' ) ? $order->get_meta( 'shipping_lat' ) : null;
    773       $destination_lon = $order->get_meta( 'shipping_lon' ) ? $order->get_meta( 'shipping_lon' ) : null;
    774 
    775       if($order->get_shipping_address_1() || $order->get_shipping_address_2())
    776       {
    777           $destination = array(
    778               "scheduledAt" => $scheduledAt->format('c'), //"2019-11-15T12:00:00+0800",
    779               "inventory" => $inventories,
    780               "contact" => array(
    781                   "name" => $order->get_shipping_first_name().' '.$order->get_shipping_last_name(),
    782                   "email" => $order->get_billing_email(),
    783                   "phone" => $r_shipping_phone ? $r_shipping_phone : $order->get_billing_phone(),
    784                   "mobile" => $r_shipping_phone ? $r_shipping_phone : $order->get_billing_phone(),
    785                   "address1" => $order->get_shipping_address_1(),
    786                   "address2" => $order->get_shipping_address_2(),
    787                   "city" => $order->get_shipping_city(),
    788                   "state" => $order->get_shipping_state(),
    789                   "postcode" => $order->get_shipping_postcode(),
    790                   "country" => $order->get_shipping_country(),
    791                   // "coord" => array(
    792                   //     "lat" => "",
    793                   //     "lon" => ""
    794                   // )
    795               ),
    796               // "note"=> $order_notes
    797           );
    798       }else {
    799           $destination = array(
    800               "scheduledAt" => $scheduledAt->format('c'), //"2019-11-15T12:00:00+0800",
    801               "inventory" => $inventories,
    802               "contact" => array(
    803                   "name" => $order->get_billing_first_name().' '.$order->get_billing_last_name(),
    804                   "email" => $order->get_billing_email(),
    805                   "phone" => $order->get_billing_phone(),
    806                   "mobile" => $order->get_billing_phone(),
    807                   "address1" => $order->get_billing_address_1(),
    808                   "address2" => $order->get_billing_address_2(),
    809                   "city" => $order->get_billing_city(),
    810                   "state" => $order->get_billing_state(),
    811                   "postcode" => $order->get_billing_postcode(),
    812                   "country" => $order->get_billing_country(),
    813                   // "coord" => array(
    814                   //     "lat" => "",
    815                   //     "lon" => ""
    816                   // )
    817               ),
    818               // "note"=> $order_notes
    819           );
    820       }
    821 
    822       if($destination_lat && $destination_lon)
    823       {
    824           $destination['contact']['coord']['lat'] = $destination_lat;
    825           $destination['contact']['coord']['lon'] = $destination_lon;
    826       }
    827       //
    828 
    829       //calculate volumetric weight
    830       $total_actual_weight = delyvax_default_weight(delyvaX_weight_to_kg($total_weight));
    831       $total_weight = $total_actual_weight;
    832 
    833       $weight = array(
    834         "value" => $total_weight,
    835         "unit" => 'kg'
    836       );
    837 
    838       //
    839       $cod = array(
    840         "id"=> -1,
    841         "qty"=> 1,
    842         "value"=> $total_price
    843       );
    844 
    845       $insurance = array(
    846         "id"=> -3,
    847         "qty"=> 1,
    848         "value"=> $total_price
    849       );
    850 
    851       $addons = array();
    852 
    853       if($order->get_payment_method() == 'cod')
    854       {
    855           array_push($addons, $cod);
    856       }
    857 
    858       if($insurance_premium == 'yes')
    859       {
    860           array_push($addons, $insurance);
    861       }
    862 
    863       $referenceNo = $main_order->get_id();
    864       //
    865      
    866       $DelyvaXOrderID = $order->get_meta( 'DelyvaXOrderID');
    867 
    868       if($DelyvaXOrderID)
    869       {
    870             $shipmentId = $DelyvaXOrderID;
    871       }else {
    872             $resultCreate = DelyvaX_Shipping_API::postCreateOrder($order, $origin, $destination, $weight, $serviceCode, $order_notes, $addons, $referenceNo);
    873 
    874             if($resultCreate)
    875             {
    876                 $shipmentId = $resultCreate["id"];
    877 
    878                 $order->update_meta_data( 'DelyvaXOrderID', $shipmentId );
    879                 $order->save();
     719        }
     720
     721        $ms2781Request = [
     722            'customerId' => $customer_id,
     723            'orderNumber' => (string) $order->get_id(),
     724            'sender' => $sender,
     725            'receiver' => $receiver,
     726            'parcel' => [
     727                'weight' => [
     728                    "unit" => "kg",
     729                    "parcelWeight" => $total_weight,
     730                ],
     731                'quantity' => 1,
     732                'orderRemarks' => $order_notes,
     733            ],
     734            'inventory' => $inventories,
     735            'deliveryService' => [
     736                'serviceType' => $serviceCode,
     737                'pickupDateTime' => $scheduledAt->format('Y-m-d H:i:s'),
     738                'codAmount' => $order->get_payment_method() == 'cod' ? $total_price : 0,
     739                'insuranceAmount' => $insurance_premium == 'yes' ? $total_price : 0,
     740                'itemType' => $settings['item_type'] ? $settings['item_type'] : 'PARCEL',
     741            ],
     742            'source' => $settings["source"],
     743
     744            'isDraft' => !$process,
     745        ];
     746
     747        if (
     748            isset($box_dimensions)
     749            && floatval($box_dimensions['width']) > 0
     750            && floatval($box_dimensions['length']) > 0
     751            && floatval($box_dimensions['height']) > 0
     752        ) {
     753            $ms2781Request['parcel']['dimension'] = [
     754                "unit" => "cm",
     755                "width" => floatval($box_dimensions['width']),
     756                "length" => floatval($box_dimensions['length']),
     757                "height" => floatval($box_dimensions['height'])
     758            ];
     759        }
     760
     761        $resultCreate = DelyvaX_Shipping_API::postCreateOrder($order, $ms2781Request);
     762
     763        if ($resultCreate) {
     764            $deliveryService = $resultCreate["deliveryService"];
     765            $shipmentId = $deliveryService["orderId"];
     766            $trackingNo = $deliveryService["trackingNumber"];
     767            $nanoId = $deliveryService["nanoId"];
     768
     769            $main_order->update_meta_data('DelyvaXOrderID', $shipmentId);
     770            $main_order->update_meta_data('DelyvaXTrackingCode', $trackingNo);
     771            $main_order->update_meta_data('DelyvaXTrackingShort', $nanoId);
     772
     773            $deliveryCost = $deliveryService['deliveryCost']['amount'];
     774
     775            if ($process) {
     776                $main_order->update_status('wc-ready-to-collect', 'Delivery order number: ' . $trackingNo . ' - <a href="https://api.delyva.app/v1.0/order/' . $shipmentId . '/label?companyId=' . $company_id . '" target="_blank">Print label</a> - <a href="https://' . $company_code . '.delyva.app/customer/strack?trackingNo=' . $trackingNo . '" target="_blank">Track</a>.', false);
    880777            }
    881       }
    882 
    883     if($process)
    884     {
    885         $resultProcess = delyvax_post_process_order($order, $user, $shipmentId);
    886 
    887         if($resultProcess)
    888         {
    889             $trackingNo = $resultProcess["consignmentNo"];
    890             $nanoId = $resultProcess["nanoId"];
    891 
    892             $main_order = $order;
    893 
    894             $main_order->update_meta_data( 'DelyvaXOrderID', $shipmentId );
    895             $main_order->update_meta_data( 'DelyvaXTrackingCode', $trackingNo );
    896             $main_order->update_meta_data( 'DelyvaXTrackingShort', $nanoId );
     778       
     779            if ($deliveryCost > 0) {
     780                $pricing = process_delivery_pricing($main_order, $deliveryCost, $total_quantity, $total_price);
     781                $main_order->update_meta_data('DelyvaXDeliveryPrice', $deliveryCost);
     782                $main_order->update_meta_data('DelyvaXMarkup', $pricing['deliveryMarkup']);
     783                $main_order->update_meta_data('DelyvaXDiscount', $pricing['deliveryDiscount']);
     784            }
    897785            $main_order->save();
    898 
    899             $main_order->update_status('wc-ready-to-collect', 'Delivery order number: '.$trackingNo.' - <a href="https://api.delyva.app/v1.0/order/'.$shipmentId.'/label?companyId='.$company_id.'" target="_blank">Print label</a> - <a href="https://'.$company_code.'.delyva.app/customer/strack?trackingNo='.$trackingNo.'" target="_blank">Track</a>.', false);
    900 
    901             $consignmentNo = $trackingNo;
    902 
    903             //store price discount or markup
    904             if($resultProcess["price"])
    905             {
    906                 $deliveryPrice = $resultProcess['price']['amount'];
    907                 $deliveryMarkup = 0;
    908                 $deliveryDiscount = 0;
    909 
    910                 $rate_adjustment_type = $settings['rate_adjustment_type'] ?? 'discount';
    911 
    912                 $ra_percentage = $settings['rate_adjustment_percentage'] ?? 1;
    913                 $percentRate = $ra_percentage / 100 * $deliveryPrice;
    914 
    915                 $flatRate = $settings['rate_adjustment_flat'] ?? 0;
    916 
    917                 if($rate_adjustment_type == 'markup')
    918                 {
    919                     $deliveryMarkup = round($percentRate + $flatRate, 2);
    920                 }else {
    921                     $deliveryDiscount = round($percentRate + $flatRate, 2);
    922                 }
    923 
    924                 $main_order->update_meta_data( 'DelyvaXDeliveryPrice', $deliveryPrice );
    925                 $main_order->update_meta_data( 'DelyvaXMarkup', $deliveryMarkup );
    926                 $main_order->update_meta_data( 'DelyvaXDiscount', $deliveryDiscount );
    927                 $main_order->save();
    928             }
    929 
    930             //handle free shipping
    931             $free_shipping_type = $settings['free_shipping_type'] ?? '';
    932             $free_shipping_condition = $settings['free_shipping_condition'] ?? '';
    933             $free_shipping_value = $settings['free_shipping_value'] ?? '0';
    934 
    935             if($free_shipping_type == 'total_quantity')
    936             {
    937                 if($free_shipping_condition == '>')
    938                 {
    939                     if($total_quantity > $free_shipping_value)
    940                     {
    941                         $deliveryDiscount = $deliveryPrice;
    942                     }
    943                 }else if($free_shipping_condition == '>=')
    944                 {
    945                     if($total_quantity >= $free_shipping_value)
    946                     {
    947                         $deliveryDiscount = $deliveryPrice;
    948                     }
    949                 }else if($free_shipping_condition == '==')
    950                 {
    951                     if($total_quantity == $free_shipping_value)
    952                     {
    953                         $deliveryDiscount = $deliveryPrice;
    954                     }
    955                 }else if($free_shipping_condition == '<=')
    956                 {
    957                     if($total_quantity <= $free_shipping_value)
    958                     {
    959                         $deliveryDiscount = $deliveryPrice;
    960                     }
    961                 }else if($free_shipping_condition == '<')
    962                 {
    963                     if($total_quantity < $free_shipping_value)
    964                     {
    965                         $deliveryDiscount = $deliveryPrice;
    966                     }
    967                 }
    968             }else if($free_shipping_type == 'total_amount')
    969             {
    970                 if($free_shipping_condition == '>')
    971                 {
    972                     if($total_price > $free_shipping_value)
    973                     {
    974                         $deliveryDiscount = $deliveryPrice;
    975                     }
    976                 }else if($free_shipping_condition == '>=')
    977                 {
    978                     if($total_price >= $free_shipping_value)
    979                     {
    980                         $deliveryDiscount = $deliveryPrice;
    981                     }
    982                 }else if($free_shipping_condition == '==')
    983                 {
    984                     if($total_price == $free_shipping_value)
    985                     {
    986                         $deliveryDiscount = $deliveryPrice;
    987                     }
    988                 }else if($free_shipping_condition == '<=')
    989                 {
    990                     if($total_price <= $free_shipping_value)
    991                     {
    992                         $deliveryDiscount = $deliveryPrice;
    993                     }
    994                 }else if($free_shipping_condition == '<')
    995                 {
    996                     if($total_price < $free_shipping_value)
    997                     {
    998                         $deliveryDiscount = $deliveryPrice;
    999                     }
    1000                 }
    1001             }
    1002 
    1003             $main_order->update_meta_data( 'DelyvaXDiscount', $deliveryDiscount );
    1004             $main_order->save();
    1005             ////end free shipping
    1006 
    1007             // no need - vendor to process sub order separately
    1008             //save tracking no into order to all parent order and suborders
    1009             /*
    1010             $sub_orders = get_children( array( 'post_parent' => $order->get_id(), 'post_type' => 'shop_order' ) );
    1011 
    1012             if( sizeof($sub_orders) > 0 )
    1013             {
    1014                 $main_order = wc_get_order($order->get_id());
    1015 
    1016                 $main_order->update_meta_data( 'DelyvaXOrderID', $shipmentId );
    1017                 $main_order->update_meta_data( 'DelyvaXTrackingCode', $trackingNo );
    1018                 $main_order->save();
    1019 
    1020                 $main_order->update_status('wc-ready-to-collect');
    1021 
    1022                 $count = 0;
    1023                 foreach ($sub_orders as $sub)
    1024                 {
    1025                     $sub_order = wc_get_order($sub->ID);
    1026 
    1027                     $sub_order->update_meta_data( 'DelyvaXOrderID', $shipmentId );
    1028                     $sub_order->update_meta_data( 'DelyvaXTrackingCode', $trackingNo );
    1029                     $sub_order->save();
    1030 
    1031                     $sub_order->update_status('wc-ready-to-collect');
    1032 
    1033                     $consignmentNo = $trackingNo."-".($count+1);
    1034 
    1035 
    1036                     $count++;
    1037                 }
    1038             }else {
    1039                 $main_order = $order;
    1040 
    1041                 $main_order->update_meta_data( 'DelyvaXOrderID', $shipmentId );
    1042                 $main_order->update_meta_data( 'DelyvaXTrackingCode', $trackingNo );
    1043                 $main_order->save();
    1044 
    1045                 $main_order->update_status('wc-ready-to-collect');
    1046 
    1047                 $consignmentNo = $trackingNo."-1";
    1048             }*/
    1049         }
    1050     }else {
    1051             $main_order = $order;
    1052 
    1053             $main_order->update_meta_data( 'DelyvaXOrderID', $shipmentId );
    1054             // $main_order->update_meta_data( 'DelyvaXTrackingCode', $trackingNo );
    1055             $main_order->save();
    1056 
    1057             // $consignmentNo = $trackingNo;
    1058 
    1059             // no need vendor to process sub order separately
    1060             //save tracking no into order to all parent order and suborders
    1061             // $sub_orders = get_children( array( 'post_parent' => $order->get_id(), 'post_type' => 'shop_order' ) );
    1062             //
    1063             // if( sizeof($sub_orders) > 0 )
    1064             // {
    1065             //     $main_order = wc_get_order($order->get_id());
    1066             //
    1067             //     $main_order->update_meta_data( 'DelyvaXOrderID', $shipmentId );
    1068             //     // $main_order->update_meta_data( 'DelyvaXTrackingCode', $trackingNo );
    1069             //     $main_order->save();
    1070             //
    1071             //     $count = 0;
    1072             //     foreach ($sub_orders as $sub)
    1073             //     {
    1074             //         $sub_order = wc_get_order($sub->ID);
    1075             //
    1076             //         $sub_order->update_meta_data( 'DelyvaXOrderID', $shipmentId );
    1077             //         // $sub_order->update_meta_data( 'DelyvaXTrackingCode', $trackingNo );
    1078             //         $sub_order->save();
    1079             //
    1080             //         $consignmentNo = $trackingNo."-".($count+1);
    1081             //
    1082             //         $count++;
    1083             //     }
    1084             // }else {
    1085             //     $main_order = $order;
    1086             //
    1087             //     $main_order->update_meta_data( 'DelyvaXOrderID', $shipmentId );
    1088             //     // $main_order->update_meta_data( 'DelyvaXTrackingCode', $trackingNo );
    1089             //     $main_order->save();
    1090             //
    1091             //     $consignmentNo = $trackingNo."-1";
    1092             // }
     786        }
    1093787    }
    1094788}
    1095789
    1096790//rewire logic here, API is only for post
    1097 function delyvax_post_process_order($order, $user, $shipmentId) {
     791function delyvax_post_process_order($order, $shipmentId) {
    1098792      //service
    1099793      $serviceCode = "";
  • delyvax/trunk/includes/delyvax-api.php

    r3158477 r3210380  
    6363        }
    6464
    65         public static function postCreateOrder($order, $origin, $destination, $weight, $serviceCode, $order_notes, $addons, $referenceNo)
    66         {
    67               $url = Self::$api_endpoint . "/order";// . trim(esc_attr($settings['integration_id']), " ");
     65        public static function postCreateOrder($order, $ms2781Request)
     66        {
     67            $url = Self::$api_endpoint . "/order/ms2781/create";
     68            $settings = get_option('woocommerce_delyvax_settings');
     69            $api_token = $settings['api_token'];
     70
     71            // Make the API request
     72            $response = wp_remote_post($url, array(
     73                'headers' => array(
     74                    'content-type' => 'application/json',
     75                    'X-Delyvax-Access-Token' => $api_token,
     76                    'X-Delyvax-Wp-Version' => DELYVAX_PLUGIN_VERSION,
     77                ),
     78                'body' => json_encode($ms2781Request),
     79                'method' => 'POST',
     80                'timeout' => 25
     81            ));
     82
     83            if (is_wp_error($response)) {
     84                $error_message = $response->get_error_message();
     85                if ($error_message == 'fsocket timed out') {
     86                    throw new Exception("Sorry, unable to create shipment, please try again later");
     87                } else {
     88                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     89                }
     90            }
     91
     92            if ($response['response']['code'] == 200) {
     93                $body = json_decode($response['body'], true);
     94                $order->delete_meta_data('DelyvaXError');
     95                return $body;
     96            } else {
     97                $body = json_decode($response['body'], true);
     98                $order->update_meta_data('DelyvaXError', $body['error']['message']);
     99                $order->save();
     100                throw new Exception("Error: " . $body['error']['message'] . ". Sorry, something went wrong with the API. If the problem persists, please contact us!");
     101            }
     102        }
     103
     104        public static function postProcessOrder($order, $shipmentId, $serviceCode)
     105        {
     106              $url = Self::$api_endpoint . "/order/process";
    68107
    69108              $settings = get_option( 'woocommerce_delyvax_settings' );
    70 
    71               $company_id = $settings['company_id'];
    72               $user_id = $settings['user_id'];
    73               $customer_id = $settings['customer_id'];
    74109              $api_token = $settings['api_token'];
    75               $processing_days = $settings['processing_days'];
    76 
    77               $source = ($settings['source']) ? $settings['source'] : "PARCEL" ;
    78 
    79               if($serviceCode)
    80               {
    81                   $postRequestArr = [
    82                       // 'companyId' => $company_id,
    83                       // 'userId' => $user_id,
    84                       "customerId" => $customer_id,
    85                       "process" => false,
    86                       "serviceCode" => $serviceCode,
    87                       'origin' => $origin,
    88                       'destination' => $destination,
    89                       'weight' => $weight,
    90                       'note' => $order_notes,
    91                       "serviceAddon" => $addons,
    92                       'source'=> $source,
    93                       'referenceNo'=> $referenceNo.""
    94                   ];
    95               }else {
    96                   $postRequestArr = [
    97                       // 'companyId' => $company_id,
    98                       // 'userId' => $user_id,
    99                       "customerId" => $customer_id,
    100                       "process" => false,
    101                       'origin' => $origin,
    102                       'destination' => $destination,
    103                       'weight' => $weight,
    104                       'note' => $order_notes,
    105                       "serviceAddon" => $addons,
    106                       'source'=> $source,
    107                       'referenceNo'=> $referenceNo.""
    108                   ];
     110
     111              $postRequestArr = [
     112                'orderId' => $shipmentId,
     113                "skipQueue" => true,
     114              ];
     115
     116              if ($serviceCode) {
     117                $postRequestArr['serviceCode'] = $serviceCode;
    109118              }
    110119
     
    123132                  $error_message = $response->get_error_message();
    124133                  if ($error_message == 'fsocket timed out') {
    125                       throw new Exception("Sorry, unable to create shipment, please try again later");
     134                      throw new Exception("Sorry, unable to process shipment, please try again later");
    126135                  } else {
    127136                      throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     
    130139                  if ($response['response']['code'] == 200) {
    131140                      $body = json_decode($response['body'], true);
     141                      $order->delete_meta_data('DelyvaXError');
     142                      $order->save();
    132143                      return $body['data'];
    133144                  } else {
    134145                      $body = json_decode($response['body'], true);
    135                       $order->update_meta_data( 'DelyvaXError', $body['error']['message'] );
     146                      $order->update_meta_data( 'DelyvaXError', $body['error']['message']);
    136147                      $order->save();
    137148                      throw new Exception("Error: ".$body['error']['message'].". Sorry, something went wrong with the API. If the problem persists, please contact us!");
    138149                  }
    139150              }
    140               ///
    141         }
    142 
    143         public static function postProcessOrder($order, $shipmentId, $serviceCode)
    144         {
    145               $url = Self::$api_endpoint . "/order/:orderId/process";// . trim(esc_attr($settings['integration_id']), " ");
     151        }
     152
     153        public static function postCancelOrder($order, $shipmentId) {
     154            $url = Self::$api_endpoint . "/order/ms2781/cancel";
     155       
     156            $settings = get_option('woocommerce_delyvax_settings');
     157       
     158            $company_id = $settings['company_id'];
     159            $user_id = $settings['user_id'];
     160            $customer_id = $settings['customer_id'];
     161            $api_token = $settings['api_token'];
     162       
     163            $postRequestArr = [
     164                "orderId" => $shipmentId
     165            ];
     166
     167            $response = wp_remote_post($url, array(
     168                'headers' => array(
     169                    'content-type' => 'application/json',
     170                    'X-Delyvax-Access-Token' => $api_token,
     171                    'X-Delyvax-Wp-Version' => DELYVAX_PLUGIN_VERSION,
     172                ),
     173                'body' => json_encode($postRequestArr),
     174                'method' => 'POST',
     175                'timeout' => 25
     176            ));
     177
     178            if (is_wp_error($response)) {
     179                $error_message = $response->get_error_message();
     180                if ($error_message == 'fsocket timed out') {
     181                    throw new Exception("Sorry, unable to cancel shipment, please try again later");
     182                } else {
     183                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     184                }
     185            }
     186       
     187            if ($response['response']['code'] == 200) {
     188                $body = json_decode($response['body'], true);
     189                return $body;
     190            }
     191           
     192            $body = json_decode($response['body'], true);
     193            $order->update_meta_data('DelyvaXError', $body['error']['message']);
     194            $order->save();
     195            throw new Exception("Error: " . $body['error']['message'] . ". Sorry, something went wrong with the API. If the problem persists, please contact us!");
     196        }
     197
     198        public static function getTrackOrderByOrderId($shipmentId)
     199        {
     200            $settings = get_option( 'woocommerce_delyvax_settings' );
     201
     202            $company_id = $settings['company_id'];
     203            $user_id = $settings['user_id'];
     204            $customer_id = $settings['customer_id'];
     205            $api_token = $settings['api_token'];
     206
     207            $url = Self::$api_endpoint . "/order/:orderId/track";
     208
     209            $url = str_replace(":orderId", $shipmentId, $url);
     210
     211            $response = wp_remote_post($url, array(
     212                'headers' => array(
     213                  'content-type' => 'application/json',
     214                  'X-Delyvax-Access-Token' => $api_token
     215                ),
     216                // 'body' => json_encode($postRequestArr),
     217                'method' => 'GET',
     218                'timeout' => 25
     219            ));
     220
     221            if (is_wp_error($response)) {
     222                $error_message = $response->get_error_message();
     223                if ($error_message == 'fsocket timed out') {
     224                    throw new Exception("Sorry, unable to track shipment, please try again later");
     225                } else {
     226                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     227                }
     228            } else {
     229                if ($response['response']['code'] == 200) {
     230                    $body = json_decode($response['body'], true);
     231                    return $body;
     232                } else {
     233                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     234                }
     235            }
     236        }
     237
     238        public static function getTrackOrderByTrackingNo($trackingNo)
     239        {
     240            $settings = get_option( 'woocommerce_delyvax_settings' );
     241
     242            $company_id = $settings['company_id'];
     243            $user_id = $settings['user_id'];
     244            $customer_id = $settings['customer_id'];
     245            $api_token = $settings['api_token'];
     246
     247            $url = Self::$api_endpoint . "/order/track/:consignmentNo?companyId=".$company_id;
     248
     249            $url = str_replace(":consignmentNo", $trackingNo, $url);
     250
     251            $response = wp_remote_post($url, array(
     252                'headers' => array(
     253                  'content-type' => 'application/json',
     254                  'X-Delyvax-Access-Token' => $api_token
     255                ),
     256                // 'body' => json_encode($postRequestArr),
     257                'method' => 'GET',
     258                'timeout' => 25
     259            ));
     260
     261            if (is_wp_error($response)) {
     262                $error_message = $response->get_error_message();
     263                if ($error_message == 'fsocket timed out') {
     264                    throw new Exception("Sorry, unable to track shipment, please try again later");
     265                } else {
     266                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     267                }
     268            } else {
     269                if ($response['response']['code'] == 200) {
     270                    $body = json_decode($response['body'], true);
     271
     272                    return $body['data'];
     273                } else {
     274                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     275                }
     276            }
     277        }
     278
     279        public static function getOrderQuotesByOrderId($shipmentId)
     280        {
     281            $settings = get_option( 'woocommerce_delyvax_settings' );
     282
     283            $company_id = $settings['company_id'];
     284            $user_id = $settings['user_id'];
     285            $customer_id = $settings['customer_id'];
     286            $api_token = $settings['api_token'];
     287
     288            $url = Self::$api_endpoint . "/order/:orderId?retrieve=quotes";
     289
     290            $url = str_replace(":orderId", $shipmentId, $url);
     291
     292            $response = wp_remote_post($url, array(
     293                'headers' => array(
     294                  'content-type' => 'application/json',
     295                  'X-Delyvax-Access-Token' => $api_token
     296                ),
     297                // 'body' => json_encode($postRequestArr),
     298                'method' => 'GET',
     299                'timeout' => 25
     300            ));
     301
     302            if (is_wp_error($response)) {
     303                $error_message = $response->get_error_message();
     304                if ($error_message == 'fsocket timed out') {
     305                    throw new Exception("Sorry, unable to track shipment, please try again later");
     306                } else {
     307                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     308                }
     309            } else {
     310                if ($response['response']['code'] == 200) {
     311                    $body = json_decode($response['body'], true);
     312                    return $body;
     313                } else {
     314                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     315                }
     316            }
     317        }
     318
     319        public static function getWebhook()
     320        {
     321            $url = Self::$api_endpoint . "/webhook";
     322            $settings = get_option( 'woocommerce_delyvax_settings' );
     323
     324            $api_token = $settings['api_token'];
     325
     326            $response = wp_remote_post($url, array(
     327                'headers' => array(
     328                  'content-type' => 'application/json',
     329                  'X-Delyvax-Access-Token' => $api_token
     330                ),
     331                'method' => 'GET',
     332                'timeout' => 25
     333            ));
     334
     335            if (is_wp_error($response)) {
     336                $error_message = $response->get_error_message();
     337                if ($error_message == 'fsocket timed out') {
     338                    throw new Exception("Sorry, unable to get webhook, please try again later");
     339                } else {
     340                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     341                }
     342            } else {
     343                if ($response['response']['code'] == 200) {
     344                    $body = json_decode($response['body'], true);
     345                    return $body['data'];
     346                } else {
     347                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     348                }
     349            }
     350        }
     351
     352        public static function deleteWebhook($webhook_id)
     353        {
     354            $url = Self::$api_endpoint . "/webhook/" . $webhook_id;
     355            $settings = get_option( 'woocommerce_delyvax_settings' );
     356
     357            $api_token = $settings['api_token'];
     358
     359            $response = wp_remote_post($url, array(
     360                'headers' => array(
     361                  'content-type' => 'application/json',
     362                  'X-Delyvax-Access-Token' => $api_token
     363                ),
     364                'method' => 'DELETE',
     365                'timeout' => 25
     366            ));
     367
     368            if (is_wp_error($response)) {
     369                $error_message = $response->get_error_message();
     370                if ($error_message == 'fsocket timed out') {
     371                    throw new Exception("Sorry, unable to delete webhook, please try again later");
     372                } else {
     373                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     374                }
     375            } else {
     376                if ($response['response']['code'] == 200) {
     377                    $body = json_decode($response['body'], true);
     378                    return $body['data'];
     379                } else {
     380                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     381                }
     382            }
     383        }
     384
     385        public static function postCreateWebhook($event_name)
     386        {
     387            $settings = get_option( 'woocommerce_delyvax_settings' );
     388
     389            $company_id = $settings['company_id'];
     390            $user_id = $settings['user_id'];
     391            $customer_id = $settings['customer_id'];
     392            $api_token = $settings['api_token'];
     393
     394            $url = Self::$api_endpoint . "//webhook/";
     395
     396            // get_option( 'woocommerce_store_url' );
     397            $store_url = get_site_url()."/?delyvax=webhook"; //"https://matdespatch.com/my/makan";
     398
     399            $postRequestArr = array(
     400                "event" => $event_name,
     401                "url" => $store_url,
     402            );
     403
     404            $response = wp_remote_post($url, array(
     405                'headers' => array(
     406                  'content-type' => 'application/json',
     407                  'X-Delyvax-Access-Token' => $api_token
     408                ),
     409                'body' => json_encode($postRequestArr),
     410                'method' => 'POST',
     411                'timeout' => 25
     412            ));
     413
     414            if (is_wp_error($response)) {
     415                $error_message = $response->get_error_message();
     416                if ($error_message == 'fsocket timed out') {
     417                    throw new Exception("Sorry, unable to create webhook, please try again later");
     418                } else {
     419                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     420                }
     421            } else {
     422                if ($response['response']['code'] == 200) {
     423                    $body = json_decode($response['body'], true);
     424
     425                    return $body['data'];
     426                } else {
     427                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     428                }
     429            }
     430        }
     431
     432        public static function updateWebhookUrl($webhook_id)
     433        {
     434            $settings = get_option( 'woocommerce_delyvax_settings' );
     435
     436            $company_id = $settings['company_id'];
     437            $user_id = $settings['user_id'];
     438            $customer_id = $settings['customer_id'];
     439            $api_token = $settings['api_token'];
     440
     441            $url = Self::$api_endpoint . "//webhook/" . $webhook_id;
     442
     443            $store_url = get_site_url()."/?delyvax=webhook"; //"https://matdespatch.com/my/makan";
     444
     445            $postRequestArr = array(
     446                "url" => $store_url,
     447            );
     448
     449            $response = wp_remote_post($url, array(
     450                'headers' => array(
     451                  'content-type' => 'application/json',
     452                  'X-Delyvax-Access-Token' => $api_token
     453                ),
     454                'body' => json_encode($postRequestArr),
     455                'method' => 'PATCH',
     456                'timeout' => 25
     457            ));
     458
     459            if (is_wp_error($response)) {
     460                $error_message = $response->get_error_message();
     461                if ($error_message == 'fsocket timed out') {
     462                    throw new Exception("Sorry, unable to update webhook, please try again later");
     463                } else {
     464                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     465                }
     466            } else {
     467                if ($response['response']['code'] == 200) {
     468                    $body = json_decode($response['body'], true);
     469
     470                    return $body['data'];
     471                } else {
     472                    throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
     473                }
     474            }
     475        }
     476   
     477        public static function updateOrderData($order, $shipmentId, $postRequestArr)
     478        {
     479              $url = Self::$api_endpoint . "/order/:orderId";
    146480
    147481              $url = str_replace(":orderId", $shipmentId, $url);
     
    154488              $api_token = $settings['api_token'];
    155489              $processing_days = $settings['processing_days'];
    156 
    157               if($serviceCode)
    158               {
    159                   $postRequestArr = [
    160                       'orderId' => $shipmentId,
    161                       "serviceCode" => $serviceCode,
    162                       "skipQueue" => true,
    163                   ];
    164               }else {
    165                   $postRequestArr = [
    166                       'orderId' => $shipmentId,
    167                       "skipQueue" => true,
    168                   ];
    169               }
    170490
    171491              $response = wp_remote_post($url, array(
     
    176496                  ),
    177497                  'body' => json_encode($postRequestArr),
    178                   'method' => 'POST',
     498                  'method' => 'PATCH',
    179499                  'timeout' => 25
    180500              ));
     
    200520              ///
    201521        }
    202 
    203         public static function postCancelOrder($order, $shipmentId)
    204         {
    205               $url = Self::$api_endpoint . "/order/:orderId/cancel";
    206 
    207               $url = str_replace(":orderId", $shipmentId, $url);
    208 
    209               $settings = get_option( 'woocommerce_delyvax_settings' );
    210 
    211               $company_id = $settings['company_id'];
    212               $user_id = $settings['user_id'];
    213               $customer_id = $settings['customer_id'];
    214               $api_token = $settings['api_token'];
    215 
    216             //   $postRequestArr = [];
    217 
    218               $response = wp_remote_post($url, array(
    219                   'headers' => array(
    220                     'content-type' => 'application/json',
    221                     'X-Delyvax-Access-Token' => $api_token,
    222                     'X-Delyvax-Wp-Version' => DELYVAX_PLUGIN_VERSION,
    223                   ),
    224                 //   'body' => json_encode($postRequestArr),
    225                   'method' => 'POST',
    226                   'timeout' => 25
    227               ));
    228 
    229               if (is_wp_error($response)) {
    230                   $error_message = $response->get_error_message();
    231                   if ($error_message == 'fsocket timed out') {
    232                       throw new Exception("Sorry, unable to cancel shipment, please try again later");
    233                   } else {
    234                       throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    235                   }
    236               } else {
    237                   if ($response['response']['code'] == 200) {
    238                       $body = json_decode($response['body'], true);
    239                       return $body['data'];
    240                   } else {
    241                       $body = json_decode($response['body'], true);
    242                       $order->update_meta_data( 'DelyvaXError', $body['error']['message'] );
    243                       $order->save();
    244                       throw new Exception("Error: ".$body['error']['message'].". Sorry, something went wrong with the API. If the problem persists, please contact us!");
    245                   }
    246               }
    247               ///
    248         }
    249 
    250         public static function getTrackOrderByOrderId($shipmentId)
    251         {
    252             $settings = get_option( 'woocommerce_delyvax_settings' );
    253 
    254             $company_id = $settings['company_id'];
    255             $user_id = $settings['user_id'];
    256             $customer_id = $settings['customer_id'];
    257             $api_token = $settings['api_token'];
    258 
    259             $url = Self::$api_endpoint . "/order/:orderId/track";
    260 
    261             $url = str_replace(":orderId", $shipmentId, $url);
    262 
    263             $response = wp_remote_post($url, array(
    264                 'headers' => array(
    265                   'content-type' => 'application/json',
    266                   'X-Delyvax-Access-Token' => $api_token
    267                 ),
    268                 // 'body' => json_encode($postRequestArr),
    269                 'method' => 'GET',
    270                 'timeout' => 25
    271             ));
    272 
    273             if (is_wp_error($response)) {
    274                 $error_message = $response->get_error_message();
    275                 if ($error_message == 'fsocket timed out') {
    276                     throw new Exception("Sorry, unable to track shipment, please try again later");
    277                 } else {
    278                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    279                 }
    280             } else {
    281                 if ($response['response']['code'] == 200) {
    282                     $body = json_decode($response['body'], true);
    283                     return $body;
    284                 } else {
    285                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    286                 }
    287             }
    288         }
    289 
    290         public static function getTrackOrderByTrackingNo($trackingNo)
    291         {
    292             $settings = get_option( 'woocommerce_delyvax_settings' );
    293 
    294             $company_id = $settings['company_id'];
    295             $user_id = $settings['user_id'];
    296             $customer_id = $settings['customer_id'];
    297             $api_token = $settings['api_token'];
    298 
    299             $url = Self::$api_endpoint . "/order/track/:consignmentNo?companyId=".$company_id;
    300 
    301             $url = str_replace(":consignmentNo", $trackingNo, $url);
    302 
    303             $response = wp_remote_post($url, array(
    304                 'headers' => array(
    305                   'content-type' => 'application/json',
    306                   'X-Delyvax-Access-Token' => $api_token
    307                 ),
    308                 // 'body' => json_encode($postRequestArr),
    309                 'method' => 'GET',
    310                 'timeout' => 25
    311             ));
    312 
    313             if (is_wp_error($response)) {
    314                 $error_message = $response->get_error_message();
    315                 if ($error_message == 'fsocket timed out') {
    316                     throw new Exception("Sorry, unable to track shipment, please try again later");
    317                 } else {
    318                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    319                 }
    320             } else {
    321                 if ($response['response']['code'] == 200) {
    322                     $body = json_decode($response['body'], true);
    323 
    324                     return $body['data'];
    325                 } else {
    326                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    327                 }
    328             }
    329         }
    330 
    331         public static function getOrderQuotesByOrderId($shipmentId)
    332         {
    333             $settings = get_option( 'woocommerce_delyvax_settings' );
    334 
    335             $company_id = $settings['company_id'];
    336             $user_id = $settings['user_id'];
    337             $customer_id = $settings['customer_id'];
    338             $api_token = $settings['api_token'];
    339 
    340             $url = Self::$api_endpoint . "/order/:orderId?retrieve=quotes";
    341 
    342             $url = str_replace(":orderId", $shipmentId, $url);
    343 
    344             $response = wp_remote_post($url, array(
    345                 'headers' => array(
    346                   'content-type' => 'application/json',
    347                   'X-Delyvax-Access-Token' => $api_token
    348                 ),
    349                 // 'body' => json_encode($postRequestArr),
    350                 'method' => 'GET',
    351                 'timeout' => 25
    352             ));
    353 
    354             if (is_wp_error($response)) {
    355                 $error_message = $response->get_error_message();
    356                 if ($error_message == 'fsocket timed out') {
    357                     throw new Exception("Sorry, unable to track shipment, please try again later");
    358                 } else {
    359                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    360                 }
    361             } else {
    362                 if ($response['response']['code'] == 200) {
    363                     $body = json_decode($response['body'], true);
    364                     return $body;
    365                 } else {
    366                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    367                 }
    368             }
    369         }
    370 
    371         public static function getWebhook()
    372         {
    373             $url = Self::$api_endpoint . "/webhook";
    374             $settings = get_option( 'woocommerce_delyvax_settings' );
    375 
    376             $api_token = $settings['api_token'];
    377 
    378             $response = wp_remote_post($url, array(
    379                 'headers' => array(
    380                   'content-type' => 'application/json',
    381                   'X-Delyvax-Access-Token' => $api_token
    382                 ),
    383                 'method' => 'GET',
    384                 'timeout' => 25
    385             ));
    386 
    387             if (is_wp_error($response)) {
    388                 $error_message = $response->get_error_message();
    389                 if ($error_message == 'fsocket timed out') {
    390                     throw new Exception("Sorry, unable to get webhook, please try again later");
    391                 } else {
    392                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    393                 }
    394             } else {
    395                 if ($response['response']['code'] == 200) {
    396                     $body = json_decode($response['body'], true);
    397                     return $body['data'];
    398                 } else {
    399                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    400                 }
    401             }
    402         }
    403 
    404         public static function deleteWebhook($webhook_id)
    405         {
    406             $url = Self::$api_endpoint . "/webhook/" . $webhook_id;
    407             $settings = get_option( 'woocommerce_delyvax_settings' );
    408 
    409             $api_token = $settings['api_token'];
    410 
    411             $response = wp_remote_post($url, array(
    412                 'headers' => array(
    413                   'content-type' => 'application/json',
    414                   'X-Delyvax-Access-Token' => $api_token
    415                 ),
    416                 'method' => 'DELETE',
    417                 'timeout' => 25
    418             ));
    419 
    420             if (is_wp_error($response)) {
    421                 $error_message = $response->get_error_message();
    422                 if ($error_message == 'fsocket timed out') {
    423                     throw new Exception("Sorry, unable to delete webhook, please try again later");
    424                 } else {
    425                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    426                 }
    427             } else {
    428                 if ($response['response']['code'] == 200) {
    429                     $body = json_decode($response['body'], true);
    430                     return $body['data'];
    431                 } else {
    432                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    433                 }
    434             }
    435         }
    436 
    437         public static function postCreateWebhook($event_name)
    438         {
    439             $settings = get_option( 'woocommerce_delyvax_settings' );
    440 
    441             $company_id = $settings['company_id'];
    442             $user_id = $settings['user_id'];
    443             $customer_id = $settings['customer_id'];
    444             $api_token = $settings['api_token'];
    445 
    446             $url = Self::$api_endpoint . "//webhook/";
    447 
    448             // get_option( 'woocommerce_store_url' );
    449             $store_url = get_site_url()."/?delyvax=webhook"; //"https://matdespatch.com/my/makan";
    450 
    451             $postRequestArr = array(
    452                 "event" => $event_name,
    453                 "url" => $store_url,
    454             );
    455 
    456             $response = wp_remote_post($url, array(
    457                 'headers' => array(
    458                   'content-type' => 'application/json',
    459                   'X-Delyvax-Access-Token' => $api_token
    460                 ),
    461                 'body' => json_encode($postRequestArr),
    462                 'method' => 'POST',
    463                 'timeout' => 25
    464             ));
    465 
    466             if (is_wp_error($response)) {
    467                 $error_message = $response->get_error_message();
    468                 if ($error_message == 'fsocket timed out') {
    469                     throw new Exception("Sorry, unable to create webhook, please try again later");
    470                 } else {
    471                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    472                 }
    473             } else {
    474                 if ($response['response']['code'] == 200) {
    475                     $body = json_decode($response['body'], true);
    476 
    477                     return $body['data'];
    478                 } else {
    479                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    480                 }
    481             }
    482         }
    483 
    484         public static function updateWebhookUrl($webhook_id)
    485         {
    486             $settings = get_option( 'woocommerce_delyvax_settings' );
    487 
    488             $company_id = $settings['company_id'];
    489             $user_id = $settings['user_id'];
    490             $customer_id = $settings['customer_id'];
    491             $api_token = $settings['api_token'];
    492 
    493             $url = Self::$api_endpoint . "//webhook/" . $webhook_id;
    494 
    495             $store_url = get_site_url()."/?delyvax=webhook"; //"https://matdespatch.com/my/makan";
    496 
    497             $postRequestArr = array(
    498                 "url" => $store_url,
    499             );
    500 
    501             $response = wp_remote_post($url, array(
    502                 'headers' => array(
    503                   'content-type' => 'application/json',
    504                   'X-Delyvax-Access-Token' => $api_token
    505                 ),
    506                 'body' => json_encode($postRequestArr),
    507                 'method' => 'PATCH',
    508                 'timeout' => 25
    509             ));
    510 
    511             if (is_wp_error($response)) {
    512                 $error_message = $response->get_error_message();
    513                 if ($error_message == 'fsocket timed out') {
    514                     throw new Exception("Sorry, unable to update webhook, please try again later");
    515                 } else {
    516                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    517                 }
    518             } else {
    519                 if ($response['response']['code'] == 200) {
    520                     $body = json_decode($response['body'], true);
    521 
    522                     return $body['data'];
    523                 } else {
    524                     throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    525                 }
    526             }
    527         }
    528    
    529         public static function updateOrderData($order, $shipmentId, $postRequestArr)
    530         {
    531               $url = Self::$api_endpoint . "/order/:orderId";
    532 
    533               $url = str_replace(":orderId", $shipmentId, $url);
    534 
    535               $settings = get_option( 'woocommerce_delyvax_settings' );
    536 
    537               $company_id = $settings['company_id'];
    538               $user_id = $settings['user_id'];
    539               $customer_id = $settings['customer_id'];
    540               $api_token = $settings['api_token'];
    541               $processing_days = $settings['processing_days'];
    542 
    543               $response = wp_remote_post($url, array(
    544                   'headers' => array(
    545                     'content-type' => 'application/json',
    546                     'X-Delyvax-Access-Token' => $api_token,
    547                     'X-Delyvax-Wp-Version' => DELYVAX_PLUGIN_VERSION,
    548                   ),
    549                   'body' => json_encode($postRequestArr),
    550                   'method' => 'PATCH',
    551                   'timeout' => 25
    552               ));
    553 
    554               if (is_wp_error($response)) {
    555                   $error_message = $response->get_error_message();
    556                   if ($error_message == 'fsocket timed out') {
    557                       throw new Exception("Sorry, unable to process shipment, please try again later");
    558                   } else {
    559                       throw new Exception("Sorry, something went wrong with the API. If the problem persists, please contact us!");
    560                   }
    561               } else {
    562                   if ($response['response']['code'] == 200) {
    563                       $body = json_decode($response['body'], true);
    564                       return $body['data'];
    565                   } else {
    566                       $body = json_decode($response['body'], true);
    567                       $order->update_meta_data( 'DelyvaXError', $body['error']['message'] );
    568                       $order->save();
    569                       throw new Exception("Error: ".$body['error']['message'].". Sorry, something went wrong with the API. If the problem persists, please contact us!");
    570                   }
    571               }
    572               ///
    573         }
    574522       
    575523    }
  • delyvax/trunk/includes/delyvax-shipping.php

    r3184993 r3210380  
    583583                        {
    584584                            $store_name = $store_info['store_name'];
    585                             $store_first_name = $store_info['first_name'];
    586                             $store_last_name = $store_info['last_name'];
    587585                            $store_phone = $store_info['phone'];
    588586                            $store_email = $store_info['email'];
     
    610608                    {
    611609                        $store_name = $store_info['store_name'];
    612                         $store_first_name = $store_info['store_name'];
    613                         $store_last_name = $store_info['store_name'];
    614610                        $store_phone = $store_info['phone'];
    615611                        $store_email = $store_info['store_email'] ? $store_info['store_email'] : $store_info['customer_support']['email'];
     
    632628                $store_name = marketking()->get_store_name_display($vendor_id);             
    633629                // $store_name = get_user_meta($vendor_id, 'marketking_store_name', true);
    634                 $store_first_name = get_user_meta($vendor_id, 'billing_first_name', true);
    635                 $store_last_name = get_user_meta($vendor_id, 'billing_last_name', true);
    636630                $store_phone = get_user_meta($vendor_id, 'billing_phone', true);
    637631                // $store_email = get_user_meta($vendor_id, 'billing_email', true);
  • delyvax/trunk/readme.txt

    r3184993 r3210380  
    33Tags: delyva, shipping, delivery, courier
    44Requires at least: 5.4
    5 Tested up to: 6.1
    6 Stable tag: 1.1.57
     5Tested up to: 6.7
     6Stable tag: 1.1.58
    77Requires PHP: 7.2
    88License: GPLv3
     
    3232
    3333== Changelog ==
     34
     35= 1.1.58 =
     36*Release Date - 19th December 2024*
     37
     38* Major update: Migrated to MS2781 order API implementation
     39* Fix: Failed to create order when timezone is set to UTC
     40* Enhanced: Optimized order creation process
    3441
    3542= 1.1.57 =
Note: See TracChangeset for help on using the changeset viewer.