· 6 years ago · Nov 25, 2019, 02:44 AM
1<?php
2
3use Tygh\Registry;
4use Tygh\Shippings\Shippings;
5
6#region SHIPPINGS
7
8/**
9 * Returns available shipping method.
10 * @param integer $profile_id : To get shipping destinations
11 * @param array $products : List of products
12 * product_id
13 * product_options
14 * amount
15 * @return array List of available shipping method.
16 */
17function fn_my_hartono_custom_get_available_shipping_methods($profile_id, $products, $excluded_type = [])
18{
19 $result = array();
20
21 if (!empty($products)) {
22
23 // get available destination
24 $user_profile = fn_my_hartono_get_user_profile_by_id($profile_id);
25 $location = fn_my_hartono_custom_get_customer_location($user_profile);
26
27 // product grouping
28 // $product_ids = array_column($products, 'product_id');
29 $__products = fn_my_hartono_custom_get_multiple_products($products);
30 foreach ($__products as &$p1) {
31 foreach ($products as $p2) {
32 if ($p1['product_id'] == $p2['product_id']) {
33 $p1['amount'] = $p2['amount'];
34 $p1['hartono_delivery_product_number'] = $p2['hartono_delivery_product_number'];
35 break;
36 }
37 }
38 }
39 $product_groups = fn_my_hartono_group_product_list($__products, $location);
40
41 $excluded_ids = array();
42 $shippings = array();
43 foreach ($product_groups as $key_group => $group) {
44 $product_groups[$key_group]['shippings'] = array();
45 $shippings_group = fn_my_hartono_get_shippings_list($group);
46
47 foreach ($shippings_group as $shipping_id => $shipping) {
48 $_shipping = $shipping;
49
50 if (!in_array($_shipping['type'], $excluded_type)) {
51
52 if (!empty($shipping['service_params']['max_weight_of_box'])) {
53 $_group = Shippings::repackProductsByWeight($group, $shipping['service_params']['max_weight_of_box']);
54 } else {
55 $_group = $group;
56 }
57
58 $_shipping['package_info'] = $_group['package_info'];
59 $_shipping['package_info_full'] = $_group['package_info_full'];
60 $_shipping['keys'] = array(
61 'group_key' => $key_group,
62 'shipping_id' => $shipping_id,
63 );
64 $shippings[] = $_shipping;
65 if ($_shipping['type'] == 'click_and_collect' || $_shipping['type'] == 'instant_collect') {
66 $excluded_ids[] = $_shipping['shipping_id'];
67 }
68
69 $shipping['group_key'] = $key_group;
70 $shipping['rate'] = 0;
71
72 // shipping is free when obtained via promotions, or group has free shipping and shipping method is suitable for free shipping
73 $shipping['free_shipping'] = ($group['free_shipping'] && Shippings::isFreeShipping($shipping));
74
75 $shipping['image'] = fn_get_image_pairs($shipping_id, 'shipping', 'M');
76 $product_groups[$key_group]['shippings'][$shipping_id] = $shipping;
77 # code...
78 }
79 }
80 }
81
82 $rates = fn_my_hartono_calculate_rates($shippings);
83
84 foreach ($rates as $rate) {
85 $g_key = $rate['keys']['group_key'];
86 $sh_id = $rate['keys']['shipping_id'];
87
88 if ($rate['price'] !== false) {
89 $rate['price'] += !empty($product_groups[$g_key]['package_info']['shipping_freight']) ? $product_groups[$g_key]['package_info']['shipping_freight'] : 0;
90 $product_groups[$g_key]['shippings'][$sh_id]['rate'] = empty($product_groups[$g_key]['shippings'][$sh_id]['free_shipping']) ? $rate['price'] : 0;
91 } else {
92 if (!in_array($sh_id, $excluded_ids)) {
93 unset($product_groups[$g_key]['shippings'][$sh_id]);
94 }
95 }
96
97 if (!empty($rate["gosend_status"])) {
98 $product_groups[$g_key]['shippings'][$sh_id]['gosend_status'] = $rate["gosend_status"];
99 }
100
101 // if (!empty($rate['service_delivery_time'])) {
102 // $product_groups[$g_key]['shippings'][$sh_id]['service_delivery_time'] = $rate['service_delivery_time'];
103 // }
104 }
105 $result = reset($product_groups);
106 // $result['destination_id'] = $destination_id;
107 }
108
109 return $result;
110}
111
112/**
113 *
114 */
115function fn_my_hartono_custom_get_shipping_rate($shipping, $origin_code, $destination_id, $weight = 1)
116{
117 $vendor_id = $shipping['vendor_id'];
118 $shipping_vendor = fn_my_hartono_get_shipping_vendor($vendor_id);
119 $rate = array();
120
121 if ($shipping_vendor['use_api']) {
122 if ($shipping_vendor['identifier'] == "si_cepat") {
123 // origin mapping
124 $origin = $origin_code == "SBY" ? "SUB" : "-";
125
126 // check if weight is less than 5 kg and shipping type is cargo
127 // if true, this shipping method not available for user
128 if ($weight < 5 && $shipping['identifier'] == "Cargo") {
129 return $rate;
130 }
131
132 // get data from si cepat api
133 $get_success = true;
134 $vendor_destination = fn_my_hartono_get_shipping_vendor_destination($vendor_id, $destination_id);
135 $destination_code = empty($vendor_destination) ? "-" : $vendor_destination['destination_code'];
136
137 session_start();
138 $rate_list = $_SESSION["si_cepat_rate"];
139
140 if (empty($rate_list)) {
141
142 $service_url = $shipping_vendor['additional_data']['get_rate_url']
143 . '?api-key=' . $shipping_vendor['api_key']
144 . '&origin=' . $origin
145 . '&destination=' . $destination_code
146 . '&weight=' . $weight;
147 $curl = curl_init($service_url);
148 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
149 $curl_response = curl_exec($curl);
150 if ($curl_response === false) {
151 // $info = curl_getinfo($curl);
152 curl_close($curl);
153 return $rate;
154 }
155
156 curl_close($curl);
157 $response = json_decode($curl_response, true);
158 $response = $response['sicepat'];
159 if (isset($response['status']) && $response['status']['code'] != 200) {
160 return $rate;
161 }
162
163 if ($get_success) {
164 $rate_list = $response['results'];
165 $_SESSION["si_cepat_rate"] = $rate_list;
166 } else {
167 $rate_list = array();
168 }
169 }
170
171 for ($i = 0; $i < count($rate_list); $i++) {
172 if ($shipping['identifier'] == $rate_list[$i]['service']) {
173 $rate = array(
174 "rate" => $rate_list[$i]['tariff'],
175 "etd" => $rate_list[$i]['etd']
176 );
177 break;
178 }
179 }
180 } else {
181 $vendor_destination = fn_my_hartono_get_shipping_vendor_destination($vendor_id, $destination_id);
182 if (isset($vendor_destination['rate']) && $vendor_destination['rate'] > 0) {
183 $rate = array(
184 "rate" => $vendor_destination['rate'],
185 "etd" => $shipping['delivery_time']
186 );
187 } else {
188 $rate = null;
189 }
190 }
191 } else {
192 if ($shipping['type'] == "kurir_pilihan_customer") {
193 // $shipping_rate = db_get_row("SELECT * FROM ?:shipping_rates
194 // WHERE shipping_id = ?i", $shipping['shipping_id']);
195 $weight = 1;
196 }
197
198 // else {
199 // $shipping_rate = db_get_row("SELECT * FROM ?:shipping_rates
200 // WHERE destination_id = ?i AND shipping_id = ?i", $destination_id, $shipping['shipping_id']);
201 // }
202
203 $shipping_rate = db_get_row("SELECT * FROM ?:shipping_rates
204 WHERE destination_id = ?i AND shipping_id = ?i", $destination_id, $shipping['shipping_id']);
205
206 if (!empty($shipping_rate) && !empty($shipping_rate['rate_value'])) {
207 $tmp = unserialize($shipping_rate['rate_value']);
208 $selected_rate = null;
209 $weight = $weight == 0 ? 1 : $weight;
210
211 foreach ($tmp['W'] as $w => $r) {
212 if ($weight > $w) {
213 $selected_rate = $r['value'] * $weight;
214 }
215 }
216
217 $rate = array(
218 "rate" => $selected_rate,
219 "etd" => $shipping['delivery_time']
220 );
221 } else {
222 $rate = null;
223 }
224 }
225
226 return $rate;
227}
228
229/**
230 * Get available destination based on location
231 * @param object $location
232 */
233function fn_my_hartono_custom_get_available_destination($location)
234{
235 $destination_id = false;
236
237 $country = !empty($location['country']) ? $location['country'] : '';
238 $state = !empty($location['state']) ? $location['state'] : '';
239 // $city = !empty($location['city']) ? $location['city'] : '';
240 $kecamatan = !empty($location['kecamatan']) ? $location['kecamatan'] : '';
241 $kelurahan = !empty($location['kelurahan']) ? $location['kelurahan'] : '';
242 $zipcode = !empty($location['zipcode']) ? $location['zipcode'] : '';
243 $address = !empty($location['address']) ? $location['address'] : '';
244
245 $as_kelurahan = false;
246 if (!empty($kelurahan)) {
247 $as_kelurahan = true;
248 }
249
250 list($destinations) = fn_my_hartono_custom_get_destinations(array(
251 'country_code' => $country,
252 'state_code' => $state,
253 'kecamatan_code' => $kecamatan,
254 'kelurahan_code' => $kelurahan,
255 'zipcodes' => $zipcode,
256 'addresses' => $address,
257 'as_kelurahan' => $as_kelurahan
258 ));
259
260 if (!empty($destinations)) {
261 $destination_id = 1;
262 foreach ($destinations as $dest) {
263 if ($dest['destination_id'] != '1') {
264 $destination_id = $dest['destination_id'];
265 break;
266 }
267 }
268 }
269
270 return $destination_id;
271}
272
273/**
274 * Get customer location from user profiles
275 * @param object $user_profile : user profile data
276 * @param boolean $billing : flag to get data from billing or shipping
277 */
278function fn_my_hartono_custom_get_customer_location($user_profile, $billing = false)
279{
280 $result = array(
281 "firstname" => $billing ? $user_profile['b_firstname'] : $user_profile['s_firstname'],
282 "lastname" => $billing ? $user_profile['b_lastname'] : $user_profile['s_lastname'],
283 "address" => $billing ? $user_profile['b_address'] : $user_profile['s_address'],
284 "kelurahan" => $billing ? $user_profile['b_kelurahan'] : $user_profile['s_kelurahan'],
285 "kecamatan" => $billing ? $user_profile['b_kecamatan'] : $user_profile['s_kecamatan'],
286 "city" => $billing ? $user_profile['b_city'] : $user_profile['s_city'],
287 "state" => $billing ? $user_profile['b_state'] : $user_profile['s_state'],
288 "country" => $billing ? $user_profile['b_country'] : $user_profile['s_country'],
289 "zipcode" => $billing ? $user_profile['b_zipcode'] : $user_profile['s_zipcode'],
290 "phone" => $billing ? $user_profile['b_phone'] : $user_profile['s_phone'],
291 "country_descr" => $billing ? $user_profile['b_country_name'] : $user_profile['s_country_name'],
292 "state_descr" => $billing ? $user_profile['b_state_name'] : $user_profile['s_state_name'],
293 "kecamatan_descr" => $billing ? $user_profile['b_kecamatan_name'] : $user_profile['s_kecamatan_name'],
294 "kelurahan_descr" => $billing ? $user_profile['b_kelurahan_name'] : $user_profile['s_kelurahan_name'],
295 "address_type" => $billing ? $user_profile['b_address_type'] : $user_profile['s_address_type'],
296 "lat" => $billing ? $user_profile['b_lat'] : $user_profile['s_lat'],
297 "lon" => $billing ? $user_profile['b_lon'] : $user_profile['s_lon']
298 );
299
300 return $result;
301}
302
303function fn_my_hartono_group_product_list($products, $location)
304{
305 $groups = array();
306 foreach ($products as $key_product => $product) {
307 if (fn_allowed_for('ULTIMATE')) {
308 $company_id = Registry::ifGet('runtime.company_id', fn_get_default_company_id());
309 } else {
310 $company_id = $product['company_id'];
311 }
312
313 if (empty($groups[$company_id])) {
314 $origination = fn_my_hartono_get_origin_data($company_id);
315 $groups[$company_id] = array(
316 'name' => $origination['name'],
317 'company_id' => (int) $company_id,
318 'origination' => $origination,
319 'location' => $location,
320 );
321 }
322 // $groups[$company_id]['products'][$product['product_id']] = $product;
323 $groups[$company_id]['products'][$key_product] = $product;
324 }
325
326 foreach ($groups as $key_group => $group) {
327 $groups[$key_group]['package_info'] = fn_my_hartono_get_package_info($group);
328 $groups[$key_group]['package_info_full'] = fn_my_hartono_get_package_info($group, true);
329 unset($groups[$key_group]['origination']);
330 unset($groups[$key_group]['location']);
331
332 $all_edp_free_shipping = true;
333 $all_free_shipping = true;
334 $free_shipping = true;
335 $shipping_no_required = true;
336 $big_product = false;
337 $is_gosend = false;
338 foreach ($group['products'] as $product) {
339 if ($product['is_edp'] != 'Y' || $product['edp_shipping'] == 'Y') {
340 $all_edp_free_shipping = false;
341 // shipping is required when having non-EDP products with shipping
342 if (empty($product['shipping_no_required']) || $product['shipping_no_required'] != 'Y') {
343 $shipping_no_required = false;
344 }
345 if (empty($product['free_shipping']) || $product['free_shipping'] != 'Y') {
346 $free_shipping = false;
347 }
348 if ($product['big_product'] == 1) {
349 $big_product = true;
350 }
351 if ($product['is_gosend'] == 1) {
352 $is_gosend = true;
353 }
354 }
355 if (empty($product['free_shipping']) || $product['free_shipping'] != 'Y') {
356 $all_free_shipping = false;
357 }
358 }
359 $groups[$key_group]['all_edp_free_shipping'] = $all_edp_free_shipping;
360 $groups[$key_group]['all_free_shipping'] = $all_free_shipping;
361 $groups[$key_group]['free_shipping'] = $free_shipping;
362 $groups[$key_group]['shipping_no_required'] = $shipping_no_required;
363 $groups[$key_group]['big_product'] = $big_product;
364 $groups[$key_group]['is_gosend'] = $is_gosend;
365 }
366
367 return array_values($groups);
368}
369
370/**
371 * FIXME: Get origin for shipping. Perlu tambahan origin untuk masing masing shipping method.
372 */
373function fn_my_hartono_get_origin_data($company_id)
374{
375 $data = array();
376
377 if (empty($company_id) || fn_allowed_for('ULTIMATE')) {
378 $data = array(
379 'name' => Registry::get('settings.Company.company_name'),
380 'address' => Registry::get('settings.Company.company_address'),
381 'city' => Registry::get('settings.Company.company_city'),
382 'country' => Registry::get('settings.Company.company_country'),
383 'state' => Registry::get('settings.Company.company_state'),
384 'zipcode' => Registry::get('settings.Company.company_zipcode'),
385 'phone' => Registry::get('settings.Company.company_phone'),
386 'fax' => Registry::get('settings.Company.company_fax'),
387 );
388 } else {
389 $company_data = fn_get_company_data($company_id);
390 $data = array(
391 'name' => $company_data['company'],
392 'address' => $company_data['address'],
393 'city' => $company_data['city'],
394 'country' => $company_data['country'],
395 'state' => $company_data['state'],
396 'zipcode' => $company_data['zipcode'],
397 'phone' => $company_data['phone'],
398 'fax' => $company_data['fax'],
399 );
400 }
401
402 return $data;
403}
404
405/**
406 *
407 */
408function fn_my_hartono_get_package_info($group, $include_free_shipping = false)
409{
410 $package_info = array();
411 $package_info['C'] = 0;
412 $package_info['W'] = 0;
413 $package_info['I'] = 0;
414 $package_info['shipping_freight'] = 0;
415 $package_info['hartono_delivery_product_number'] = 0;
416 $hartono_delivery_applied = false;
417
418 if (is_array($group['products'])) {
419 foreach ($group['products'] as $key_product => $product) {
420 if (($product['is_edp'] == 'Y' && $product['edp_shipping'] != 'Y') || (!empty($product['free_shipping']) && $product['free_shipping'] == 'Y' && !$include_free_shipping)
421 ) {
422 continue;
423 }
424
425 if (!empty($product['exclude_from_calculate'])) {
426 $product_price = 0;
427 } elseif (!empty($product['subtotal'])) {
428 $product_price = $product['subtotal'];
429 } elseif (!empty($product['price'])) {
430 $product_price = $product['price'];
431 } elseif (!empty($product['base_price'])) {
432 $product_price = $product['base_price'];
433 } else {
434 $product_price = 0;
435 }
436
437 if ($include_free_shipping || !(!empty($product['free_shipping']) && $product['free_shipping'] == 'Y')) {
438 if (empty($product['exclude_from_calculate'])) {
439 $package_info['C'] += $product_price;
440 $package_info['W'] += !empty($product['weight']) ? $product['weight'] * $product['amount'] : 0;
441 }
442 $package_info['I'] += $product['amount'];
443 if (!empty($product['hartono_delivery_product_number']) && !$hartono_delivery_applied) {
444 $package_info['hartono_delivery_product_number'] += $product['hartono_delivery_product_number'];
445 $hartono_delivery_applied = true;
446 }
447
448 if (isset($product['shipping_freight'])) {
449 $package_info['shipping_freight'] += $product['shipping_freight'] * $product['amount'];
450 }
451 }
452 }
453 }
454
455 $package_info['W'] = !empty($package_info['W']) ? sprintf("%.3f", $package_info['W']) : '1';
456
457 $package_groups = array(
458 'personal' => array(),
459 'global' => array(
460 'products' => array(),
461 'amount' => 0,
462 ),
463 );
464
465 foreach ($group['products'] as $cart_id => $product) {
466 $free_or_simple_edp = ($product['is_edp'] == 'Y' && $product['edp_shipping'] != 'Y') || (!$include_free_shipping && !empty($product['free_shipping']) && $product['free_shipping'] == 'Y');
467
468 if (empty($product['shipping_params']) || (empty($product['shipping_params']['min_items_in_box']) && empty($product['shipping_params']['max_items_in_box']))) {
469 if (!$free_or_simple_edp) {
470 $package_groups['global']['products'][$cart_id] = $product['amount'];
471 $package_groups['global']['amount'] += $product['amount'];
472 }
473 } else {
474 if (!isset($package_groups['personal'][$product['product_id']])) {
475 $package_groups['personal'][$product['product_id']] = array(
476 'shipping_params' => $product['shipping_params'],
477 'amount' => 0,
478 'products' => array(),
479 );
480 }
481
482 if (!$free_or_simple_edp) {
483 $package_groups['personal'][$product['product_id']]['amount'] += $product['amount'];
484 $package_groups['personal'][$product['product_id']]['products'][$cart_id] = $product['amount'];
485 }
486 }
487 }
488
489 // Divide the products into a separate packages
490 $packages = array();
491
492 if (!empty($package_groups['personal'])) {
493 foreach ($package_groups['personal'] as $product_id => $package_products) {
494
495 while ($package_products['amount'] > 0) {
496 if (!empty($package_products['shipping_params']['min_items_in_box']) && $package_products['amount'] < $package_products['shipping_params']['min_items_in_box']) {
497 $full_package_size = 0;
498
499 list($package_products_pack, $package_size) = fn_my_hartono_get_package_by_amount($package_products['amount'], $package_products['products']);
500
501 foreach ($package_products_pack as $cart_id => $amount) {
502 $package_groups['global']['products'][$cart_id] = isset($package_groups['global']['products'][$cart_id]) ? $package_groups['global']['products'][$cart_id] : 0;
503 $package_groups['global']['products'][$cart_id] += $amount;
504 $package_groups['global']['amount'] += $amount;
505
506 $full_package_size += $amount;
507 }
508 } else {
509 $amount = empty($package_products['shipping_params']['max_items_in_box']) ? $package_products['amount'] : $package_products['shipping_params']['max_items_in_box'];
510
511 $pack_products = $package_products['products'];
512 $full_package_size = 0;
513
514 do {
515 list($package_products_pack, $package_size) = fn_my_hartono_get_package_by_amount($amount, $pack_products);
516
517 $packages[] = array(
518 'shipping_params' => $package_products['shipping_params'],
519 'products' => $package_products_pack,
520 'amount' => array_sum($package_products_pack),
521 );
522
523 $full_package_size += array_sum($package_products_pack);
524
525 $package_size -= array_sum($package_products_pack);
526 foreach ($package_products_pack as $cart_id => $_pack_amount) {
527 $pack_products[$cart_id] -= $_pack_amount;
528 if ($pack_products[$cart_id] <= 0) {
529 unset($pack_products[$cart_id]);
530 }
531 }
532 } while ($package_size > 0);
533
534 // Re-check package (amount, min_amount, max_amount)
535 foreach ($packages as $package_id => $package) {
536 $valid = true;
537
538 if (!empty($package['shipping_params']['min_items_in_box']) && $package['amount'] < $package['shipping_params']['min_items_in_box']) {
539 $valid = false;
540 }
541
542 if (!empty($package['shipping_params']['max_items_in_box']) && $package['amount'] > $package['shipping_params']['max_items_in_box']) {
543 $valid = false;
544 }
545
546 if (!$valid) {
547 foreach ($package['products'] as $cart_id => $amount) {
548 if (!isset($package_groups['global']['products'][$cart_id])) {
549 $package_groups['global']['products'][$cart_id] = 0;
550 }
551
552 if (!isset($package_groups['global']['amount'])) {
553 $package_groups['global']['amount'] = 0;
554 }
555
556 $package_groups['global']['products'][$cart_id] += $amount;
557 $package_groups['global']['amount'] += $amount;
558 }
559
560 unset($packages[$package_id]);
561 }
562 }
563 }
564
565 // Decrease the current product amount in the global package groups
566 foreach ($package_products_pack as $cart_id => $amount) {
567 $package_products['products'][$cart_id] -= $amount;
568 }
569 $package_products['amount'] -= $full_package_size;
570 }
571 }
572 }
573
574 if (!empty($package_groups['global']['products'])) {
575 $packages[] = $package_groups['global'];
576 }
577
578 // Calculate the package additional info (weight, cost)
579 foreach ($packages as $package_id => $package) {
580 $weight = 0;
581 $cost = 0;
582
583 foreach ($package['products'] as $cart_id => $amount) {
584 $_weight = !empty($group['products'][$cart_id]['weight']) ? $group['products'][$cart_id]['weight'] : 0;
585 if (!empty($group['products'][$cart_id]['price'])) {
586 $price = $group['products'][$cart_id]['price'];
587 } elseif (!empty($group['products'][$cart_id]['base_price'])) {
588 $price = $group['products'][$cart_id]['base_price'];
589 } else {
590 $price = 0;
591 }
592 $weight += $_weight * $amount;
593 $cost += $price * $amount;
594 }
595
596 $packages[$package_id]['weight'] = !empty($weight) ? $weight : 0.1;
597 $packages[$package_id]['cost'] = $cost;
598 }
599
600 $package_info['packages'] = $packages;
601 $package_info['origination'] = $group['origination'];
602 $package_info['location'] = $group['location'];
603
604 return $package_info;
605}
606
607/**
608 *
609 */
610function fn_my_hartono_get_package_by_amount($amount, $products)
611{
612 $data = array();
613 $package_size = 0;
614
615 foreach ($products as $cart_id => $product_amount) {
616 if ($product_amount == 0 || $amount == 0) {
617 continue;
618 }
619 $data[$cart_id] = min($product_amount, $amount);
620 $package_size += $data[$cart_id];
621 $amount -= $data[$cart_id];
622
623 if ($amount <= 0) {
624 break;
625 }
626 }
627
628 return array($data, $package_size);
629}
630
631/**
632 *
633 */
634function fn_my_hartono_get_company_shippings($company_id)
635{
636 if (fn_allowed_for('ULTIMATE')) {
637 $shippings = db_get_fields("SELECT shipping_id FROM ?:shippings WHERE status = ?s", 'A');
638 } else {
639 $shippings = explode(',', db_get_field("SELECT shippings FROM ?:companies WHERE company_id = ?i", $company_id));
640 $shippings = db_get_fields("SELECT shipping_id FROM ?:shippings WHERE (company_id = ?i OR (company_id = ?i AND shipping_id IN (?n))) AND status = ?s", $company_id, 0, $shippings, 'A');
641 }
642
643 return $shippings;
644}
645
646function fn_my_hartono_get_shippings_list($group, $lang = CART_LANGUAGE, $area = AREA)
647{
648 $shippings = fn_my_hartono_get_company_shippings($group['company_id']);
649 $condition = '';
650
651 $package_weight = $group['package_info_full']['W'];
652 $big_product = $group['big_product'];
653 $is_gosend = $group['is_gosend'];
654
655 $fields = array(
656 "?:shippings.shipping_id",
657 "?:shipping_descriptions.shipping",
658 "?:shipping_descriptions.delivery_time",
659 "?:shipping_descriptions.description",
660 "?:shippings.rate_calculation",
661 "?:shippings.service_params",
662 "?:shippings.destination",
663 "?:shippings.min_weight",
664 "?:shippings.max_weight",
665 "?:shippings.service_id",
666 "?:shippings.free_shipping",
667 "?:shipping_services.module",
668 "?:shipping_services.code as service_code",
669 "?:shippings.type",
670 "?:shippings.identifier",
671 "?:shippings.as_kelurahan",
672 "?:shippings.vendor_id",
673 "?:shippings.time_from",
674 "?:shippings.time_to",
675 "?:shippings.as_kelurahan",
676 "?:shippings.big_product",
677 "?:shippings.is_gosend",
678 "?:shippings.status",
679 "?:shippings.tiket_depo",
680 "sv.name vendor_name",
681 "sv.identifier vendor_identifier",
682 "sv.additional_data vendor_additional_data",
683 "sv.status vendor_status",
684 "sv.use_api vendor_use_api"
685 );
686
687 $join = "LEFT JOIN ?:shipping_descriptions ON ?:shippings.shipping_id = ?:shipping_descriptions.shipping_id ";
688 $join .= "LEFT JOIN ?:shipping_services ON ?:shipping_services.service_id = ?:shippings.service_id ";
689 $join .= "LEFT JOIN ?:hartono_shipping_vendor sv ON ?:shippings.vendor_id = sv.id";
690
691 $condition .= db_quote('?:shippings.status = ?s', 'A');
692 $condition .= db_quote(' AND ?:shippings.shipping_id IN (?n)', $shippings);
693 $condition .= db_quote(' AND (?:shippings.min_weight <= ?d', $package_weight);
694 $condition .= db_quote(' AND (?:shippings.max_weight >= ?d OR ?:shippings.max_weight = 0.00))', $package_weight);
695 $condition .= db_quote(' AND ?:shipping_descriptions.lang_code = ?s', $lang);
696
697 if (!empty($big_product)) {
698 $condition .= db_quote(' AND ?:shippings.big_product = ?i', 1);
699 } else {
700 $condition .= db_quote(' AND ?:shippings.big_product IN (?a)', array(0, 1));
701 }
702 if (!empty($is_gosend)) {
703 $condition .= db_quote(' AND ?:shippings.is_gosend IN (?a)', array(0, 1));
704 } else {
705 $condition .= db_quote(' AND ?:shippings.is_gosend = 0');
706 }
707
708 if ($area == 'C') {
709 $condition .= " AND (" . fn_find_array_in_set(\Tygh::$app['session']['auth']['usergroup_ids'], '?:shippings.usergroup_ids', true) . ")";
710 }
711
712 $order_by = '?:shippings.position';
713 $shippings_info = db_get_hash_array('SELECT ' . implode(', ', $fields) . ' FROM ?:shippings ' . $join . ' WHERE ?p ORDER BY ?p', 'shipping_id', $condition, $order_by);
714 $destination_id = fn_my_hartono_custom_get_available_destination(array(
715 'country' => $group['package_info']['location']['country'],
716 'state' => $group['package_info']['location']['state'],
717 'kecamatan' => $group['package_info']['location']['kecamatan']
718 ));
719 foreach ($shippings_info as $key => $shipping_info) {
720 $rate_info = array();
721
722 if ($shipping_info['vendor_use_api']) {
723 $rate_info = array(
724 "destination_id" => $destination_id,
725 "rate_value" => array(
726 "W" => array(
727 "amount" => 0,
728 "value" => 0,
729 "type" => "F",
730 "per_unit" => "N"
731 )
732 ),
733 );
734 } else {
735 $dest_id = $destination_id;
736 // if ($shipping_info['type'] == "kurir_pilihan_customer") {
737 // $dest_id = 1;
738 // } else
739
740 if ($shipping_info['as_kelurahan'] == 1) {
741 $dest_id = fn_my_hartono_custom_get_available_destination(array(
742 'country' => $group['package_info']['location']['country'],
743 'state' => $group['package_info']['location']['state'],
744 'kecamatan' => $group['package_info']['location']['kecamatan'],
745 'kelurahan' => $group['package_info']['location']['kelurahan']
746 ));
747 }
748
749 $rate_info = db_get_row(
750 "SELECT rate_id, rate_value FROM ?:shipping_rates"
751 . " WHERE shipping_id = ?i AND destination_id = ?i"
752 . " ORDER BY destination_id desc",
753 $shipping_info['shipping_id'],
754 $dest_id
755 );
756 if (!empty($rate_info)) {
757 $rate_info['rate_value'] = unserialize($rate_info['rate_value']);
758 }
759 }
760
761 $shippings_info[$key]['rate_info'] = $rate_info;
762 $shippings_info[$key]['service_params'] = !empty($shippings_info[$key]['service_params']) ? unserialize($shippings_info[$key]['service_params']) : array();
763 $shippings_info[$key]['vendor_additional_data'] = json_decode($shippings_info[$key]['vendor_additional_data'], true);
764 }
765
766 return $shippings_info;
767}
768
769function fn_my_hartono_calculate_rates($shippings)
770{
771 $mode = array(
772 'real' => array(),
773 'manual' => array(),
774 );
775 $rates = array();
776
777 foreach ($shippings as $shipping) {
778 if ($shipping['rate_calculation'] == 'R') {
779 $shipping['keys']['mode_key'] = count($mode['real']);
780 $mode['real'][] = $shipping;
781 } else {
782 $shipping['keys']['mode_key'] = count($mode['manual']);
783 $mode['manual'][] = $shipping;
784 }
785 }
786
787 if (!empty($mode['manual'])) {
788 foreach ($mode['manual'] as $shipping) {
789 if ($shipping['type'] == 'click_and_collect' || $shipping['type'] == 'instant_collect') {
790 $rate = 0;
791 } else {
792 $rate = fn_my_hartono_calculate_manual_rate($shipping);
793 }
794 unset($shipping['keys']['mode_key']);
795 $rate_data = array(
796 'price' => $rate,
797 'keys' => !empty($shipping['keys']) ? $shipping['keys'] : array(),
798 );
799
800 // -1 untuk gosend yang berarti lat long empty
801 if ($shipping['vendor_identifier'] == 'go_send' && $rate == -1) {
802 $rate_data['price'] = 0;
803 $rate_data['gosend_status'] = "LOCATION_EMPTY";
804 }
805 // -2 untuk gosend yang berarti tidak available
806 else if ($shipping['vendor_identifier'] == 'go_send' && $rate == -2) {
807 $rate_data['price'] = 0;
808 $rate_data['gosend_status'] = "NOT_AVAILABLE";
809 }
810 // -3 untuk gosend yang berarti tidak available
811 else if ($shipping['vendor_identifier'] == 'go_send' && $rate == -3) {
812 $rate_data['price'] = 0;
813 $rate_data['gosend_status'] = "CLOSE";
814 }
815
816 $rates[] = $rate_data;
817 }
818 }
819
820 unset($_SESSION["go_send_rate"]);
821 unset($_SESSION["si_cepat_rate"]);
822 return array_values($rates);
823}
824
825function fn_my_hartono_calculate_manual_rate($shipping)
826{
827 if (empty($shipping['rate_info']['rate_value'])) {
828 return false;
829 }
830
831 if (isset($shipping['free_shipping'])) {
832 $free_shipping = $shipping['free_shipping'];
833 } else {
834 $free_shipping = db_get_field("SELECT free_shipping FROM ?:shippings WHERE shipping_id = ?i", $shipping['shipping_id']);
835 }
836 if ($free_shipping == 'Y') {
837 $shipping['package_info'] = $shipping['package_info_full'];
838 }
839 unset($shipping['package_info_full']);
840
841 $base_cost = $shipping['package_info']['C'];
842 $rate = 0;
843
844 foreach ($shipping['package_info'] as $type => $amount) {
845 if($type == 'hartono_delivery_product_number') {
846 continue;
847 }
848 if (isset($shipping['rate_info']['rate_value'][$type]) && is_array($shipping['rate_info']['rate_value'][$type])) {
849 $rate_value = array_reverse($shipping['rate_info']['rate_value'][$type], true);
850
851 if ($shipping['vendor_use_api'] && $type == 'W') {
852 $dest_id = $shipping['rate_info']['destination_id'];
853 if ($shipping['vendor_identifier'] == "si_cepat") {
854 // origin mapping
855 $origin = "SUB";
856 $weight = $amount;
857
858 // check if weight is less than 5 kg and shipping type is cargo
859 // if true, this shipping method not available for user
860 if ($weight < 5 && $shipping['identifier'] == "Cargo") {
861 // return $rate_info;
862 continue;
863 }
864
865 // get data from si cepat api
866 $get_success = true;
867 $vendor_destination = fn_my_hartono_get_shipping_vendor_destination($shipping['vendor_id'], $dest_id);
868 $destination_code = empty($vendor_destination) ? "-" : $vendor_destination['destination_code'];
869
870 session_start();
871 $rate_list = $_SESSION["si_cepat_rate"];
872
873 if (empty($rate_list)) {
874 $service_url = $shipping['vendor_additional_data']['get_rate_url']
875 . '?api-key=' . $shipping['vendor_additional_data']['api_key']
876 . '&origin=' . $origin
877 . '&destination=' . $destination_code
878 . '&weight=' . $weight;
879 $curl = curl_init($service_url);
880 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
881 $curl_response = curl_exec($curl);
882 if ($curl_response === false) {
883 // $info = curl_getinfo($curl);
884 curl_close($curl);
885 // return $rate_info;
886 continue;
887 }
888
889 curl_close($curl);
890 $response = json_decode($curl_response, true);
891 $response = $response['sicepat'];
892 if (isset($response['status']) && $response['status']['code'] != 200) {
893 // return $rate_info;
894 continue;
895 }
896
897 if ($get_success) {
898 $rate_list = $response['results'];
899 $_SESSION["si_cepat_rate"] = $rate_list;
900 } else {
901 $rate_list = array();
902 }
903 }
904
905 for ($i = 0; $i < count($rate_list); $i++) {
906 if ($shipping['identifier'] == $rate_list[$i]['service']) {
907 $rate = $rate_list[$i]['tariff'];
908 break;
909 }
910 }
911 } else if ($shipping['vendor_identifier'] == "go_send") {
912 date_default_timezone_set('Asia/Jakarta');
913 $curr_date = strtotime(date('Y-m-d H:i'));
914 $date_from = strtotime(date('Y-m-d') . ' ' . $shipping['time_from']);
915 $date_to = strtotime(date('Y-m-d') . ' ' . $shipping['time_to']);
916
917 if ($curr_date >= $date_from && $curr_date <= $date_to) {
918 $rate = fn_my_hartono_get_gosend_rate($shipping);
919 } else {
920 $rate = -2;
921 }
922 }
923 } else {
924 if ($shipping['type'] == 'hartono_delivery') {
925 $base_rate = [];
926 $hartono_delivery_product_number = 0;
927 if($type == 'I' && !empty($shipping['package_info']['hartono_delivery_product_number'])) {
928 $hartono_delivery_product_number = $shipping['package_info']['hartono_delivery_product_number'];
929 // $tmp_amount = $shipping['package_info']['hartono_delivery_product_number'];
930 }
931
932 // first product and qty 1
933 if ($hartono_delivery_product_number == 1 && $amount == 1) {
934 $tmp_amount = 1;
935 } else if ($hartono_delivery_product_number == 1 && $amount > 1) {
936 $base_rate = $rate_value[0];
937 $tmp_amount = $amount;
938 if($type == 'I') {
939 $amount -= 1;
940 }
941 } else { // others
942 $tmp_amount = $hartono_delivery_product_number;
943 }
944
945 foreach ($rate_value as $rate_amount => $data) {
946 if ($rate_amount < $tmp_amount || ($rate_amount == 0.00 && $tmp_amount == 0.00)) {
947 $value = $data['type'] == 'F' ? $data['value'] : (($base_cost * $data['value']) / 100);
948 $per_unit = (!empty($data['per_unit']) && $data['per_unit'] == 'Y') ? $amount : 1;
949 $rate += $value * $per_unit;
950 // $rate += $value;
951
952 if (!empty($base_rate)) {
953 $base_value = $base_rate['type'] == 'F' ? $base_rate['value'] : (($base_cost * $base_rate['value']) / 100);
954 $rate += $base_value;
955 }
956
957 break;
958 }
959 }
960 } else {
961 foreach ($rate_value as $rate_amount => $data) {
962 if ($rate_amount < $amount || ($rate_amount == 0.00 && $amount == 0.00)) {
963 $value = $data['type'] == 'F' ? $data['value'] : (($base_cost * $data['value']) / 100);
964 $per_unit = (!empty($data['per_unit']) && $data['per_unit'] == 'Y') ? $shipping['package_info'][$type] : 1;
965 $rate += $value * $per_unit;
966
967 break;
968 }
969 }
970 }
971 }
972 }
973 }
974
975 // $tiket_depo = db_get_field("SELECT tiket_depo FROM ?:shippings WHERE shipping_id = ?i", $shipping['shipping_id']);
976 if (!empty($$shipping['tiket_depo'])) {
977 $rate += $$shipping['tiket_depo'];
978 }
979
980 return fn_format_price($rate);
981}
982
983#endregion
984
985#region SHIPPING VENDOR
986
987function fn_my_hartono_get_shipping_vendor_destination($vendor_id, $destination_id)
988{
989 $result = null;
990
991 if (isset($vendor_id) && isset($destination_id)) {
992 $result = db_get_row("SELECT * FROM ?:hartono_shipping_vendor_destinations " .
993 " WHERE shipping_vendor_id = ?i AND destination_id = ?i ", $vendor_id, $destination_id);
994 }
995
996 return $result;
997}
998
999#region Shipping Vendor
1000
1001function fn_my_hartono_get_all_shipping_vendor($params = array())
1002{
1003 $conditions = '1';
1004 $pagination = db_quote('');
1005
1006 if (!empty($params['name'])) {
1007 $conditions .= " AND name LIKE " . "'%" . $params['name'] . "%' ";
1008 }
1009
1010 $page = $params['page'];
1011 $items_per_page = $params['items_per_page'];
1012 if (!empty($page) && !empty($items_per_page)) {
1013 $pagination = db_quote(" LIMIT ?i OFFSET ?i ", $items_per_page, ($page - 1) * $items_per_page);
1014 }
1015
1016 $result = db_get_array("SELECT * FROM ?:hartono_shipping_vendor
1017 WHERE ?p
1018 ORDER BY name
1019 $pagination
1020 ", $conditions);
1021
1022 $total = db_get_field("SELECT count(id) FROM ?:hartono_shipping_vendor
1023 WHERE ?p ", $conditions);
1024
1025 return array(
1026 "result" => $result,
1027 "page" => $page,
1028 "items_per_page" => $items_per_page,
1029 "total_items" => $total
1030 );
1031}
1032
1033function fn_my_hartono_get_shipping_vendor($vendor_id)
1034{
1035 $result = null;
1036
1037 if (isset($vendor_id)) {
1038 $result = db_get_row('SELECT * FROM ?:hartono_shipping_vendor where id = ?i ', $vendor_id);
1039 $result['additional_data'] = json_decode($result['additional_data']);
1040 }
1041
1042 return $result;
1043}
1044
1045function fn_my_hartono_add_new_shipping_vendor($data)
1046{
1047 $shipping_vendor = array(
1048 "name" => $data['name'],
1049 "identifier" => $data['identifier'],
1050 "use_api" => !empty($data['use_api']),
1051 "additional_data" => json_encode($data['additional_data']),
1052 "status" => "A"
1053 );
1054
1055 // result = 'shipping vendor id'
1056 $result = db_query('INSERT INTO ?:hartono_shipping_vendor ?e', $shipping_vendor);
1057 return $result;
1058}
1059
1060function fn_my_hartono_update_shipping_vendor($id, $data)
1061{
1062 $success = false;
1063 $shipping_vendor = array();
1064
1065 if (isset($data['name'])) {
1066 $shipping_vendor['name'] = $data['name'];
1067 }
1068 if (isset($data['use_api'])) {
1069 $shipping_vendor['use_api'] = $data['use_api'];
1070 }
1071 if (isset($data['identifier'])) {
1072 $shipping_vendor['identifier'] = $data['identifier'];
1073 }
1074 if (isset($data['additional_data'])) {
1075 $shipping_vendor['additional_data'] = json_encode($data['additional_data']);
1076 }
1077 if (isset($data['status'])) {
1078 $shipping_vendor['status'] = $data['status'];
1079 }
1080
1081 if (isset($id)) {
1082 $result = db_query('UPDATE ?:hartono_shipping_vendor SET ?u WHERE id = ?i', $shipping_vendor, $id);
1083 if ($result > 0) {
1084 $success = true;
1085 }
1086 }
1087
1088 return $success;
1089}
1090
1091function fn_my_hartono_delete_shipping_vendor($vendor_id)
1092{
1093 $result = db_query('DELETE FROM ?:hartono_shipping_vendor WHERE id = ?i', $vendor_id);
1094 return $result;
1095}
1096
1097#endregion
1098
1099#region Si Cepat
1100
1101// Function untuk update data terbaru dari vendor, mengambil data dari API yang disediakan oleh masing masing vendor
1102function fn_my_hartono_update_shipping_destination_from_sicepat_api($vendor_id)
1103{
1104 $shipping_vendor = fn_my_hartono_get_shipping_vendor($vendor_id);
1105
1106 // get destination list from api
1107 $get_success = true;
1108 $destination_list = array();
1109
1110 $service_url = $shipping_vendor['additional_data']['get_destination_url'] . '?api-key=' . $shipping_vendor['api_key'];
1111 $curl = curl_init($service_url);
1112 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
1113 $curl_response = curl_exec($curl);
1114 if ($curl_response === false) {
1115 // $info = curl_getinfo($curl);
1116 curl_close($curl);
1117 return false;
1118 }
1119
1120 curl_close($curl);
1121 $response = json_decode($curl_response, true);
1122 $response = $response['sicepat'];
1123 if (isset($response['status']) && $response['status']['code'] != 200) {
1124 return false;
1125 }
1126
1127 if ($get_success) {
1128 $destination_list = $response['results'];
1129 }
1130 // get destination list from api
1131
1132 // loop semua destinasi, cek apakah udah ada di table location, kalau belum di add
1133
1134 $selected_province = "";
1135 $selected_city = "";
1136 $selected_district = "";
1137
1138 foreach ($destination_list as $dest) {
1139 // add province if empty
1140 if ($selected_province != $dest['province']) {
1141 $selected_province = $dest['province'];
1142 list($countries) = fn_get_countries(array('country_codes' => array($selected_province)));
1143 if (count($countries) == 0) {
1144 // add new countries aka province
1145 $new_province = array(
1146 "code" => $dest['province'],
1147 "code_A3" => "",
1148 "code_N3" => "",
1149 "region" => "AS",
1150 "lat" => 0,
1151 "lon" => 0,
1152 "status" => "A"
1153 );
1154 $new_province_desc = array(
1155 "code" => $dest['province'],
1156 "lang_code" => DEFAULT_LANGUAGE,
1157 "country" => $dest['province'],
1158 );
1159 db_query("INSERT INTO ?:countries ?e", $new_province);
1160 db_query("INSERT INTO ?:country_descriptions ?e", $new_province_desc);
1161 }
1162 }
1163
1164 // add city if empty
1165 if ($selected_city != $dest['city']) {
1166 $selected_city = $dest['city'];
1167 // list($states) = fn_get_states(array("q" => $selected_city, "country_code" => $selected_province));
1168 $state = db_get_row("SELECT * FROM ?:state_descriptions WHERE state = ?s ", $selected_city);
1169 if (!isset($state) || empty($state)) {
1170 // add new state aka city
1171 $new_city = array(
1172 "country_code" => $dest['province'],
1173 "code" => $dest['city'],
1174 "status" => "A"
1175 );
1176 $state_id = db_query("INSERT INTO ?:states ?e", $new_city);
1177 $new_city_desc = array(
1178 "state_id" => $state_id,
1179 "lang_code" => DEFAULT_LANGUAGE,
1180 "state" => $dest['city'],
1181 );
1182 db_query("INSERT INTO ?:state_descriptions ?e", $new_city_desc);
1183 }
1184 }
1185
1186 // add district if empty
1187 if ($selected_district != $dest['subdistrict']) {
1188 $selected_district = $dest['subdistrict'];
1189
1190 $district = db_get_row("SELECT * FROM ?:hartono_districts WHERE district = ?s ", $selected_district);
1191 $state = db_get_row("SELECT * FROM ?:state_descriptions WHERE state = ?s ", $selected_city);
1192
1193 if (!isset($district) || empty($district)) {
1194 $new_district = array(
1195 "state_id" => $state['state_id'],
1196 "district" => $selected_district,
1197 "status" => "A"
1198 );
1199 db_query("INSERT INTO ?:hartono_districts ?e", $new_district);
1200 }
1201
1202 $destination = db_get_row("SELECT * FROM ?:destination_descriptions WHERE destination = ?s ", $selected_district);
1203 if (!isset($destination) || empty($destination)) {
1204 $new_destination = array(
1205 "destination" => $selected_district,
1206 "status" => "A",
1207 "countries" => array($selected_province),
1208 "states" => array($state['state_id']),
1209 "zipcodes" => "",
1210 "cities" => $selected_district,
1211 "addresses" => ""
1212 );
1213 $destination_id = fn_update_destination($new_destination, null, DESCR_SL);
1214
1215 $new_vendor_destination = array(
1216 "shipping_vendor_id" => $vendor_id,
1217 "destination_id" => $destination_id,
1218 "destination_code" => $dest['destination_code']
1219 );
1220 db_query("INSERT INTO ?:hartono_shipping_vendor_destinations ?e", $new_vendor_destination);
1221 }
1222 }
1223 }
1224
1225 // list($countries) = fn_get_countries(array('country_codes' => array('IM', 'CW')));
1226 // return array();
1227
1228 return true;
1229}
1230
1231#endregion
1232
1233#endregion
1234
1235#region customer own courier
1236
1237function fn_my_hartono_get_customer_own_courier_info($id)
1238{
1239 $result = null;
1240
1241 if (isset($id)) {
1242 $result = db_get_row('SELECT * FROM ?:hartono_customer_own_courier where id = ?i ', $id);
1243 }
1244
1245 return $result;
1246}
1247
1248function fn_my_hartono_get_customer_own_courier($params)
1249{
1250 if (!empty($params)) {
1251 $result = db_get_array("SELECT coc.*,
1252 IFNULL(kls.kelurahan, '') as kelurahan,
1253 IFNULL(kcs.kecamatan, '') as kecamatan,
1254 IFNULL(sds.state, '') as state,
1255 IFNULL(cds.country, '') as country
1256 FROM ?:hartono_customer_own_courier coc
1257 LEFT JOIN ?:country_descriptions cds ON cds.code = coc.country_code
1258 LEFT JOIN ?:states ss ON ss.code = coc.state_code
1259 JOIN ?:state_descriptions sds ON sds.state_id = ss.state_id
1260 LEFT JOIN ?:hartono_kecamatan kcs ON kcs.kecamatan_code = coc.kecamatan_code
1261 LEFT JOIN ?:hartono_kelurahan kls ON kls.code = coc.kelurahan_code
1262 where ?w ", $params);
1263 } else {
1264 $result = db_get_array("SELECT coc.*
1265 IFNULL(kls.kelurahan, ''),
1266 IFNULL(kcs.kecamatan, ''),
1267 IFNULL(sds.state, '') as state,
1268 IFNULL(cds.country, '') as country
1269 FROM ?:hartono_customer_own_courier coc
1270 LEFT JOIN ?:country_descriptions cds ON cds.code = coc.country_code
1271 LEFT JOIN ?:states ss ON ss.code = coc.state_code
1272 JOIN ?:state_descriptions sds ON sds.state_id = ss.state_id
1273 LEFT JOIN ?:hartono_kecamatan kcs ON kcs.kecamatan_code = coc.kecamatan_code
1274 LEFT JOIN ?:hartono_kelurahan kls ON kls.code = coc.kelurahan_code ");
1275 }
1276
1277 return $result;
1278}
1279
1280function fn_my_hartono_get_distinct_customer_own_courier($params)
1281{
1282 if (!empty($params)) {
1283 $result = db_get_array('SELECT DISTINCT courier FROM ?:hartono_customer_own_courier where ?w ORDER BY courier', $params);
1284 } else {
1285 $result = db_get_array('SELECT DISTINCT courier FROM ?:hartono_customer_own_courier ORDER BY courier');
1286 }
1287
1288 return $result;
1289}
1290
1291function fn_my_hartono_add_customer_own_courier($params)
1292{
1293 try {
1294 $data = array(
1295 "user_id" => $params['user_id'],
1296 "nama_ekspedisi" => $params['nama_ekspedisi'],
1297 "alamat_ekspedisi" => $params['alamat_ekspedisi'],
1298 "phone_number" => $params['phone_number'],
1299 "pic" => $params['pic'],
1300 "notes" => $params['notes'],
1301 "country_code" => $params['country_code'],
1302 "state_code" => $params['state_code'],
1303 "kecamatan_code" => $params['kecamatan_code'],
1304 "kelurahan_code" => $params['kelurahan_code'],
1305 // "kelurahan" => $params['kelurahan'],
1306 "kelurahan" => empty($params['kelurahan']) ? "" : $params['kelurahan'],
1307 );
1308 $result = db_query('INSERT INTO ?:hartono_customer_own_courier ?e', $data);
1309 return $result;
1310 } catch (\Throwable $th) {
1311 fn_my_hartono_log_data("E", "OTHERS", "Kurir Pilihan Customer", "Add new customer own courier failed", $th);
1312 return false;
1313 }
1314}
1315
1316function fn_my_hartono_update_customer_own_courier($params, $customer_own_courier_id)
1317{
1318 // $data = array(
1319 // "user_id" => $params['user_id'],
1320 // "nama_ekspedisi" => $params['nama_ekspedisi'],
1321 // "alamat_ekspedisi" => $params['alamat_ekspedisi'],
1322 // "phone_number" => $params['phone_number'],
1323 // "pic" => $params['pic'],
1324 // "notes" => $params['notes']
1325 // );
1326
1327 $data = $params;
1328
1329 $result = db_query('UPDATE ?:hartono_customer_own_courier SET ?u WHERE id = ?i', $data, $customer_own_courier_id);
1330 return $result;
1331}
1332
1333function fn_my_hartono_delete_customer_own_courier($id)
1334{
1335 try {
1336 $success = false;
1337 $result = db_query('DELETE FROM ?:hartono_customer_own_courier WHERE id = ?i ', $id);
1338 if ($result > 0) {
1339 $success = true;
1340 }
1341
1342 return $success;
1343 } catch (\Throwable $th) {
1344 fn_my_hartono_log_data("E", "OTHERS", "Kurir Pilihan Customer", "Delete customer own courier failed", $th);
1345 return false;
1346 }
1347}
1348
1349#endregion
1350
1351#region HOOKS
1352
1353// HOOKS : fn_update_shipping
1354function fn_my_hartono_update_shipping(&$shipping_data, $shipping_id, $lang_code)
1355{
1356 $shipping_data['as_kelurahan'] = !empty($shipping_data['as_kelurahan']);
1357}
1358
1359#endregion
1360
1361#region Go-Send
1362function fn_my_hartono_get_gosend_rate($shipping)
1363{
1364 $rate = 0;
1365 // get data from gosend api
1366 $cust_location = $shipping["package_info"]["location"];
1367 $dest_lat = $cust_location["lat"];
1368 $dest_lon = $cust_location["lon"];
1369 if (!empty($dest_lat) && !empty($dest_lon)) {
1370 $hartono_store_location = fn_my_hartono_get_available_gosend_store_location($dest_lat, $dest_lon);
1371 $origin_lat = $hartono_store_location["lat"];
1372 $origin_lon = $hartono_store_location["lon"];
1373
1374 if (!empty($hartono_store_location) && !empty($origin_lat) && !empty($origin_lon)) {
1375 session_start();
1376 $go_send_rate = $_SESSION["go_send_rate"];
1377
1378 if (empty($go_send_rate)) {
1379 $additional_data = $shipping["vendor_additional_data"];
1380 $api_key = $additional_data["api_key"];
1381 $client_id = $additional_data["client_id"];
1382 $rate_url = $additional_data["get_rate_url"];
1383
1384 $header = array(
1385 "Accept: application/json",
1386 "client-id: " . $client_id,
1387 "pass-key: " . $api_key
1388 );
1389
1390 $service_url = $rate_url
1391 . '?origin=' . $origin_lat . ',' . $origin_lon
1392 . '&destination=' . $dest_lat . ',' . $dest_lon;
1393 $curl = curl_init($service_url);
1394 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
1395 curl_setopt($curl, CURLOPT_HEADER, false);
1396 curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
1397
1398 $curl_response = curl_exec($curl);
1399 if ($curl_response === false) {
1400 curl_close($curl);
1401 $rate = -2;
1402 return $rate;
1403 } else {
1404 curl_close($curl);
1405 $response = json_decode($curl_response, true);
1406
1407 if ($response == false) {
1408 $rate = -2;
1409 return $rate;
1410 } else {
1411 $go_send_rate = $response;
1412 $_SESSION["go_send_rate"] = $go_send_rate;
1413 }
1414 }
1415 }
1416
1417 if ($shipping['identifier'] == "instant") {
1418 if ($go_send_rate['Instant']['serviceable'] && $go_send_rate['Instant']['active']) {
1419 $rate = $go_send_rate['Instant']['price']['total_price'];
1420 } else {
1421 $rate = -2;
1422 }
1423 } else if ($shipping['identifier'] == "sameday") {
1424 if ($go_send_rate['SameDay']['serviceable'] && $go_send_rate['SameDay']['active']) {
1425 $rate = $go_send_rate['SameDay']['price']['total_price'];
1426 } else {
1427 $rate = -2;
1428 }
1429 }
1430 } else {
1431 $rate = -2;
1432 }
1433 } else {
1434 $rate = -1;
1435 }
1436
1437 return $rate;
1438}
1439
1440function fn_my_hartono_get_available_gosend_store_location($lat, $lon)
1441{
1442 $result = db_get_row("SELECT (6371*acos(cos(radians(" . $lat . "))*cos(radians(`latitude`))*cos(radians(`longitude`)-radians(" . $lon . "))+sin(radians(" . $lat . "))*sin(radians(`latitude`)))) AS distance,
1443 l.store_name, l.location_id, l.longitude as lon, l.latitude as lat, s.gosend_radius
1444 FROM ?:hartono_locations l
1445 JOIN ?:hartono_store s ON s.location = l.location_id
1446 WHERE l.service_center = 'N' AND s.gosend_default_location = 1
1447
1448 ORDER BY distance ASC ");
1449
1450 // HAVING distance <= gosend_radius
1451 return $result;
1452}
1453
1454function fn_my_hartono_order_gosend($order_id)
1455{
1456 $order_data = db_get_row("SELECT o.user_id, o.profile_id, o.shipping_ids, s.identifier, gl.*, sv.additional_data
1457 FROM ?:orders o
1458 JOIN ?:shippings s ON s.shipping_id = o.shipping_ids
1459 JOIN ?:hartono_shipping_vendor sv ON sv.id = s.vendor_id
1460 JOIN ?:hartono_gosend_logs gl ON gl.order_id = o.order_id
1461 WHERE o.order_id = ?i AND sv.identifier = 'go_send' ", $order_id);
1462 if (!empty($order_data)) {
1463 $user_data = fn_my_hartono_get_user_profile_by_id($order_data['profile_id']);
1464 $order_data['user_data'] = $user_data;
1465
1466 $store_data = db_get_row('SELECT s.*, l.address
1467 FROM ?:hartono_store s
1468 JOIN ?:hartono_locations l ON s.location = l.location_id
1469 WHERE s.store_code = ?s ', $order_data['origin_store_code']);
1470 $order_data['store_data'] = $store_data;
1471
1472 $products = db_get_array("SELECT product_code, price FROM ?:order_details WHERE order_id = ?i ", $order_id);
1473 $order_data['products'] = $products;
1474
1475 $order_data['additional_data'] = json_decode($order_data['additional_data'], true);
1476
1477 $items = "";
1478 $total_price = 0;
1479 $pcount = count($order_data['products']);
1480 for ($i = 0; $i < $pcount; $i++) {
1481 $p = $order_data['products'][$i];
1482 $items .= preg_replace('/[\x00-\x1f]/', ' ', $p['product_code']);
1483 $total_price += $p['price'];
1484 if ($i < $pcount - 1) {
1485 $items .= ",";
1486 }
1487 }
1488
1489 $gosend_data = array(
1490 "paymentType" => "3",
1491 "collection_location" => "pickup",
1492 "shipment_method" => $order_data['identifier'] == "instant" ? "Instant" : "SameDay",
1493 "routes" => array(
1494 array(
1495 "originName" => $order_data['store_data']['gosend_name'],
1496 "originNote" => $order_data['origin_note'],
1497 "originContactName" => $order_data['store_data']['gosend_contact_name'],
1498 "originContactPhone" => $order_data['store_data']['gosend_contact_phone'],
1499 "originLatLong" => $order_data['origin_lat'] . ',' . $order_data['origin_lon'],
1500 "originAddress" => $order_data['store_data']['address'],
1501 "destinationName" => "",
1502 "destinationNote" => "",
1503 "destinationContactName" => $order_data['user_data']['s_firstname'] . ' ' . $order_data['user_data']['s_lastname'],
1504 "destinationContactPhone" => $order_data['user_data']['s_phone'],
1505 "destinationLatLong" => $order_data['destination_lat'] . ',' . $order_data['destination_lon'],
1506 "destinationAddress" => $order_data['user_data']['s_address'] . " " .
1507 $order_data['user_data']['s_kelurahan_name'] . ", " .
1508 $order_data['user_data']['s_kecamatan_name'] . ", " .
1509 $order_data['user_data']['s_state_name'] . ", " .
1510 $order_data['user_data']['s_country_name'],
1511 "item" => $items,
1512 "storeOrderId" => $order_data['order_id'],
1513 "insuranceDetails" => array(
1514 "applied" => "true",
1515 "fee" => "2500",
1516 "product_description" => $items,
1517 "product_price" => (string) $total_price
1518 )
1519 )
1520 ),
1521 );
1522
1523 $curl = curl_init();
1524 curl_setopt_array($curl, array(
1525 CURLOPT_URL => $order_data['additional_data']['booking_url'],
1526 CURLOPT_RETURNTRANSFER => true,
1527 CURLOPT_ENCODING => "",
1528 CURLOPT_MAXREDIRS => 10,
1529 CURLOPT_TIMEOUT => 300,
1530 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
1531 CURLOPT_CUSTOMREQUEST => "POST",
1532 CURLOPT_POSTFIELDS => json_encode($gosend_data),
1533 CURLOPT_HTTPHEADER => array(
1534 "Content-Type: application/json",
1535 "Client-ID: " . $order_data['additional_data']['client_id'],
1536 "Pass-Key: " . $order_data['additional_data']['api_key']
1537 ),
1538 ));
1539
1540 // $info = curl_getinfo($curl);
1541 $response = curl_exec($curl);
1542 curl_close($curl);
1543
1544 $gosend_result = json_decode($response, true);
1545
1546 $gosend_log = array(
1547 "data_sent" => json_encode($gosend_data),
1548 "data_response" => json_encode($gosend_result),
1549 "status" => "FAILED"
1550 );
1551 if (!empty($gosend_result) && empty($gosend_result['errors'])) {
1552 $tracking_data = fn_my_hartono_track_gosend(array(
1553 "tracking_url" => $order_data['additional_data']['tracking_url'] . "/" . $gosend_result['orderNo'],
1554 "client_id" => $order_data['additional_data']['client_id'],
1555 "api_key" => $order_data['additional_data']['api_key'],
1556 ));
1557
1558 $orderCreatedTime = new DateTime($tracking_data['orderCreatedTime']);
1559 $status_list = array();
1560 $status_list[] = array(
1561 "status" => $tracking_data['status'],
1562 "timestamp" => $orderCreatedTime->format('d-m-Y H:i')
1563 );
1564
1565 $gosend_log["bookingType"] = $tracking_data['bookingType'];
1566 $gosend_log["order_no"] = $gosend_result['orderNo'];
1567 $gosend_log["status"] = "CREATED";
1568 $gosend_log["latest_gosend_status"] = $tracking_data['status'];
1569 $gosend_log["cost"] = $tracking_data['totalPrice'];
1570 $gosend_log["status_list"] = json_encode((array) $status_list);
1571 $gosend_log["live_tracking_url"] = $tracking_data['liveTrackingUrl'];
1572 }
1573
1574 db_query("UPDATE ?:hartono_gosend_logs SET ?u WHERE order_id = ?i ", $gosend_log, $order_data['order_id']);
1575 }
1576}
1577
1578function fn_my_hartono_refresh_gosend_tracking_result($order_id)
1579{
1580 $vendor_data = db_get_row("SELECT * FROM ?:hartono_shipping_vendor WHERE identifier = 'go_send' ");
1581 $vendor_data['additional_data'] = json_decode($vendor_data['additional_data'], true);
1582
1583 $log_data = db_get_row("SELECT order_id, order_no, status_list, status, latest_gosend_status
1584 FROM ?:hartono_gosend_logs WHERE order_id = ?i", $order_id);
1585
1586 $tracking_data = fn_my_hartono_track_gosend(array(
1587 "tracking_url" => $vendor_data['additional_data']['tracking_url'] . "/" . $log_data['order_no'],
1588 "client_id" => $vendor_data['additional_data']['client_id'],
1589 "api_key" => $vendor_data['additional_data']['api_key'],
1590 ));
1591
1592 // Finding Driver
1593 // Enroute Pickup
1594 // Enroute Drop
1595 // On Hold
1596 // Rejected
1597 // Driver not Found
1598 // Cancelled
1599 // Completed
1600
1601 // Finding Driver
1602 // Driver Allocated
1603 // Item Picked
1604 $status_list = json_decode($log_data['status_list'], true);
1605 $latest_gosend_status = $log_data['latest_gosend_status'];
1606 $status = $log_data['status'];
1607 $driver_data = array(
1608 "driver_id" => '',
1609 "driver_name" => '',
1610 "driver_phone" => '',
1611 "driver_photo" => '',
1612 "vehicle_number" => '',
1613 );
1614 $receiver_name = "";
1615
1616 if ($tracking_data['status'] != $latest_gosend_status) {
1617 $latest_gosend_status = $tracking_data['status'];
1618
1619 if (empty($status_list)) {
1620 $status_list = array();
1621 }
1622
1623 switch ($tracking_data['status']) {
1624 case 'Finding Driver':
1625 $orderTime = new DateTime($tracking_data['orderCreatedTime']);
1626 $status_list[] = array(
1627 "status" => $tracking_data['status'],
1628 "timestamp" => $orderTime->format('d-m-Y H:i')
1629 );
1630 $status = "CREATED";
1631 break;
1632 case 'Driver Allocated': // sameDay
1633 $orderTime = new DateTime(date('d-m-Y H:i'));
1634 $status_list[] = array(
1635 "status" => $tracking_data['status'],
1636 "timestamp" => $orderTime->format('d-m-Y H:i')
1637 );
1638 $driver_data = array(
1639 "driver_id" => $tracking_data['driverId'],
1640 "driver_name" => $tracking_data['driverName'],
1641 "driver_phone" => $tracking_data['driverPhone'],
1642 "driver_photo" => $tracking_data['driverPhoto'],
1643 "vehicle_number" => $tracking_data['vehicleNumber'],
1644 );
1645 $status = "PICKUP";
1646 break;
1647 case 'Enroute Pickup':
1648 $orderTime = new DateTime($tracking_data['orderDispatchTime']);
1649 $status_list[] = array(
1650 "status" => $tracking_data['status'],
1651 "timestamp" => $orderTime->format('d-m-Y H:i')
1652 );
1653 $driver_data = array(
1654 "driver_id" => $tracking_data['driverId'],
1655 "driver_name" => $tracking_data['driverName'],
1656 "driver_phone" => $tracking_data['driverPhone'],
1657 "driver_photo" => $tracking_data['driverPhoto'],
1658 "vehicle_number" => $tracking_data['vehicleNumber'],
1659 );
1660 $status = "PICKUP";
1661 break;
1662 case 'Item Picked': // sameDay
1663 $orderTime = new DateTime($tracking_data['orderArrivalTime']);
1664 $status_list[] = array(
1665 "status" => $tracking_data['status'],
1666 "timestamp" => $orderTime->format('d-m-Y H:i')
1667 );
1668 $status = "PICKUP";
1669 break;
1670
1671 case 'Enroute Drop':
1672 $orderTime = new DateTime($tracking_data['orderArrivalTime']);
1673 $status_list[] = array(
1674 "status" => $tracking_data['status'],
1675 "timestamp" => $orderTime->format('d-m-Y H:i')
1676 );
1677 $status = "SEND";
1678 break;
1679 case 'On Hold':
1680 $orderTime = new DateTime(date('d-m-Y H:i'));
1681 $status_list[] = array(
1682 "status" => $tracking_data['status'],
1683 "timestamp" => $orderTime->format('d-m-Y H:i')
1684 );
1685 $status = "SEND";
1686 break;
1687
1688 case 'Rejected':
1689 $orderTime = new DateTime(date('d-m-Y H:i'));
1690 $status_list[] = array(
1691 "status" => $tracking_data['status'],
1692 "timestamp" => $orderTime->format('d-m-Y H:i')
1693 );
1694 $status = "FAILED";
1695 break;
1696 case 'Driver not found':
1697 $orderTime = new DateTime(date('d-m-Y H:i'));
1698 $status_list[] = array(
1699 "status" => $tracking_data['status'],
1700 "timestamp" => $orderTime->format('d-m-Y H:i')
1701 );
1702 $status = "FAILED";
1703 break;
1704 case 'Cancelled':
1705 $orderTime = new DateTime(date('d-m-Y H:i'));
1706 $status_list[] = array(
1707 "status" => $tracking_data['status'],
1708 "timestamp" => $orderTime->format('d-m-Y H:i')
1709 );
1710 $status = "FAILED";
1711 break;
1712 case 'Completed':
1713 $orderTime = new DateTime($tracking_data['orderClosedTime']);
1714 $status_list[] = array(
1715 "status" => $tracking_data['status'],
1716 "timestamp" => $orderTime->format('d-m-Y H:i')
1717 );
1718 $status = "SUCCESS";
1719 $receiver_name = $tracking_data['receiverName'];
1720 break;
1721 default:
1722 break;
1723 }
1724 }
1725
1726 $status_list = json_encode($status_list);
1727 db_query("UPDATE ?:hartono_gosend_logs SET ?u WHERE order_id = ?i ", array(
1728 'status_list' => $status_list,
1729 'latest_gosend_status' => $latest_gosend_status,
1730 'status' => $status,
1731 'receiver_name' => $receiver_name,
1732 'driver_id' => $driver_data['driverId'],
1733 'driver_name' => $driver_data['driverName'],
1734 'driver_phone' => $driver_data['driverPhone'],
1735 'driver_photo' => $driver_data['driverPhoto'],
1736 'vehicle_number' => $driver_data['vehicleNumber'],
1737 ), $log_data['order_id']);
1738}
1739
1740function fn_my_hartono_track_gosend($data)
1741{
1742 $curl = curl_init();
1743 curl_setopt_array($curl, array(
1744 CURLOPT_URL => $data['tracking_url'],
1745 CURLOPT_RETURNTRANSFER => true,
1746 CURLOPT_ENCODING => "",
1747 CURLOPT_MAXREDIRS => 10,
1748 CURLOPT_TIMEOUT => 300,
1749 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
1750 CURLOPT_CUSTOMREQUEST => "GET",
1751 CURLOPT_HTTPHEADER => array(
1752 "Content-Type: application/json",
1753 "Client-ID: " . $data['client_id'],
1754 "Pass-Key: " . $data['api_key']
1755 ),
1756 ));
1757
1758 // $info = curl_getinfo($curl);
1759 $response = curl_exec($curl);
1760 curl_close($curl);
1761
1762 $gosend_result = json_decode($response, true);
1763
1764 return $gosend_result;
1765}
1766
1767function fn_my_hartono_cancel_order_gosend($order_id)
1768{
1769 $order_data = db_get_row(
1770 "SELECT o.user_id, o.profile_id, o.shipping_ids, s.identifier, gl.*, sv.additional_data
1771 FROM ?:orders o
1772 JOIN ?:shippings s ON s.shipping_id = o.shipping_ids
1773 JOIN ?:hartono_shipping_vendor sv ON sv.id = s.vendor_id
1774 JOIN ?:hartono_gosend_logs gl ON gl.order_id = o.order_id
1775 WHERE o.order_id = ?i AND sv.identifier = 'go_send' ",
1776 $order_id
1777 );
1778
1779 if (!empty($order_data)) {
1780 $gosend_data = array(
1781 'orderNo' => $order_data['order_no']
1782 );
1783 $additional_data = json_decode($order_data['additional_data'], true);
1784
1785 $curl = curl_init();
1786 curl_setopt_array($curl, array(
1787 CURLOPT_URL => $additional_data['cancel_url'],
1788 CURLOPT_RETURNTRANSFER => true,
1789 CURLOPT_ENCODING => "",
1790 CURLOPT_MAXREDIRS => 10,
1791 CURLOPT_TIMEOUT => 300,
1792 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
1793 CURLOPT_CUSTOMREQUEST => "PUT",
1794 CURLOPT_POSTFIELDS => json_encode($gosend_data),
1795 CURLOPT_HTTPHEADER => array(
1796 "Content-Type: application/json",
1797 "Client-ID: " . $additional_data['client_id'],
1798 "Pass-Key: " . $additional_data['api_key']
1799 ),
1800 ));
1801
1802 $curl_response = curl_exec($curl);
1803 curl_close($curl);
1804
1805 if ($curl_response) {
1806 $status_list = json_decode($order_data['status_list'], true);
1807
1808 $orderTime = new DateTime(date('d-m-Y H:i'));
1809 $status_list[] = array(
1810 "status" => "Cancelled",
1811 "timestamp" => $orderTime->format('d-m-Y H:i')
1812 );
1813
1814 $gosend_log["status"] = "FAILED";
1815 $gosend_log["status_list"] = json_encode($status_list);
1816 $gosend_log["latest_gosend_status"] = "Cancelled";
1817
1818 db_query("UPDATE ?:hartono_gosend_logs SET ?u WHERE order_id = ?i ", $gosend_log, $order_data['order_id']);
1819 }
1820 }
1821}
1822
1823#endregion
1824
1825function fn_my_hartono_get_customer_own_courier_by_user_id($params)
1826{
1827 $customer_own_courier_id = $params;
1828 $res = db_get_row(
1829 "SELECT hc.*, hkl.kelurahan, hkl.kode_pos, hkc.kecamatan, sd.state FROM ?:hartono_customer_own_courier hc
1830 LEFT JOIN ?:hartono_kelurahan hkl ON hkl.code = hc.kelurahan_code
1831 LEFT JOIN ?:hartono_kecamatan hkc ON hkc.kecamatan_code = hc.kecamatan_code
1832 LEFT JOIN ?:states s ON s.code = hc.state_code
1833 LEFT JOIN ?:state_descriptions sd ON sd.state_id = s.state_id
1834 WHERE id = ?i",
1835 $customer_own_courier_id
1836 );
1837
1838 return $res;
1839}
1840
1841function fn_my_hartono_list_customer_own_courier_info_by_user_id($params)
1842{
1843 $customer_own_courier_id = $params;
1844 $res = db_get_array(
1845 "SELECT hc.*, cd.country, hkl.kelurahan, hkl.kode_pos, hkc.kecamatan, sd.state FROM ?:hartono_customer_own_courier hc
1846 LEFT JOIN ?:hartono_kelurahan hkl ON hkl.code = hc.kelurahan_code
1847 LEFT JOIN ?:hartono_kecamatan hkc ON hkc.kecamatan_code = hc.kecamatan_code
1848 LEFT JOIN ?:states s ON s.code = hc.state_code
1849 LEFT JOIN ?:state_descriptions sd ON sd.state_id = s.state_id
1850 LEFT JOIN ?:country_descriptions cd ON cd.code = hc.country_code
1851 WHERE user_id = ?i",
1852 $customer_own_courier_id
1853 );
1854
1855 return $res;
1856}
1857
1858function fn_my_hartono_remapping_shipping_methods_by_usergroups_id($profile_id, $shippings)
1859{
1860 $user_id = db_get_field("SELECT user_id FROM ?:user_profiles WHERE profile_id = ?i", $profile_id);
1861 $user_group_ids = db_get_fields("SELECT usergroup_id FROM ?:usergroup_links WHERE user_id = ?i AND `status` = ?s", $user_id, 'A');
1862
1863 // re-mapping available shipping method
1864 $shipping_ids = array_column($shippings['shippings'], 'shipping_id');
1865 $list_shippings = db_get_array("SELECT shipping_id, usergroup_ids FROM ?:shippings WHERE shipping_id IN (?a)", $shipping_ids);
1866 foreach ($list_shippings as $ls) {
1867 if ($ls['usergroup_ids'] == '0') {
1868 $valid_shipping_ids[$ls['shipping_id']] = true;
1869
1870 } elseif ($ls['usergroup_ids'] == '1') {
1871 $valid_shipping_ids[$ls['shipping_id']] = true;
1872
1873 } elseif ($ls['usergroup_ids'] == '2') {
1874 $valid_shipping_ids[$ls['shipping_id']] = true;
1875
1876 } elseif ($ls['usergroup_ids'] == '0,1') {
1877 $valid_shipping_ids[$ls['shipping_id']] = true;
1878
1879 } elseif ($ls['usergroup_ids'] == '0,2') {
1880 $valid_shipping_ids[$ls['shipping_id']] = true;
1881
1882 } elseif ($ls['usergroup_ids'] == '0,1,2') {
1883 $valid_shipping_ids[$ls['shipping_id']] = true;
1884
1885 } elseif ($ls['usergroup_ids'] == '1,2') {
1886 $valid_shipping_ids[$ls['shipping_id']] = true;
1887
1888 } else {
1889 $temp_usergroup_ids = explode(',', $ls['usergroup_ids']);
1890
1891 $valid_shipping_ids[$ls['shipping_id']] = false;
1892 foreach ($user_group_ids as $user_group_id) {
1893 if (in_array($user_group_id, $temp_usergroup_ids)) {
1894 $valid_shipping_ids[$ls['shipping_id']] = true;
1895 }
1896 }
1897 }
1898 }
1899
1900 foreach ($shippings['shippings'] as $k => $s) {
1901 if ($valid_shipping_ids[$s['shipping_id']]) {
1902 $_shippings[] = $s;
1903 }
1904 }
1905
1906 $result = !empty($_shippings) ? $_shippings : array();
1907 return $result;
1908}