page_hook = add_submenu_page( 'weship-acs-sync-for-woocommerce', __( 'Settings', 'weship-acs-sync-for-woocommerce' ), __( 'Settings', 'weship-acs-sync-for-woocommerce' ), 'manage_woocommerce', self::PAGE_SLUG, array( $this, 'render_page' ) ); } /** * Enqueue this page's scripts/styles, only on its own screen. Which tab * is active is read the same way render_page() does, so the right subset * loads on every tab without loading all of them everywhere. * * @param string $hook Current admin page hook suffix. */ public function enqueue_assets( $hook ) { if ( $hook !== $this->page_hook ) { return; } $active_tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'settings'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended 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 ); if ( 'settings' === $active_tab ) { wp_enqueue_script( 'weship-acs-sync-settings', WESHIP_ACS_SYNC_URL . 'admin/js/weship-acs-sync-settings.js', array(), WESHIP_ACS_SYNC_VERSION, true ); wp_localize_script( 'weship-acs-sync-settings', 'weshipAcsSyncSettings', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( self::NONCE ), 'i18n' => array( 'saving' => __( 'Saving…', 'weship-acs-sync-for-woocommerce' ), 'requestFailed' => __( 'Request failed. Please try again.', 'weship-acs-sync-for-woocommerce' ), ), ) ); } elseif ( 'logs' === $active_tab ) { 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-logs', WESHIP_ACS_SYNC_URL . 'admin/js/weship-acs-sync-logs.js', array( 'jquery' ), WESHIP_ACS_SYNC_VERSION, true ); } } /** * Default settings values, shared by the render form and the sanitize * callback's "discard on failed channel sync" fallback. * * @return array */ private function default_settings() { return array( 'base_url' => '', 'api_key' => '', 'account_id' => '', 'client_name' => '', 'channel_name' => 'WooCommerce', 'tags_enabled' => 'no', 'required_tag' => '', 'order_delay' => 'no', 'order_delay_interval' => 5, 'ccp_enabled' => 'no', 'ccp_ship_enabled' => 'no', 'client_code' => '', 'client_facility_code' => '', 'ccp_email_enabled' => 'no', 'ccp_label_enabled' => 'no', 'ccp_packing_slip_enabled' => 'no', 'ccp_rate_enabled' => 'no', ); } /** * AJAX: sanitize, sync with ACS and persist the settings submitted from * the Settings tab form. * * This is now the ONLY save path for this option — deliberately not * wired through register_setting()'s sanitize_callback. That filter * (`sanitize_option_{$option}`) fires on every single add_option()/ * update_option() call for the option, not just ones coming from * options.php: WordPress's own update_option() delegates to add_option() * the first time an option is created, and BOTH of those independently * run sanitize_option() — so a registered sanitize_callback actually * runs twice on an option's first-ever save. The second pass receives * the callback's own already-sanitized output as its "raw" input, where * every checkbox key is always present (even when its value is the * string 'no') — so `isset( $input['ccp_enabled'] )` is true regardless * of the real value, and every checkbox comes back 'yes'. That's the * actual mechanism behind the "checkboxes save as checked on first * install" bug, and it's why process_settings() below is only ever * invoked here, once, followed by a plain update_option() with no * sanitize_callback registered to reprocess it. */ public function ajax_save_settings() { if ( ! current_user_can( 'manage_woocommerce' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'weship-acs-sync-for-woocommerce' ) ), 403 ); } check_ajax_referer( self::NONCE ); $input = isset( $_POST['settings'] ) ? (array) wp_unslash( $_POST['settings'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash $result = $this->process_settings( $input ); update_option( self::OPTION_KEY, $result['settings'] ); if ( $result['success'] ) { wp_send_json_success( array( 'message' => $result['message'], 'settings' => $result['settings'], ) ); } else { wp_send_json_error( array( 'message' => $result['message'], 'settings' => $result['settings'], ) ); } } /** * Validate/sanitize submitted settings and sync the channel with ACS. * Doesn't persist anything itself — ajax_save_settings() does that with * a plain update_option() once this returns (see its docblock for why * this must run exactly once per save, with no sanitize_callback * registered to reprocess the result). * * @param array $input Raw input, e.g. $_POST['settings'] from the AJAX call. * @return array{settings:array,success:bool,message:string} */ private function process_settings( $input ) { $input = is_array( $input ) ? $input : array(); $clean = array(); $clean['base_url'] = isset( $input['base_url'] ) ? esc_url_raw( trim( $input['base_url'] ) ) : ''; $clean['api_key'] = isset( $input['api_key'] ) ? sanitize_text_field( $input['api_key'] ) : ''; $clean['account_id'] = isset( $input['account_id'] ) ? sanitize_text_field( $input['account_id'] ) : ''; $clean['client_name'] = isset( $input['client_name'] ) ? sanitize_text_field( $input['client_name'] ) : ''; // Not user-editable: always the WordPress site title (this store's channel name). $site_title = sanitize_text_field( get_bloginfo( 'name' ) ); $clean['channel_name'] = '' !== $site_title ? $site_title : 'WooCommerce'; // 800 Program (CCP) settings — these get sent to ACS in the channel // registration payload, so they're gated behind a successful // verification below (same as the credential fields above). $clean['ccp_enabled'] = isset( $input['ccp_enabled'] ) ? 'yes' : 'no'; $clean['ccp_ship_enabled'] = isset( $input['ccp_ship_enabled'] ) ? 'yes' : 'no'; $clean['client_code'] = isset( $input['client_code'] ) ? sanitize_text_field( $input['client_code'] ) : ''; $clean['client_facility_code'] = isset( $input['client_facility_code'] ) ? sanitize_text_field( $input['client_facility_code'] ) : ''; $clean['ccp_email_enabled'] = isset( $input['ccp_email_enabled'] ) ? 'yes' : 'no'; $clean['ccp_label_enabled'] = isset( $input['ccp_label_enabled'] ) ? 'yes' : 'no'; $clean['ccp_packing_slip_enabled'] = isset( $input['ccp_packing_slip_enabled'] ) ? 'yes' : 'no'; // Rate-shopping is not exposed in this UI; kept internally for schema parity. $clean['ccp_rate_enabled'] = 'no'; // Local-only settings: never sent to ACS, so — unlike the fields above — // these always save regardless of whether the ACS verification below // succeeds. A flaky/unreachable ACS connection has no bearing on whether // the store should filter by tag or queue orders. $clean['tags_enabled'] = isset( $input['tags_enabled'] ) ? 'yes' : 'no'; $clean['required_tag'] = isset( $input['required_tag'] ) ? sanitize_text_field( $input['required_tag'] ) : ''; $clean['order_delay'] = isset( $input['order_delay'] ) ? 'yes' : 'no'; $interval = isset( $input['order_delay_interval'] ) ? (int) $input['order_delay_interval'] : 5; $clean['order_delay_interval'] = in_array( $interval, Weship_ACS_Sync_Cron::ALLOWED_INTERVALS, true ) ? $interval : 5; $local_only_keys = array( 'tags_enabled', 'required_tag', 'order_delay', 'order_delay_interval' ); $previous = get_option( self::OPTION_KEY, $this->default_settings() ); // Mirrors AuthenticationService.configureAppInfo(): verify credentials and // add/update the channel in ACS. If that round trip fails, discard the // credential and CCP fields and keep their previously stored values // (matching the connector) — build_channel_payload() only sends // isRateEnabled/isEmailEnabled/isLabelEnabled/isPackingSlipEnabled/ // facilityCode to addChannel/updateChannel when ccp_enabled is 'yes' in // $clean, so CCP can be configured in the same save as the initial API // connection as long as it verifies. The local-only fields above are // exempt from this discard: they don't depend on ACS, so they always // keep the admin's just-submitted values below. $sync_result = weship_acs_sync()->channel->sync_channel( $clean ); $success = ! is_wp_error( $sync_result ); if ( $success ) { $final = $clean; $message = __( 'Settings saved and the ACS channel was verified successfully.', 'weship-acs-sync-for-woocommerce' ); } else { $final = wp_parse_args( $previous, $clean ); foreach ( $local_only_keys as $key ) { $final[ $key ] = $clean[ $key ]; } $message = sprintf( /* translators: %s: error message */ __( 'Connection and 800 Program settings were not saved: %s Your other settings were saved.', 'weship-acs-sync-for-woocommerce' ), $sync_result->get_error_message() ); } // Keep the cron event in lockstep with the Order Delay setting: only // scheduled while it's on, cleared the moment it's turned off. This runs // regardless of the ACS verification outcome above, since Order Delay // is one of the local-only settings. if ( 'yes' === $final['order_delay'] ) { $previous_interval = isset( $previous['order_delay_interval'] ) ? (int) $previous['order_delay_interval'] : 5; if ( $previous_interval !== $final['order_delay_interval'] || ! wp_next_scheduled( Weship_ACS_Sync_Cron::HOOK ) ) { Weship_ACS_Sync_Cron::schedule( $final['order_delay_interval'] ); } } else { wp_clear_scheduled_hook( Weship_ACS_Sync_Cron::HOOK ); } return array( 'settings' => $final, 'success' => $success, 'message' => $message, ); } /** * Render the settings page (tabbed). */ public function render_page() { if ( ! current_user_can( 'manage_woocommerce' ) ) { return; } $settings = wp_parse_args( get_option( self::OPTION_KEY, array() ), $this->default_settings() ); $tabs = array( 'settings' => __( 'Settings', 'weship-acs-sync-for-woocommerce' ), // 'ship-methods' => __( 'Ship Methods', 'weship-acs-sync-for-woocommerce' ), 'order-tags' => __( 'Order / CCP Tags', 'weship-acs-sync-for-woocommerce' ), 'webhooks' => __( 'Inbound Webhooks', 'weship-acs-sync-for-woocommerce' ), 'logs' => __( 'Logs', 'weship-acs-sync-for-woocommerce' ), ); $active_tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'settings'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( ! isset( $tabs[ $active_tab ] ) ) { $active_tab = 'settings'; } ?>

render_ship_methods_tab(); break; case 'order-tags': $this->render_order_tags_tab(); break; case 'webhooks': $this->render_webhooks_tab( $settings ); break; case 'logs': $this->render_logs(); break; default: $this->render_settings_form( $settings ); break; } ?>

ACS ship method code. * * @return array */ private function ship_methods() { return Weship_ACS_Sync_Order_Sync::ship_methods(); } /** * Render the Ship Methods tab. */ private function render_ship_methods_tab() { ?>

ship_methods() as $row ) : ?>
array( array( 'title' => 'Tag to Show Pending Fulfillment', 'tag' => 'Pending_Fulfillment', 'description' => '' ), array( 'title' => 'Tag to Show Error in Order', 'tag' => 'Error_in_WSE', 'description' => '' ), array( 'title' => 'Tag to check Order with Ice Pack', 'tag' => 'icepack', 'description' => '' ), array( 'title' => 'Tag to enter customer DOB', 'tag' => 'CustomerDOB-{DOB}', 'description' => '(Replace {DOB} with DOB date. Eg: "CustomerDOB-03/01/1994")' ), array( 'title' => 'Tag to enter insurance amount', 'tag' => 'Insurance-{amount}', 'description' => '(Replace {amount} with amount. Eg: "Insurance-15")' ), array( 'title' => 'Weship Wine', 'tag' => 'weship-wine', 'description' => '' ), array( 'title' => 'Weship Beer', 'tag' => 'weship-beer', 'description' => '' ), array( 'title' => 'Weship Alt', 'tag' => 'weship-alt', 'description' => '' ), array( 'title' => 'Weship Ambient', 'tag' => 'weship-ambient', 'description' => '' ), ), 'fulfillment' => array( array( 'title' => 'Tag to check Order with Ice Pack', 'tag' => 'icepack', 'description' => '' ), array( 'title' => 'Tag to enter customer DOB', 'tag' => 'CustomerDOB-{DOB}', 'description' => '(Replace {DOB} with DOB date. Eg: "CustomerDOB-MM/DD/YYYY")' ), array( 'title' => 'Tag to enter ship date', 'tag' => 'ShipDate-{DATE}', 'description' => '(Replace {DATE} with ship date. Eg: "ShipDate-YYYY/MM/DD")' ), array( 'title' => 'Tag to enter insurance amount', 'tag' => 'Insurance-{amount}', 'description' => '(Replace {amount} with amount. Eg: "Insurance-15")' ), array( 'title' => 'Tag to enter monthly subscription', 'tag' => 'Monthly', 'description' => '(Applicable only to recurring or prepaid subscription orders)' ), array( 'title' => 'Tag to enter Bi-Monthly subscription', 'tag' => 'Bi-Monthly', 'description' => '(Applicable only to recurring or prepaid subscription orders)' ), array( 'title' => 'Tag to enter quarterly subscription', 'tag' => 'Quarterly', 'description' => '(Applicable only to recurring or prepaid subscription orders)' ), array( 'title' => 'Tag to enter prepaid subscription', 'tag' => 'Prepaid', 'description' => '(Applicable only to recurring or prepaid subscription orders)' ), array( 'title' => 'Shipping method for Will Call (Self Pickup) orders', 'tag' => 'Create a Shipping method as "Local Pickup"', 'description' => '' ), array( 'title' => 'Shipping method for Build a Case orders', 'tag' => 'Create a Shipping method as "Build-a-Case"', 'description' => '' ), ), ); } /** * Render one order-tag reference table. * * @param string $title Table heading. * @param array $tags Rows with title/tag/description. */ private function render_order_tags_table( $title, $tags ) { ?>


master_order_tags(); ?>

render_order_tags_table( __( 'Fulfillment Order Tags', 'weship-acs-sync-for-woocommerce' ), $master['fulfillment'] ); $this->render_order_tags_table( __( '800 Program (CCP) Order Tags', 'weship-acs-sync-for-woocommerce' ), $master['ccp'] ); } /** * Build a sample cURL command for a webhook, using the real Account ID * (not a secret) but a placeholder for the API key. * * @param string $method HTTP method. * @param string $url Full URL, including query string if any. * @param string $account_id Configured account ID, if any. * @param array|null $body Request body to encode as JSON, or null for none. * @return string */ private function sample_curl( $method, $url, $account_id, $body = null ) { $account_id = '' !== $account_id ? $account_id : 'YOUR_ACCOUNT_ID'; $lines = array(); $lines[] = sprintf( "curl -X %s '%s' \\", $method, $url ); $lines[] = " -H 'Content-Type: application/json' \\"; $lines[] = " -H 'ApiKey: YOUR_API_KEY' \\"; if ( null !== $body ) { $lines[] = sprintf( " -H 'AccountId: %s' \\", $account_id ); $lines[] = " -d '" . wp_json_encode( $body, JSON_PRETTY_PRINT ) . "'"; } else { $lines[] = sprintf( " -H 'AccountId: %s'", $account_id ); } return implode( "\n", $lines ); } /** * Render one Inbound Webhooks row plus its collapsible sample-cURL row. * * @param string $index Unique row index (for the toggle target id). * @param string $label Row label. * @param string $url Endpoint URL (including query string if any). * @param string $curl Sample cURL command text. */ private function render_webhook_row( $index, $label, $url, $curl ) { $target_id = 'weship-acs-sync-curl-' . $index; ?>
1, 'per_page' => 20 ), rest_url( 'weship-acs-sync/v1/products' ) ); // Two boxes, to demonstrate that a multi-box shipment produces // multiple tracking entries on the order (one per box). $order_status_body = array( 'carrier' => 'UPS', 'carrierService' => 'Ground', 'carrierTrackingId' => 'string', 'estimatedCost' => 'string', 'noOfPackages' => 2, 'orderNumber' => '1001', 'orderReferenceNumber' => 'string', 'orderState' => 'string', 'orderStatus' => 6, 'orderStatusDesc' => 'Shipped', 'subOrdersList' => array( array( 'boxId' => '1', 'carrier' => 'UPS', 'carrierService' => 'Ground', 'carrierTrackingId' => '1Z999AA10123456784', 'deliveryDate' => 'string', 'deliveryTargetTime' => 'string', 'noOfPackages' => 1, 'orderItems' => array( array( 'quantity' => 1, 'serialIds' => (object) array(), 'sku' => 'SKU-123', ), ), 'orderNumber' => '1001', 'orderStatus' => 6, 'orderStatusDesc' => 'Shipped', 'orderType' => 0, 'orderTypeDesc' => 'string', 'parentOrder' => '1001', 'productType' => 0, 'productTypeDesc' => 'string', 'reason' => 'string', 'referenceId' => '1001', 'totalQuantity' => 1, 'totalWeight' => 0, 'trackingId' => 'string', 'trackingUrl' => 'https://www.ups.com/track?tracknum=1Z999AA10123456784', 'warehouseLocationId' => 0, ), array( 'boxId' => '2', 'carrier' => 'FedEx', 'carrierService' => 'Home Delivery', 'carrierTrackingId' => '794658393423', 'deliveryDate' => 'string', 'deliveryTargetTime' => 'string', 'noOfPackages' => 1, 'orderItems' => array( array( 'quantity' => 1, 'serialIds' => (object) array(), 'sku' => 'SKU-456', ), ), 'orderNumber' => '1001', 'orderStatus' => 6, 'orderStatusDesc' => 'Shipped', 'orderType' => 0, 'orderTypeDesc' => 'string', 'parentOrder' => '1001', 'productType' => 0, 'productTypeDesc' => 'string', 'reason' => 'string', 'referenceId' => '1001', 'totalQuantity' => 1, 'totalWeight' => 0, 'trackingId' => 'string', 'trackingUrl' => 'https://www.fedex.com/fedextrack/?trknbr=794658393423', 'warehouseLocationId' => 0, ), ), 'totalItems' => 2, 'totalProductType' => 1, 'totalSubOrders' => 2, 'trackingId' => 'string', 'trackingUrl' => 'string', ); $inventory_body = array( array( 'allocated' => 0, 'availableToPromise' => 0, 'customerId' => 'string', 'damaged' => 0, 'delivered' => 0, 'expirationDate' => 'string', 'freeze' => 0, 'icqa' => 0, 'inreview' => 0, 'marketDesc' => 'string', 'maxAttr' => 'string', 'minAttr' => 'string', 'onHand' => 0, 'packageType' => (object) array(), 'packageTypeDesc' => (object) array(), 'productCategory' => 0, 'productId' => 0, 'productName' => 'string', 'productType' => 0, 'shrink' => 0, 'skuNumber' => 'string', 'uom' => 'string', 'upc' => 'string', 'warehouseLocation' => 0, ), ); $weather_hold_body = array( 'orderId' => '1001', 'channelName' => $channel_name, 'weatherHold' => true, ); ?>

