{ meta_key, numeric }. Sorted via * get_ordered_ids_by_meta() — see the comment in render_page(). * * A method rather than a class const so it can reference * Weship_ACS_Sync_Order_Sync::META_SYNC_STATUS. * * @return array */ private static function meta_orderby_columns() { return array( 'customer' => array( 'meta_key' => '_shipping_last_name', 'numeric' => false, ), 'sync_status' => array( 'meta_key' => Weship_ACS_Sync_Order_Sync::META_SYNC_STATUS, 'numeric' => false, ), 'weather_hold' => array( 'meta_key' => '_weship_acs_sync_weather_hold', 'numeric' => true, ), ); } /** * Order sync. * * @var Weship_ACS_Sync_Order_Sync */ private $order_sync; /** * Logger. * * @var Weship_ACS_Sync_Logger */ private $logger; /** * Print job service. * * @var Weship_ACS_Sync_Print_Job_Service */ private $print_jobs; /** * Constructor. * * @param Weship_ACS_Sync_Order_Sync $order_sync Order sync. * @param Weship_ACS_Sync_Logger $logger Logger. * @param Weship_ACS_Sync_Print_Job_Service $print_jobs Print job service. */ public function __construct( Weship_ACS_Sync_Order_Sync $order_sync, Weship_ACS_Sync_Logger $logger, Weship_ACS_Sync_Print_Job_Service $print_jobs ) { $this->order_sync = $order_sync; $this->logger = $logger; $this->print_jobs = $print_jobs; add_action( 'admin_menu', array( $this, 'add_menu' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); add_action( 'wp_ajax_weship_acs_sync_get_order_logs', array( $this, 'ajax_get_logs' ) ); add_action( 'wp_ajax_weship_acs_sync_sync_order', array( $this, 'ajax_sync_order' ) ); add_action( 'wp_ajax_weship_acs_sync_cancel_order', array( $this, 'ajax_cancel_order' ) ); add_action( 'wp_ajax_weship_acs_sync_create_print_job', array( $this, 'ajax_create_print_job' ) ); } /** * Enqueue this page's styles/scripts, only on its own screen. * * @param string $hook Current admin page hook suffix. */ public function enqueue_assets( $hook ) { if ( $hook !== $this->page_hook ) { return; } wp_enqueue_style( 'weship-acs-sync-admin', WESHIP_ACS_SYNC_URL . 'admin/css/weship-acs-sync-admin.css', array(), WESHIP_ACS_SYNC_VERSION ); wp_enqueue_script( 'weship-acs-sync-admin-common', WESHIP_ACS_SYNC_URL . 'admin/js/weship-acs-sync-admin-common.js', array( 'jquery' ), WESHIP_ACS_SYNC_VERSION, true ); wp_enqueue_script( 'weship-acs-sync-orders-page', WESHIP_ACS_SYNC_URL . 'admin/js/weship-acs-sync-orders-page.js', array( 'jquery' ), WESHIP_ACS_SYNC_VERSION, true ); wp_localize_script( 'weship-acs-sync-orders-page', 'weshipAcsSyncOrders', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( self::NONCE ), 'i18n' => array( 'loading' => __( 'Loading…', 'weship-acs-sync-for-woocommerce' ), 'noLogEntries' => __( 'No log entries found.', 'weship-acs-sync-for-woocommerce' ), 'view' => __( 'View', 'weship-acs-sync-for-woocommerce' ), 'done' => __( 'Done.', 'weship-acs-sync-for-woocommerce' ), 'requestFailed' => __( 'Request failed.', 'weship-acs-sync-for-woocommerce' ), 'confirmCancel' => __( 'Are you sure you want to cancel this order in ACS?', 'weship-acs-sync-for-woocommerce' ), 'printJobCreated' => __( 'Print job created.', 'weship-acs-sync-for-woocommerce' ), 'noShippingLabels' => __( 'No shipping labels available for the selected orders.', 'weship-acs-sync-for-woocommerce' ), 'noPackingSlips' => __( 'No packing slips available for the selected orders.', 'weship-acs-sync-for-woocommerce' ), ), ) ); } /** * Register the top-level admin menu (not nested under WooCommerce), with * Orders as its default/landing page. */ public function add_menu() { $this->page_hook = add_menu_page( __( 'WSE ACS Sync for WooCommerce', 'weship-acs-sync-for-woocommerce' ), __( 'WSE ACS Sync for WooCommerce', 'weship-acs-sync-for-woocommerce' ), 'manage_woocommerce', self::PAGE_SLUG, array( $this, 'render_page' ), 'dashicons-networking', 56 ); // add_menu_page() alone would auto-create the first submenu entry // using the top-level title above ("WSE ACS Sync for WooCommerce"). // Explicitly adding a submenu page with the same slug as the parent // renames just that entry to "Orders", without adding a second/ // duplicate item. add_submenu_page( self::PAGE_SLUG, __( 'Orders', 'weship-acs-sync-for-woocommerce' ), __( 'Orders', 'weship-acs-sync-for-woocommerce' ), 'manage_woocommerce', self::PAGE_SLUG, array( $this, 'render_page' ) ); } /** * Common AJAX permission + nonce check. */ private function check_ajax_permissions() { if ( ! current_user_can( 'edit_shop_orders' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'weship-acs-sync-for-woocommerce' ) ), 403 ); } check_ajax_referer( self::NONCE ); } /** * AJAX: return log rows for the given order IDs. */ public function ajax_get_logs() { $this->check_ajax_permissions(); $order_ids = isset( $_POST['order_ids'] ) ? array_map( 'absint', (array) wp_unslash( $_POST['order_ids'] ) ) : array(); $logs = $this->logger->get_by_order_ids( $order_ids ); $data = array_map( function ( $row ) { return array( 'id' => (int) $row->id, 'orderId' => (int) $row->order_id, 'acsResponseCode' => $row->status_code, 'acsResponseMessage' => $row->message, 'type' => $row->event, 'direction' => $row->direction, 'url' => $row->url, 'request' => $row->request, 'response' => $row->response, 'createdOn' => $row->created_at, ); }, $logs ); wp_send_json_success( $data ); } /** * AJAX: manually sync a single order. */ public function ajax_sync_order() { $this->check_ajax_permissions(); $order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0; $order = $order_id ? wc_get_order( $order_id ) : false; if ( ! $order ) { wp_send_json_error( array( 'message' => __( 'Order not found.', 'weship-acs-sync-for-woocommerce' ) ) ); } $success = $this->order_sync->sync_order( $order ); wp_send_json_success( array( 'success' => $success, 'message' => $success ? __( 'Order synced successfully.', 'weship-acs-sync-for-woocommerce' ) : __( 'Order sync failed. Check the logs for details.', 'weship-acs-sync-for-woocommerce' ), ) ); } /** * AJAX: manually cancel a single order in ACS. */ public function ajax_cancel_order() { $this->check_ajax_permissions(); $order_id = isset( $_POST['order_id'] ) ? absint( $_POST['order_id'] ) : 0; $order = $order_id ? wc_get_order( $order_id ) : false; if ( ! $order ) { wp_send_json_error( array( 'message' => __( 'Order not found.', 'weship-acs-sync-for-woocommerce' ) ) ); } if ( $order->has_status( 'cancelled' ) ) { wp_send_json_error( array( 'message' => __( 'Order is already cancelled.', 'weship-acs-sync-for-woocommerce' ) ) ); } $success = $this->order_sync->cancel_order( $order_id, true ); wp_send_json_success( array( 'success' => (bool) $success, 'message' => $success ? __( 'Cancellation sent.', 'weship-acs-sync-for-woocommerce' ) : __( 'Cancellation failed.', 'weship-acs-sync-for-woocommerce' ), ) ); } /** * AJAX: create a bulk print job from the selected orders. */ public function ajax_create_print_job() { $this->check_ajax_permissions(); $order_ids = isset( $_POST['order_ids'] ) ? array_map( 'absint', (array) wp_unslash( $_POST['order_ids'] ) ) : array(); $reference_ids = isset( $_POST['reference_ids'] ) ? array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['reference_ids'] ) ) : array(); $pdf_urls = isset( $_POST['pdf_urls'] ) ? array_map( 'sanitize_text_field', (array) wp_unslash( $_POST['pdf_urls'] ) ) : array(); $job_type = isset( $_POST['job_type'] ) ? sanitize_key( wp_unslash( $_POST['job_type'] ) ) : ''; $job_id = $this->print_jobs->create_job( $order_ids, $reference_ids, $pdf_urls, $job_type ); if ( is_wp_error( $job_id ) ) { wp_send_json_error( array( 'message' => $job_id->get_error_message() ) ); } wp_send_json_success( array( 'jobId' => $job_id, 'message' => __( 'Print job created. See the Print Jobs page for status.', 'weship-acs-sync-for-woocommerce' ), ) ); } /** * Render the Orders page. */ public function render_page() { if ( ! current_user_can( 'manage_woocommerce' ) ) { return; } $page = isset( $_GET['paged'] ) ? max( 0, absint( $_GET['paged'] ) - 1 ) : 0; $size = isset( $_GET['size'] ) ? absint( $_GET['size'] ) : 50; $size = in_array( $size, array( 50, 100, 500 ), true ) ? $size : 50; $keyword = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : ''; $weather_hold = isset( $_GET['weather_hold'] ) ? sanitize_key( wp_unslash( $_GET['weather_hold'] ) ) : ''; $weather_hold = in_array( $weather_hold, array( 'yes', 'no' ), true ) ? $weather_hold : ''; $sort_dir = isset( $_GET['order'] ) && 'asc' === strtolower( wp_unslash( $_GET['order'] ) ) ? 'ASC' : 'DESC'; $orderby = isset( $_GET['orderby'] ) ? sanitize_key( wp_unslash( $_GET['orderby'] ) ) : 'date'; $orderby = in_array( $orderby, self::SORTABLE_COLUMNS, true ) ? $orderby : 'date'; $args = array( 'limit' => $size, 'page' => $page + 1, 'paginate' => true, 'order' => $sort_dir, ); // Each active filter narrows the result to a list of matching order // IDs; multiple filters are combined with an intersection. A raw // 'meta_query' arg passed to wc_get_orders() is silently dropped — // WC_Data_Store_WP::get_wp_query_args() explicitly skips copying the // 'meta_query' key over from the incoming query vars, so it never // reaches WP_Query — which is why filtering has to go through // 'post__in' (a native WP_Query arg, also remapped to 'id' by the // HPOS order-table query) instead. $post_in_filters = array(); if ( '' !== $keyword ) { if ( is_numeric( $keyword ) ) { $post_in_filters[] = array( absint( $keyword ) ); } else { // wc_order_search() is WooCommerce's own storage-engine-agnostic // helper (used by the core Orders screen's search box) — it // matches billing/shipping name, email and order number and // returns matching order IDs directly. $post_in_filters[] = wc_order_search( $keyword ); } } if ( '' !== $weather_hold ) { $post_in_filters[] = $this->get_order_ids_by_weather_hold( 'yes' === $weather_hold ); } // When the 800 Program (CCP) is on, only orders carrying one of the // recognised CCP order tags are ever actually routed through the CCP // feed (see build_ccp_payload()) — an order with no/invalid tags // wouldn't classify to any product type there, so hide it here too // rather than showing orders that can't meaningfully be CCP-synced. if ( 'yes' === Weship_ACS_Sync_Api_Client::get_setting( 'ccp_enabled', 'no' ) ) { $post_in_filters[] = $this->get_order_ids_with_valid_ccp_tags(); } // Order #/Date sort natively via WP_Query. The other sortable columns // are meta-backed, and for the same reason described above, sorting // them can't go through wc_get_orders()'s own 'orderby' + 'meta_key' // either (WP_Query would build its own implicit meta_query behind the // scenes, but we have no way to add the NOT-EXISTS half described in // get_ordered_ids_by_meta() to it — so it'd silently drop every order // missing that meta from the whole list, not just leave it unordered). // Instead, fetch the full sort order as an ID list and prepend it to // the filters above: array_intersect() preserves the first array's // order, so the final list below comes out sorted *and* filtered. $meta_orderby_columns = self::meta_orderby_columns(); if ( isset( $meta_orderby_columns[ $orderby ] ) ) { $meta_config = $meta_orderby_columns[ $orderby ]; array_unshift( $post_in_filters, $this->get_ordered_ids_by_meta( $meta_config['meta_key'], $meta_config['numeric'], $sort_dir ) ); $args['orderby'] = 'post__in'; } else { $args['orderby'] = 'order' === $orderby ? 'ID' : 'date'; } if ( ! empty( $post_in_filters ) ) { $matching_ids = 1 === count( $post_in_filters ) ? $post_in_filters[0] : array_values( array_intersect( ...$post_in_filters ) ); // An empty array is a no-op to WP_Query's post__in (it's treated // as "no restriction", not "match nothing"), so a filter with // zero matches would otherwise fall through to the unfiltered // list. Force an impossible ID instead. $args['post__in'] = ! empty( $matching_ids ) ? $matching_ids : array( 0 ); } $results = wc_get_orders( $args ); $orders = $results->orders; $total_pages = max( 1, (int) $results->max_num_pages ); $base_url = Weship_ACS_Sync_Api_Client::get_setting( 'base_url' ); $tracking_url = ''; if ( $base_url ) { $parts = wp_parse_url( $base_url ); if ( ! empty( $parts['scheme'] ) && ! empty( $parts['host'] ) ) { $tracking_url = $parts['scheme'] . '://' . $parts['host'] . '/weship/tracking/tracking-details/'; } } ?>

render_sortable_th( __( 'Order #', 'weship-acs-sync-for-woocommerce' ), 'order', $orderby, $sort_dir, $keyword, $weather_hold, $size ); ?> render_sortable_th( __( 'Customer', 'weship-acs-sync-for-woocommerce' ), 'customer', $orderby, $sort_dir, $keyword, $weather_hold, $size ); ?> render_sortable_th( __( 'Sync Status', 'weship-acs-sync-for-woocommerce' ), 'sync_status', $orderby, $sort_dir, $keyword, $weather_hold, $size ); ?> render_sortable_th( __( 'Weather Hold', 'weship-acs-sync-for-woocommerce' ), 'weather_hold', $orderby, $sort_dir, $keyword, $weather_hold, $size ); ?> render_sortable_th( __( 'Date', 'weship-acs-sync-for-woocommerce' ), 'date', $orderby, $sort_dir, $keyword, $weather_hold, $size ); ?> get_meta( Weship_ACS_Sync_Order_Sync::META_LABEL ); $packing_slip = (string) $order->get_meta( Weship_ACS_Sync_Order_Sync::META_PACKING_SLIP ); $is_ccp = (int) $order->get_meta( Weship_ACS_Sync_Order_Sync::META_IS_CCP ); $cancel_msg = (string) $order->get_meta( Weship_ACS_Sync_Order_Sync::META_CANCEL_MESSAGE ); $row_weather_hold = (int) $order->get_meta( '_weship_acs_sync_weather_hold' ); $fulfillment_status = (string) $order->get_meta( Weship_ACS_Sync_Order_Sync::META_FULFILLMENT_STATUS ); $ever_synced = (bool) $order->get_meta( Weship_ACS_Sync_Order_Sync::META_EVER_SYNCED ); ?>
has_status( 'cancelled' ) ); ?> /> get_order_number() ); ?> get_shipping_first_name() . ' ' . $order->get_shipping_last_name() ) ); ?> get_date_created() ? $order->get_date_created()->date_i18n( 'Y-m-d H:i' ) : '' ); ?>
has_status( array( 'cancelled', 'pending' ) ) ) : ?>
render_pagination( $page, $total_pages, $size, $keyword, $weather_hold ); ?>
add_query_arg( 'paged', '%#%' ), 'format' => '', 'current' => $page + 1, 'total' => $total_pages, 'add_args' => array( 'size' => $size, 's' => $keyword, 'weather_hold' => $weather_hold, ), ) ); ?>
self::PAGE_SLUG, 'orderby' => $column, 'order' => $next_order, 's' => $keyword, 'weather_hold' => $weather_hold, 'size' => $size, ), admin_url( 'admin.php' ) ); ?> Matching order IDs. */ private function get_order_ids_by_meta_query( array $meta_query ) { if ( $this->using_hpos() ) { return array_map( 'absint', (array) wc_get_orders( array( 'type' => 'shop_order', 'limit' => -1, 'return' => 'ids', 'meta_query' => $meta_query, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query ) ) ); } return get_posts( array( 'post_type' => 'shop_order', 'post_status' => array_keys( wc_get_order_statuses() ), 'posts_per_page' => -1, 'fields' => 'ids', 'meta_query' => $meta_query, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query ) ); } /** * Get ALL order IDs (unpaginated), ordered by the given meta value. * * Every order is included regardless of whether it has this meta at all * — orders carrying it are sorted by value via get_order_ids_by_meta_query()'s * EXISTS/NOT EXISTS support (portable across both storage backends, unlike * an implicit WP_Query 'orderby' => 'meta_value', which would use an INNER * JOIN and drop every order missing the meta entirely); orders without it * are appended after, unordered, rather than dropped. * * @param string $meta_key Meta key to sort by. * @param bool $numeric Whether to sort numerically (vs. as a string). * @param string $direction 'ASC' or 'DESC'. * @return array Order IDs in sorted order. */ private function get_ordered_ids_by_meta( $meta_key, $numeric, $direction ) { $with_meta = $this->get_order_ids_by_meta_query( array( array( 'key' => $meta_key, 'compare' => 'EXISTS', ), ) ); $without_meta = $this->get_order_ids_by_meta_query( array( array( 'key' => $meta_key, 'compare' => 'NOT EXISTS', ), ) ); $values = array(); foreach ( $with_meta as $order_id ) { $order = wc_get_order( $order_id ); if ( ! $order ) { continue; } $value = $order->get_meta( $meta_key ); $values[ $order_id ] = $numeric ? (float) $value : (string) $value; } $numeric ? asort( $values, SORT_NUMERIC ) : asort( $values, SORT_STRING ); if ( 'DESC' === $direction ) { $values = array_reverse( $values, true ); } return array_merge( array_keys( $values ), $without_meta ); } /** * Get order IDs matching the given weather hold state. * * Queried via get_order_ids_by_meta_query() rather than wc_get_orders() * directly — see that method's docblock for why a raw 'meta_query' can't * just be passed to wc_get_orders() on every backend. "No" also matches * orders that have never received a weather-hold webhook at all (no meta * row), matching the "No" shown for those orders in the Weather Hold column. * * @param bool $on_hold True for orders on weather hold, false otherwise. * @return array Order IDs; array( 0 ) (an impossible ID) if none match. */ private function get_order_ids_by_weather_hold( $on_hold ) { $meta_query = $on_hold ? array( array( 'key' => '_weship_acs_sync_weather_hold', 'value' => '1', ), ) : array( 'relation' => 'OR', array( 'key' => '_weship_acs_sync_weather_hold', 'value' => '1', 'compare' => '!=', ), array( 'key' => '_weship_acs_sync_weather_hold', 'compare' => 'NOT EXISTS', ), ); $ids = $this->get_order_ids_by_meta_query( $meta_query ); return ! empty( $ids ) ? $ids : array( 0 ); } /** * Get order IDs carrying at least one recognised CCP order tag * (Weship_ACS_Sync_Order_Sync::CCP_ORDER_TAGS), used to filter the Orders * page when the 800 Program (CCP) is enabled. * * Tags are a comma-separated string in one order meta value, so this * can't be expressed as a single meta_query LIKE without either missing * tags separated from others by punctuation or false-matching a tag that * merely contains another as a substring. Instead, every order with any * tags at all is fetched via get_order_ids_by_meta_query() and each one's * tags are parsed and checked in PHP, the same way * Weship_ACS_Sync_Order_Sync::get_order_tags() and build_ccp_payload() * do it. * * @return array Order IDs; array( 0 ) (an impossible ID) if none match. */ private function get_order_ids_with_valid_ccp_tags() { $order_ids = $this->get_order_ids_by_meta_query( array( array( 'key' => Weship_ACS_Sync_Order_Sync::META_ORDER_TAGS, 'value' => '', 'compare' => '!=', ), ) ); if ( empty( $order_ids ) ) { return array( 0 ); } $valid_tags = array_map( 'strtolower', Weship_ACS_Sync_Order_Sync::CCP_ORDER_TAGS ); $matching = array(); foreach ( $order_ids as $order_id ) { $order = wc_get_order( $order_id ); if ( ! $order ) { continue; } $raw = (string) $order->get_meta( Weship_ACS_Sync_Order_Sync::META_ORDER_TAGS ); $tags = array_map( 'strtolower', array_filter( array_map( 'trim', explode( ',', $raw ) ) ) ); if ( array_intersect( $tags, $valid_tags ) ) { $matching[] = $order_id; } } return ! empty( $matching ) ? $matching : array( 0 ); } }