ACS. * * Handles the outbound flow: * - order created/updated -> build ACS payload -> POST /order/createOrder * - order cancelled -> POST /order/cancelOrderForWoocommerce * - tag filter (only sync orders carrying a required tag, when enabled) * - tag-driven payload fields (IcePack, customerdob-*, shipdate-*, insurance-*, * subscription plan tags, Weship ship-method tag mapping) * - order delay + retry queue * * @package Weship_ACS_Sync */ defined( 'ABSPATH' ) || exit; /** * Class Weship_ACS_Sync_Order_Sync */ class Weship_ACS_Sync_Order_Sync { const META_SYNC_STATUS = '_weship_acs_sync_sync_status'; // pending|synced|failed|timeout|skipped|cancelled. const META_SYNC_MESSAGE = '_weship_acs_sync_sync_message'; const META_SYNC_ATTEMPTS = '_weship_acs_sync_sync_attempts'; const META_ORDER_TAGS = '_weship_acs_sync_tags'; // comma separated tags, optional. const META_GIFT_NOTE = '_weship_acs_sync_gift_note'; const META_CANCEL_MESSAGE = '_weship_acs_sync_cancel_message'; const META_SYNC_HASH = '_weship_acs_sync_sync_hash'; const META_SENT_HASH = '_weship_acs_sync_sent_hash'; // md5 of the exact request body ACS last accepted — see sync_order(). const META_IS_CCP = '_weship_acs_sync_is_ccp'; const META_LABEL = '_weship_acs_sync_label'; const META_PACKING_SLIP = '_weship_acs_sync_packing_slip'; const META_CCP_DESCRIPTION = '_weship_acs_sync_ccp_description'; const META_FULFILLMENT_STATUS = '_weship_acs_sync_fulfillment_status'; // Shipped|Delivered, set from the ACS status webhook — independent of the WooCommerce order status. const META_EVER_SYNCED = '_weship_acs_sync_ever_synced'; // Set once sync_status first reaches 'synced'; never cleared, so the Sync Status column can keep showing "Synced" even after a later cancellation overwrites sync_status. const DEFAULT_PHONE = '999-999-9999'; /** * The only accepted date formats for the date-carrying order tags, as * documented in the Order Tags reference (Settings): "CustomerDOB-MM/DD/YYYY" * and "ShipDate-YYYY/MM/DD". See get_tag_date_error(). */ const DOB_TAG_FORMAT = 'm/d/Y'; const SHIP_DATE_TAG_FORMAT = 'Y/m/d'; /** * 800 Program (CCP) product-type tags. */ const CCP_ORDER_TAGS = array( 'WeShip_Express', 'WeShip_Express_Liquor', 'Weship-Wine', 'Weship-Ambient', 'Weship-ALT', 'Weship-Tobg', 'Weship-Beer', 'Weship-CDB', ); /** * API client. * * @var Weship_ACS_Sync_Api_Client */ private $api; /** * Logger. * * @var Weship_ACS_Sync_Logger */ private $logger; /** * True while sync_order()/queue_order()/cancel_order() is writing its * own result. Those methods call $order->save(), which synchronously * fires woocommerce_update_order — the same hook maybe_resync_on_update() * listens on. Without this guard, that nested call re-enters with a * freshly wc_get_order()'d copy of the order that may not yet reflect * the status/hash we just wrote, sees what looks like a changed * payload, and immediately overwrites the status we just set (typically * stomping 'synced'/'failed'/'cancelled' back to 'pending' on every call). * * @var bool */ private $is_writing = false; /** * Order IDs saved during this request, waiting for maybe_resync_on_update() * at shutdown — see queue_resync_on_update(). * * @var array */ private $resync_queue = array(); /** * Constructor. * * @param Weship_ACS_Sync_Api_Client $api API client. * @param Weship_ACS_Sync_Logger $logger Logger. */ public function __construct( Weship_ACS_Sync_Api_Client $api, Weship_ACS_Sync_Logger $logger ) { $this->api = $api; $this->logger = $logger; // Orders are only ever synced once they reach Processing — not configurable. add_action( 'woocommerce_order_status_processing', array( $this, 'maybe_sync_order' ), 20, 1 ); add_action( 'woocommerce_order_status_cancelled', array( $this, 'cancel_order' ), 20, 1 ); // Re-send already-synced orders to ACS when their address, // tags or line items change (e.g. edited on the order screen). add_action( 'woocommerce_update_order', array( $this, 'queue_resync_on_update' ), 20, 1 ); } /** * Note that an order was saved, and resync it once at the end of the * request instead of on every save. * * A single "Update" on the order edit screen saves the order several * times, one per meta box on woocommerce_process_shop_order_meta: items * (priority 10), our tags/gift note (20), then address/status (40), each * firing woocommerce_update_order. Resyncing on each one sent ACS one * request per changed section — the earlier ones with data the later * saves hadn't written yet. woocommerce_update_order also fires before * WC_Abstract_Order::save() has saved the line items, so a resync from * inside the hook can see stale items. Deferring to shutdown sends the * final state once. * * @param int $order_id Order ID. */ public function queue_resync_on_update( $order_id ) { // Our own result writes are not edits — see $is_writing's docblock. if ( $this->is_writing || ! $order_id ) { return; } if ( ! $this->resync_queue ) { add_action( 'shutdown', array( $this, 'process_resync_queue' ) ); } $this->resync_queue[ (int) $order_id ] = true; } /** * Run maybe_resync_on_update() once for every order saved this request. */ public function process_resync_queue() { $order_ids = array_keys( $this->resync_queue ); $this->resync_queue = array(); foreach ( $order_ids as $order_id ) { $this->maybe_resync_on_update( $order_id ); } } /** * Entry point when an order reaches a sync-eligible status. * * @param int $order_id Order ID. */ public function maybe_sync_order( $order_id ) { $order = wc_get_order( $order_id ); if ( ! $order ) { return; } // Already synced? Don't double-send. if ( 'synced' === $order->get_meta( self::META_SYNC_STATUS ) ) { return; } $skip_reason = $this->get_skip_reason( $order ); if ( '' !== $skip_reason ) { $order->update_meta_data( self::META_SYNC_STATUS, 'skipped' ); $order->update_meta_data( self::META_SYNC_MESSAGE, $skip_reason ); $order->save(); return; } // Order delay flag: queue for the cron instead of sending now. if ( $this->should_queue( $order ) ) { $this->queue_order( $order ); return; } $this->sync_order( $order ); } /** * Whether the order should be queued for the retry scheduler (Order * Delay enabled) rather than sent now. * * An order with invalid date tags is never queued: sync_order() rejects * it straight away instead, so the error shows on the order immediately * rather than only once the scheduler gets to it. * * @param WC_Order $order Order. * @return bool */ private function should_queue( WC_Order $order ) { return 'yes' === Weship_ACS_Sync_Api_Client::get_setting( 'order_delay', 'no' ) && '' === $this->get_tag_date_error( $this->get_order_tags( $order ) ); } /** * Whether $order currently qualifies to be skipped, and why. * * Shared between maybe_sync_order() (initial eligibility) and * maybe_resync_on_update() (re-evaluating a previously-skipped order), * since two of these three conditions are tag-driven and tags are exactly * the kind of thing a merchant corrects on an order after the fact (e.g. * adding the missing CCP product-type tag) — a skip caused by them isn't * permanent the way "no fulfillment required" (virtual/downloadable * order) is. * * @param WC_Order $order Order. * @return string Skip reason message, or '' if it should sync. */ private function get_skip_reason( WC_Order $order ) { // Tag filter (mirrors accounts.is_tags_enabled + order_tags). if ( 'yes' === Weship_ACS_Sync_Api_Client::get_setting( 'tags_enabled', 'no' ) ) { $required_tag = Weship_ACS_Sync_Api_Client::get_setting( 'required_tag' ); if ( $required_tag && ! in_array( strtolower( $required_tag ), array_map( 'strtolower', $this->get_order_tags( $order ) ), true ) ) { /* translators: %s: tag name */ return sprintf( __( 'Skipped: required tag "%s" not present.', 'weship-acs-sync-for-woocommerce' ), $required_tag ); } } // No fulfillment required (virtual/downloadable-only orders). if ( ! $this->order_needs_shipping( $order ) ) { return __( 'No Fulfillment Required', 'weship-acs-sync-for-woocommerce' ); } // 800 Program (CCP): only orders carrying a recognised CCP tag can be // classified to a product type there (see build_ccp_payload()) — an // order with none would just error out at ACS, so skip it locally // instead of attempting the send. if ( 'yes' === Weship_ACS_Sync_Api_Client::get_setting( 'ccp_enabled', 'no' ) && ! $this->has_valid_ccp_tags( $order ) ) { return __( 'Skipped: 800 Program (CCP) is enabled but no valid CCP order tag is present.', 'weship-acs-sync-for-woocommerce' ); } return ''; } /** * Queue an order for the retry scheduler instead of sending it now. * * Also stamps META_SYNC_HASH with the payload as queued, so the * woocommerce_update_order save this triggers (and any further * unrelated save before the scheduler runs) doesn't see a "changed" * payload and re-queue/re-send on top of it — see maybe_resync_on_update(). * Uses payload_hash() (not a hash of $payload alone) so it stays * consistent with the hash sync_order() stores on the same field. * * @param WC_Order $order Order. */ private function queue_order( WC_Order $order ) { $this->is_writing = true; $is_ccp = 'yes' === Weship_ACS_Sync_Api_Client::get_setting( 'ccp_enabled', 'no' ); $payload = $this->build_sync_payload( $order ); $order->update_meta_data( self::META_SYNC_STATUS, 'pending' ); $order->update_meta_data( self::META_SYNC_HASH, $this->payload_hash( $order ) ); $order->update_meta_data( self::META_SYNC_MESSAGE, __( 'Queued (order delay enabled).', 'weship-acs-sync-for-woocommerce' ) ); $order->save(); $this->is_writing = false; // No HTTP call happens yet — log the payload as queued so it's visible // in the Logs tab / Orders page before the retry scheduler sends it. $this->logger->log( $is_ccp ? 'ccp_save_order' : 'create_order', 'outbound', '', $order->get_id(), 'queued', __( 'Order delay enabled — queued for the next retry scheduler run.', 'weship-acs-sync-for-woocommerce' ), (string) wp_json_encode( $payload ) ); } /** * Runs at shutdown for each order saved during the request (see * queue_resync_on_update()). Re-sends the order to ACS when its * address, tags or line items changed since our last attempt. * * ACS has no partial-update endpoint — an updated order is * resent to the same create-order endpoint in full. We narrow that to * orders that are still Processing and whose outbound payload actually * changed since our last attempt — otherwise every order save * (including our own, after syncing) would trigger a resend loop. * * Applies to 'synced', 'pending', 'failed' AND 'skipped' orders, since * editing the order (e.g. fixing a bad address, or adding the CCP/ * required tag that was missing at creation) may be exactly what makes a * retry succeed or a skip no longer apply. Only '' (never evaluated) and * 'cancelled' orders are left alone. * * @param int $order_id Order ID. */ public function maybe_resync_on_update( $order_id ) { // Don't re-enter while sync_order()/queue_order()/cancel_order() is // mid-write — see $is_writing's docblock. if ( $this->is_writing ) { return; } $order = wc_get_order( $order_id ); if ( ! $order ) { return; } $status = (string) $order->get_meta( self::META_SYNC_STATUS ); if ( in_array( $status, array( '', 'cancelled' ), true ) ) { return; } // Once shipped/cancelled/refunded, further edits are not sent on. if ( ! $order->has_status( 'processing' ) ) { return; } if ( 'skipped' === $status ) { // A skip can be tag-driven (required tag / CCP tag) and tags are // exactly the kind of thing that gets corrected after the order // was created — re-run the same eligibility check // maybe_sync_order() used rather than assuming the original skip // reason still holds. $skip_reason = $this->get_skip_reason( $order ); if ( '' !== $skip_reason ) { if ( $skip_reason !== (string) $order->get_meta( self::META_SYNC_MESSAGE ) ) { $this->is_writing = true; $order->update_meta_data( self::META_SYNC_MESSAGE, $skip_reason ); $order->save(); $this->is_writing = false; } return; } // No longer skip-eligible (e.g. a valid tag was just added) — // fall through and treat this as a fresh initial-sync attempt. } else { // Resend only if the payload actually changed since our last // attempt (successful or not) — this is what stops every // incidental save (including our own) from re-triggering a send. $current_hash = $this->payload_hash( $order ); if ( $current_hash === (string) $order->get_meta( self::META_SYNC_HASH ) ) { return; } } // Order delay flag: queue for the cron instead of sending now. if ( $this->should_queue( $order ) ) { $this->queue_order( $order ); return; } // 'synced': treat as an update resync (a failed attempt won't knock it // back to pending/failed). 'pending'/'failed'/'skipped'-now-eligible: // never successfully synced, so treat as a fresh initial-sync attempt. $this->sync_order( $order, 'synced' === $status ); } /** * Build whichever outbound payload is currently active (standard ACS * feed or 800 Program/CCP), without sending it. * * @param WC_Order $order Order. * @return array */ private function build_sync_payload( WC_Order $order ) { return 'yes' === Weship_ACS_Sync_Api_Client::get_setting( 'ccp_enabled', 'no' ) ? $this->build_ccp_payload( $order ) : $this->build_acs_payload( $order ); } /** * Hash used to detect whether an order actually changed since it was * last synced/queued. * * Built from the outbound sync payload (address, tags, items, etc.) plus * the raw Weship tags string. The raw string is needed on top of the * payload because not every tag maps into a payload field — see * extract_tag_fields() — so a tag that isn't IcePack/CustomerDOB-/ * ShipDate-/Insurance-/a subscription tag/a recognised ship-method tag * has zero effect on the payload, and would never be seen as a change * (and thus never trigger a resync) without it. * * @param WC_Order $order Order. * @return string */ private function payload_hash( WC_Order $order ) { $snapshot = $this->build_sync_payload( $order ); $snapshot['_weship_acs_sync_raw_tags'] = $order->get_meta( self::META_ORDER_TAGS ); return md5( (string) wp_json_encode( $snapshot ) ); } /** * Build the payload and send the order to ACS. * * @param WC_Order $order Order. * @param bool $is_update Whether this is a resync of an already-synced order * (address/tags/items changed), vs. the initial sync. * @param bool $force Send even if the request is identical to the one ACS * last accepted (manual "Sync Order" button). * @return bool Success. */ public function sync_order( WC_Order $order, $is_update = false, $force = false ) { $this->is_writing = true; $is_ccp = 'yes' === Weship_ACS_Sync_Api_Client::get_setting( 'ccp_enabled', 'no' ); $tag_error = $this->get_tag_date_error( $this->get_order_tags( $order ) ); if ( '' !== $tag_error ) { // Invalid ShipDate/CustomerDOB tag: never send it to ACS. Log it // against the same event the send would have used, so it shows up // in the order's "View Logs" alongside its other sync attempts. $log_event = $is_update ? 'update_order' : ( $is_ccp ? 'ccp_save_order' : 'create_order' ); $result = array( 'success' => false, 'code' => 0, 'body' => $tag_error, 'log_id' => $this->logger->log( $log_event, 'outbound', '', $order->get_id(), 'error', $tag_error, (string) wp_json_encode( $this->build_sync_payload( $order ) ) ), 'timed_out' => false, 'validation_error' => true, ); } else { if ( $is_ccp ) { /** * Filter the ACS 800 Program (CCP) order payload before it is sent. * * @param array $payload Payload. * @param WC_Order $order Order. */ $payload = apply_filters( 'weship_acs_sync_ccp_order_payload', $this->build_ccp_payload( $order ), $order ); } else { /** * Filter the ACS order payload before it is sent. * * @param array $payload Payload. * @param WC_Order $order Order. */ $payload = apply_filters( 'weship_acs_sync_order_payload', $this->build_acs_payload( $order ), $order ); } // Never send ACS the same request twice: if this exact body is // what ACS last accepted for the order, there is nothing new to // send (e.g. a tag was changed that doesn't map to any payload // field). Only a successful send is remembered, so a failed or // timed-out attempt can still be retried with the same data. The // manual "Sync Order" button passes $force and always resends. $request_hash = md5( (string) wp_json_encode( $payload ) ); if ( ! $force && $request_hash === (string) $order->get_meta( self::META_SENT_HASH ) ) { $this->skip_unchanged_request( $order, $payload, $is_update ? 'update_order' : ( $is_ccp ? 'ccp_save_order' : 'create_order' ) ); return true; } $result = $is_ccp ? $this->sync_order_ccp( $order, $payload, $is_update ) : $this->api->create_order( $payload, $order->get_id(), $is_update ? 'update_order' : 'create_order' ); if ( $result['success'] ) { $order->update_meta_data( self::META_SENT_HASH, $request_hash ); } } // Record the payload we just attempted — success or not. This lets // maybe_resync_on_update() tell "genuinely edited" apart from "an // unrelated save happened while this order sits pending/failed", // without retrying an unchanged payload on every incidental save. $order->update_meta_data( self::META_SYNC_HASH, $this->payload_hash( $order ) ); // Attempts is an informational counter of initial-sync tries; update // resyncs don't count since a failed update never changes sync status. $attempts = (int) $order->get_meta( self::META_SYNC_ATTEMPTS ); if ( ! $is_update ) { $attempts++; $order->update_meta_data( self::META_SYNC_ATTEMPTS, $attempts ); } if ( $result['success'] ) { $order->update_meta_data( self::META_SYNC_STATUS, 'synced' ); $order->update_meta_data( self::META_EVER_SYNCED, '1' ); $order->update_meta_data( self::META_SYNC_MESSAGE, $is_update ? __( 'Order update sent to ACS.', 'weship-acs-sync-for-woocommerce' ) : __( 'Order sent to ACS.', 'weship-acs-sync-for-woocommerce' ) ); $order->add_order_note( $is_update ? __( 'WSE ACS Sync: order update (address/tags/items) synced successfully.', 'weship-acs-sync-for-woocommerce' ) : __( 'WSE ACS Sync: order synced successfully.', 'weship-acs-sync-for-woocommerce' ) ); } else { $message = is_string( $result['body'] ) ? $result['body'] : wp_json_encode( $result['body'] ); $timed_out = ! empty( $result['timed_out'] ); // An update resync failing shouldn't flip an already-synced order back to "Not Synced". // Any ACS error on the initial sync marks it "Not Synced" immediately (displayed // label for 'failed') — it only ever shows "Pending" while queued by Order Delay. // // A TIMEOUT specifically lands on its own 'timeout' status rather than // 'failed': we genuinely don't know whether ACS received and processed // the request before we gave up waiting for a response. 'failed' orders // get automatically resent by the retry cron (retry_pending_orders()) — // doing that here risks creating a duplicate order in ACS if the original // request actually went through. 'timeout' is deliberately excluded from // that automatic retry; resolving it means a human confirms with ACS // first, then uses "Sync Order" to resend manually if it's really needed. if ( ! $is_update ) { $order->update_meta_data( self::META_SYNC_STATUS, $timed_out ? 'timeout' : 'failed' ); } $order->update_meta_data( self::META_SYNC_MESSAGE, wp_strip_all_tags( (string) $message ) ); if ( ! empty( $result['validation_error'] ) ) { $order->add_order_note( sprintf( /* translators: %s: validation error message */ $is_update ? __( 'WSE ACS Sync: order update NOT sent to ACS. %s', 'weship-acs-sync-for-woocommerce' ) : __( 'WSE ACS Sync: order NOT sent to ACS. %s', 'weship-acs-sync-for-woocommerce' ), $message ) ); } elseif ( $timed_out ) { $order->add_order_note( sprintf( /* translators: %s: error message */ $is_update ? __( 'WSE ACS Sync: order update timed out waiting for ACS. %s The order may still have been received by ACS — this update was NOT automatically retried.', 'weship-acs-sync-for-woocommerce' ) : __( 'WSE ACS Sync: timed out waiting for ACS. %s The order may still have been received by ACS — verify there before using "Sync Order" again, to avoid creating a duplicate. This will not be retried automatically.', 'weship-acs-sync-for-woocommerce' ), wp_strip_all_tags( (string) $message ) ) ); } else { $order->add_order_note( sprintf( /* translators: 1: HTTP code, 2: error message */ $is_update ? __( 'WSE ACS Sync: order update failed (HTTP %1$s). %2$s', 'weship-acs-sync-for-woocommerce' ) : __( 'WSE ACS Sync: sync failed (HTTP %1$s). %2$s', 'weship-acs-sync-for-woocommerce' ), $result['code'], wp_strip_all_tags( (string) $message ) ) ); } } $order->save(); $this->is_writing = false; return (bool) $result['success']; } /** * Finish a sync_order() call whose request is identical to the one ACS * last accepted, without sending it. * * ACS already holds exactly this data, so the order is marked synced * (that also repairs the status if a later duplicate attempt had failed). * META_SYNC_HASH is refreshed so maybe_resync_on_update() doesn't keep * re-evaluating the same change. Logged as 'skipped' so it shows in * "View Logs", but no order note is added. * * @param WC_Order $order Order. * @param array $payload The request that would have been sent. * @param string $event Log event the send would have used. */ private function skip_unchanged_request( WC_Order $order, array $payload, $event ) { $message = __( 'No changes since the last request accepted by ACS — not sent again.', 'weship-acs-sync-for-woocommerce' ); $this->logger->log( $event, 'outbound', '', $order->get_id(), 'skipped', $message, (string) wp_json_encode( $payload ) ); $order->update_meta_data( self::META_SYNC_HASH, $this->payload_hash( $order ) ); $order->update_meta_data( self::META_SYNC_STATUS, 'synced' ); $order->update_meta_data( self::META_SYNC_MESSAGE, $message ); $order->save(); $this->is_writing = false; } /** * Send an order through the ACS 800 Program (CCP) and capture the * shipping label / packing slip URLs from the response. * * Handles both the ordersHeldInGateway and rejectedorders branches of * the CCP response. * * @param WC_Order $order Order. * @param array $payload Filtered CCP payload (see sync_order()). * @param bool $is_update Whether this is a resync of an already-synced order. * @return array{success:bool,code:int,body:array|string} */ private function sync_order_ccp( WC_Order $order, array $payload, $is_update = false ) { $result = $this->api->ccp_save_order( $payload, $order->get_id(), $is_update ? 'update_order' : 'ccp_save_order' ); if ( is_array( $result['body'] ) ) { $rejection = $this->apply_ccp_response( $order, $result['body'] ); // ACS returns HTTP 200 for a CCP order landing in rejectedorders // (a business-level rejection, e.g. "Tracking Id not generated"), // not just for an accepted one — the generic HTTP-status success // check in Weship_ACS_Sync_Api_Client::post() can't tell these // apart, so override it here using the response body instead. if ( '' !== $rejection ) { $result['success'] = false; $result['body'] = $rejection; // The log row was already written by post() with message // "OK" (it only sees the HTTP-level success) — amend it so // the Logs tab / "View Logs" modal shows the actual // rejection instead of a misleading "OK". $this->logger->update_message( $result['log_id'], $rejection ); } } return $result; } /** * Store the shipping label, packing slip and description returned by * the 800 Program on the order. * * @param WC_Order $order Order. * @param array $body Decoded CCP response body. * @return string Rejection description if the order was in rejectedorders, '' otherwise. */ private function apply_ccp_response( WC_Order $order, array $body ) { $order->update_meta_data( self::META_IS_CCP, 1 ); if ( ! empty( $body['ordersHeldInGateway'][0] ) && is_array( $body['ordersHeldInGateway'][0] ) ) { $ccp_order = $body['ordersHeldInGateway'][0]; if ( ! empty( $ccp_order['barcodeFileName'] ) ) { $order->update_meta_data( self::META_LABEL, sanitize_text_field( $ccp_order['barcodeFileName'] ) ); } if ( ! empty( $ccp_order['packingSlipUrl'] ) ) { $order->update_meta_data( self::META_PACKING_SLIP, esc_url_raw( $ccp_order['packingSlipUrl'] ) ); } if ( ! empty( $ccp_order['description'] ) ) { $order->update_meta_data( self::META_CCP_DESCRIPTION, sanitize_text_field( $ccp_order['description'] ) ); } return ''; } if ( ! empty( $body['rejectedorders']['order'][0] ) && is_array( $body['rejectedorders']['order'][0] ) ) { $rejected = $body['rejectedorders']['order'][0]; return ! empty( $rejected['description'] ) ? sanitize_text_field( $rejected['description'] ) : __( 'Order rejected by ACS (800 Program).', 'weship-acs-sync-for-woocommerce' ); } return ''; } /** * Cancel the order in ACS when cancelled in WooCommerce. * * @param int $order_id Order ID. * @param bool $force Skip the "must already be synced" guard (used by the manual Cancel Order button). * @return bool|null Success, or null if the order was skipped. */ public function cancel_order( $order_id, $force = false ) { $order = wc_get_order( $order_id ); if ( ! $order || ( ! $force && 'synced' !== $order->get_meta( self::META_SYNC_STATUS ) ) ) { return null; } $this->is_writing = true; $result = $this->api->cancel_order( array( $this->get_order_number( $order ) ), 'Order cancelled', $order->get_id() ); if ( $result['success'] ) { $body = $result['body']; // ACS's success body is { responseStatus, responseStatusCode, // responseObject } — responseObject carries the actual outcome // message (e.g. "Order cancelled"). $message = ( is_array( $body ) && isset( $body['responseObject'] ) && is_string( $body['responseObject'] ) ) ? $body['responseObject'] : ( is_string( $body ) ? $body : wp_json_encode( $body ) ); $message = wp_strip_all_tags( (string) $message ); $order->update_meta_data( self::META_SYNC_STATUS, 'cancelled' ); $order->update_meta_data( self::META_CANCEL_MESSAGE, $message ); // ACS no longer holds the last request we sent, so a later "Sync // Order" with the same data is a genuine resend, not a duplicate. $order->delete_meta_data( self::META_SENT_HASH ); $order->add_order_note( sprintf( /* translators: %s: message returned by ACS */ __( 'WSE ACS Sync: cancellation sent. ACS response: %s', 'weship-acs-sync-for-woocommerce' ), $message ) ); $order->save(); // Only ACS's exact cancellation-confirmed message actually // cancels the WooCommerce order — any other success message // (e.g. a partial/queued outcome) leaves its status untouched. if ( ! $order->has_status( 'cancelled' ) && 'order cancelled' === strtolower( trim( $message ) ) ) { $order->update_status( 'cancelled', __( 'WSE ACS Sync: order cancelled in ACS.', 'weship-acs-sync-for-woocommerce' ) ); } } else { $message = is_string( $result['body'] ) ? $result['body'] : wp_json_encode( $result['body'] ); $order->update_meta_data( self::META_CANCEL_MESSAGE, wp_strip_all_tags( (string) $message ) ); $order->add_order_note( __( 'WSE ACS Sync: cancellation failed. Please cancel manually in ACS.', 'weship-acs-sync-for-woocommerce' ) ); $order->save(); } $this->is_writing = false; return (bool) $result['success']; } /** * Retry both pending and failed orders (invoked by cron on the Order * Delay interval — there is no separate retry enable/disable flag). * * Deliberately does NOT include 'timeout' orders — see the 'timed_out' * handling in sync_order(): we don't know whether ACS actually received * one of those, so auto-resending it here could create a duplicate. * Those require a human to confirm with ACS and resync manually. */ public function retry_pending_orders() { $orders = wc_get_orders( array( 'limit' => 25, 'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query array( 'key' => self::META_SYNC_STATUS, 'value' => array( 'pending', 'failed' ), 'compare' => 'IN', ), ), ) ); foreach ( $orders as $order ) { // A 'failed' order whose date tags are still invalid would only // fail validation again (and add another identical log row/note // every run) — it waits for the tags to be corrected, which // triggers a resync via maybe_resync_on_update(). 'pending' // (queued) orders still go through, so a ship date that has // slipped into the past while queued gets reported. if ( 'failed' === $order->get_meta( self::META_SYNC_STATUS ) && '' !== $this->get_tag_date_error( $this->get_order_tags( $order ) ) ) { continue; } $this->sync_order( $order ); } } /** * Build the ACS order payload from a WooCommerce order. * * @param WC_Order $order Order. * @return array */ public function build_acs_payload( WC_Order $order ) { $account_id = Weship_ACS_Sync_Api_Client::get_setting( 'account_id' ); $items = array(); foreach ( $order->get_items() as $item ) { if ( ! $item instanceof WC_Order_Item_Product ) { continue; } $product = $item->get_product(); $qty = (int) $item->get_quantity(); $items[] = array( 'sku' => $product && $product->get_sku() ? $product->get_sku() : null, 'price' => $qty > 0 ? (string) wc_format_decimal( (float) $item->get_total() / $qty, 2 ) : '0.0', 'quantity' => $qty, ); } $tags = $this->get_order_tags( $order ); $tag_fields = $this->extract_tag_fields( $tags ); $shipping_title = $order->get_shipping_method(); $is_pickup = ( false !== stripos( (string) $shipping_title, 'local pickup' ) ) || $this->order_has_pickup_shipping( $order ); $ship_phone = $order->get_shipping_phone() ? $order->get_shipping_phone() : $order->get_billing_phone(); $payload = array( 'accountId' => $account_id, 'channel' => $account_id, // 'channelName' => Weship_ACS_Sync_Api_Client::get_setting( 'channel_name', 'WooCommerce' ), 'clientName' => Weship_ACS_Sync_Api_Client::get_setting( 'client_name' ), 'orderNumber' => $this->get_order_number( $order ), 'orgOrderNumber' => (string) $order->get_id(), 'referenceId' => $this->get_order_number( $order ), 'orderSourceDate' => $order->get_date_created() ? $order->get_date_created()->date( 'm-d-Y H:i:s' ) : '', 'orderType' => $is_pickup ? 7 : 2, 'd2cOrder' => true, 'orderItems' => $items, 'shipToName' => trim( $order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name() ), 'shipToEmail' => $order->get_billing_email(), 'shipToAddress' => $order->get_shipping_address_1() ? trim( $order->get_shipping_address_1() ) : null, 'shipToAddress2' => $order->get_shipping_address_2(), 'shipToCity' => $order->get_shipping_city(), 'shipToState' => $order->get_shipping_state(), 'shipToCountry' => $order->get_shipping_country(), 'postalCode' => $order->get_shipping_postcode() ? $order->get_shipping_postcode() : null, 'shipToMobile' => $ship_phone ? $ship_phone : self::DEFAULT_PHONE, 'companyName' => Weship_ACS_Sync_Api_Client::get_setting( 'channel_name', 'WooCommerce' ), 'billToName' => trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ), 'billToEmail' => $order->get_billing_email(), 'billToAddress' => $order->get_billing_address_1(), 'billToAddress2' => $order->get_billing_address_2(), 'billToCity' => $order->get_billing_city(), 'billToState' => $order->get_billing_state(), 'billToCountry' => $order->get_billing_country(), 'billToPostal' => $order->get_billing_postcode(), 'billToMobile' => $order->get_billing_phone() ? $order->get_billing_phone() : self::DEFAULT_PHONE, 'instructions' => $order->get_customer_note(), 'packingInstructions' => '', 'driverInstructions' => '', 'giftNote' => (string) $order->get_meta( self::META_GIFT_NOTE ), 'icePack' => $tag_fields['ice_pack'], 'customerDOB' => $tag_fields['customer_dob'], 'shipByDate' => $tag_fields['ship_date'], 'insuranceAmount' => $tag_fields['insurance'], 'subscriptionTag' => $tag_fields['subscription_tag'], 'wsShipMethod' => $tag_fields['ship_method'], ); // Drop nulls, like @JsonInclude(NON_NULL) in the original. return array_filter( $payload, function ( $value ) { return null !== $value; } ); } /** * Build the 800 Program (CCP) order payload from a WooCommerce order. * * @param WC_Order $order Order. * @return array */ public function build_ccp_payload( WC_Order $order ) { $tags = $this->get_order_tags( $order ); $tag_fields = $this->extract_tag_fields( $tags ); $ship_only = 'yes' === Weship_ACS_Sync_Api_Client::get_setting( 'ccp_ship_enabled', 'no' ); $product_type = ''; if ( ! $ship_only ) { $ccp_tags_lower = array_map( 'strtolower', self::CCP_ORDER_TAGS ); $matches = array_filter( $tags, function ( $tag ) use ( $ccp_tags_lower ) { return 0 !== strcasecmp( $tag, 'WeShip_Express' ) && in_array( strtolower( $tag ), $ccp_tags_lower, true ); } ); $product_type = implode( ',', $matches ); } $ship_phone = $order->get_shipping_phone() ? $order->get_shipping_phone() : $order->get_billing_phone(); $bill_phone = $order->get_billing_phone() ? $order->get_billing_phone() : self::DEFAULT_PHONE; $ship_to_address = array( 'name' => trim( $order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name() ), 'company' => $order->get_shipping_company(), 'address1' => $order->get_shipping_address_1(), 'address2' => $order->get_shipping_address_2(), 'city' => $order->get_shipping_city(), 'state' => $order->get_shipping_state(), 'postalCode' => $order->get_shipping_postcode(), 'country' => $order->get_shipping_country(), 'workPhone' => $ship_phone ? $ship_phone : self::DEFAULT_PHONE, 'homePhone' => $ship_phone ? $ship_phone : self::DEFAULT_PHONE, 'email' => $order->get_billing_email(), ); $bill_to_address = array( 'name' => trim( $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() ), 'company' => $order->get_billing_company(), 'address1' => $order->get_billing_address_1(), 'address2' => $order->get_billing_address_2(), 'city' => $order->get_billing_city(), 'state' => $order->get_billing_state(), 'postalCode' => $order->get_billing_postcode(), 'country' => $order->get_billing_country(), 'workPhone' => $bill_phone, 'homePhone' => $bill_phone, 'email' => $order->get_billing_email(), ); $items = array(); foreach ( $order->get_items() as $item ) { if ( ! $item instanceof WC_Order_Item_Product ) { continue; } $product = $item->get_product(); $qty = (int) $item->get_quantity(); $weight = $product && $product->get_weight() ? (float) $product->get_weight() : 0.0; $item_data = array( 'productSKU' => $product && $product->get_sku() ? $product->get_sku() : null, 'quantity' => $qty, 'price' => $qty > 0 ? (string) wc_format_decimal( (float) $item->get_total() / $qty, 2 ) : '0.0', 'productName' => $item->get_name(), 'productType' => $this->product_meta_with_parent_fallback( $product, '_weship_acs_sync_product_type' ), 'ccpProductType' => $this->product_meta_with_parent_fallback( $product, '_weship_acs_sync_ccp_product_type' ), 'pctAlcohol' => $this->product_meta_with_parent_fallback( $product, '_weship_acs_sync_pct_alcohol' ), 'bottleSize' => $this->product_meta_with_parent_fallback( $product, '_weship_acs_sync_bottle_size' ), ); // Omit weight entirely when the product has none, rather than sending 0. if ( $weight * $qty > 0 ) { $item_data['weight'] = $weight * $qty; } /** * Filter a single CCP order item before it is sent. * * @param array $item_data Item data. * @param WC_Product|false $product Product. * @param WC_Order_Item_Product $item Order item. */ $items[] = apply_filters( 'weship_acs_sync_ccp_order_item', $item_data, $product, $item ); } return array( 'formatVersion' => '209', 'clientCode' => Weship_ACS_Sync_Api_Client::get_setting( 'client_code' ), 'allowDuplicates' => 'N', 'companyName' => Weship_ACS_Sync_Api_Client::get_setting( 'channel_name', 'WooCommerce' ), 'order' => array( array( 'orderNo' => $this->get_order_number( $order ), 'orgOrderNumber' => (string) $order->get_id(), 'refNumber' => $this->get_order_number( $order ), 'isCCP' => $ship_only ? 'true' : 'false', 'subClub' => '800ship', 'orderDate' => $order->get_date_created() ? $order->get_date_created()->date( 'Y-m-d' ) : gmdate( 'Y-m-d' ), 'orderSourceDate' => $order->get_date_created() ? $order->get_date_created()->date( 'm-d-Y H:i:s' ) : gmdate( 'm-d-Y H:i:s' ), 'shipMethod' => $tag_fields['ship_method'], 'invoice' => '', 'fulfillmentLocation' => Weship_ACS_Sync_Api_Client::get_setting( 'client_facility_code' ), 'requestedShipDate' => $tag_fields['ship_date'], 'productType' => $product_type, 'customerDOB' => $tag_fields['customer_dob'], 'icePack' => $tag_fields['ice_pack'] ? 'Yes' : 'No', 'lob' => '', 'shipToAddress' => $ship_to_address, 'billToAddress' => $bill_to_address, 'specialInstructions' => $order->get_customer_note(), 'doNotReconfigure' => 'N', 'licenseType' => '', 'gift' => '', 'giftMessage' => (string) $order->get_meta( self::META_GIFT_NOTE ), 'insurance' => $tag_fields['insurance'], 'ftt' => '', 'fbta' => '', 'fbtpc' => '', 'ml' => '', 'sv' => '', 'altCompanyName' => $order->get_billing_company(), 'orderItems' => array( 'orderItem' => $items ), ), ), ); } /** * Read a CCP product-classification meta value, falling back to the * parent product's value when the item's product is a variation with * that field left blank (set via Weship_ACS_Sync_Product_Fields). * * @param WC_Product|false $product Order item's product (may be a variation). * @param string $meta_key Meta key to read. * @return string */ private function product_meta_with_parent_fallback( $product, $meta_key ) { if ( ! $product ) { return ''; } $value = (string) $product->get_meta( $meta_key ); if ( '' !== $value ) { return $value; } if ( $product instanceof WC_Product_Variation ) { $parent = wc_get_product( $product->get_parent_id() ); if ( $parent ) { return (string) $parent->get_meta( $meta_key ); } } return ''; } /** * Get the order number used as the ACS reference. * * @param WC_Order $order Order. * @return string */ public function get_order_number( WC_Order $order ) { return (string) $order->get_order_number(); } /** * Extract Weship-specific fields from order tags. * * Ports the tag loop in getAcsOrderRequest(): * - "IcePack" -> icePack=1 * - "customerdob-MM/DD/YYYY" -> customerDOB (sent as-is) * - "shipdate-YYYY/MM/DD" -> shipByDate (sent as YYYY-MM-DD) * - "insurance-100" -> insuranceAmount * - monthly / bi-monthly / quarterly / prepaid -> subscriptionTag * - tag mapped in the ship-method mapping -> wsShipMethod * * @param array $tags Tags. * @return array */ private function extract_tag_fields( $tags ) { $fields = array( 'ice_pack' => 0, 'customer_dob' => '', 'ship_date' => '', 'insurance' => '', 'ship_method' => '', 'subscription_tag' => '', ); $plan = ''; $prepaid = ''; $map = $this->get_ship_method_map(); foreach ( $tags as $tag ) { $lower = strtolower( $tag ); if ( isset( $map[ $lower ] ) ) { $fields['ship_method'] = $map[ $lower ]; } if ( 'icepack' === $lower ) { $fields['ice_pack'] = 1; } if ( false !== strpos( $lower, 'customerdob' ) ) { $parts = explode( '-', $tag, 2 ); $fields['customer_dob'] = isset( $parts[1] ) ? $parts[1] : ''; } if ( false !== strpos( $lower, 'shipdate' ) ) { $parts = explode( '-', $tag, 2 ); $ship_date = isset( $parts[1] ) ? $this->parse_tag_date( $parts[1], self::SHIP_DATE_TAG_FORMAT ) : null; $fields['ship_date'] = $ship_date ? $ship_date->format( 'Y-m-d' ) : ''; } if ( false !== strpos( $lower, 'insurance' ) ) { $parts = explode( '-', $tag, 2 ); $fields['insurance'] = isset( $parts[1] ) ? $parts[1] : ''; } if ( false !== strpos( $lower, 'bi-monthly' ) || false !== strpos( $lower, 'quarterly' ) ) { $plan = $tag; } elseif ( false !== strpos( $lower, 'monthly' ) ) { $plan = $tag; } if ( false !== strpos( $lower, 'prepaid' ) ) { $prepaid = $tag; } } $fields['subscription_tag'] = $plan; if ( '' !== $prepaid ) { $fields['subscription_tag'] = '' !== $plan ? $plan . ', ' . $prepaid : $prepaid; } return $fields; } /** * Validate the date-carrying order tags (matched the same way * extract_tag_fields() matches them): * - CustomerDOB-{DOB}: must be exactly MM/DD/YYYY, a real date, and not * after today (site timezone). * - ShipDate-{DATE}: must be exactly YYYY/MM/DD, a real date, and not * before today (site timezone). Today itself is allowed. * * @param array $tags Tags. * @return string Error message (one sentence per bad tag), or '' if all valid. */ private function get_tag_date_error( $tags ) { $errors = array(); $today = current_time( 'Y-m-d' ); foreach ( $tags as $tag ) { $lower = strtolower( $tag ); $parts = explode( '-', $tag, 2 ); $value = isset( $parts[1] ) ? $parts[1] : ''; if ( false !== strpos( $lower, 'customerdob' ) ) { $dob = $this->parse_tag_date( $value, self::DOB_TAG_FORMAT ); if ( ! $dob ) { /* translators: %s: order tag */ $errors[] = sprintf( __( 'Invalid date in tag "%s": customer DOB must be in MM/DD/YYYY format (e.g. CustomerDOB-03/01/1994).', 'weship-acs-sync-for-woocommerce' ), $tag ); } elseif ( $dob->format( 'Y-m-d' ) > $today ) { /* translators: %s: order tag */ $errors[] = sprintf( __( 'Invalid date in tag "%s": customer DOB cannot be in the future.', 'weship-acs-sync-for-woocommerce' ), $tag ); } } if ( false !== strpos( $lower, 'shipdate' ) ) { $ship_date = $this->parse_tag_date( $value, self::SHIP_DATE_TAG_FORMAT ); if ( ! $ship_date ) { /* translators: %s: order tag */ $errors[] = sprintf( __( 'Invalid date in tag "%s": ship date must be in YYYY/MM/DD format (e.g. ShipDate-2026/08/01).', 'weship-acs-sync-for-woocommerce' ), $tag ); } elseif ( $ship_date->format( 'Y-m-d' ) < $today ) { /* translators: %s: order tag */ $errors[] = sprintf( __( 'Invalid date in tag "%s": ship date cannot be in the past.', 'weship-acs-sync-for-woocommerce' ), $tag ); } } } return implode( ' ', $errors ); } /** * Strictly parse a tag date: the value must match $format exactly * (zero-padded, no other separators) and be a real calendar date, so * e.g. "2026-08-01", "2026/8/1" or "2026/02/30" are all rejected. * * @param string $value Date string from the tag. * @param string $format DateTime format, e.g. self::SHIP_DATE_TAG_FORMAT. * @return DateTimeImmutable|null */ private function parse_tag_date( $value, $format ) { $date = DateTimeImmutable::createFromFormat( '!' . $format, (string) $value ); return ( $date && $date->format( $format ) === $value ) ? $date : null; } /** * Static ship-method tags, mirroring the connector's ship_methods table. * Not configurable — order tag => ACS ship method code. * * 'carrier' is the human-readable carrier name for each ship method. * * @return array */ public static function ship_methods() { return array( array( 'tag' => 'UPS_2nd_Day_Air', 'method' => 'UP2', 'carrier' => 'UPS' ), array( 'tag' => 'UPS_3_Day_Select', 'method' => 'UP3', 'carrier' => 'UPS' ), array( 'tag' => 'UPS_Ground', 'method' => 'UPS', 'carrier' => 'UPS' ), array( 'tag' => 'UPS_Next_Day_Air', 'method' => 'UP1', 'carrier' => 'UPS' ), array( 'tag' => 'UPS_Next_Day_Air_Saver', 'method' => 'UPS7', 'carrier' => 'UPS' ), array( 'tag' => 'FedEx_2Day', 'method' => 'FEX', 'carrier' => 'FedEx' ), array( 'tag' => 'FedEx_Express_Saver', 'method' => 'FXE', 'carrier' => 'FedEx' ), array( 'tag' => 'FedEx_Ground', 'method' => 'FXG', 'carrier' => 'FedEx' ), array( 'tag' => 'FedEx_Home_Delivery', 'method' => 'FEH', 'carrier' => 'FedEx' ), array( 'tag' => 'FedEx_Priority_Overnight', 'method' => 'FXP', 'carrier' => 'FedEx' ), array( 'tag' => 'FedEx_Standard_Overnight', 'method' => 'FXO', 'carrier' => 'FedEx' ), array( 'tag' => 'GSO_Ground', 'method' => 'GSC', 'carrier' => 'GSO' ), array( 'tag' => 'GSO_Priority', 'method' => 'GSP', 'carrier' => 'GSO' ), array( 'tag' => 'GSO_Pallet_Service', 'method' => 'GSO3', 'carrier' => 'GSO' ), array( 'tag' => 'United_Delivery_Service_Ground', 'method' => 'UDS', 'carrier' => 'United Delivery Service' ), array( 'tag' => 'Wine_2_U_Arizona_Shipper', 'method' => 'AZS', 'carrier' => 'Wine 2 U' ), array( 'tag' => 'AEX', 'method' => 'AEX', 'carrier' => 'Concise' ), array( 'tag' => 'CAPX', 'method' => 'CAPX', 'carrier' => 'CAPEX' ), array( 'tag' => 'CDL', 'method' => 'CDL', 'carrier' => 'CDL' ), array( 'tag' => 'CSL', 'method' => 'CSL', 'carrier' => 'Concise' ), array( 'tag' => 'DIT', 'method' => 'DIT', 'carrier' => 'Concise' ), array( 'tag' => 'GIO', 'method' => 'GIO', 'carrier' => 'Concise' ), array( 'tag' => 'GSS', 'method' => 'GSS', 'carrier' => 'Concise' ), array( 'tag' => 'JTL', 'method' => 'JTL', 'carrier' => 'Concise' ), array( 'tag' => 'LSO', 'method' => 'LSO', 'carrier' => 'LSO' ), array( 'tag' => 'MERC', 'method' => 'MERC', 'carrier' => 'Concise' ), array( 'tag' => 'PRMD', 'method' => 'PRMD', 'carrier' => 'Concise' ), array( 'tag' => 'PWD', 'method' => 'PWD', 'carrier' => 'PWD' ), array( 'tag' => 'SONIC', 'method' => 'SONIC', 'carrier' => 'SONIC' ), array( 'tag' => 'STAT', 'method' => 'STAT', 'carrier' => 'Concise' ), array( 'tag' => 'UDS', 'method' => 'UDS', 'carrier' => 'United Delivery Service' ), array( 'tag' => 'W2U', 'method' => 'W2U', 'carrier' => 'W2U' ), array( 'tag' => 'ZIP', 'method' => 'ZIP', 'carrier' => 'Concise' ), array( 'tag' => 'GLS', 'method' => 'GLS', 'carrier' => 'GLS Concise' ), array( 'tag' => 'VIAD_FXG', 'method' => 'VIAD_FXG', 'carrier' => 'FedEx' ), array( 'tag' => 'VIAD_UPS', 'method' => 'VIAD_UPS', 'carrier' => 'UPS' ), array( 'tag' => 'GLS_CPS', 'method' => 'GLS_CPS', 'carrier' => 'GLS Direct' ), array( 'tag' => 'WANHUB', 'method' => 'WANHUB', 'carrier' => 'WANHUB' ), ); } /** * Ship-method mapping, keyed by lowercased order tag. * * @return array Lowercased tag => ship method. */ private function get_ship_method_map() { $map = array(); foreach ( self::ship_methods() as $row ) { $map[ strtolower( $row['tag'] ) ] = $row['method']; } return $map; } /** * Get tags for an order. * * WooCommerce has no native order tags, so tags are read from the * `_weship_acs_sync_tags` order meta (comma separated) and can be * extended via the `weship_acs_sync_order_tags` filter. * * @param WC_Order $order Order. * @return array */ public function get_order_tags( WC_Order $order ) { $raw = (string) $order->get_meta( self::META_ORDER_TAGS ); $tags = array_filter( array_map( 'trim', explode( ',', $raw ) ) ); /** * Filter the list of tags associated with an order. * * @param array $tags Tags. * @param WC_Order $order Order. */ return apply_filters( 'weship_acs_sync_order_tags', $tags, $order ); } /** * Whether an order carries at least one recognised CCP order tag * (self::CCP_ORDER_TAGS) — the only tags build_ccp_payload() actually * classifies to an 800 Program product type. Used to skip attempting a * CCP send for an order that would have nothing valid to classify to. * * @param WC_Order $order Order. * @return bool */ public function has_valid_ccp_tags( WC_Order $order ) { $valid_tags = array_map( 'strtolower', self::CCP_ORDER_TAGS ); $tags = array_map( 'strtolower', $this->get_order_tags( $order ) ); return (bool) array_intersect( $tags, $valid_tags ); } /** * Whether an order contains at least one shippable item. * * @param WC_Order $order Order. * @return bool */ private function order_needs_shipping( WC_Order $order ) { foreach ( $order->get_items() as $item ) { if ( $item instanceof WC_Order_Item_Product ) { $product = $item->get_product(); if ( $product && $product->needs_shipping() ) { return true; } } } return false; } /** * Whether the order used a pickup shipping method. * * @param WC_Order $order Order. * @return bool */ private function order_has_pickup_shipping( WC_Order $order ) { foreach ( $order->get_shipping_methods() as $shipping ) { if ( 'local_pickup' === $shipping->get_method_id() ) { return true; } } return false; } }