PluginProbe
MakeCommerce for WooCommerce / 2.6.2
MakeCommerce for WooCommerce v2.6.2
4.1.0 4.0.8 trunk 1.0 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 2.0.0 2.1.0 2.1.1 2.1.2 2.1.3 2.1.4 2.1.5 2.2.0 2.2.1 2.2.2 All 96 releases
makecommerce / makecommerce-transport.php

makecommerce-transport.php in MakeCommerce for WooCommerce 2.6.2, at makecommerce-transport.php

2,418 lines 107.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 // Parcel machine specific stuff
4 function transport_add_method() {
5
6 // Delete all the wc_ship transient scum, you aren’t wanted around here, move along.
7 // Same as being in shipping debug mode
8 global $wpdb;
9 $transients = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '_transient_wc_ship%'");
10 if (count($transients)) {
11 foreach ($transients as $tr) {
12 $hash = substr($tr, 11);
13 delete_transient($hash);
14 }
15 }
16 $transient_value = get_transient('shipping-transient-version');
17 WC_Cache_Helper::delete_version_transients( $transient_value );
18 if (WC()->session) {
19 WC()->session->set('shipping_for_package', '');
20 }
21
22
23 if ( ! class_exists( 'WC_ParcelMachine_Shipping_Method' ) ) {
24
25 class WC_ParcelMachine_Shipping_Method extends WC_Shipping_Method {
26
27 function __construct($instance_id = 0) {
28 if (!$this->ext) {
29 throw new Exception('Do not call this class directly!');
30 }
31 $this->id = 'parcelmachine_' . mb_strtolower($this->ext);
32 $this->instance_id = absint($instance_id);
33 $this->method_title = $this->name_ext . ' ' . __(' Parcel Machine (MC)', 'wc_makecommerce_domain');
34 // $this->method_description = sprintf(__('Parcel machine transport method for %s', 'wc_makecommerce_domain'), $this->ext);
35 $this->supports = array('shipping-zones', 'instance-settings', 'instance-settings-modal', 'settings');
36 $this->init();
37 $this->check_updates();
38 }
39
40 function check_updates() {
41 if (($cur_ver = get_site_option('wc_mc_version', 0)) < WC_MC_VERSION) {
42 update_site_option('wc_mc_version', WC_MC_VERSION);
43 error_log("Need to update from [{$cur_ver}] to [".WC_MC_VERSION."]");
44 if (WC_MC_VERSION === 2.0) {
45 // Check if omniva / smartpost is enabled and in which countries
46 // Convert to shipping zone
47 foreach (array('parcelmachine_omniva' => 'WC_ParcelMachine_Shipping_Method_Omniva', 'parcelmachine_smartpost' => 'WC_ParcelMachine_Shipping_Method_SmartPost', 'parcelmachine_dpd' => 'WC_ParcelMachine_Shipping_Method_DPD') as $method_name => $method_class) {
48 $transport_class_omniva = new $method_class();
49 if ($transport_class_omniva->enable === 'yes') {
50 $zones = WC_Shipping_Zones::get_zones();
51 if (!empty($transport_class_omniva->countries)) { continue; }
52 foreach ($transport_class_omniva->countries as $ecountry) {
53 $has_ecountry = false;
54 foreach ($zones as $zone) {
55 foreach ($zone['zone_locations'] as $location) {
56 if ($location->code === $ecountry) {
57 $has_ecountry = $zone['zone_id'];
58 foreach ($zone['shipping_methods'] as $method) {
59 if ($method->id === $method_name) {
60 continue 4;
61 }
62 }
63 }
64 }
65 }
66 if (!$has_ecountry) {
67 $zone = new WC_Shipping_Zone();
68 $zone->set_zone_name($ecountry);
69 $zone->add_location($ecountry, 'country');
70 $zone->save();
71 } else {
72 $zone = new WC_Shipping_Zone($has_ecountry);
73 }
74 $instance_id = $zone->add_shipping_method($method_name);
75 $transport_class = new $method_class($instance_id);
76 $price = !empty($transport_class->settings['price_'.strtolower($ecountry)]) ? $transport_class->settings['price_'.strtolower($ecountry)] : 0;
77 $free_shipping_min_amount = !empty($transport_class->settings['free_shipping_min_amount_'.strtolower($ecountry)]) ? $transport_class->settings['free_shipping_min_amount_'.strtolower($ecountry)] : 0;
78 $transport_class->set_post_data(array($transport_class->get_field_key('price') => $price, $transport_class->get_field_key('free_shipping_min_amount') => $free_shipping_min_amount));
79 $transport_class->process_admin_options();
80 }
81 }
82 }
83 }
84 }
85 }
86
87 function init() {
88 $this->init_form_fields();
89 $this->init_settings();
90
91 $this->enable = $this->settings['active'];
92 $this->title = !empty($this->settings['method_name']) ? $this->settings['method_name'] : '';
93 if (defined('ICL_LANGUAGE_CODE') && !empty($this->settings['method_name_'.ICL_LANGUAGE_CODE])) {
94 $this->title = $this->settings['method_name_'.ICL_LANGUAGE_CODE];
95 }
96 if(!$this->title) {
97 $this->title = $this->method_title;
98 }
99 $this->availability = 'specific';
100 $this->countries = !empty($this->settings['countries']) ? $this->settings['countries'] : array();
101 $this->prioritization = $this->settings['prioritization'];
102 $this->free_shipping_min_amount = !empty($this->settings['free_shipping_min_amount']) ? $this->settings['free_shipping_min_amount'] : 0;
103 $this->maximum_weight = (double)$this->settings['maximum_weight'];
104 $this->short_office_names = $this->settings['short_office_names'];
105 $this->order_country = 'unknown';
106 add_action('woocommerce_update_options_shipping_' . $this->id, array(&$this, 'process_admin_options'));
107 add_filter('woocommerce_review_order_after_shipping' , array(&$this, 'add_parcelmachine_checkout_fields'));
108 add_action('woocommerce_checkout_process', array(&$this, 'check_parcelmachine_checkout_fields'));
109 add_action('woocommerce_after_checkout_validation', array(&$this, 'check_parcelmachine_checkout_fields'));
110 add_action('woocommerce_checkout_update_order_meta', array(&$this, 'add_parcelmachine_order_meta'));
111
112 // Woocommerce Multilingual overrides
113 if (is_plugin_active('woocommerce-multilingual/wpml-woocommerce.php')) {
114 add_filter('woocommerce_package_rates', array($this, 'override_label_translation'), 50);
115 add_filter('woocommerce_order_get_items', array($this, 'override_shipping_title_translation'), 50, 2);
116 }
117 }
118
119 public function override_label_translation($rates) {
120 $id_instance = $this->id . ':' . $this->instance_id;
121 if(array_key_exists($id_instance, $rates)) {
122 $rates[$id_instance]->label = $this->title;
123 }
124 return $rates;
125 }
126
127 public function override_shipping_title_translation($items, $order) {
128 foreach ($items as $key => $item) {
129 if($item['type'] == 'shipping') {
130 foreach ($item['item_meta_array'] as $meta) {
131 if ($meta->key === 'method_id') {
132 $tmp = explode(':', $meta->value);
133 if ($tmp[0] == $this->id) {
134 $items[$key]['name'] = $this->title;
135 }
136 }
137 }
138 }
139 }
140 return $items;
141 }
142
143 public function generate_shipping_ui_javascript_html( $key, $data ) { ?>
144 <script type="text/javascript">
145 jQuery(document).ready(function($) {
146 var country_select = $('#woocommerce_parcelmachine_<?php echo strtolower($this->ext); ?>_countries');
147 var prices = [], free_shippings = [];
148 $.each(country_select.find('option'), function(i, option) {
149 prices[$(option).val()] = $('#woocommerce_parcelmachine_<?php echo strtolower($this->ext); ?>_price_' + $(option).val().toLowerCase()).closest('tr');
150 free_shippings[$(option).val()] = $('#woocommerce_parcelmachine_<?php echo strtolower($this->ext); ?>_free_shipping_min_amount_' + $(option).val().toLowerCase()).closest('tr');
151 });
152 country_select.on('change', function(){
153 var countries = $(this).val();
154 if(countries) {
155 hidePrices(countries);
156 }
157 });
158 hidePrices(country_select.val());
159 function hidePrices(countries) {
160 for (var key in prices) {
161 if(countries.indexOf(key) == -1){
162 prices[key].hide();
163 free_shippings[key].hide();
164 } else {
165 prices[key].show();
166 free_shippings[key].show();
167 }
168 }
169 }
170 });
171 </script>
172 <?php }
173
174 function calculate_shipping($package = array()) {
175 $price = isset($this->instance_settings['price']) ? $this->instance_settings['price'] : (isset($this->settings['price_'.$package['destination']['country']]) ? $this->settings['price_'.$package['destination']['country']] : 0);
176
177 $free_shipping_min_amount = $this->instance_settings['free_shipping_min_amount'];
178
179 if ($free_shipping_min_amount && $package['contents_cost'] >= $free_shipping_min_amount) {
180 $price = 0;
181 }
182
183 $free_shipping = true;
184 foreach ($package['contents'] as $line) {
185
186 $free_shipping = get_post_meta($line['product_id'], '_no_shipping_cost', true) === 'yes' ? $free_shipping : false;
187 }
188
189 if($free_shipping) {
190 $price = 0;
191 }
192
193 //check if there is a free shipping coupon (if it's free then allow free shipping)
194 if (isset($package['applied_coupons']) && $this->instance_settings["allow_free_shipping_coupons"] === "yes") {
195 foreach ($package['applied_coupons'] as $coupon_code) {
196 $coupon = new WC_Coupon($coupon_code);
197 if ($coupon->get_free_shipping() === true) {
198 $price = 0;
199 break;
200 }
201 }
202 }
203
204 $rate = array(
205 'id' => $this->get_rate_id(),
206 'label' => $this->title,
207 'cost' => $price,
208 'package' => $package,
209 'calc_tax' => 'per_order',
210 );
211
212 $this->add_rate( $rate );
213 }
214
215 function fits_parcel_machine($package) {
216 foreach ($package['contents'] as $line) {
217 if (get_post_meta($line['product_id'], '_no_parcel_machine', true) === 'yes') {
218 return false;
219 }
220 }
221 return true;
222 }
223
224 function is_available($package) {
225 if (!$this->fits_parcel_machine($package)) {
226 return false;
227 }
228
229 //check if cart weight exceeds max weight
230 if (WC()->cart->cart_contents_weight > $this->maximum_weight) {
231 return false;
232 }
233
234 $is_available = $this->enable === 'yes';
235 if (!$is_available || !mk_is_api_set()) {
236 return false;
237 }
238
239 $this->order_country = $package['destination']['country'];
240 return apply_filters('woocommerce_shipping_' . $this->id . '_is_available', $is_available, $package);
241 }
242
243 function mk_get_machines() {
244 $machines = mk_get_machines($this->ext, $this->order_country);
245 if ($this->prioritization === 'yes') {
246 usort($machines, function($a, $b) {
247 $sortorder = array(
248 'tallinn', 'tartu linn','tartu', 'narva', 'pärnu linn','pärnu', 'viljandi', 'kohtla-järve', 'rakvere', 'maardu', 'sillamäe', 'kuressaare',
249 'helsinki', 'espoo', 'tampere', 'vantaa', 'oulu', 'turku', 'jüväskülä', 'lahti', 'kuopio', 'kouvola',
250 'rīga','riga', 'daugavpils', 'liepāja','liepaja', 'jelgava', 'jūrmala','jurmala', 'ventspils', 'rezekne', 'valmiera', 'jekabpils',
251 'vilnius', 'kaunas', 'klaipeda', 'siauliai', 'panevezys', 'alytus', 'mariampole', 'mazeikiai', 'jonava', 'utena'
252 );
253 $acity = mb_strtolower($a['city']);
254 $bcity = mb_strtolower($b['city']);
255 if (!$acity) { $acity = 'xxxxxxx'; }
256 if (!$bcity) { $bcity = 'xxxxxxx'; }
257 $aidx = array_search($acity, $sortorder);
258 $bidx = array_search($bcity, $sortorder);
259 if ($aidx !== false) {
260 $acity = str_pad($aidx, 4, "0", STR_PAD_LEFT) . '-' . $acity;
261 }
262 if ($bidx !== false) {
263 $bcity = str_pad($bidx, 4, "0", STR_PAD_LEFT) . '-' . $bcity;
264 }
265 $acity .= '-' . mb_strtolower($a['name']);
266 $bcity .= '-' . mb_strtolower($b['name']);
267 return $acity < $bcity ? -1 : 1;
268 });
269 }
270 return $machines;
271 }
272
273 function add_parcelmachine_checkout_fields($fragments) {
274 $this->order_country = WC()->customer->get_shipping_country();
275 $res = '';
276 $res .= '<tr style="display: none;" class="parcel_machine_checkout parcel_machine_checkout_parcelmachine_'.mb_strtolower($this->ext).'">';
277 // echo '<th>' . $this->title . '</th>';
278 // echo '<td>';
279 $res .= '<td colspan="2">';
280 $options = array();
281 $machines = $this->mk_get_machines();
282 $res .= '<p class="form-row" id="'.esc_attr($this->id).'_field">';
283 $res .= '<select class="select" name="'.esc_attr($this->id).'" id="'.esc_attr($this->id).'">';
284 $res .= '<option value="">'.__('-- select parcel machine --', 'wc_makecommerce_domain').'</option>';
285 $pcity = false;
286 foreach ($machines as $machine) {
287 $city = strtolower($machine['city']);
288 if ($city !== $pcity) {
289 if ($pcity) $res .= '</optgroup>';
290 $res .= '<optgroup label="'.$machine['city'].'">';
291 }
292 $mname = $machine['name'];
293 if ($this->short_office_names !== 'yes') $mname .= ' - ' . $machine['city'] . ', ' . $machine['address'];
294 $res .= '<option value="'.esc_attr($machine['carrier'].'||'.$machine['id']).'">'.$mname.'</option>';
295 $pcity = $city;
296 }
297 if ($pcity) $res .= '</optgroup>';
298 $res .= '</select>';
299 $res .= '</p>';
300 $res .= '</td></tr>';
301 echo $res;
302 }
303
304 function check_parcelmachine_checkout_fields() {
305 static $added1 = false;
306 static $added2 = false;
307 $shipping_method = !empty($_POST['shipping_method']) ? $_POST['shipping_method'] : false;
308 if (!empty($shipping_method[0])) { $shipping_method_ext = explode(':', $shipping_method[0]); }
309 if (!$added1 && $shipping_method_ext[0] === $this->id && empty($_POST[$shipping_method_ext[0]])) {
310 wc_add_notice(__('<strong>Parcel machine</strong> is a required field.', 'wc_makecommerce_domain'), 'error');
311 $added1 = true;
312 }
313 if (!$added2 && $shipping_method_ext[0] === $this->id && !$this->valid_phone_number($_POST['billing_phone'])) {
314 wc_add_notice(__('<strong>Parcel machine</strong> can be used with local phone number only. Please specify your phone number with international access code (like +372xxxxxxx)', 'wc_makecommerce_domain'), 'error');
315 $added2 = true;
316 }
317 }
318
319 function valid_phone_number($phone) {
320 $phone = trim($phone);
321 $phone = trim($phone, '+');
322 // Estonia for all
323 if (substr($phone, 0, 4) === '3725' || substr($phone, 0, 1) === '5') { return true; }
324 // Latvia for Omniva +3712
325 if ($this->carrier === 'omniva' && substr($phone, 0, 3) === '371') { return true; }
326 // Lithuania for Omniva
327 if ($this->carrier === 'omniva' && substr($phone, 0, 3) === '370') { return true; }
328 // Finland for Smartpost
329 if ($this->carrier === 'smartpost' && substr($phone, 0, 3) === '358') { return true; }
330 // FI, LT, LV, EE, SE for DPD
331 if ($this->carrier === 'dpd' && (substr($phone, 0, 3) === '358' || substr($phone, 0, 3) === '370' || substr($phone, 0, 3) === '371' || substr($phone, 0, 3) === '372' || substr($phone, 0, 2) === '46')) {
332 return true;
333 }
334 return false;
335 }
336
337 function add_parcelmachine_order_meta($order_id) {
338 $shipping_method = !empty($_POST['shipping_method']) ? $_POST['shipping_method'] : false;
339 if (!empty($shipping_method[0])) { $shipping_method_ext = explode(':', $shipping_method[0]); }
340 if ($shipping_method_ext[0] === $this->id && !empty($_POST[$this->id])) {
341 list($carrier, $machine) = explode('||', $_POST[$this->id]);
342 $machine = mk_get_machine($carrier, $machine);
343 if (!empty($machine['id'])) {
344 update_post_meta($order_id, '_shipping_first_name', get_post_meta($order_id, '_billing_first_name', true));
345 update_post_meta($order_id, '_shipping_last_name', get_post_meta($order_id, '_billing_last_name', true));
346 update_post_meta($order_id, '_shipping_address_1', sanitize_text_field($machine['name']));
347 update_post_meta($order_id, '_shipping_address_2', sanitize_text_field($machine['address']));
348 update_post_meta($order_id, '_shipping_city', sanitize_text_field($machine['city']));
349 update_post_meta($order_id, '_shipping_postcode', '');
350 update_post_meta($order_id, '_parcel_machine', sanitize_text_field($_POST[$this->id]));
351 }
352 }
353 }
354 }
355
356
357
358 $enable = get_option('mk_transport_apt_omniva', 'yes');
359 if ($enable === 'yes') {
360 class WC_ParcelMachine_Shipping_Method_Omniva extends WC_ParcelMachine_Shipping_Method {
361 function __construct($instance_id = 0) {
362 $this->ext = 'Omniva';
363 $this->name_ext = 'Omniva';
364 $this->carrier = 'omniva';
365 $this->type = 'apt';
366 parent::__construct($instance_id);
367 if (is_admin()) {
368 add_action( 'wp_ajax_verify_feature_swc', array(&$this, 'mc_check_feature_swc') );
369 }
370
371 }
372
373
374 public function mc_check_feature_swc() {
375 $status = $this->mc_check_feature('shipments_without_credentials');
376 wp_send_json(array('feature_name' => 'shipments_without_credentials', 'feature_status' => $status));
377 exit;
378 }
379
380
381 public function mc_check_feature($feature_name = '') {
382
383 $feature_enabled = false;
384
385 $request_params = array(
386 'environment' => json_encode(array(
387 'platform' => 'woocommerce '. WC()->version,
388 'module' => 'makecommerce feature_staus_check',
389 )),
390 );
391
392 $MK = mk_get_api();
393 if (!$MK) {
394 return false;
395 }
396
397 try {
398 $shopConfig = $MK->getShopConfig($request_params);
399 $features = $shopConfig->features;
400 } catch (Exception $e) {
401 error_log(print_r($e, 1));
402 return false;
403 }
404
405 if(isset($features)) {
406 foreach($features as $feature) {
407 if ($feature->name == $feature_name) {
408 $feature_enabled = $feature->enabled;
409 }
410
411 }
412 }
413
414 return $feature_enabled;
415 }
416
417
418 function init_form_fields() {
419
420 $this->instance_form_fields = array();
421 $this->instance_form_fields['logo'] = array('type' => 'title', 'description' => __get_logo_html());
422 $this->instance_form_fields['price'] = array(
423 'title' => __('Shipping price', 'wc_makecommerce_domain'),
424 'type' => 'text',
425 'default' => '5.00'
426 );
427 $this->instance_form_fields['free_shipping_min_amount'] = array(
428 'title' => __('Free shipping amount', 'wc_makecommerce_domain'),
429 'type' => 'number',
430 'default' => '0',
431 'desc_tip' => __('(0 means no free shipping)', 'wc_makecommerce_domain'),
432 );
433
434 $this->instance_form_fields['allow_free_shipping_coupons'] = array(
435 'title' => __('Free shipping coupons', 'wc_makecommerce_domain'),
436 'type' => 'checkbox',
437 'default' => 'no',
438 'desc_tip' => __('Allow using free shipping coupons to be used with this method', 'wc_makecommerce_domain'),
439 );
440
441 $this->form_fields = array();
442 $this->form_fields['logo'] = array('type' => 'title', 'description' => __get_logo_html());
443 $this->form_fields['generic'] = array(
444 'type' => 'title',
445 'title' => __('Generic and pricing options', 'wc_makecommerce_domain'),
446 'description' => __('You can always exclude a product from being available for the Parcel Machine delivery by clicking "Does not fit parcel machine" in the product\'s shipping options.', 'wc_makecommerce_domain').'<br>'.__('You can mark there also a product as "Free shipping in parcel machine."', 'wc_makecommerce_domain'),
447 );
448 $this->form_fields['active'] = array(
449 'title' => __('Enable', 'wc_makecommerce_domain'),
450 'type' => 'checkbox',
451 'label' => __('enabled', 'wc_makecommerce_domain'),
452 'default' => 'no',
453 );
454 $this->form_fields['maximum_weight'] = array(
455 'title' => sprintf(__('Maximum weight allowed for shipping (%s)', 'wc_makecommerce_domain'), get_option('woocommerce_weight_unit' )),
456 'type' => 'text',
457 'default' => '30'
458 );
459
460 $this->form_fields['look_and_feel'] = array( 'type' => 'title', 'title' => '<hr><br>'.__('Look and feel options', 'wc_makecommerce_domain'), 'description' => __('Options for presentation on check-out page', 'wc_makecommerce_domain'));
461
462 if ( function_exists('icl_object_id') && !function_exists('pll_languages_list')) {
463 $languages = apply_filters('wpml_active_languages', NULL, 'skip_missing=0');
464 }
465 else if (function_exists('pll_languages_list')) {
466 $pl_locales = pll_languages_list( array('fields'=>'locale') );
467 foreach ($pl_locales as $key => $locale_pl ) {
468 $language = array( 'id' => $key,
469 'code' => $locale_pl) ;
470 $languages[$locale_pl] = $language;
471 }
472 }
473
474 if (empty($languages)) {
475 $this->form_fields['method_name'] = array(
476 'title' => __('Shipping Method Title', 'wc_makecommerce_domain'),
477 'type' => 'text',
478 'default' => __('Omniva Parcel Machine', 'wc_makecommerce_domain')
479 );
480 } else {
481 foreach ($languages as $language_code => $language) {
482 $language_name = !empty($language['translated_name']) ? $language['translated_name'] : $language_code;
483 $defaultName = __('Omniva Parcel Machine', 'wc_makecommerce_domain');
484 switch (substr($language_code, 0, 2)) {
485 case 'et':
486 $defaultName = 'Omniva pakiautomaat';
487 break;
488 case 'ru':
489 $defaultName = 'Omniva посылочный автомат';
490 break;
491 case 'fi':
492 $defaultName = 'Omniva pakettiautomaatti';
493 break;
494 case 'lv':
495 $defaultName = 'Omniva Pakomāts';
496 break;
497 }
498 $this->form_fields['method_name_'.substr($language_code, 0, 2)] = array(
499 'title' => __('Shipping Method Title', 'wc_makecommerce_domain').sprintf(' (%s)', substr($language_code, 0, 2)),
500 'type' => 'text',
501 'default' => $defaultName
502 );
503 }
504 }
505 $this->form_fields['prioritization'] = array(
506 'title' => __('Prioritize', 'wc_makecommerce_domain'),
507 'type' => 'checkbox',
508 'label' => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
509 'default' => 'yes'
510 );
511 $this->form_fields['short_office_names'] = array(
512 'title' => __('Short names', 'wc_makecommerce_domain'),
513 'type' => 'checkbox',
514 'label' => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
515 'default' => 'no'
516 );
517
518 $this->form_fields['api_access'] = array( 'type' => 'title', 'title' => '<hr><br>'.__('API access for', 'wc_makecommerce_domain').' '.$this->ext, 'description' => __('You can automatically register the shipments into Omniva system and print out the package labels right here, at the shop orders view. <br> (see more on <a href="https://makecommerce.net/en/integration-modules/makecommerce-woocommerce-payment-plugin/#carriers-integration">MakeCommerce plugin homepage</a>.)', 'wc_makecommerce_domain'). '<br><br>' .__('If you do not have contract with Ominva, no worries - you can send the parcels using MakeCommerce transport mediation service.<br>The cost of transport will be deducted on your Makecommerce account. See more info and pricing <a href="https://makecommerce.net/service/delivery/">here</a> ', 'wc_makecommerce_domain').'<br>'.__('The service can be enabled in', 'wc_makecommerce_domain').' <a href="https://merchant-test.maksekeskus.ee/features.html">'.__('Merchant Portal', 'wc_makecommerce_domain').'</a>');
519
520 $this->form_fields['use_mk_contract'] = array(
521 'type' => 'select',
522 'title' => __('Contract', 'wc_makecommerce_domain'),
523 'options' => array(
524 false => __('use my own Omniva contract', 'wc_makecommerce_domain'),
525 true => __('use MakeCommerce transport mediation service', 'wc_makecommerce_domain'),
526 ),
527 'default' => false,
528 'description' => '',
529 );
530 $this->form_fields['verify_feature_swc'] = array(
531 'type' => 'verify_feature_swc',
532 'title' => __('Verify service status', 'wc_makecommerce_domain'),
533 'description' => __('You must enable the Transport mediation service before using it.', 'wc_makecommerce_domain'),
534 'desc_tip' => __('This will check if the Transport mediation service has been enabled for your shop.', 'wc_makecommerce_domain'),
535 'placeholder' => __('Verify', 'wc_makecommerce_domain'),
536 );
537 $this->form_fields['service_carrier'] = array(
538 'type' => 'select',
539 'title' => __('Integration country', 'wc_makecommerce_domain'),
540 'options' => array(
541 "OMNIVA" => __('Estonia', 'wc_makecommerce_domain'),
542 "OMNIVA_LV" => __('Latvia', 'wc_makecommerce_domain'),
543 "OMNIVA_LT" => __('Lithuania', 'wc_makecommerce_domain'),
544 ),
545 'default' => "ee",
546 'description' => __("Which country's carrier gave you the credentials", 'wc_makecommerce_domain'),
547 );
548 $this->form_fields['service_user'] = array(
549 'title' => __('Omniva web services username', 'wc_makecommerce_domain'),
550 'type' => 'text',
551 'default' => ''
552 );
553 $this->form_fields['service_password'] = array(
554 'title' => __('Omniva web services password', 'wc_makecommerce_domain'),
555 'type' => 'text',
556 'default' => ''
557 );
558 $this->form_fields['return_address'] = array( 'type' => 'title', 'title' => '<br><br>'.__('Return address', 'wc_makecommerce_domain'), 'description' => __('Return address is printed on parcel labels, and is also used when customer wants to return the parcel', 'wc_makecommerce_domain'));
559 $this->form_fields['shop_name'] = array(
560 'type' => 'text',
561 'title' => __('Shop name', 'wc_makecommerce_domain'),
562 'class' => 'input-text regular-input',
563 );
564 $this->form_fields['shop_phone'] = array(
565 'type' => 'text',
566 'title' => __('Shop phone', 'wc_makecommerce_domain'),
567 'title' => __('Shop phone', 'wc_makecommerce_domain'),
568 'class' => 'input-text regular-input',
569 );
570 $this->form_fields['shop_email'] = array(
571 'type' => 'text',
572 'title' => __('Shop email', 'wc_makecommerce_domain'),
573 'class' => 'input-text regular-input',
574 );
575 $this->form_fields['shop_address_country'] = array(
576 'type' => 'select',
577 'title' => __('Shop address country', 'wc_makecommerce_domain'),
578 'options' => array(
579 'EE' => 'EE',
580 'LV' => 'LV',
581 'LT' => 'LT',
582 ),
583 'default' => 'EE',
584 );
585 $this->form_fields['shop_address_city'] = array(
586 'type' => 'text',
587 'title' => __('Shop address city', 'wc_makecommerce_domain'),
588 'class' => 'input-text regular-input',
589 );
590 $this->form_fields['shop_address_street'] = array(
591 'type' => 'text',
592 'title' => __('Shop address street', 'wc_makecommerce_domain'),
593 'class' => 'input-text regular-input',
594 );
595 $this->form_fields['shop_postal_code'] = array(
596 'type' => 'text',
597 'title' => __('Shop postal code', 'wc_makecommerce_domain'),
598 'class' => 'input-text regular-input',
599 );
600 $this->form_fields['shipping_ui_javascript'] = array(
601 'type' => 'shipping_ui_javascript',
602 );
603
604 }
605
606 public function generate_verify_feature_swc_html( $key, $data ) {
607 $field = $this->get_field_key( $key );
608 $defaults = array(
609 'title' => '',
610 'disabled' => false,
611 'class' => '',
612 'css' => '',
613 'placeholder' => '',
614 'type' => 'text',
615 'desc_tip' => false,
616 'description' => '',
617 'custom_attributes' => array()
618 );
619
620 $data = wp_parse_args( $data, $defaults );
621
622 ob_start();
623 ?>
624
625 <tr valign="top">
626 <th scope="row" class="titledesc">
627 <label for="<?php echo esc_attr( $field ); ?>"><?php echo wp_kses_post( $data['title'] ); ?></label>
628 <?php echo $this->get_tooltip_html( $data ); ?>
629 </th>
630 <td class="forminp">
631 <fieldset>
632 <legend class="screen-reader-text"><span><?php echo wp_kses_post( $data['title'] ); ?></span></legend>
633 <input id="verify_feature_swc" class="button <?php echo esc_attr( $data['class'] ); ?>" type="button" name="<?php echo esc_attr( $field ); ?>" id="<?php echo esc_attr( $field ); ?>" style="<?php echo esc_attr( $data['css'] ); ?>" value="<?php echo esc_attr( $data['placeholder'] ); ?>" placeholder="<?php echo esc_attr( $data['placeholder'] ); ?>" <?php disabled( $data['disabled'], true ); ?> <?php echo $this->get_custom_attribute_html( $data ); ?> />
634 <!-- <br><p><?php echo esc_attr( $data['description'] ); ?></p> -->
635 <script type="text/javascript">
636 jQuery('input#verify_feature_swc').on('click', function() {
637 init_mc_loading();
638 jQuery.ajax({
639 url: '<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php',
640 type: 'POST',
641 data: 'action=verify_feature_swc',
642 success: function (output) {
643 if(output) {
644 if (output.feature_status == true) {
645 alert('<?php echo __('There Transport Mediation service is already enabled for your Shop. \n You are good to go!', 'wc_makecommerce_domain'); ?>');
646 } else {
647 alert('<?php echo __('There Transport Mediation service is NOT ENABLED enabled for your Shop. \n Please go to Merchant Portal to activate it!', 'wc_makecommerce_domain'); ?>');
648 }
649
650 } else {
651 alert('<?php echo __('There was an error with your request. Please try again.', 'wc_makecommerce_domain'); ?>');
652 }
653 },
654 complete: function() { stop_mc_loading(); }
655 });
656 });
657
658 function init_mc_loading() {
659 jQuery('input#verify_feature_swc').attr('disabled', 'disabled');
660 }
661
662 function stop_mc_loading() {
663 jQuery('input#verify_feature_swc').removeAttr('disabled');
664 }
665 </script>
666 </fieldset>
667 </td>
668 </tr>
669 <?php
670
671 return ob_get_clean();
672 }
673
674 }
675 }
676
677 $enable = get_option('mk_transport_apt_dpd', 'yes');
678 if ($enable === 'yes') {
679 class WC_ParcelMachine_Shipping_Method_DPD extends WC_ParcelMachine_Shipping_Method {
680 function __construct($instance_id = 0) {
681 $this->ext = 'DPD';
682 $this->name_ext = 'DPD';
683 $this->carrier = 'dpd';
684 $this->type = 'apt';
685 parent::__construct($instance_id);
686 $this->method_title = __('DPD', 'wc_makecommerce_domain').' '. __('parcel machine', 'wc_makecommerce_domain') .' (MC)';
687 }
688 function init_form_fields() {
689
690 $this->instance_form_fields = array();
691 $this->instance_form_fields['logo'] = array('type' => 'title', 'description' => __get_logo_html());
692 $this->instance_form_fields['price'] = array(
693 'title' => __('Shipping price', 'wc_makecommerce_domain'),
694 'type' => 'text',
695 'default' => '5.00'
696 );
697 $this->instance_form_fields['free_shipping_min_amount'] = array(
698 'title' => __('Free shipping amount', 'wc_makecommerce_domain'),
699 'type' => 'number',
700 'default' => '0',
701 'desc_tip' => __('(0 means no free shipping)', 'wc_makecommerce_domain'),
702 );
703 $this->instance_form_fields['allow_free_shipping_coupons'] = array(
704 'title' => __('Free shipping coupons', 'wc_makecommerce_domain'),
705 'type' => 'checkbox',
706 'default' => 'no',
707 'desc_tip' => __('Allow using free shipping coupons to be used with this method', 'wc_makecommerce_domain'),
708 );
709
710 $this->form_fields = array();
711 $this->form_fields['logo'] = array('type' => 'title', 'description' => __get_logo_html());
712 $this->form_fields['generic'] = array(
713 'type' => 'title',
714 'title' => __('Generic and pricing options', 'wc_makecommerce_domain'),
715 'description' => __('You can always exclude a product from being available for the Parcel Machine delivery by clicking "Does not fit parcel machine" in the product\'s shipping options.', 'wc_makecommerce_domain').'<br>'.__('You can mark there also a product as "Free shipping in parcel machine."', 'wc_makecommerce_domain'),
716 );
717 $this->form_fields['active'] = array(
718 'title' => __('Enable', 'wc_makecommerce_domain'),
719 'type' => 'checkbox',
720 'label' => __('enabled', 'wc_makecommerce_domain'),
721 'default' => 'no',
722 );
723 $this->form_fields['maximum_weight'] = array(
724 'title' => sprintf(__('Maximum weight allowed for shipping (%s)', 'wc_makecommerce_domain'), get_option('woocommerce_weight_unit' )),
725 'type' => 'text',
726 'default' => '30'
727 );
728
729 $this->form_fields['look_and_feel'] = array( 'type' => 'title', 'title' => '<hr><br>'.__('Look and feel options', 'wc_makecommerce_domain'), 'description' => __('Options for presentation on check-out page', 'wc_makecommerce_domain'));
730
731 if ( function_exists('icl_object_id') && !function_exists('pll_languages_list')) {
732 $languages = apply_filters('wpml_active_languages', NULL, 'skip_missing=0');
733 }
734 else if (function_exists('pll_languages_list')) {
735 $pl_locales = pll_languages_list( array('fields'=>'locale') );
736 foreach ($pl_locales as $key => $locale_pl ) {
737 $language = array( 'id' => $key,
738 'code' => $locale_pl) ;
739 $languages[$locale_pl] = $language;
740 }
741 }
742
743 if (empty($languages)) {
744 $this->form_fields['method_name'] = array(
745 'title' => __('Shipping Method Title', 'wc_makecommerce_domain'),
746 'type' => 'text',
747 'default' => __('DPD', 'wc_makecommerce_domain') . ' ' . __('parcel machine', 'wc_makecommerce_domain')
748 );
749 } else {
750 foreach ($languages as $language_code => $language) {
751 $language_name = !empty($language['translated_name']) ? $language['translated_name'] : $language_code;
752 $defaultName = __('DPD', 'wc_makecommerce_domain') . ' ' . __('parcel machine', 'wc_makecommerce_domain');
753 $this->form_fields['method_name_'.substr($language_code, 0, 2)] = array(
754 'title' => __('Shipping Method Title', 'wc_makecommerce_domain').sprintf(' (%s)', substr($language_code, 0, 2)),
755 'type' => 'text',
756 'default' => $defaultName
757 );
758 }
759 }
760 $this->form_fields['prioritization'] = array(
761 'title' => __('Prioritize', 'wc_makecommerce_domain'),
762 'type' => 'checkbox',
763 'label' => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
764 'default' => 'yes'
765 );
766 $this->form_fields['short_office_names'] = array(
767 'title' => __('Short names', 'wc_makecommerce_domain'),
768 'type' => 'checkbox',
769 'label' => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
770 'default' => 'no'
771 );
772 if (mk_wc_version("3.4.0")) $a = 'admin.php?page=wc-settings&tab=advanced&section=mk_api'; else $a = 'admin.php?page=wc-settings&tab=api&section=mk_api';
773 $this->form_fields['api_access'] = array( 'type' => 'title', 'title' => '<hr><br>'.__('API access for', 'wc_makecommerce_domain').' '.$this->ext, 'description' => sprintf(__('You can automatically create shipments into DPD system, DPD will send parcel-labels automatically to your e-mail <br> Please set your InterConnect (IC) account credentials below here. <br>See more details on <a href="https://makecommerce.net/en/integration-modules/makecommerce-woocommerce-payment-plugin/#carriers-integration">MakeCommerce plugin page</a>.', 'wc_makecommerce_domain'), admin_url($a)));
774 $this->form_fields['service_carrier'] = array(
775 'type' => 'select',
776 'title' => __('Integration country', 'wc_makecommerce_domain'),
777 'options' => array(
778 "DPD" => __('Estonia', 'wc_makecommerce_domain'),
779 "DPD_LV" => __('Latvia', 'wc_makecommerce_domain'),
780 "DPD_LT" => __('Lithuania', 'wc_makecommerce_domain'),
781 ),
782 'default' => "ee",
783 'description' => __("Which country's carrier gave you the credentials", 'wc_makecommerce_domain'),
784 );
785 $this->form_fields['service_user'] = array(
786 'title' => __('DPD InterConnect username', 'wc_makecommerce_domain'),
787 'type' => 'text',
788 'default' => ''
789 );
790 $this->form_fields['service_password'] = array(
791 'title' => __('DPD InterConnect password', 'wc_makecommerce_domain'),
792 'type' => 'text',
793 'default' => ''
794 );
795 $this->form_fields['return_address'] = array( 'type' => 'title', 'title' => __('Return address', 'wc_makecommerce_domain'), 'description' => __('Please define return address for DPD shipments', 'wc_makecommerce_domain'));
796 $this->form_fields['shop_name'] = array(
797 'type' => 'text',
798 'title' => __('Shop name', 'wc_makecommerce_domain'),
799 'class' => 'input-text regular-input',
800 );
801 $this->form_fields['shop_phone'] = array(
802 'type' => 'text',
803 'title' => __('Shop phone', 'wc_makecommerce_domain'),
804 'class' => 'input-text regular-input',
805 );
806 $this->form_fields['shop_email'] = array(
807 'type' => 'text',
808 'title' => __('Shop email', 'wc_makecommerce_domain'),
809 'class' => 'input-text regular-input',
810 );
811 $this->form_fields['shop_address_country'] = array(
812 'type' => 'select',
813 'title' => __('Shop address country', 'wc_makecommerce_domain'),
814 'options' => array(
815 'EE' => 'EE',
816 'LV' => 'LV',
817 'LT' => 'LT',
818 ),
819 'default' => 'EE',
820 );
821 $this->form_fields['shop_address_city'] = array(
822 'type' => 'text',
823 'title' => __('Shop address city', 'wc_makecommerce_domain'),
824 'class' => 'input-text regular-input',
825 );
826 $this->form_fields['shop_address_street'] = array(
827 'type' => 'text',
828 'title' => __('Shop address street', 'wc_makecommerce_domain'),
829 'class' => 'input-text regular-input',
830 );
831 $this->form_fields['shop_postal_code'] = array(
832 'type' => 'text',
833 'title' => __('Shop postal code', 'wc_makecommerce_domain'),
834 'class' => 'input-text regular-input',
835 );
836 $this->form_fields['shipping_ui_javascript'] = array(
837 'type' => 'shipping_ui_javascript',
838 );
839 }
840 }
841 }
842
843
844
845
846
847 $enable = get_option('mk_transport_apt_smartpost', 'yes');
848 if ($enable === 'yes') {
849 class WC_ParcelMachine_Shipping_Method_Smartpost extends WC_ParcelMachine_Shipping_Method {
850 function __construct($instance_id = 0) {
851 $this->ext = 'SmartPost';
852 $this->name_ext = 'SmartPOST';
853 $this->carrier = 'smartpost';
854 $this->type = 'apt';
855 parent::__construct($instance_id);
856 }
857 function init_form_fields() {
858
859 global $woocommerce;
860
861 $this->instance_form_fields = array();
862 $this->instance_form_fields['logo'] = array('type' => 'title', 'description' => __get_logo_html());
863
864 $this->instance_form_fields['price'] = array(
865 'title' => __('Shipping price', 'wc_makecommerce_domain'),
866 'type' => 'text',
867 'default' => '5.00'
868 );
869 $this->instance_form_fields['free_shipping_min_amount'] = array(
870 'title' => __('Free shipping amount', 'wc_makecommerce_domain'),
871 'type' => 'number',
872 'default' => '0',
873 'desc_tip' => __('(0 means no free shipping)', 'wc_makecommerce_domain'),
874 );
875 $this->instance_form_fields['allow_free_shipping_coupons'] = array(
876 'title' => __('Free shipping coupons', 'wc_makecommerce_domain'),
877 'type' => 'checkbox',
878 'default' => 'no',
879 'desc_tip' => __('Allow using free shipping coupons to be used with this method', 'wc_makecommerce_domain'),
880 );
881
882 $this->form_fields = array();
883 $this->form_fields['logo'] = array('type' => 'title', 'description' => __get_logo_html());
884 $this->form_fields['generic'] = array(
885 'type' => 'title',
886 'title' => __('Generic and pricing options', 'wc_makecommerce_domain'),
887 'description' => __('You can always exclude a product from being available for the Parcel Machine delivery by clicking "Does not fit parcel machine" in the product\'s shipping options.', 'wc_makecommerce_domain').'<br>'.__('You can mark there also a product as "Free shipping in parcel machine."', 'wc_makecommerce_domain'),
888 );
889
890 $this->form_fields['active'] = array(
891 'title' => __('Enable', 'wc_makecommerce_domain'),
892 'type' => 'checkbox',
893 'label' => __('enabled', 'wc_makecommerce_domain'),
894 'default' => 'no',
895 );
896 $this->form_fields['maximum_weight'] = array(
897 'title' => sprintf(__('Maximum weight allowed for shipping (%s)', 'wc_makecommerce_domain'), get_option('woocommerce_weight_unit' )),
898 'type' => 'text',
899 'default' => '30'
900 );
901
902 $this->form_fields['look_and_feel'] = array( 'type' => 'title', 'title' => '<hr><br>'.__('Look and feel options', 'wc_makecommerce_domain'), 'description' => __('Options for presentation on checkout page', 'wc_makecommerce_domain'));
903
904 if ( function_exists('icl_object_id') && !function_exists('pll_languages_list')) {
905 $languages = apply_filters('wpml_active_languages', NULL, 'skip_missing=0');
906 }
907 else if (function_exists('pll_languages_list')) {
908 $pl_locales = pll_languages_list( array('fields'=>'locale') );
909 foreach ($pl_locales as $key => $locale_pl ) {
910 $language = array( 'id' => $key,
911 'code' => $locale_pl) ;
912 $languages[$locale_pl] = $language;
913 }
914 }
915
916 if (empty($languages)) {
917 $this->form_fields['method_name'] = array(
918 'title' => __('Shipping Method Title', 'wc_makecommerce_domain'),
919 'type' => 'text',
920 'default' => __('SmartPOST Parcel Machine', 'wc_makecommerce_domain')
921 );
922 } else {
923 foreach ($languages as $language_code => $language) {
924 $language_name = !empty($language['translated_name']) ? $language['translated_name'] : $language_code;
925 $defaultName = __('SmartPOST Parcel Machine', 'wc_makecommerce_domain');
926 switch (substr($language_code, 0, 2)) {
927 case 'et':
928 $defaultName = 'SmartPOST pakiautomaat';
929 break;
930 case 'ru':
931 $defaultName = 'SmartPOST посылочный автомат';
932 break;
933 case 'fi':
934 $defaultName = 'SmartPOST pakettiautomaatti';
935 break;
936 case 'lv':
937 $defaultName = 'SmartPOST Pakomāts';
938 break;
939 }
940 $this->form_fields['method_name_'.substr($language_code, 0, 2)] = array(
941 'title' => __('Shipping Method Title', 'wc_makecommerce_domain').sprintf(' (%s)', substr($language_code, 0, 2)),
942 'type' => 'text',
943 'default' => $defaultName
944 );
945 }
946 }
947 $this->form_fields['prioritization'] = array(
948 'title' => __('Prioritize', 'wc_makecommerce_domain'),
949 'type' => 'checkbox',
950 'label' => __('Bigger cities will be on top of list, others sorted alphabetically', 'wc_makecommerce_domain'),
951 'default' => 'yes'
952 );
953 $this->form_fields['short_office_names'] = array(
954 'title' => __('Short names', 'wc_makecommerce_domain'),
955 'type' => 'checkbox',
956 'label' => __('Display only parcel machine names, without addresses', 'wc_makecommerce_domain'),
957 'default' => 'no'
958 );
959 if (mk_wc_version("3.4.0")) $a = 'admin.php?page=wc-settings&tab=advanced&section=mk_api'; else $a = 'admin.php?page=wc-settings&tab=api&section=mk_api';
960 $this->form_fields['api_access'] = array( 'type' => 'title', 'title' => '<hr><br>'.__('API access for', 'wc_makecommerce_domain').' '.$this->ext, 'description' => sprintf(__('You can automatically create shipments into smartpost.ee system and print the out the package labels right here, at the shop orders view. <br> Please set your smartpost.ee account credentials below here. <br>(See more on <a href="https://makecommerce.net/en/integration-modules/makecommerce-woocommerce-payment-plugin/#carriers-integration">MakeCommerce plugin page</a>. Don\'t forget to enable also <a href="%s">MC API keys</a>!)', 'wc_makecommerce_domain'), admin_url($a)));
961 $this->form_fields['service_user'] = array(
962 'title' => __('eservice.smartpost.ee username', 'wc_makecommerce_domain'),
963 'type' => 'text',
964 'default' => ''
965 );
966 $this->form_fields['service_password'] = array(
967 'title' => __('eservice.smartpost.ee password', 'wc_makecommerce_domain'),
968 'type' => 'text',
969 'default' => ''
970 );
971 $this->form_fields['return_address'] = array( 'type' => 'title', 'title' => __('Return address', 'wc_makecommerce_domain'), 'description' => __('Please define return address for SmartPOST shipments (used on parcel labels)', 'wc_makecommerce_domain'));
972 $this->form_fields['shop_name'] = array(
973 'type' => 'text',
974 'title' => __('Shop name', 'wc_makecommerce_domain'),
975 'class' => 'input-text regular-input',
976 );
977 $this->form_fields['shop_phone'] = array(
978 'type' => 'text',
979 'title' => __('Shop phone', 'wc_makecommerce_domain'),
980 'class' => 'input-text regular-input',
981 );
982 $this->form_fields['shop_email'] = array(
983 'type' => 'text',
984 'title' => __('Shop email', 'wc_makecommerce_domain'),
985 'class' => 'input-text regular-input',
986 );
987 $this->form_fields['shipping_ui_javascript'] = array(
988 'type' => 'shipping_ui_javascript',
989 );
990 }
991 }
992 }
993
994 }
995
996 if ( ! class_exists( 'WC_Courier_Shipping_Method' ) ) {
997
998 class WC_Courier_Shipping_Method extends WC_Shipping_Method {
999
1000 public function __construct($instance_id = 0) {
1001 $this->id = 'courier_'.$this->carrier;
1002 $this->type = 'cou';
1003 $this->instance_id = absint($instance_id);
1004 $this->method_title = $this->name_ext .' '.__('courier (MC)', 'wc_makecommerce_domain');
1005 // $this->method_description = sprintf(__('Courier transport method for %s', 'wc_makecommerce_domain'), $this->ext);
1006 $this->supports = array('shipping-zones', 'instance-settings', 'instance-settings-modal', 'settings');
1007 $this->init();
1008 }
1009
1010 public function init() {
1011 $this->init_form_fields();
1012 $this->init_settings();
1013
1014 $this->enable = $this->settings['active'];
1015 if (defined('ICL_LANGUAGE_CODE') && !empty($this->settings['method_name_'.ICL_LANGUAGE_CODE])) {
1016 $this->title = $this->settings['method_name_'.ICL_LANGUAGE_CODE];
1017 } else if (!empty($this->settings['method_name'])) {
1018 $this->title = $this->settings['method_name'];
1019 }
1020 if (empty($this->title)) {
1021 $this->title = $this->method_title;
1022 }
1023 $this->availability = 'specific';
1024 $this->free_shipping_min_amount = !empty($this->settings['free_shipping_min_amount']) ? $this->settings['free_shipping_min_amount'] : 0;
1025 $this->maximum_weight = (double)$this->settings['maximum_weight'];
1026 $this->order_country = 'unknown';
1027 add_action('woocommerce_update_options_shipping_' . $this->id, array(&$this, 'process_admin_options'));
1028 // !!! Commented out for now
1029 // add_filter('woocommerce_order_shipping_to_display_shipped_via', array(&$this, 'add_admin_courier_via_field'));
1030 // add_filter('woocommerce_order_shipping_method', array(&$this, 'add_admin_courier_via_field'));
1031
1032 // Woocommerce Multilingual overrides
1033 if (is_plugin_active('woocommerce-multilingual/wpml-woocommerce.php')) {
1034 add_filter('woocommerce_package_rates', array($this, 'override_label_translation'), 50);
1035 add_filter('woocommerce_order_get_items', array($this, 'override_shipping_title_translation'), 50, 2);
1036 }
1037 }
1038
1039 public function override_label_translation($rates) {
1040 $id_instance = $this->id . ':' . $this->instance_id;
1041 if(array_key_exists($id_instance, $rates)) {
1042 $rates[$id_instance]->label = $this->title;
1043 }
1044 return $rates;
1045 }
1046
1047 public function override_shipping_title_translation($items, $order) {
1048 foreach ($items as $key => $item) {
1049 if($item['type'] == 'shipping') {
1050 foreach ($item['item_meta_array'] as $meta) {
1051 if ($meta->key === 'method_id') {
1052 $tmp = explode(':', $meta->value);
1053 if ($tmp[0] == $this->id) {
1054 $items[$key]['name'] = $this->title;
1055 }
1056 }
1057 }
1058 }
1059 }
1060 return $items;
1061 }
1062
1063 public function calculate_shipping($package = array()) {
1064
1065 $price = $this->instance_settings['price'];
1066
1067 $free_shipping_min_amount = $this->instance_settings['free_shipping_min_amount'];
1068
1069 if ($free_shipping_min_amount && $package['contents_cost'] >= $free_shipping_min_amount) {
1070 $price = 0;
1071 }
1072
1073 //check if there is a free shipping coupon (if it's free then allow free shipping)
1074 if (isset($package['applied_coupons']) && $this->instance_settings["allow_free_shipping_coupons"] === "yes") {
1075 foreach ($package['applied_coupons'] as $coupon_code) {
1076 $coupon = new WC_Coupon($coupon_code);
1077 if ($coupon->get_free_shipping() === true) {
1078 $price = 0;
1079 break;
1080 }
1081 }
1082 }
1083
1084 $rate = array(
1085 'id' => $this->get_rate_id(),
1086 'label' => $this->title,
1087 'cost' => $price,
1088 'package' => $package,
1089 'calc_tax' => 'per_order',
1090 );
1091 $this->add_rate( $rate );
1092 }
1093
1094 public function is_available($package) {
1095 //check if cart weight exceeds max weight
1096 if (WC()->cart->cart_contents_weight > $this->maximum_weight) {
1097 return false;
1098 }
1099
1100 $is_available = $this->enable === 'yes';
1101 if (!$is_available || !mk_is_api_set()) {
1102 return false;
1103 }
1104
1105 $this->order_country = $package['destination']['country'];
1106
1107 return apply_filters('woocommerce_shipping_' . $this->id . '_is_available', $is_available, $package);
1108 }
1109
1110 public function add_admin_courier_via_field($order) {
1111 return ' <small>(via ' . $this->name_ext . ' ' . __('Courier', 'wc_makecommerce_domain') . ')</small>';
1112 }
1113
1114 }
1115
1116
1117 $enable = get_option('mk_transport_courier_omniva', 'yes');
1118 if ($enable === 'yes') {
1119 class WC_Courier_Shipping_Method_Omniva extends WC_Courier_Shipping_Method {
1120
1121 public function __construct($instance_id = 0) {
1122 $this->ext = 'Omniva';
1123 $this->name_ext = 'Omniva';
1124 $this->carrier = 'omniva';
1125 parent::__construct($instance_id);
1126 }
1127
1128 public function init_form_fields() {
1129
1130 global $woocommerce;
1131
1132 $this->instance_form_fields = array();
1133 $this->instance_form_fields['logo'] = array('type' => 'title', 'description' => __get_logo_html());
1134 $this->instance_form_fields['price'] = array(
1135 'title' => __('Shipping price', 'wc_makecommerce_domain'),
1136 'type' => 'text',
1137 'default' => '4.95'
1138 );
1139 $this->instance_form_fields['free_shipping_min_amount'] = array(
1140 'title' => __('Free shipping amount', 'wc_makecommerce_domain'),
1141 'type' => 'number',
1142 'default' => '0',
1143 'desc_tip' => __('(0 means no free shipping)', 'wc_makecommerce_domain'),
1144 );
1145 $this->instance_form_fields['allow_free_shipping_coupons'] = array(
1146 'title' => __('Free shipping coupons', 'wc_makecommerce_domain'),
1147 'type' => 'checkbox',
1148 'default' => 'no',
1149 'desc_tip' => __('Allow using free shipping coupons to be used with this method', 'wc_makecommerce_domain'),
1150 );
1151
1152 $this->form_fields = array();
1153 $this->form_fields['logo'] = array('type' => 'title', 'description' => __get_logo_html());
1154 $this->form_fields['generic'] = array(
1155 'type' => 'title',
1156 'title' => __('Generic and pricing options', 'wc_makecommerce_domain'),
1157 // 'description' => __('', 'wc_makecommerce_domain'),
1158 );
1159 $this->form_fields['active'] = array(
1160 'title' => __('Enable', 'wc_makecommerce_domain'),
1161 'type' => 'checkbox',
1162 'label' => __('enabled', 'wc_makecommerce_domain'),
1163 'default' => 'no',
1164 );
1165 $this->form_fields['maximum_weight'] = array(
1166 'title' => sprintf(__('Maximum weight allowed for shipping (%s)', 'wc_makecommerce_domain'), get_option('woocommerce_weight_unit' )),
1167 'type' => 'text',
1168 'default' => '60'
1169 );
1170
1171 $this->form_fields['look_and_feel'] = array( 'type' => 'title', 'title' => '<hr><br>'.__('Look and feel options', 'wc_makecommerce_domain'), 'description' => __('Options for presentation on check-out page', 'wc_makecommerce_domain'));
1172
1173 if ( function_exists('icl_object_id') && !function_exists('pll_languages_list')) {
1174 $languages = apply_filters('wpml_active_languages', NULL, 'skip_missing=0');
1175 }
1176 else if (function_exists('pll_languages_list')) {
1177 $pl_locales = pll_languages_list( array('fields'=>'locale') );
1178 foreach ($pl_locales as $key => $locale_pl ) {
1179 $language = array( 'id' => $key,
1180 'code' => $locale_pl) ;
1181 $languages[$locale_pl] = $language;
1182 }
1183 }
1184
1185 if (empty($languages)) {
1186 $this->form_fields['method_name'] = array(
1187 'title' => __('Shipping Method Title', 'wc_makecommerce_domain'),
1188 'type' => 'text',
1189 'default' => __('Omniva Courier', 'wc_makecommerce_domain')
1190 );
1191 } else {
1192 foreach ($languages as $language_code => $language) {
1193 $language_name = !empty($language['translated_name']) ? $language['translated_name'] : $language_code;
1194 $defaultName = __('Omniva Courier', 'wc_makecommerce_domain');
1195 switch (substr($language_code, 0, 2)) {
1196 case 'et':
1197 $defaultName = 'Omniva kuller';
1198 break;
1199 case 'ru':
1200 $defaultName = 'Omniva Курьер';
1201 break;
1202 case 'fi':
1203 $defaultName = 'Omniva kuriiri';
1204 break;
1205 case 'lv':
1206 $defaultName = 'Omniva kurjers';
1207 break;
1208 case 'lt':
1209 $defaultName = 'Omniva kurjeris';
1210 break;
1211 }
1212 $this->form_fields['method_name_'.substr($language_code, 0, 2)] = array(
1213 'title' => __('Shipping Method Title', 'wc_makecommerce_domain').sprintf(' (%s)', substr($language_code, 0, 2)),
1214 'type' => 'text',
1215 'default' => $defaultName
1216 );
1217 }
1218 }
1219
1220 if (mk_wc_version("3.4.0")) $a = 'admin.php?page=wc-settings&tab=advanced&section=mk_api'; else $a = 'admin.php?page=wc-settings&tab=api&section=mk_api';
1221 $this->form_fields['api_access'] = array( 'type' => 'title', 'title' => '<hr><br>'.__('API access for', 'wc_makecommerce_domain').' '.$this->ext, 'description' => sprintf(__('You can automatically create shipments into Omniva system and print the out the package labels right here, at the shop orders view. <br> Please set your Omniva web servises account credentials below here. <br>(see more on <a href="https://makecommerce.net/en/integration-modules/makecommerce-woocommerce-payment-plugin/#carriers-integration">MakeCommerce plugin page</a>. Don\'t forget to enable also <a href="%s">MC API keys</a>!)', 'wc_makecommerce_domain'), admin_url($a)));
1222
1223 $this->form_fields['registerOnPaymentCode'] = array(
1224 'title' => __('Register shipments automatically as', 'wc_makecommerce_domain'),
1225 'type' => 'select',
1226 'label' => __('register on Payment', 'wc_makecommerce_domain'),
1227 'description' => __('Shipments will be automatically registered on payment using the selected Omniva service code', 'wc_makecommerce_domain'),
1228 'options' => array(
1229 'QP' => __('QP - handover to Omniva at Post Office', 'wc_makecommerce_domain'),
1230 'PK' => __('PK - handover to Omniva via Parcel Machine', 'wc_makecommerce_domain'),
1231 '' => __('None - do not register automatically', 'wc_makecommerce_domain'),
1232 ),
1233 'default' => 'QP',
1234 );
1235 $this->form_fields['service_carrier'] = array(
1236 'type' => 'select',
1237 'title' => __('Integration country', 'wc_makecommerce_domain'),
1238 'options' => array(
1239 "OMNIVA" => __('Estonia', 'wc_makecommerce_domain'),
1240 "OMNIVA_LV" => __('Latvia', 'wc_makecommerce_domain'),
1241 "OMNIVA_LT" => __('Lithuania', 'wc_makecommerce_domain'),
1242 ),
1243 'default' => "ee",
1244 'description' => __("Which country's carrier gave you the credentials", 'wc_makecommerce_domain'),
1245 );
1246 $this->form_fields['service_user'] = array(
1247 'title' => __('Omniva web services username', 'wc_makecommerce_domain'),
1248 'type' => 'text',
1249 'default' => ''
1250 );
1251 $this->form_fields['service_password'] = array(
1252 'title' => __('Omniva web services password', 'wc_makecommerce_domain'),
1253 'type' => 'text',
1254 'default' => ''
1255 );
1256 $this->form_fields['return_address'] = array( 'type' => 'title', 'title' => __('Return address', 'wc_makecommerce_domain'), 'description' => __('Please define return address for Omniva shipments', 'wc_makecommerce_domain'));
1257 $this->form_fields['shop_name'] = array(
1258 'type' => 'text',
1259 'title' => __('Shop name', 'wc_makecommerce_domain'),
1260 'class' => 'input-text regular-input',
1261 );
1262 $this->form_fields['shop_phone'] = array(
1263 'type' => 'text',
1264 'title' => __('Shop phone', 'wc_makecommerce_domain'),
1265 'class' => 'input-text regular-input',
1266 );
1267 $this->form_fields['shop_email'] = array(
1268 'type' => 'text',
1269 'title' => __('Shop email', 'wc_makecommerce_domain'),
1270 'class' => 'input-text regular-input',
1271 );
1272 $this->form_fields['shop_address_country'] = array(
1273 'type' => 'select',
1274 'title' => __('Shop address country', 'wc_makecommerce_domain'),
1275 'options' => array(
1276 'EE' => 'EE',
1277 'LV' => 'LV',
1278 'LT' => 'LT',
1279 ),
1280 'default' => 'EE',
1281 );
1282 $this->form_fields['shop_address_city'] = array(
1283 'type' => 'text',
1284 'title' => __('Shop address city', 'wc_makecommerce_domain'),
1285 'class' => 'input-text regular-input',
1286 );
1287 $this->form_fields['shop_address_street'] = array(
1288 'type' => 'text',
1289 'title' => __('Shop address street', 'wc_makecommerce_domain'),
1290 'class' => 'input-text regular-input',
1291 );
1292 $this->form_fields['shop_postal_code'] = array(
1293 'type' => 'text',
1294 'title' => __('Shop postal code', 'wc_makecommerce_domain'),
1295 'class' => 'input-text regular-input',
1296 );
1297 }
1298 }
1299 }
1300
1301 $enable = get_option('mk_transport_courier_smartpost', 'yes');
1302 if ($enable === 'yes') {
1303 class WC_Courier_Shipping_Method_SmartPost extends WC_Courier_Shipping_Method {
1304
1305 public function __construct($instance_id = 0) {
1306 $this->ext = 'SmartPost';
1307 $this->name_ext = 'SmartPost';
1308 $this->carrier = 'smartpost';
1309 add_filter('woocommerce_review_order_after_shipping' , array(&$this, 'add_smartpost_courier_checkout_fields'));
1310 add_action('woocommerce_checkout_process', array(&$this, 'check_checkout_fields'));
1311 add_action('woocommerce_after_checkout_validation', array(&$this, 'check_checkout_fields'));
1312 add_action('woocommerce_checkout_update_order_meta', array(&$this, 'add_order_meta'));
1313 parent::__construct($instance_id);
1314 }
1315
1316 public function add_smartpost_courier_checkout_fields($fragment) {
1317 $res = '';
1318 $res .= '<tr style="display: none;" class="parcel_machine_checkout parcel_machine_checkout_courier_'.mb_strtolower($this->ext).'">';
1319 $res .= '<td colspan="2">';
1320 $res .= '<p class="form-row" id="'.esc_attr($this->id).'_field">';
1321 $res .= '<label class="courier_arrival_time_window_label">'.__('Pick courier arrival time window', 'wc_makecommerce_domain').'</label>';
1322 $res .= '<select class="select" name="'.esc_attr($this->id).'" id="'.esc_attr($this->id).'">';
1323 $res .= '<option value="1">'.__('Any time', 'wc_makecommerce_domain').'</option>';
1324 $res .= '<option value="2">'.__('Worktime (09:00..17:00)', 'wc_makecommerce_domain').'</option>';
1325 $res .= '<option value="3">'.__('After worktime (17:00..21:00)', 'wc_makecommerce_domain').'</option>';
1326 $res .= '</select>';
1327 $res .= '</p>';
1328 $res .= '</td></tr>';
1329 echo $res;
1330 }
1331
1332 function check_checkout_fields() {
1333 #static $added = false;
1334 #if (!$added && empty($_POST[$this->id])) {
1335 # wc_add_notice(__('<strong>Delivery time</strong> is a required field.', 'wc_makecommerce_domain'), 'error');
1336 # $added = true;
1337 #}
1338 }
1339
1340 function add_order_meta($order_id) {
1341 if (!empty($_POST[$this->id])) {
1342 update_post_meta($order_id, '_delivery_time', sanitize_text_field($_POST[$this->id]));
1343 }
1344 }
1345
1346 public function init_form_fields() {
1347
1348 global $woocommerce;
1349
1350 $this->instance_form_fields = array();
1351 $this->instance_form_fields['logo'] = array('type' => 'title', 'description' => __get_logo_html());
1352 $this->instance_form_fields['price'] = array(
1353 'title' => __('Shipping price', 'wc_makecommerce_domain'),
1354 'type' => 'text',
1355 'default' => '4.95'
1356 );
1357 $this->instance_form_fields['free_shipping_min_amount'] = array(
1358 'title' => __('Free shipping amount', 'wc_makecommerce_domain'),
1359 'type' => 'number',
1360 'default' => '0',
1361 'desc_tip' => __('(0 means no free shipping)', 'wc_makecommerce_domain'),
1362 );
1363 $this->instance_form_fields['allow_free_shipping_coupons'] = array(
1364 'title' => __('Free shipping coupons', 'wc_makecommerce_domain'),
1365 'type' => 'checkbox',
1366 'default' => 'no',
1367 'desc_tip' => __('Allow using free shipping coupons to be used with this method', 'wc_makecommerce_domain'),
1368 );
1369
1370 $this->form_fields = array();
1371 $this->form_fields['logo'] = array('type' => 'title', 'description' => __get_logo_html());
1372 $this->form_fields['generic'] = array(
1373 'type' => 'title',
1374 'title' => __('Generic and pricing options', 'wc_makecommerce_domain'),
1375 // 'description' => __('', 'wc_makecommerce_domain'),
1376 );
1377 $this->form_fields['active'] = array(
1378 'title' => __('Enable', 'wc_makecommerce_domain'),
1379 'type' => 'checkbox',
1380 'label' => __('enabled', 'wc_makecommerce_domain'),
1381 'default' => 'no',
1382 );
1383 $this->form_fields['maximum_weight'] = array(
1384 'title' => sprintf(__('Maximum weight allowed for shipping (%s)', 'wc_makecommerce_domain'), get_option('woocommerce_weight_unit' )),
1385 'type' => 'text',
1386 'default' => '60'
1387 );
1388
1389 $this->form_fields['look_and_feel'] = array( 'type' => 'title', 'title' => '<hr><br>'.__('Look and feel options', 'wc_makecommerce_domain'), 'description' => __('Options for presentation on check-out page', 'wc_makecommerce_domain'));
1390
1391 if ( function_exists('icl_object_id') && !function_exists('pll_languages_list')) {
1392 $languages = apply_filters('wpml_active_languages', NULL, 'skip_missing=0');
1393 }
1394 else if (function_exists('pll_languages_list')) {
1395 $pl_locales = pll_languages_list( array('fields'=>'locale') );
1396 foreach ($pl_locales as $key => $locale_pl ) {
1397 $language = array( 'id' => $key,
1398 'code' => $locale_pl) ;
1399 $languages[$locale_pl] = $language;
1400 }
1401 }
1402
1403 if (empty($languages)) {
1404 $this->form_fields['method_name'] = array(
1405 'title' => __('Shipping Method Title', 'wc_makecommerce_domain'),
1406 'type' => 'text',
1407 'default' => __('SmartPOST Courier', 'wc_makecommerce_domain')
1408 );
1409 } else {
1410 foreach ($languages as $language_code => $language) {
1411 $language_name = !empty($language['translated_name']) ? $language['translated_name'] : $language_code;
1412 $defaultName = __('SmartPOST Courier', 'wc_makecommerce_domain');
1413 switch (substr($language_code, 0, 2)) {
1414 case 'et':
1415 $defaultName = 'SmartPOST kuller';
1416 break;
1417 case 'ru':
1418 $defaultName = 'SmartPOST Курьер';
1419 break;
1420 case 'fi':
1421 $defaultName = 'SmartPOST kuriiri';
1422 break;
1423 case 'lv':
1424 $defaultName = 'SmartPOST kurjers';
1425 break;
1426 case 'lt':
1427 $defaultName = 'SmartPOST kurjeris';
1428 break;
1429 }
1430 $this->form_fields['method_name_'.substr($language_code, 0, 2)] = array(
1431 'title' => __('Shipping Method Title', 'wc_makecommerce_domain').sprintf(' (%s)', substr($language_code, 0, 2)),
1432 'type' => 'text',
1433 'default' => $defaultName
1434 );
1435 }
1436 }
1437
1438 if (mk_wc_version("3.4.0")) $a = 'admin.php?page=wc-settings&tab=advanced&section=mk_api'; else $a = 'admin.php?page=wc-settings&tab=api&section=mk_api';
1439 $this->form_fields['api_access'] = array( 'type' => 'title', 'title' => '<hr><br>'.__('API access for', 'wc_makecommerce_domain').' '.$this->ext, 'description' => sprintf(__('You can automatically create shipments into SmartPOST system and print the out the package labels right here, at the shop orders view. <br> Please set your SmartPOST web servises account credentials below here. <br>(see more on <a href="https://makecommerce.net/en/integration-modules/makecommerce-woocommerce-payment-plugin/#carriers-integration">MakeCommerce plugin page</a>. Don\'t forget to enable also <a href="%s">MC API keys</a>!)', 'wc_makecommerce_domain'), admin_url($a)));
1440
1441 $this->form_fields['service_user'] = array(
1442 'title' => __('eservice.smartpost.ee username', 'wc_makecommerce_domain'),
1443 'type' => 'text',
1444 'default' => ''
1445 );
1446 $this->form_fields['service_password'] = array(
1447 'title' => __('eservice.smartpost.ee password', 'wc_makecommerce_domain'),
1448 'type' => 'text',
1449 'default' => ''
1450 );
1451 $this->form_fields['return_address'] = array( 'type' => 'title', 'title' => __('Return address', 'wc_makecommerce_domain'), 'description' => __('Please define return address for SmartPOST shipments (used on parcel labels)', 'wc_makecommerce_domain'));
1452 $this->form_fields['shop_name'] = array(
1453 'type' => 'text',
1454 'title' => __('Shop name', 'wc_makecommerce_domain'),
1455 'class' => 'input-text regular-input',
1456 );
1457 $this->form_fields['shop_phone'] = array(
1458 'type' => 'text',
1459 'title' => __('Shop phone', 'wc_makecommerce_domain'),
1460 'class' => 'input-text regular-input',
1461 );
1462 $this->form_fields['shop_email'] = array(
1463 'type' => 'text',
1464 'title' => __('Shop email', 'wc_makecommerce_domain'),
1465 'class' => 'input-text regular-input',
1466 );
1467 $this->form_fields['shop_postal_code'] = array(
1468 'type' => 'text',
1469 'title' => __('Shop postal code', 'wc_makecommerce_domain'),
1470 'class' => 'input-text regular-input',
1471 );
1472 }
1473 }
1474 }
1475 }
1476 }
1477 add_action('woocommerce_shipping_init', 'transport_add_method');
1478
1479
1480 function add_mc_shipping_method($methods) {
1481 $methods['parcelmachine_omniva'] = 'WC_ParcelMachine_Shipping_Method_Omniva';
1482 $methods['parcelmachine_smartpost'] = 'WC_ParcelMachine_Shipping_Method_Smartpost';
1483 $methods['parcelmachine_dpd'] = 'WC_ParcelMachine_Shipping_Method_DPD';
1484 $methods['courier_omniva'] = 'WC_Courier_Shipping_Method_Omniva';
1485 $methods['courier_smartpost'] = 'WC_Courier_Shipping_Method_Smartpost';
1486 return $methods;
1487 }
1488 add_filter('woocommerce_shipping_methods', 'add_mc_shipping_method');
1489
1490 function mk_mc_add_assets() {
1491 wp_enqueue_style('parcelmachine-css', plugin_dir_url(__FILE__).'/css/parcelmachine.css');
1492 wp_enqueue_script('parcelmachine-js', plugin_dir_url(__FILE__).'/scripts/parcelmachine.js', array('jquery'));
1493 }
1494 function mk_mc_add_assets_admin() {
1495 wp_enqueue_style('parcelmachine-css-admin', plugin_dir_url(__FILE__).'/css/parcelmachine-admin.css');
1496 wp_enqueue_script('parcelmachine-js-admin', plugin_dir_url(__FILE__).'/scripts/parcelmachine-admin.js', array('jquery'));
1497 }
1498 add_action('wp_enqueue_scripts', 'mk_mc_add_assets');
1499 add_action('admin_enqueue_scripts', 'mk_mc_add_assets_admin');
1500
1501 add_action('woocommerce_admin_field_api_javascript_ui', 'api_javascript_ui');
1502
1503
1504
1505 // ======== Woo Admin dialogs related stuff
1506
1507
1508 function mk_admin_restrict_manage_posts() {
1509 global $typenow;
1510 if ( in_array( $typenow, wc_get_order_types( 'order-meta-boxes' ) ) ) {
1511 $selected_method = !empty($_REQUEST['_shipping_method']) ? $_REQUEST['_shipping_method'] : false;
1512 $methods = WC()->shipping->load_shipping_methods();
1513 echo '<select name="_shipping_method" id="shipping_type" class="enhanced">';
1514 echo '<option value="">'.__('-- filter by shipping method', 'wc_makecommerce_domain') . '</option>';
1515 foreach ($methods as $method) {
1516 echo '<option value="'.$method->id.'"'.($selected_method === $method->id ? ' selected="selected"' : '').'>'.$method->title.'</option>';
1517 }
1518 echo '</select>';
1519 }
1520 }
1521 function mk_admin_shipping_filter($where, $wp_query) {
1522 global $pagenow, $wpdb;
1523 $method = !empty($_REQUEST['_shipping_method']) ? $_REQUEST['_shipping_method'] : false;
1524 if (is_admin() && $pagenow=='edit.php' && $wp_query->query_vars['post_type'] == 'shop_order' && !empty($method) ) {
1525 $where .= $GLOBALS['wpdb']->prepare( ' AND ID
1526 IN (
1527 SELECT items.order_id
1528 FROM '.$wpdb->prefix.'woocommerce_order_itemmeta meta, '.$wpdb->prefix.'woocommerce_order_items items
1529 WHERE meta.order_item_id = items.order_item_id
1530 AND meta.meta_key = "method_id"
1531 AND meta.meta_value = %s
1532 ) ', $method );
1533 }
1534 return $where;
1535 }
1536 add_filter('restrict_manage_posts', 'mk_admin_restrict_manage_posts');
1537 add_filter('posts_where', 'mk_admin_shipping_filter', 10, 2);
1538
1539 function mk_admin_bulk_actions() {
1540 wp_enqueue_script('jquery-ui-core');
1541 wp_enqueue_script('jquery-ui-datepicker');
1542 wp_enqueue_script('wc_mk_timepicker', plugins_url('/scripts/jquery-ui.timepicker.js', __FILE__));
1543 wp_enqueue_style('wc_mk_timepicker-css', plugins_url('/css/jquery-ui.timepicker.css', __FILE__));
1544 global $post_type;
1545 if ('shop_order' === $post_type) { ?>
1546 <script type="text/javascript">
1547 jQuery(function() {
1548 jQuery('<option>').val('parcel_machine_labels').text('<?php _e( 'Register parcel machine shipments', 'wc_makecommerce_domain' )?>').appendTo('select[name="action"]');
1549 jQuery('<option>').val('parcel_machine_labels').text('<?php _e( 'Register parcel machine shipments', 'wc_makecommerce_domain' )?>').appendTo('select[name="action2"]');
1550 jQuery('<option>').val('parcel_machine_print_labels').text('<?php _e( 'Print parcel machine labels', 'wc_makecommerce_domain' )?>').appendTo('select[name="action"]');
1551 jQuery('<option>').val('parcel_machine_print_labels').text('<?php _e( 'Print parcel machine labels', 'wc_makecommerce_domain' )?>').appendTo('select[name="action2"]');
1552 //jQuery('<option>').val('parcel_machine_order_courier').text('<?php _e( 'Order courier for parcel machine deliveries', 'wc_makecommerce_domain' )?>').appendTo('select[name="action"]');
1553 //jQuery('<option>').val('parcel_machine_order_courier').text('<?php _e( 'Order courier for parcel machine deliveries', 'wc_makecommerce_domain' )?>').appendTo('select[name="action2"]');
1554 jQuery('select[name="action"]').after('<input type="text" name="transport_time" class="hidden timepicker"/>');
1555 jQuery('select[name="action"], select[name="action2"]').on('change', function(){
1556 var val = jQuery(this).val();
1557 if (val === 'parcel_machine_order_courier') {
1558 jQuery('.timepicker').removeClass('hidden');
1559 } else {
1560 jQuery('.timepicker').addClass('hidden');
1561 }
1562 });
1563 jQuery('.tablenav.bottom .actions.bulkactions').hide();
1564 var now = new Date();
1565 var mins = now.getMinutes();
1566 var quarterHours = Math.ceil(mins/15);
1567 if (quarterHours == 4) { now.setHours(now.getHours()+1); }
1568 var rounded = (quarterHours*15)%60;
1569 now.setMinutes(rounded);
1570 jQuery('.timepicker').datetimepicker({dateFormat: 'dd/mm/yy', timeFormat: 'HH:mm', stepMinute: 15, minDateTime: now, devaultValue: jQuery.datepicker.formatTime('dd/mm/yyyy HH:mm', now)});
1571 });
1572 </script>
1573 <?php if (!empty($_REQUEST['mk_err'])) { ?>
1574 <script type="text/javascript">
1575 jQuery(function(){
1576 alert('<?php echo htmlspecialchars($_REQUEST['mk_err']) ?>');
1577 });
1578 </script>
1579 <?php } ?>
1580 <?php if (!empty($_REQUEST['mk_pdf'])) { ?>
1581 <script type="text/javascript">
1582 jQuery(function(){
1583 window.open('<?php echo $_REQUEST['mk_pdf'] ?>', 'pdf');
1584 });
1585 </script>
1586 <?php }
1587 }
1588 }
1589 function mk_admin_bulk_action_labels() {
1590 $wp_list_table = _get_list_table('WP_Posts_List_Table');
1591 $post_ids = array_map('absint', (array)$_REQUEST['post']);
1592 mk_get_shipment_ids($post_ids);
1593 }
1594 function mk_admin_bulk_action_print() {
1595 $wp_list_table = _get_list_table('WP_Posts_List_Table');
1596 $post_ids = array_map('absint', (array)$_REQUEST['post']);
1597 mk_get_labels($post_ids);
1598 }
1599 function mk_admin_bulk_action_order_courier() {
1600 return;
1601 $wp_list_table = _get_list_table('WP_Posts_List_Table');
1602 $post_ids = array_map('absint', (array)$_REQUEST['post']);
1603 $transport_time = !empty($_REQUEST['transport_time']) ? strtotime(str_replace('/', '-', $_REQUEST['transport_time'])) : false;
1604 if ($transport_time && $transport_time > time()) {
1605 mk_get_shipment_ids($post_ids, 'omniva');
1606 } else {
1607 die('Please select transport time that is in the future');
1608 }
1609 }
1610 add_action('admin_footer', 'mk_admin_bulk_actions', 11);
1611 add_action('admin_action_parcel_machine_labels', 'mk_admin_bulk_action_labels');
1612 add_action('admin_action_parcel_machine_print_labels', 'mk_admin_bulk_action_print');
1613 add_action('admin_action_parcel_machine_order_courier', 'mk_admin_bulk_action_order_courier');
1614
1615 function mk_admin_save_post($post_id) {
1616 $post_type = get_post_type($post_id);
1617 if ('shop_order' !== $post_type) { return; }
1618 if (isset($_POST['_mk_machine_id'])) {
1619 update_post_meta($post_id, '_parcel_machine', $_POST['_mk_machine_id']);
1620 mk_get_shipment_ids($post_id);
1621 }
1622 }
1623
1624 add_action('save_post', 'mk_admin_save_post');
1625
1626
1627
1628 function mk_admin_parcelmachine_order_meta($order) {
1629 echo '</div>';
1630 echo '<div class="order_data_column" style="float: right;">';
1631 $order_id = $order->get_id();
1632 $machine_id = get_post_meta($order_id, '_parcel_machine', true);
1633 if (!empty($machine_id)) {
1634 list($carrier, $machine) = explode('||', $machine_id);
1635 if (!empty($machine)) {
1636 $machine = mk_get_machine($carrier, $machine);
1637 if ($machine) {
1638 echo '<h3>'.__('Selected parcel machine', 'wc_makecommerce_domain').'<a href="#" class="edit_address">'.__('Edit').'</a></h3>';
1639 echo '<div class="edit_address">';
1640 echo '<p class="form-field form-field-wide _mk_machine_id">';
1641 echo '<label for="_mk_machine_id">'.__('Parcel machine', 'wc_makecommerce_domain').'</label>';
1642 echo '<select id="_mk_machine_id" name="_mk_machine_id" class="wc-enhanced-select select">';
1643 $res = '';
1644 $machines = mk_get_machines($carrier, method_exists($order, 'get_shipping_country') ? $order->get_shipping_country() : $order->shipping_country);
1645 $res .= '<option value="">'.__('-- select parcel machine --', 'wc_makecommerce_domain').'</option>';
1646 $pcity = false;
1647 foreach ($machines as $smachine) {
1648 $city = strtolower($smachine['city']);
1649 if ($city !== $pcity) {
1650 if ($pcity) $res .= '</optgroup>';
1651 $res .= '<optgroup label="'.$smachine['city'].'">';
1652 }
1653 $mname = $smachine['name'];
1654 $res .= '<option value="'.esc_attr($smachine['carrier'].'||'.$smachine['id']).'" '.($machine['id'] === $smachine['id'] ? ' selected="selected"' : '').'>'.$mname.'</option>';
1655 $pcity = $city;
1656 }
1657 if ($pcity) $res .= '</optgroup>';
1658 echo $res;
1659 echo '</select>';
1660 echo '</p>';
1661 echo '</div>';
1662 echo '<div class="address">';
1663 echo '<p>'.$carrier.'</strong><br/>'.$machine['name'] . '<br/><small>' . $machine['address'] . '</small></p>';
1664 echo '</div>';
1665 }
1666 }
1667 }
1668
1669 if (empty($carrier)) {
1670 $carrier = '';
1671 }
1672
1673 $shipment_id = get_post_meta($order_id, '_parcel_machine_shipment_id', true);
1674 $shipment_id_error = get_post_meta($order_id, '_parcel_machine_error', true);
1675 $shipment_manifest = get_post_meta($order_id, '_parcel_machine_manifest', true);
1676
1677 //currently the only delivery time option exists for smartpost courier shipping method.
1678 $showDeliveryTime = false;
1679 foreach ($order->get_shipping_methods() as $shippingMethod) {
1680 if ($shippingMethod["method_id"] == "courier_smartpost") {
1681 $showDeliveryTime = true;
1682 }
1683 }
1684
1685 $delivery_time = get_post_meta($order_id, '_delivery_time', true);
1686 if (!$shipment_id_error && $showDeliveryTime) {
1687 if ($delivery_time === '1') {
1688 echo '<p><strong>'.__('Delivery time', 'wc_makecommerce_domain').'</strong> - '.__('Any time', 'wc_makecommerce_domain').'</p>';
1689 }
1690
1691 if ($delivery_time === '2') {
1692 echo '<p><strong>'.__('Delivery time', 'wc_makecommerce_domain').'</strong> - 09:00..17:00</p>';
1693 }
1694
1695 if ($delivery_time === '3') {
1696 echo '<p><strong>'.__('Delivery time', 'wc_makecommerce_domain').'</strong> - 17:00..21:00</p>';
1697 }
1698 }
1699
1700 if ($shipment_id) {
1701 $trackinglink = '<p><strong>'.__('Shipment tracking code', 'wc_makecommerce_domain').'</strong>';
1702
1703 //check if its omniva courier
1704 if ($carrier == "") {
1705 foreach ($order->get_shipping_methods() as $shippingMethod) {
1706 if ($shippingMethod["method_id"] == "courier_omniva") {
1707 $carrier = "omniva";
1708 }
1709 }
1710 }
1711
1712 $theLink = get_tracking_link($carrier, $shipment_id, $order_id, true);
1713 if ($carrier != "" && $theLink != "") {
1714 $trackinglink .= ' ('. ucfirst($carrier) .'): <br/> <a target="_blank" href="'.$theLink.$shipment_id.'">'.$shipment_id.'</a>';
1715 } else {
1716 $trackinglink .= ': <br/>'.$shipment_id;
1717 }
1718
1719 echo $trackinglink.'</p>';
1720 }
1721
1722 if ($shipment_manifest) {
1723 echo '<p><strong>'.__('Shipments pickup manifest').':</strong><br/><a href="' . $shipment_manifest . '" target="_blank">link</a></small></p>';
1724 }
1725
1726 if ($shipment_id_error) {
1727 echo '<p><strong style="color: red;">'.__('Shipment registration error').':</strong><br/>' . $shipment_id_error . '</small></p>';
1728 }
1729
1730 echo '</div>';
1731 }
1732
1733 //returns the correct link to be used for tracking information
1734 function get_tracking_link($carrier, $order_id, $shopLocation = false)
1735 {
1736 //do we use shop location or delivery location
1737 if ($shopLocation) {
1738 //get_base_country returns either EE, LT or LV. Everything else is irrelevant
1739 $tld = substr(strtolower(WC()->countries->get_base_country()), 0, 2);
1740 /* $userLang = get_locale();//en_, lv_, et_, lt_, ru_ <- this could be used aswell */
1741 $userLang = $tld;
1742 } else {
1743 //get order delivery location. Returns EE, LT or LV. Evertyhing else is irrelevant
1744 $tld = substr(strtolower(get_post_meta($order_id, '_shipping_country', true)), 0, 2);
1745 $userLang = substr(strtolower(get_post_meta($order_id, 'wpml_language', true)), 0, 2); //returns nothing if it doesnt exist, otherwise returns en, et, lt, lv, ru
1746 }
1747
1748 //
1749 // create array for different options [carrier][tld][lang]
1750 // first one in the list must be default, this goes for the tld aswell as for the userLang.
1751 //
1752
1753 /* Omniva */
1754 //EST
1755 $trackingURLS["omniva"]["ee"]["ee"] = 'https://www.omniva.ee/abi/jalgimine?barcode=';
1756 $trackingURLS["omniva"]["ee"]["en"] = 'https://www.omniva.ee/private/track_and_trace?barcode=';
1757 $trackingURLS["omniva"]["ee"]["ru"] = 'https://www.omniva.ee/chastnyj/otslezhivanie_posylki?barcode=';
1758
1759 //LT
1760 $trackingURLS["omniva"]["lt"]["lt"] = 'https://www.omniva.lt/verslo/siuntos_sekimas?barcode=';
1761 $trackingURLS["omniva"]["lt"]["en"] = 'https://www.omniva.lt/business/track_and_trace?barcode=';
1762
1763 //LV
1764 $trackingURLS["omniva"]["lv"]["lv"] = 'https://www.omniva.lv/privats/sutijuma_atrasanas_vieta?barcode=';
1765 $trackingURLS["omniva"]["lv"]["en"] = 'https://www.omniva.lv/private/track_and_trace?barcode=';
1766 $trackingURLS["omniva"]["lv"]["ru"] = 'https://www.omniva.lv/chastnyj/mestonahozhdenie_posylki?barcode=';
1767
1768 /* DPD */
1769 //EE
1770 $trackingURLS["dpd"]["ee"]["ee"] = 'https://tracking.dpd.de/status/et_EE/parcel/';
1771 $trackingURLS["dpd"]["ee"]["en"] = 'https://tracking.dpd.de/status/en_EE/parcel/';
1772
1773 //LT
1774 $trackingURLS["dpd"]["lt"]["lt"] = 'https://tracking.dpd.de/status/lt_LT/parcel/';
1775 $trackingURLS["dpd"]["lt"]["en"] = 'https://tracking.dpd.de/status/en_LT/parcel/';
1776
1777 //LV
1778 $trackingURLS["dpd"]["lv"]["lv"] = 'https://tracking.dpd.de/status/lv_LV/parcel/';
1779 $trackingURLS["dpd"]["lv"]["en"] = 'https://tracking.dpd.de/status/en_LV/parcel/';
1780
1781 //carrier exists
1782 if (isset($trackingURLS[$carrier])) {
1783 //country exists
1784 if (isset($trackingURLS[$carrier][$tld])) {
1785 if (isset($trackingURLS[$carrier][$tld][$userLang])) {
1786 return $trackingURLS[$carrier][$tld][$userLang];
1787 } else {
1788 //selected language not found, return carrier tld default language.
1789 return current($trackingURLS[$carrier][$tld]);
1790 }
1791 } else {
1792 //selected tld not found, return carrier default tld + language
1793 $defaultCarrierTLD = current($trackingURLS[$carrier]);
1794 return current($defaultCarrierTLD);
1795 }
1796 }
1797
1798 //not even carrier was found. Return nothing
1799 return "";
1800 }
1801
1802 function mk_admin_render_shop_order_columns( $column ) {
1803 global $post, $woocommerce, $the_order;
1804 if (!$the_order) return;
1805 $the_order_id = $the_order->get_id();
1806 if (empty($the_order) || $the_order_id != $post->ID) {
1807 $the_order = wc_get_order($post->ID);
1808 }
1809 if ($column === 'shipping_address') {
1810 $machine_id = get_post_meta($the_order_id, '_parcel_machine', true);
1811 $shipment_id = get_post_meta($the_order_id, '_parcel_machine_shipment_id', true);
1812 $shipment_id_error = get_post_meta($the_order_id, '_parcel_machine_error', true);
1813 if ($machine_id && !$shipment_id) {
1814 //echo __('Shipment ID not generated for delivery', 'wc_makecommerce_domain');
1815 }
1816 if ($shipment_id) {
1817 echo __('Shipment tracking code', 'wc_makecommerce_domain') . ': ' . $shipment_id . '<br/>';
1818 echo '<span class="has_shipment_id"></span>';
1819 }
1820 else if ($shipment_id_error) echo '<span style="color: red;">'.__('Package shipment generation error:', 'wc_makecommerce_domain') . '</span><br/>' .$shipment_id_error;
1821 }
1822
1823 }
1824
1825 function mk_add_email_customer_details_fields($fields, $sent_to_admin, $order)
1826 {
1827 //this only applies for Polylang. In WPML it will break
1828 if (function_exists('pll_languages_list')) {
1829 $orderLang = get_locale();
1830
1831 if ($orderLang != "") {
1832 //Workaround for broken Polylang functionality:
1833 //switch to a different than current language first. Otherwise hooks for polylang dont seem to work...
1834 if (substr($orderLang, 0 ,2) == "en") {
1835 switch_to_locale("et");
1836 do_action('wpml_switch_language', "et");
1837 } else {
1838 switch_to_locale("en_GB");
1839 do_action('wpml_switch_language', "en_GB");
1840 }
1841
1842 //switch back to original language
1843 switch_to_locale($orderLang);
1844 do_action('wpml_switch_language', $orderLang);
1845 load_plugin_textdomain('wc_makecommerce_domain', false, dirname(plugin_basename(__FILE__)) . '/languages/');
1846 }
1847 }
1848
1849 $machine_id = get_post_meta($order->get_id(), '_parcel_machine', true);
1850
1851 $machine = "";
1852 $carrier = "";
1853
1854 $machineIdArr = explode('||', $machine_id);
1855 if (count($machineIdArr) == 2) {
1856 $carrier = $machineIdArr[0];
1857 $machine = $machineIdArr[1];
1858 } else if (count($machineIdArr) == 1) {
1859 $carrier = $machineIdArr[0];
1860 }
1861
1862 $machine = mk_get_machine($carrier, $machine);
1863
1864 if ($machine != "" && $carrier != "") {
1865 //add parcel machine name/location
1866 $fields[] = array('label' => __('Parcel machine', 'wc_makecommerce_domain').' ('.ucfirst($carrier).')', 'value' => $machine['name'].' - '.$machine['address']);
1867 }
1868
1869 $shipment_id_error = get_post_meta($order->get_id(), '_parcel_machine_error', true);
1870
1871 //currently the only delivery time option exists for smartpost courier shipping method.
1872 $showDeliveryTime = false;
1873 foreach ($order->get_shipping_methods() as $shippingMethod) {
1874 if ($shippingMethod["method_id"] == "courier_smartpost") {
1875 $showDeliveryTime = true;
1876 }
1877 }
1878
1879 $delivery_time = get_post_meta($order->get_id(), '_delivery_time', true);
1880 if (!$shipment_id_error && $showDeliveryTime) {
1881 if ($delivery_time === '1') {
1882 $fields[] = array('label' => __('Delivery time', 'wc_makecommerce_domain'), 'value' => __('Any time', 'wc_makecommerce_domain'));
1883 }
1884
1885 if ($delivery_time === '2') {
1886 $fields[] = array('label' => __('Delivery time', 'wc_makecommerce_domain'), 'value' => "09:00..17:00");
1887 }
1888
1889 if ($delivery_time === '3') {
1890 $fields[] = array('label' => __('Delivery time', 'wc_makecommerce_domain'), 'value' => "17:00..21:00");
1891 }
1892 }
1893
1894 //add tracking information (if possible)
1895 $shipment_id = get_post_meta($order->get_id(), "_parcel_machine_shipment_id", true);
1896
1897 if ($shipment_id) {
1898 $trackinglink = '<p><strong>'.__('Shipment tracking code', 'wc_makecommerce_domain').'</strong>';
1899
1900 $href = get_tracking_link($carrier, $order->get_id());
1901 if ($href != "") {
1902 $href .= $shipment_id;
1903 $fields[] = array('label' => __('Shipment tracking info', 'wc_makecommerce_domain').' ('.$carrier.')', 'value' => "<a target='_blank' title='".__('Shipment tracking code', 'wc_makecommerce_domain')."' href='".$href."'>".$href."</a>");
1904 } else {
1905 $fields[] = array('label' => __('Shipment tracking info', 'wc_makecommerce_domain'), 'value' => $shipment_id);
1906 }
1907 }
1908
1909 return $fields;
1910 }
1911
1912 function mk_add_order_customer_details_fields($order) {
1913 $machine_id = get_post_meta($order->get_id(), '_parcel_machine', true);
1914 if (empty($machine_id)) return;
1915 list($carrier, $machine) = explode('||', $machine_id);
1916 if (empty($machine)) return;
1917 $machine = mk_get_machine($carrier, $machine);
1918 if (!$machine) return;
1919 echo '<tr>';
1920 echo '<th>'.__('Parcel machine', 'wc_makecommerce_domain').' ('.ucfirst($carrier).') </th>';
1921 echo '<td>'.$machine['name'].'<br/>'.$machine['address'].'</td>';
1922 echo '</tr>';
1923 }
1924 function mk_admin_product_option_fields($fields) {
1925 echo '<div class="options_group">';
1926 woocommerce_wp_checkbox(
1927 array(
1928 'id' => '_no_parcel_machine',
1929 'label' => __('Does not fit parcel machine', 'wc_makecommerce_domain'),
1930 'description' => __('When this is checked, parcel machine shipping option is not available for a cart with this product', 'wc_makecommerce_domain')
1931 )
1932 );
1933 woocommerce_wp_checkbox(
1934 array(
1935 'id' => '_no_shipping_cost',
1936 'label' => __('Free parcel machine', 'wc_makecommerce_domain'),
1937 'description' => __('When this is checked, parcel machine is free for this product', 'wc_makecommerce_domain')
1938 )
1939 );
1940 echo '</div>';
1941 }
1942 function mk_admin_product_fields_save($post_id) {
1943 $no_parcel_machine = isset($_POST['_no_parcel_machine']) ? 'yes' : 'no';
1944 update_post_meta($post_id, '_no_parcel_machine', $no_parcel_machine);
1945 $no_shipping_cost = isset($_POST['_no_shipping_cost']) ? 'yes' : 'no';
1946 update_post_meta($post_id, '_no_shipping_cost', $no_shipping_cost);
1947 }
1948
1949
1950
1951
1952
1953
1954
1955 add_action('woocommerce_product_options_shipping', 'mk_admin_product_option_fields');
1956 add_action('woocommerce_process_product_meta', 'mk_admin_product_fields_save');
1957 add_action('woocommerce_admin_order_data_after_shipping_address', 'mk_admin_parcelmachine_order_meta', 10, 1);
1958 add_action('manage_shop_order_posts_custom_column', 'mk_admin_render_shop_order_columns', 3);
1959 add_filter('woocommerce_email_customer_details_fields', 'mk_add_email_customer_details_fields', 10, 3 );
1960 add_action('woocommerce_order_details_after_customer_details', 'mk_add_order_customer_details_fields');
1961 add_action('woocommerce_order_status_processing', 'mk_get_shipment_ids');
1962
1963
1964
1965
1966 // ===== MK API communication related stuff
1967
1968 function mk_get_shipment_ids($post_ids, $select_carrier = null) {
1969 if (!is_array($post_ids)) {
1970 $post_ids = array($post_ids);
1971 }
1972 transport_add_method();
1973 $shipping_request = array('credentials' => array(), 'orders' => array());
1974 $shipping_classes_map = array(
1975 'parcelmachine_omniva' => 'WC_ParcelMachine_Shipping_Method_Omniva',
1976 'parcelmachine_smartpost' => 'WC_ParcelMachine_Shipping_Method_Smartpost',
1977 'parcelmachine_dpd' => 'WC_ParcelMachine_Shipping_Method_DPD',
1978 'courier_omniva' => 'WC_Courier_Shipping_Method_Omniva',
1979 'courier_smartpost' => 'WC_Courier_Shipping_Method_Smartpost'
1980 );
1981 foreach ($post_ids as $post_id) {
1982 $oldId = get_post_meta($post_id, '_parcel_machine_shipment_id', true);
1983 if (strlen($oldId)>6) continue;
1984 $order = new WC_Order($post_id);
1985
1986 //check if the post state is even paid, if not, ignore this post...
1987 //this could perhaps be in a way better location. Why is the function even called when post state is set to failed.
1988 if ((string)$order->get_status() !== "completed" && (string)$order->get_status() !== "processing") {
1989 continue;
1990 }
1991
1992 $shipping_methods = $order->get_shipping_methods();
1993 if (empty($shipping_methods)) { continue; }
1994 foreach ($shipping_methods as $shipping_method) {
1995 $shipping_id = explode(':', $shipping_method['method_id']);
1996 $shipping_class = $shipping_id[0];
1997 $shipping_instance = !empty($shipping_id[1]) ? $shipping_id[1] : null;
1998 if (empty($shipping_classes_map[$shipping_class])) {
1999 continue;
2000 }
2001
2002 $transport_class = new $shipping_classes_map[$shipping_class]($shipping_instance);
2003 $carrier_uc = mb_strtoupper($transport_class->carrier);
2004
2005 if ($transport_class->type === 'apt') {
2006 $parcel_machine = get_post_meta($post_id, '_parcel_machine', true);
2007 if (!$parcel_machine) { continue; }
2008 list($carrier, $machine_id) = explode('||', $parcel_machine);
2009 if (!$carrier || !$machine_id) { continue; }
2010 }
2011
2012 if (empty($shipping_request['credentials'][$carrier_uc])) {
2013 $api_user = $transport_class->settings['service_user'];
2014 $api_password = $transport_class->settings['service_password'];
2015
2016 //change carrier_uc if it has been set in the interface.
2017 if (isset($transport_class->settings['service_carrier'])) {
2018 $carrier_uc = $transport_class->settings['service_carrier'];
2019 }
2020
2021 $use_mk_contract = false;
2022 if ( isset($transport_class->settings['use_mk_contract']) ) {
2023 $use_mk_contract = $transport_class->settings['use_mk_contract'];
2024 }
2025
2026 if ( (!$api_user || !$api_password) and (!$use_mk_contract) ) {
2027 add_action('admin_notices', 'mk_admin_error');
2028 continue;
2029 }
2030
2031 // if $use_mk_contract is enabled, do not add credentials array to the request
2032 if (!$use_mk_contract) {
2033 $shipping_request['credentials'][$carrier_uc] = array('carrier' => $carrier_uc, 'username' => $api_user, 'password' => $api_password);
2034 }
2035 }
2036 $sender = array(
2037 'name' => !empty($transport_class->settings['shop_name']) ? $transport_class->settings['shop_name'] : '',
2038 'phone' => !empty($transport_class->settings['shop_phone']) ? $transport_class->settings['shop_phone'] : '',
2039 'email' => !empty($transport_class->settings['shop_email']) ? $transport_class->settings['shop_email'] : '',
2040 'country' => !empty($transport_class->settings['shop_address_country']) ? $transport_class->settings['shop_address_country'] : '',
2041 'city' => !empty($transport_class->settings['shop_address_city']) ? $transport_class->settings['shop_address_city'] : '',
2042 'street' => !empty($transport_class->settings['shop_address_street']) ? $transport_class->settings['shop_address_street'] : '',
2043 'postalCode' => !empty($transport_class->settings['shop_postal_code']) ? $transport_class->settings['shop_postal_code'] : ''
2044 );
2045 $s_first_name = method_exists($order, 'get_shipping_first_name') ? $order->get_shipping_first_name() : $order->shipping_first_name;
2046 $s_last_name = method_exists($order, 'get_shipping_last_name') ? $order->get_shipping_last_name() : $order->shipping_last_name;
2047 $b_first_name = method_exists($order, 'get_billing_first_name') ? $order->get_billing_first_name() : $order->billing_first_name;
2048 $b_last_name = method_exists($order, 'get_billing_last_name') ? $order->get_billing_last_name() : $order->billing_last_name;
2049 $b_phone = method_exists($order, 'get_billing_phone') ? $order->get_billing_phone() : $order->billing_phone;
2050 $b_email = method_exists($order, 'get_billing_email') ? $order->get_billing_email() : $order->billing_email;
2051 $recipient_name = $s_first_name && $s_last_name ? $s_first_name . ' ' . $s_last_name : $b_first_name . ' ' . $b_last_name;
2052 $sr_order = array(
2053 'carrier' => $carrier_uc,
2054 'orderId' => $order->get_id(),
2055 'recipient' => array('name' => $recipient_name, 'phone' => $b_phone, 'email' => $b_email),
2056 'sender' => $sender,
2057 'destination' => array(),
2058 );
2059 $m_service_type = null;
2060 if ($transport_class->carrier === 'omniva' && $transport_class->type === 'atp') {
2061 $m_service_type = 'PA';
2062 } else if (!empty($transport_class->settings['registerOnPaymentCode'])) {
2063 $m_service_type = $transport_class->settings['registerOnPaymentCode'];
2064 }
2065
2066 if (!empty($machine_id)) {
2067 $sr_order['destination']['destinationId'] = $machine_id;
2068 }
2069 if ($transport_class->type === 'cou') {
2070 $s_postcode = method_exists($order, 'get_shipping_postcode') ? $order->get_shipping_postcode() : $order->shipping_postcode;
2071 $s_country = method_exists($order, 'get_shipping_country') ? $order->get_shipping_country() : $order->shipping_country;
2072 $s_state = method_exists($order, 'get_shipping_state') ? $order->get_shipping_state() : $order->shipping_state;
2073 $s_city = method_exists($order, 'get_shipping_city') ? $order->get_shipping_city() : $order->shipping_city;
2074 $s_address_1 = method_exists($order, 'get_shipping_address_1') ? $order->get_shipping_address_1() : $order->shipping_address_1;
2075 $s_address_2 = method_exists($order, 'get_shipping_address_2') ? $order->get_shipping_address_2() : $order->shipping_address_2;
2076 $sr_order['destination'] = array(
2077 'postalCode' => $s_postcode,
2078 'country' => $s_country,
2079 'county' => $s_state,
2080 'city' => $s_city,
2081 'street' => $s_address_1 . ' ' . $s_address_2
2082 );
2083
2084 if ($shipping_class == "courier_smartpost") {
2085 $delivery_time = get_post_meta($post_id, '_delivery_time', true);
2086 if ($delivery_time) {
2087 $sr_order['destination']['timeWindow'] = $delivery_time;
2088 }
2089 }
2090 }
2091
2092 if ($m_service_type) {
2093 $sr_order['services'] = array('serviceType' => $m_service_type);
2094 }
2095
2096 $shipping_request['orders'][] = $sr_order;
2097 }
2098 }
2099
2100 $shipping_request['credentials'] = array_values($shipping_request['credentials']);
2101 if (empty($shipping_request['orders'])) {
2102 return;
2103 }
2104
2105 $MK = mk_get_api();
2106 if (!$MK) {
2107 return;
2108 }
2109
2110 try {
2111 $response = $MK->createShipments($shipping_request);
2112 } catch (Exception $e) {
2113 error_log('Error while creating shipment ['.$e->getMessage().']');
2114 return;
2115 }
2116
2117 $shipments = !empty($response->shipments) ? $response->shipments : $response;
2118 $manifest = !empty($response->manifests) ? $response->manifests[0] : false;
2119
2120 foreach ($shipments as $order) {
2121 if ($manifest) {
2122 update_post_meta((int)$order->orderId, '_parcel_machine_manifest', sanitize_text_field($manifest));
2123 }
2124 if (!empty($order->orderId) && !empty($order->shipmentId)) {
2125 update_post_meta((int)$order->orderId, '_parcel_machine_shipment_id', sanitize_text_field($order->shipmentId));
2126 update_post_meta((int)$order->orderId, '_tracking_number', sanitize_text_field($order->shipmentId)); //default value used by other plugins, such as WooCommerce PDF Invoices and so on
2127 delete_post_meta((int)$order->orderId, '_parcel_machine_error');
2128 } else if (!empty($order->orderId) && !empty($order->barCode)) {
2129 update_post_meta((int)$order->orderId, '_parcel_machine_shipment_id', sanitize_text_field($order->barCode));
2130 update_post_meta((int)$order->orderId, '_tracking_number', sanitize_text_field($order->barCode)); //default value used by other plugins, such as WooCommerce PDF Invoices and so on
2131 delete_post_meta((int)$order->orderId, '_parcel_machine_error');
2132 } else if (!empty($order->orderId) && !empty($order->errorMessage)) {
2133 update_post_meta((int)$order->orderId, '_parcel_machine_error', sanitize_text_field($order->errorMessage));
2134 }
2135 }
2136 }
2137
2138 function mk_get_labels($post_ids, $ajax = false)
2139 {
2140 if (!is_array($post_ids)) {
2141 $post_ids = array($post_ids);
2142 }
2143 transport_add_method();
2144 $shipping_request = array('credentials' => array(), 'orders' => array(), 'printFormat' => 'A4');
2145 $shipping_classes_map = array(
2146 'parcelmachine_omniva' => 'WC_ParcelMachine_Shipping_Method_Omniva',
2147 'parcelmachine_smartpost' => 'WC_ParcelMachine_Shipping_Method_Smartpost',
2148 'parcelmachine_dpd' => 'WC_ParcelMachine_Shipping_Method_DPD',
2149 'courier_omniva' => 'WC_Courier_Shipping_Method_Omniva',
2150 'courier_smartpost' => 'WC_Courier_Shipping_Method_Smartpost'
2151 );
2152 $missing_ids = array();
2153 foreach ($post_ids as $post_id) {
2154 $shipment_id = get_post_meta($post_id, '_parcel_machine_shipment_id', true);
2155 if (!$shipment_id) {
2156 $missing_ids[] = $post_id;
2157 continue;
2158 }
2159 $order = new WC_Order($post_id);
2160 $shipping_methods = $order->get_shipping_methods();
2161 if (empty($shipping_methods)) { continue; }
2162 foreach ($shipping_methods as $shipping_method) {
2163 $shipping_id = explode(':', $shipping_method['method_id']);
2164 $shipping_class = $shipping_id[0];
2165 $shipping_instance = !empty($shipping_id[1]) ? $shipping_id[1] : null;
2166 if (empty($shipping_classes_map[$shipping_class])) {
2167 continue;
2168 }
2169
2170 $transport_class = new $shipping_classes_map[$shipping_class]($shipping_instance);
2171 $carrier_uc = mb_strtoupper($transport_class->carrier);
2172
2173 if ($transport_class->type === 'apt') {
2174 $parcel_machine = get_post_meta($post_id, '_parcel_machine', true);
2175 if (!$parcel_machine) { continue; }
2176 list($carrier, $machine_id) = explode('||', $parcel_machine);
2177 if (!$carrier || !$machine_id) { continue; }
2178 }
2179 if (empty($shipping_request['credentials'][$carrier_uc])) {
2180 $api_user = $transport_class->settings['service_user'];
2181 $api_password = $transport_class->settings['service_password'];
2182
2183 $use_mk_contract = false;
2184 if ( isset($transport_class->settings['use_mk_contract']) ) {
2185 $use_mk_contract = $transport_class->settings['use_mk_contract'];
2186 }
2187
2188 //change carrier_uc if it has been set in the interface.
2189 if (isset($transport_class->settings['service_carrier'])) {
2190 $carrier_uc = $transport_class->settings['service_carrier'];
2191 }
2192
2193 if ( (!$api_user || !$api_password) and (!$use_mk_contract) ) {
2194 add_action('admin_notices', 'mk_admin_error');
2195 continue;
2196 }
2197 if (!$use_mk_contract) {
2198 $shipping_request['credentials'][$carrier_uc] = array('carrier' => $carrier_uc, 'username' => $api_user, 'password' => $api_password);
2199 }
2200 }
2201 $sender = array(
2202 'name' => $transport_class->settings['shop_name'],
2203 'phone' => $transport_class->settings['shop_phone'],
2204 'email' => $transport_class->settings['shop_email'],
2205 'postalCode' => !empty($transport_class->settings['shop_postal_code']) ? $transport_class->settings['shop_postal_code'] : '',
2206 'country' => !empty($transport_class->settings['shop_address_country']) ? $transport_class->settings['shop_address_country'] : '',
2207 'city' => !empty($transport_class->settings['shop_address_city']) ? $transport_class->settings['shop_address_city'] : '',
2208 'street' => !empty($transport_class->settings['shop_address_street']) ? $transport_class->settings['shop_address_street'] : ''
2209 );
2210 $s_first_name = method_exists($order, 'get_shipping_first_name') ? $order->get_shipping_first_name() : $order->shipping_first_name;
2211 $s_last_name = method_exists($order, 'get_shipping_last_name') ? $order->get_shipping_last_name() : $order->shipping_last_name;
2212 $recipient = trim($s_first_name . ' ' . $s_last_name);
2213 if (empty($recipient)) {
2214 $b_first_name = method_exists($order, 'get_billing_first_name') ? $order->get_billing_first_name() : $order->billing_first_name;
2215 $b_last_name = method_exists($order, 'get_billing_last_name') ? $order->get_billing_last_name() : $order->billing_last_name;
2216 $recipient = trim($b_first_name . ' ' . $b_last_name);
2217 }
2218 $b_phone = method_exists($order, 'get_billing_phone') ? $order->get_billing_phone() : $order->billing_phone;
2219 $b_email = method_exists($order, 'get_billing_email') ? $order->get_billing_email() : $order->billing_email;
2220 $sr_order = array(
2221 'carrier' => $carrier_uc,
2222 'orderId' => $order->get_id(),
2223 'recipient' => array('name' => $recipient, 'phone' => $b_phone, 'email' => $b_email),
2224 'sender' => $sender,
2225 'shipmentId' => $shipment_id
2226 );
2227 $m_service_type = null;
2228 if ($transport_class->carrier === 'omniva' && $transport_class->type === 'atp') {
2229 $m_service_type = 'PA';
2230 } else if (!empty($transport_class->settings['registerOnPaymentCode'])) {
2231 $m_service_type = $transport_class->settings['registerOnPaymentCode'];
2232 }
2233
2234 if (!empty($machine_id)) {
2235 $sr_order['destination']['destinationId'] = $machine_id;
2236 }
2237 if ($transport_class->type === 'cou') {
2238 $sr_order['destination'] = array(
2239 'postalCode' => $order->shipping_postcode,
2240 'country' => $order->shipping_country,
2241 'county' => $order->shipping_state,
2242 'city' => $order->shipping_city,
2243 'street' => $order->shipping_address_1 . ' ' . $order->shipping_address_2
2244 );
2245
2246 if ($shipping_class == "courier_smartpost") {
2247 $delivery_time = get_post_meta($post_id, '_delivery_time', true);
2248 if ($delivery_time) {
2249 $sr_order['destination']['timeWindow'] = $delivery_time;
2250 }
2251 }
2252 }
2253
2254 if ($m_service_type) {
2255 $sr_order['services'] = array('serviceType' => $m_service_type);
2256 }
2257
2258 $shipping_request['orders'][] = $sr_order;
2259 }
2260 }
2261 $shipping_request['credentials'] = array_values($shipping_request['credentials']);
2262 if (empty($shipping_request['orders'])) {
2263 return;
2264 }
2265 $MK = mk_get_api();
2266 if (!$MK) {
2267 return;
2268 }
2269 try {
2270 $response = $MK->createLabels($shipping_request);
2271 } catch (Exception $e) {
2272 echo $e->getMessage();
2273 exit();
2274 }
2275 if (empty($response->labelUrl)) {
2276 return;
2277 }
2278 if ($ajax) {
2279 return $response->labelUrl;
2280 }
2281 $mk_err = false;
2282 if (!empty($missing_ids)) { $mk_err = sprintf(__('Orders %s did not have shipment ID attached so no labels was printed! Please register those packages if you think this is an error!', 'wc_makecommerce_domain'), join(', ', $missing_ids)); }
2283 $sendback = add_query_arg(array('post_type' => 'shop_order', 'mk_pdf' => urlencode($response->labelUrl), 'mk_err' => urlencode($mk_err)), '');
2284 wp_redirect(esc_url_raw($sendback));
2285 exit();
2286 }
2287
2288 function mk_get_machines($carrier, $country = null) {
2289 $data = get_option('mk_machines_cache', false);
2290 $data_expires = get_option('mk_machines_expires', false);
2291 if (!$data || empty($data) || $data_expires < time()) {
2292 $MK = mk_get_api();
2293 if(!$MK) {
2294 return array();
2295 }
2296 $data = $MK->getDestinations(array('type' => 'APT,PUP'));
2297 update_option('mk_machines_cache', $data, 'no');
2298 update_option('mk_machines_expires', time()+3*60*60, 'no');
2299 }
2300
2301 $machines = array();
2302 if (!$data || empty($data)) {
2303 return array();
2304 }
2305 foreach ($data as $machine) {
2306 if ((!$country || $machine->country === $country) && ($machine->type === 'APT' || $machine->type === 'PUP') && ($carrier === '*' || strtolower($carrier) === strtolower($machine->carrier))) {
2307 $machines[] = array(
2308 'carrier' => strtolower($machine->carrier),
2309 'id' => $machine->id,
2310 'name' => $machine->name,
2311 'city' => $machine->city,
2312 'address' => !empty($machine->address) ? $machine->address : '',
2313 );
2314 }
2315 }
2316 usort($machines, function($a, $b){
2317 if ($a['city'] === $b['city']) {
2318 return $a['name'] > $b['name'];
2319 }
2320 return $a['city'] > $b['city'];
2321 });
2322 return $machines;
2323 }
2324
2325 function mk_get_machine($carrier, $id) {
2326 $machines = mk_get_machines($carrier);
2327 foreach ($machines as $machine) {
2328 if ($machine['carrier'] === $carrier && $machine['id'] == $id) {
2329 return $machine;
2330 }
2331 }
2332 return false;
2333 }
2334
2335 function print_parcel_machine_label_action( $post_id ) {
2336 $shipment_id = get_post_meta($post_id, '_parcel_machine_shipment_id', true);
2337 if (!$shipment_id) { return; }
2338 ?>
2339 <li class="wide">
2340 <a id="print_parcel_machine_label" href="#" class="button"><?php _e('Print parcel label', 'wc_makecommerce_domain');?></a>
2341 <img class="mc_loading" src="<?php echo site_url('/wp-admin/images/loading.gif');?>">
2342 <script type="text/javascript">
2343 jQuery(function($){
2344 var data = {
2345 'action': 'print_pml',
2346 'id': '<?php echo $post_id; ?>'
2347 };
2348 var loading = $('.mc_loading');
2349 $('#print_parcel_machine_label').click(function(e){
2350 e.preventDefault();
2351 var button = $(this);
2352 button.addClass('disabled');
2353 loading.show();
2354 $.post(ajaxurl, data, function(response) {
2355 button.removeClass('disabled');
2356 loading.hide();
2357 window.open(response, 'pdf');
2358 });
2359 });
2360 });
2361 </script>
2362 </li>
2363 <?php
2364 }
2365 add_action('woocommerce_order_actions_end', 'print_parcel_machine_label_action');
2366
2367 function ajax_print_pml() {
2368 if(!current_user_can('manage_woocommerce') ) {
2369 die();
2370 }
2371 echo mk_get_labels(array(intval($_POST['id'])), true);
2372 die();
2373 }
2374 add_action( 'wp_ajax_print_pml', 'ajax_print_pml' );
2375
2376
2377 function clear_wc_shipping_rates_cache(){
2378 $packages = WC()->cart->get_shipping_packages();
2379 foreach ($packages as $key => $value) {
2380 $shipping_session = "shipping_for_package_$key";
2381 unset(WC()->session->$shipping_session);
2382 }
2383 }
2384 add_filter('woocommerce_checkout_update_order_review', 'clear_wc_shipping_rates_cache');
2385
2386
2387
2388 function api_javascript_ui( $data ) {
2389 ?>
2390 <script type="text/javascript">
2391 jQuery(document).ready(function($) {
2392 var env_select = $('#mk_api_type');
2393 var test_fields = ['mk_test_shop_id', 'mk_test_private_key', 'mk_test_public_key'];
2394 var live_fields = ['mk_shop_id', 'mk_private_key', 'mk_public_key'];
2395
2396 env_select.on('change', function(){
2397 hideFileds($(this).val());
2398 });
2399 hideFileds(env_select.val());
2400 function hideFileds(type) {
2401 var hide = type == 'live' ? test_fields : live_fields;
2402 var show = type == 'live' ? live_fields : test_fields;
2403 $.each(hide, function(i, elem) {
2404 $('#'+elem).closest('tr').hide();
2405 });
2406 $.each(show, function(i, elem) {
2407 $('#'+elem).closest('tr').show();
2408 });
2409 }
2410 });
2411 </script>
2412 <?php
2413 }
2414
2415
2416
2417
2418