$party, 'carrier' => isset($s['return_carrier']) ? sanitize_key((string) $s['return_carrier']) : '', ); } public static function describe_party($party) { if ('recipient' === $party) { return __('The shop pays for the return', 'ai-eshop-optimizer'); } if ('sender' === $party) { return __('The customer pays for the return', 'ai-eshop-optimizer'); } return __('Not decided yet', 'ai-eshop-optimizer'); } private static function boot_couriers() { static $done = false; if ($done) { return; } $done = true; if (class_exists('AIEO_Courier_Driver_Base', false)) { return; } if (!defined('AIEO_DIR')) { return; } $base = AIEO_DIR . 'includes/dmm/fulfillment/'; foreach (array( 'class-aieo-courier-driver-base.php', 'class-aieo-courier-driver-api-base.php', 'class-aieo-runtime-fulfillment-urls.php', 'class-aieo-fulfillment-settings.php', ) as $f) { if (file_exists($base . $f)) { require_once $base . $f; } } foreach ((array) glob($base . 'drivers/class-aieo-courier-driver-*.php') as $path) { require_once $path; } } public static function drivers() { self::boot_couriers(); if (!class_exists('AIEO_Courier_Driver_Base')) { return array(); } $drivers = apply_filters('aieo_fulfillment_couriers', array()); return is_array($drivers) ? $drivers : array(); } private static function has_credentials($driver, array $cfg) { if (empty($cfg)) { return false; } $required = array(); if (method_exists($driver, 'settings_schema')) { foreach ((array) $driver->settings_schema() as $field => $meta) { if (!empty($meta['required'])) { $required[] = $field; } } } if (!empty($required)) { foreach ($required as $field) { if (!isset($cfg[$field]) || trim((string) $cfg[$field]) === '') { return false; } } return true; } return AIEO_Courier_Driver_Base::has_own_settings($cfg); } public static function courier_options() { $defaults = array( (string) self::policy()['carrier'], (string) (class_exists('AIEO_Fulfillment_Settings') ? AIEO_Fulfillment_Settings::get('default_carrier', '') : ''), ); $out = array(); foreach (self::drivers() as $code => $driver) { $cfg = class_exists('AIEO_Fulfillment_Settings') ? (array) AIEO_Fulfillment_Settings::get('courier_' . $code, array()) : array(); $mode = method_exists($driver, 'create_mode') ? (string) $driver->create_mode() : 'api'; $configured = ('api' === $mode) && self::has_credentials($driver, $cfg); $rmode = method_exists($driver, 'returns_mode') ? (string) $driver->returns_mode($cfg) : (!empty($cfg['supports_returns']) ? 'api' : 'none'); $out[$code] = array( 'label' => (string) $driver->label(), 'configured' => $configured, 'can_print' => $configured && $driver->has_capability('print'), 'can_return' => $driver->has_capability('returns'), 'returns_mode' => $rmode, 'offers_returns' => 'none' !== $rmode, 'api_returns' => 'api' === $rmode && $driver->has_capability('returns') && $configured, 'in_use' => method_exists($driver, 'in_use') ? $driver->in_use($cfg) : (0 === strpos($code, 'custom__') || !empty($cfg)), ); } return $out; } public static function return_courier_options() { $all = self::courier_options(); $out = array(); $any = array(); $any_use = false; foreach ($all as $code => $o) { if (!empty($o['in_use'])) { $any_use = true; } if (empty($o['offers_returns'])) { continue; } $any[$code] = $o; if (!empty($o['in_use'])) { $out[$code] = $o; } } return ($any_use || empty($any)) ? $out : $any; } public static function manual_return_couriers() { $out = array(); foreach (self::courier_options() as $code => $o) { if (empty($o['in_use'])) { continue; } if (empty($o['offers_returns'])) { continue; } if (!empty($o['api_returns'])) { continue; } $out[$code] = $o; } return $out; } public static function default_carrier($row) { $options = self::return_courier_options(); if (empty($options)) { return ''; } $recorded = isset($row->return_carrier) ? (string) $row->return_carrier : ''; if ($recorded !== '' && isset($options[$recorded])) { return $recorded; } $preferred = array( self::policy()['carrier'], self::dispatch_carrier((int) $row->order_id), ); foreach ($preferred as $c) { if ($c !== '' && isset($options[$c]) && !empty($options[$c]['api_returns'])) { return $c; } } foreach ($options as $code => $o) { if (!empty($o['api_returns'])) { return $code; } } foreach ($preferred as $c) { if ($c !== '' && isset($options[$c]) && $options[$c]['configured']) { return $c; } } foreach ($options as $code => $o) { if ($o['configured']) { return $code; } } foreach ($preferred as $c) { if ($c !== '' && isset($options[$c])) { return $c; } } return (string) key($options); } public static function driver($code) { $code = sanitize_key((string) $code); if ($code === '') { return null; } $all = self::drivers(); return isset($all[$code]) ? $all[$code] : null; } public static function resolve_carrier($row, $chosen = '') { $options = self::return_courier_options(); $usable = static function ($code) use ($options) { return $code !== '' && isset($options[$code]) && !empty($options[$code]['api_returns']); }; $chosen = sanitize_key((string) $chosen); if ($usable($chosen)) { return $chosen; } $explicit = isset($row->return_carrier) ? sanitize_key((string) $row->return_carrier) : ''; if ($usable($explicit)) { return $explicit; } if ($usable(self::policy()['carrier'])) { return self::policy()['carrier']; } $dispatch = self::dispatch_carrier((int) $row->order_id); if ($usable($dispatch)) { return $dispatch; } foreach ($options as $code => $o) { if (!empty($o['api_returns'])) { return $code; } } return self::NO_CARRIER; } public static function dispatch_carrier($order_id) { global $wpdb; $t = $wpdb->prefix . 'aieo_dmm_fulfillment_vouchers'; if ($wpdb->get_var("SHOW TABLES LIKE '{$t}'") !== $t) { return ''; } return (string) $wpdb->get_var($wpdb->prepare( "SELECT carrier FROM {$t} WHERE order_id = %d ORDER BY id DESC LIMIT 1", (int) $order_id )); } public static function declaration($declaration_id) { global $wpdb; $t = $wpdb->prefix . 'aieo_dmm_withdrawal_declarations'; return $wpdb->get_row($wpdb->prepare( "SELECT * FROM {$t} WHERE id = %d", (int) $declaration_id )); } public static function issue($declaration_id, $chosen = '') { $row = self::declaration($declaration_id); if (!$row) { return new WP_Error('aieo_wdr_missing', __('Declaration not found.', 'ai-eshop-optimizer')); } if (!empty($row->return_voucher_no)) { return array('carrier' => (string) $row->return_carrier, 'voucher_no' => (string) $row->return_voucher_no); } if (AIEO_Withdrawal::TIER_AUTO_CANCEL === $row->tier) { return self::fail($declaration_id, __('This order was cancelled before dispatch, so there is nothing to send back.', 'ai-eshop-optimizer')); } $policy = self::policy(); if ($policy['charge_party'] === '') { return self::fail($declaration_id, __('Set who pays for withdrawal returns in Operations → Withdrawal Right before issuing return vouchers.', 'ai-eshop-optimizer')); } $carrier = self::resolve_carrier($row, $chosen); if ($carrier === self::NO_CARRIER) { return self::fail($declaration_id, __('No courier here can issue a return voucher through its API. Set "Collects returns for us" on the couriers that collect for you, in Operations → Couriers (the carrier list, not Courier Settings). If they take returns but we hold no API for them, book the collection at their portal and record the number below.', 'ai-eshop-optimizer')); } $driver = self::driver($carrier); if (!$driver || !$driver->has_capability('returns')) { return self::fail($declaration_id, sprintf( __('Courier "%s" cannot issue return vouchers — arrange the collection manually and record the number here.', 'ai-eshop-optimizer'), $carrier )); } $order = wc_get_order((int) $row->order_id); if (!$order instanceof WC_Order) { return self::fail($declaration_id, __('Order not found.', 'ai-eshop-optimizer')); } $result = $driver->create_return_voucher(self::payload($order, $row, $policy)); if (empty($result['ok']) || empty($result['voucher_no'])) { return self::fail($declaration_id, (string) ($result['error'] ?? __('The courier rejected the return voucher.', 'ai-eshop-optimizer'))); } self::store($declaration_id, $carrier, (string) $result['voucher_no']); if ($driver->has_capability('calculate_cost')) { $cost = $driver->calculate_cost(self::payload($order, $row, $policy)); if (!empty($cost['ok']) && isset($cost['cost'])) { self::store_cost($declaration_id, (int) $row->order_id, (float) $cost['cost']); } } return array('carrier' => $carrier, 'voucher_no' => (string) $result['voucher_no']); } public static function record_manual($declaration_id, $carrier, $voucher_no) { $row = self::declaration($declaration_id); if (!$row) { return new WP_Error('aieo_wdr_missing', __('Declaration not found.', 'ai-eshop-optimizer')); } $carrier = sanitize_key((string) $carrier); $voucher_no = trim(sanitize_text_field((string) $voucher_no)); if ($voucher_no === '') { return new WP_Error('aieo_wdr_no_number', __('Enter the return voucher number.', 'ai-eshop-optimizer')); } self::store($declaration_id, $carrier, $voucher_no); return array('carrier' => $carrier, 'voucher_no' => $voucher_no); } public static function pickup_fields() { return array('name', 'address_1', 'city', 'postcode', 'phone'); } public static function pickup_for($row, WC_Order $order) { $base = array( 'name' => trim($order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name()) ?: trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name()), 'address_1' => trim($order->get_shipping_address_1() . ' ' . $order->get_shipping_address_2()) ?: trim($order->get_billing_address_1() . ' ' . $order->get_billing_address_2()), 'city' => $order->get_shipping_city() ?: $order->get_billing_city(), 'postcode' => $order->get_shipping_postcode() ?: $order->get_billing_postcode(), 'phone' => $order->get_billing_phone(), 'country' => $order->get_shipping_country() ?: $order->get_billing_country() ?: 'GR', 'email' => $order->get_billing_email(), ); $stored = (isset($row->return_pickup) && $row->return_pickup !== null && $row->return_pickup !== '') ? json_decode((string) $row->return_pickup, true) : null; if (!is_array($stored)) { return $base; } foreach (self::pickup_fields() as $f) { if (isset($stored[$f]) && trim((string) $stored[$f]) !== '') { $base[$f] = trim((string) $stored[$f]); } } return $base; } public static function set_pickup($declaration_id, array $fields) { $row = self::declaration($declaration_id); if (!$row) { return new WP_Error('aieo_wdr_missing', __('Declaration not found.', 'ai-eshop-optimizer')); } if (!empty($row->return_voucher_no)) { return new WP_Error( 'aieo_wdr_locked', __('The voucher is already printed with the current address. Cancel it before changing where the courier collects.', 'ai-eshop-optimizer') ); } $clean = array(); foreach (self::pickup_fields() as $f) { if (!isset($fields[$f])) { continue; } $v = trim(sanitize_text_field((string) $fields[$f])); if ($v !== '') { $clean[$f] = mb_substr($v, 0, 190); } } global $wpdb; $wpdb->update( $wpdb->prefix . 'aieo_dmm_withdrawal_declarations', array('return_pickup' => empty($clean) ? null : wp_json_encode($clean)), array('id' => (int) $declaration_id), array('%s'), array('%d') ); return $clean; } public static function clear_voucher($declaration_id) { $row = self::declaration($declaration_id); if (!$row) { return new WP_Error('aieo_wdr_missing', __('Declaration not found.', 'ai-eshop-optimizer')); } if (!empty($row->approved_at_gmt)) { return new WP_Error( 'aieo_wdr_approved', __('The customer already has this label. Contact them before changing the courier.', 'ai-eshop-optimizer') ); } if (empty($row->return_voucher_no) && empty($row->return_label_path)) { return array('cleared' => false); } $was_carrier = (string) $row->return_carrier; $was_voucher = (string) $row->return_voucher_no; self::delete_uploaded_label($row); global $wpdb; $wpdb->update( $wpdb->prefix . 'aieo_dmm_withdrawal_declarations', array( 'return_carrier' => null, 'return_voucher_no' => null, 'return_voucher_at_gmt' => null, 'return_shipping_cost' => null, 'return_label_path' => null, ), array('id' => (int) $declaration_id), array('%s', '%s', '%s', '%s', '%s'), array('%d') ); $order = wc_get_order((int) $row->order_id); if ($order instanceof WC_Order) { $order->add_order_note( sprintf( __('Withdrawal return voucher detached (%1$s %2$s) so a different courier could be chosen. It was NOT cancelled at the carrier — cancel it there if it is not being reused.', 'ai-eshop-optimizer'), $was_carrier, $was_voucher ), false ); } return array('cleared' => true, 'carrier' => $was_carrier, 'voucher_no' => $was_voucher); } public static function approve($declaration_id, $actor_id = 0) { $row = self::declaration($declaration_id); if (!$row) { return new WP_Error('aieo_wdr_missing', __('Declaration not found.', 'ai-eshop-optimizer')); } if (AIEO_Withdrawal::STATUS_AWAITING_APPROVAL !== $row->status) { return new WP_Error('aieo_wdr_not_awaiting', __('That declaration is not awaiting approval.', 'ai-eshop-optimizer')); } $has_voucher = !empty($row->return_voucher_no) || !empty($row->return_label_path); global $wpdb; $wpdb->update( $wpdb->prefix . 'aieo_dmm_withdrawal_declarations', array( 'status' => AIEO_Withdrawal::STATUS_PENDING, 'approved_at_gmt' => current_time('mysql', true), 'approved_by_user_id' => (int) $actor_id, ), array('id' => (int) $declaration_id), array('%s', '%s', '%d'), array('%d') ); $order = wc_get_order((int) $row->order_id); if ($order instanceof WC_Order) { $order->add_order_note( $has_voucher ? sprintf( __('Withdrawal return approved and sent to the customer (%1$s, voucher %2$s).', 'ai-eshop-optimizer'), (string) $row->return_carrier, (string) $row->return_voucher_no ) : __('Withdrawal return approved. No courier voucher — the collection is being arranged manually.', 'ai-eshop-optimizer'), false ); } do_action('aieo_withdrawal_return_approved', (int) $declaration_id, $order, $has_voucher); return array('status' => AIEO_Withdrawal::STATUS_PENDING, 'has_voucher' => $has_voucher); } public static function payload(WC_Order $order, $row, array $policy) { $shop = class_exists('AIEO_Order_Document_Base') ? AIEO_Order_Document_Base::shop_info() : array(); $pickup = self::pickup_for($row, $order); $sender = array( 'name' => $pickup['name'], 'address' => $pickup['address_1'], 'city' => $pickup['city'], 'zip' => $pickup['postcode'], 'country' => $pickup['country'], 'phone' => $pickup['phone'], 'email' => $pickup['email'], ); $recipient = array( 'name' => (string) ($shop['name'] ?? get_bloginfo('name')), 'address' => trim((string) ($shop['address_1'] ?? '') . ' ' . (string) ($shop['address_2'] ?? '')), 'city' => (string) ($shop['city'] ?? ''), 'zip' => (string) ($shop['postcode'] ?? ''), 'country' => (string) ($shop['country'] ?? 'GR') ?: 'GR', 'phone' => (string) ($shop['phone'] ?? ''), 'email' => (string) ($shop['email'] ?? get_option('admin_email')), ); return array( 'order_id' => (int) $order->get_id(), 'is_return' => true, 'sender' => $sender, 'recipient' => $recipient, 'charge_party' => (string) $policy['charge_party'], 'reference_1' => (string) $order->get_order_number(), 'pieces' => 1, 'weight' => 0.5, 'cod_amount' => 0, 'comments' => sprintf( __('Withdrawal return for order %s', 'ai-eshop-optimizer'), $order->get_order_number() ), ); } public static function allowed_label_types() { return array( 'pdf' => 'application/pdf', 'png' => 'image/png', 'jpg' => 'image/jpeg', ); } public static function store_uploaded_label($declaration_id, array $file, $carrier = '') { $row = self::declaration($declaration_id); if (!$row) { return new WP_Error('aieo_wdr_missing', __('Declaration not found.', 'ai-eshop-optimizer')); } if (!empty($row->approved_at_gmt)) { return new WP_Error( 'aieo_wdr_approved', __('The customer already has a label for this return. Contact them before replacing it.', 'ai-eshop-optimizer') ); } if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) { return new WP_Error('aieo_wdr_no_file', __('No file was uploaded.', 'ai-eshop-optimizer')); } if (!empty($file['error'])) { return new WP_Error('aieo_wdr_upload_error', __('The upload did not complete. Try again.', 'ai-eshop-optimizer')); } $max = (int) apply_filters('aieo_withdrawal_label_max_bytes', 8 * MB_IN_BYTES); if ((int) $file['size'] > $max) { return new WP_Error('aieo_wdr_too_big', sprintf( __('That file is larger than %s.', 'ai-eshop-optimizer'), size_format($max) )); } $allowed = self::allowed_label_types(); $ext = ''; if (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = $finfo ? finfo_file($finfo, $file['tmp_name']) : ''; if ($finfo) { finfo_close($finfo); } $ext = (string) array_search((string) $mime, $allowed, true); } if ($ext === '') { $check = wp_check_filetype_and_ext($file['tmp_name'], (string) $file['name'], $allowed); $ext = !empty($check['ext']) ? (string) $check['ext'] : ''; } if ($ext === '' || !isset($allowed[$ext])) { return new WP_Error('aieo_wdr_bad_type', __('Labels must be a PDF, PNG or JPEG.', 'ai-eshop-optimizer')); } $uploads = wp_upload_dir(null, false); if (!empty($uploads['error'])) { return new WP_Error('aieo_wdr_uploads', (string) $uploads['error']); } $rel_dir = 'aieo-dmm/withdrawal/labels/' . gmdate('Y/m'); $abs_dir = trailingslashit($uploads['basedir']) . $rel_dir; if (!wp_mkdir_p($abs_dir)) { return new WP_Error('aieo_wdr_mkdir', __('Could not create the label folder.', 'ai-eshop-optimizer')); } try { $name = 'return-' . bin2hex(random_bytes(16)) . '.' . $ext; } catch (Exception $e) { return new WP_Error('aieo_wdr_random', __('Could not generate a filename.', 'ai-eshop-optimizer')); } if (!@move_uploaded_file($file['tmp_name'], $abs_dir . '/' . $name)) { return new WP_Error('aieo_wdr_move', __('Could not save the uploaded label.', 'ai-eshop-optimizer')); } @chmod($abs_dir . '/' . $name, 0644); self::delete_uploaded_label($row); global $wpdb; $wpdb->update( $wpdb->prefix . 'aieo_dmm_withdrawal_declarations', array('return_label_path' => $rel_dir . '/' . $name), array('id' => (int) $declaration_id), array('%s'), array('%d') ); $carrier = sanitize_key((string) $carrier); if ('' !== $carrier && empty($row->return_carrier)) { self::store($declaration_id, $carrier, (string) $row->return_voucher_no); } return array('path' => $rel_dir . '/' . $name, 'ext' => $ext); } private static function delete_uploaded_label($row) { if (empty($row->return_label_path)) { return; } $uploads = wp_upload_dir(null, false); if (!empty($uploads['error'])) { return; } $rel = ltrim((string) $row->return_label_path, '/'); if (strpos($rel, '..') !== false) { return; } $abs = trailingslashit($uploads['basedir']) . $rel; if (is_file($abs)) { @unlink($abs); } } public static function uploaded_label_path($row) { if (empty($row->return_label_path)) { return ''; } $rel = ltrim((string) $row->return_label_path, '/'); if (strpos($rel, '..') !== false) { return ''; } $uploads = wp_upload_dir(null, false); if (!empty($uploads['error'])) { return ''; } $abs = trailingslashit($uploads['basedir']) . $rel; return is_readable($abs) ? $abs : ''; } public static function has_label($row) { if (self::uploaded_label_path($row) !== '') { return true; } if (empty($row->return_voucher_no)) { return false; } $options = self::courier_options(); $carrier = (string) $row->return_carrier; return isset($options[$carrier]) && $options[$carrier]['can_print']; } public static function label_pdf($row) { $fail = static function ($msg) { return array('ok' => false, 'pdf' => null, 'filename' => '', 'mime' => '', 'error' => $msg); }; $uploaded = self::uploaded_label_path($row); if ($uploaded !== '') { $bytes = @file_get_contents($uploaded); if ($bytes === false) { return $fail(__('The uploaded label could not be read. Upload it again.', 'ai-eshop-optimizer')); } $ext = strtolower((string) pathinfo($uploaded, PATHINFO_EXTENSION)); $allowed = self::allowed_label_types(); return array( 'ok' => true, 'pdf' => $bytes, 'filename' => sanitize_file_name('return-label-' . (int) $row->id . '.' . $ext), 'mime' => isset($allowed[$ext]) ? $allowed[$ext] : 'application/octet-stream', 'error' => null, ); } if (empty($row->return_voucher_no)) { return $fail(__('No return label has been issued or uploaded for this withdrawal yet.', 'ai-eshop-optimizer')); } $driver = self::driver((string) $row->return_carrier); if (!$driver || !$driver->has_capability('print')) { return $fail(__('This courier cannot produce a label for us to send. Upload the one from their portal instead.', 'ai-eshop-optimizer')); } $res = $driver->get_label_pdf((string) $row->return_voucher_no); if (empty($res['ok']) || empty($res['pdf'])) { return $fail((string) ($res['error'] ?? __('The courier did not return a label.', 'ai-eshop-optimizer'))); } return array( 'ok' => true, 'pdf' => $res['pdf'], 'filename' => sanitize_file_name( 'return-' . (string) $row->return_carrier . '-' . (string) $row->return_voucher_no . '.pdf' ), 'mime' => 'application/pdf', 'error' => null, ); } public static function label_row_for_order($order_id) { global $wpdb; $t = $wpdb->prefix . 'aieo_dmm_withdrawal_declarations'; $rows = (array) $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$t} WHERE order_id = %d AND approved_at_gmt IS NOT NULL ORDER BY id DESC LIMIT 5", (int) $order_id )); foreach ($rows as $row) { if (self::has_label($row)) { return $row; } } return null; } private static function store($declaration_id, $carrier, $voucher_no) { global $wpdb; $wpdb->update( $wpdb->prefix . 'aieo_dmm_withdrawal_declarations', array( 'return_carrier' => $carrier, 'return_voucher_no' => $voucher_no, 'return_voucher_at_gmt' => current_time('mysql', true), 'return_voucher_error' => null, ), array('id' => (int) $declaration_id), array('%s', '%s', '%s', '%s'), array('%d') ); do_action('aieo_withdrawal_return_voucher_issued', (int) $declaration_id, $carrier, $voucher_no); } private static function store_cost($declaration_id, $order_id, $cost) { global $wpdb; $wpdb->update( $wpdb->prefix . 'aieo_dmm_withdrawal_declarations', array('return_shipping_cost' => (float) $cost), array('id' => (int) $declaration_id), array('%f'), array('%d') ); $oc = $wpdb->prefix . 'aieo_dmm_order_cancellations'; if ($wpdb->get_var("SHOW TABLES LIKE '{$oc}'") === $oc) { $wpdb->update( $oc, array('return_shipping_cost' => (float) $cost), array('order_id' => (int) $order_id), array('%f'), array('%d') ); } } private static function fail($declaration_id, $message) { global $wpdb; $wpdb->update( $wpdb->prefix . 'aieo_dmm_withdrawal_declarations', array('return_voucher_error' => mb_substr($message, 0, 255)), array('id' => (int) $declaration_id), array('%s'), array('%d') ); return new WP_Error('aieo_wdr_failed', $message); } }