render_webhook_row( 'order-status', __( 'Order status / tracking', 'weship-acs-sync-for-woocommerce' ), $order_status_url, $this->sample_curl( 'POST', $order_status_url, $account_id, $order_status_body ) ); $this->render_webhook_row( 'inventory', __( 'Inventory update', 'weship-acs-sync-for-woocommerce' ), $inventory_url, $this->sample_curl( 'POST', $inventory_url, $account_id, $inventory_body ) ); $this->render_webhook_row( 'weather-hold', __( 'Weather hold', 'weship-acs-sync-for-woocommerce' ), $weather_hold_url, $this->sample_curl( 'POST', $weather_hold_url, $account_id, $weather_hold_body ) ); $this->render_webhook_row( 'products', __( 'Get products (paginated)', 'weship-acs-sync-for-woocommerce' ), $products_url, $this->sample_curl( 'GET', $products_url, $account_id, null ) ); ?>

$event, 'direction' => $direction, 'order_id' => $order_id, 'status' => $status, ); $logger = weship_acs_sync()->logger; $result = $logger ? $logger->get_recent( $page, $size, $filters, $orderby, $sort_dir ) : array( 'items' => array(), 'total_pages' => 1, ); $logs = $result['items']; $total_pages = max( 1, $result['total_pages'] ); $events = $logger ? $logger->get_distinct_events() : array(); // Preserved on every sort link / pagination link so changing one // doesn't reset the others. $preserved_args = array( 'page' => self::PAGE_SLUG, 'tab' => 'logs', 'size' => $size, 'event' => $event, 'direction' => $direction, 'order_id' => $order_id ? $order_id : '', 'status' => $status, ); ?>
render_logs_sortable_th( __( 'Date', 'weship-acs-sync-for-woocommerce' ), 'date', $orderby, $sort_dir, $preserved_args ); ?> render_logs_sortable_th( __( 'Event', 'weship-acs-sync-for-woocommerce' ), 'event', $orderby, $sort_dir, $preserved_args ); ?> render_logs_sortable_th( __( 'Direction', 'weship-acs-sync-for-woocommerce' ), 'direction', $orderby, $sort_dir, $preserved_args ); ?> render_logs_sortable_th( __( 'Order', 'weship-acs-sync-for-woocommerce' ), 'order', $orderby, $sort_dir, $preserved_args ); ?> render_logs_sortable_th( __( 'Status', 'weship-acs-sync-for-woocommerce' ), 'status', $orderby, $sort_dir, $preserved_args ); ?>
created_at ); ?> format_label( $row->event ) ); ?> direction ) ); ?> order_id ) : ?> #order_id ); ?> — url ) ? '' . esc_html( $row->url ) . '' : '—'; ?> status_code ); ?> message, 30 ) ); ?> request ) || ! empty( $row->response ) ) : ?> —
render_logs_pagination( $page, $total_pages, $pagination_args ); ?>
add_query_arg( 'paged', '%#%' ), 'format' => '', 'current' => $page + 1, 'total' => $total_pages, 'add_args' => $add_args, ) ); ?>
$column, 'order' => $next_order, ) ), admin_url( 'admin.php' ) ); ?>