init_hooks();
$this->api = new CARRYBEE_WP_API();
}
/**
* Initialize hooks
*/
private function init_hooks() {
// Admin menu
add_action('admin_menu', array($this, 'add_admin_menu'), 99);
// Admin settings
add_action('admin_init', array($this, 'register_settings'));
// Enqueue admin scripts and styles
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
// Add order actions
add_filter('woocommerce_order_actions', array($this, 'add_order_actions'));
// Process order actions
add_action('woocommerce_order_action_carrybee_wp_send_to_courier', array($this, 'process_send_to_courier'));
add_action('admin_notices', array($this, 'render_queued_admin_notice'));
// Shop Managers (manage_woocommerce) can open the settings page, so let them save it too.
add_filter('option_page_capability_' . CARRYBEE_WP_SETTINGS_GROUP, array($this, 'settings_capability'));
add_filter('woocommerce_order_data_store_cpt_get_orders_query', array($this, 'apply_cpt_meta_query'), 10, 2);
// Add settings link on plugins page
add_filter('plugin_action_links_' . CARRYBEE_WP_PLUGIN_BASENAME, array($this, 'add_settings_link'));
// AJAX handlers
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_LOGIN, array($this, 'handle_login'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_CHECK_ACCESS_TOKEN, array($this, 'handle_check_access_token'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_TEST_API_CONNECTION, array($this, 'test_api_connection'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_SEND_ORDER, array($this, 'handle_send_order_to_courier'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_BULK_SEND, array($this, 'handle_bulk_send_to_courier'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_GET_ORDER_DATA, array($this, 'handle_get_order_data'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_GET_BULK_ORDER_DATA, array($this, 'handle_get_bulk_order_data'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_GET_STORES, array($this, 'handle_get_stores'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_GET_CITIES, array($this, 'handle_get_cities'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_GET_ZONES, array($this, 'handle_get_zones'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_GET_AREAS, array($this, 'handle_get_areas'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_GET_ALL_ZONES, array($this, 'handle_get_all_zones'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_PARSE_ADDRESS, array($this, 'handle_parse_address'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_PARSE_ADDRESSES_BULK, array($this, 'handle_parse_addresses_bulk'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_CLEAR_CITIES_CACHE, array($this, 'handle_clear_cities_cache'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_CLEAR_STORES_CACHE, array($this, 'handle_clear_stores_cache'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_CLEAR_ALL_CACHE, array($this, 'handle_clear_all_cache'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_REFRESH_ORDER_STATUS, array($this, 'handle_refresh_order_status'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_UPDATE_DEFAULT_STORE, array($this, 'handle_update_default_store'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_DIRECT_SEND_TO_COURIER, array($this, 'handle_direct_send_to_courier'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_DIRECT_BULK_SEND_TO_COURIER, array($this, 'handle_direct_bulk_send_to_courier'));
add_action('wp_ajax_' . CARRYBEE_WP_AJAX_PRINT_POD, array($this, 'handle_print_pod'));
// Reload API credentials after settings update
add_action('update_option_' . CARRYBEE_WP_SETTINGS_OPTION, array($this, 'reload_api_credentials'), 5, 2);
// REST API for webhooks
add_action('rest_api_init', array($this, 'register_webhook_endpoint'));
// Add order meta box
add_action('add_meta_boxes', array($this, 'add_order_meta_box'));
// Add custom columns to WooCommerce orders list
add_filter('manage_edit-shop_order_columns', array($this, 'add_order_columns'), 20);
add_action('manage_shop_order_posts_custom_column', array($this, 'render_order_columns'), 20, 2);
add_filter('manage_edit-shop_order_sortable_columns', array($this, 'make_columns_sortable'));
// For HPOS (High Performance Order Storage) compatibility
add_filter('manage_woocommerce_page_wc-orders_columns', array($this, 'add_order_columns'), 20);
add_action('manage_woocommerce_page_wc-orders_custom_column', array($this, 'render_order_columns_hpos'), 20, 2);
// Direct send bulk action on WooCommerce orders pages (legacy + HPOS)
add_filter('bulk_actions-edit-shop_order', array($this, 'register_wc_orders_bulk_actions'), 20);
add_filter('handle_bulk_actions-edit-shop_order', array($this, 'handle_wc_orders_bulk_action'), 10, 3);
add_filter('bulk_actions-woocommerce_page_wc-orders', array($this, 'register_wc_orders_bulk_actions'), 20);
add_filter('handle_bulk_actions-woocommerce_page_wc-orders', array($this, 'handle_wc_orders_bulk_action'), 10, 3);
add_action('admin_notices', array($this, 'render_direct_bulk_send_notice'));
add_action('admin_notices', array($this, 'render_missing_webhook_secret_notice'));
// Sent/not-sent to courier filter on WooCommerce orders pages (legacy + HPOS), defaults to all
add_action('restrict_manage_posts', array($this, 'render_wc_orders_courier_filter_legacy'));
add_action('pre_get_posts', array($this, 'apply_wc_orders_courier_filter_legacy'));
add_action('woocommerce_order_list_table_restrict_manage_orders', array($this, 'render_wc_orders_courier_filter_hpos'), 10, 2);
add_filter('woocommerce_order_list_table_prepare_items_query_args', array($this, 'apply_wc_orders_courier_filter_hpos'));
// Add modal to WooCommerce orders pages
add_action('admin_footer', array($this, 'render_modal_on_orders_page'));
}
/**
* Add admin menu for courier
*/
public function add_admin_menu() {
// Top-level menu opens Orders (the daily task). Settings comes second.
$this->orders_hook = add_menu_page(
CARRYBEE_WP_COURIER_NAME,
CARRYBEE_WP_COURIER_NAME,
'manage_woocommerce',
CARRYBEE_WP_ORDERS_SLUG,
array($this, 'render_orders_page'),
'data:image/svg+xml;base64,' . base64_encode((string) file_get_contents(CARRYBEE_WP_PLUGIN_DIR . 'assets/images/menu-icon.svg')),
56
);
// First submenu item repeats the top-level page, labelled "Orders".
add_submenu_page(
CARRYBEE_WP_ORDERS_SLUG,
__('Orders', 'carrybee'),
$this->submenu_label('dashicons-archive', __('Orders', 'carrybee')),
'manage_woocommerce',
CARRYBEE_WP_ORDERS_SLUG,
array($this, 'render_orders_page')
);
$this->settings_hook = add_submenu_page(
CARRYBEE_WP_ORDERS_SLUG,
__('Settings', 'carrybee'),
$this->submenu_label('dashicons-admin-generic', __('Settings', 'carrybee')),
'manage_woocommerce',
CARRYBEE_WP_MENU_SLUG,
array($this, 'render_settings_page')
);
}
/**
* Submenu label with a small dashicon in front of it.
*
* @param string $dashicon Dashicons class, e.g. dashicons-archive.
* @param string $label Translated label.
* @return string
*/
private function submenu_label($dashicon, $label) {
return ' ' . esc_html($label);
}
/**
* Register plugin settings
*/
public function register_settings() {
register_setting(CARRYBEE_WP_SETTINGS_GROUP, CARRYBEE_WP_SETTINGS_OPTION, array(
'sanitize_callback' => array($this, 'sanitize_settings'),
));
// API Settings Section
add_settings_section(
CARRYBEE_WP_COURIER_SLUG . '_api_settings',
__('API Configuration', 'carrybee'),
array($this, 'api_settings_section_callback'),
CARRYBEE_WP_MENU_SLUG
);
add_settings_field(
CARRYBEE_WP_COURIER_SLUG . '_environment',
__('Environment', 'carrybee'),
array($this, 'environment_field_callback'),
CARRYBEE_WP_MENU_SLUG,
CARRYBEE_WP_COURIER_SLUG . '_api_settings'
);
add_settings_field(
CARRYBEE_WP_COURIER_SLUG . '_client_id',
__('Client ID', 'carrybee'),
array($this, 'client_id_field_callback'),
CARRYBEE_WP_MENU_SLUG,
CARRYBEE_WP_COURIER_SLUG . '_api_settings'
);
add_settings_field(
CARRYBEE_WP_COURIER_SLUG . '_client_secret',
__('Client Secret', 'carrybee'),
array($this, 'client_secret_field_callback'),
CARRYBEE_WP_MENU_SLUG,
CARRYBEE_WP_COURIER_SLUG . '_api_settings'
);
add_settings_field(
CARRYBEE_WP_COURIER_SLUG . '_client_context',
__('Client Context', 'carrybee'),
array($this, 'client_context_field_callback'),
CARRYBEE_WP_MENU_SLUG,
CARRYBEE_WP_COURIER_SLUG . '_api_settings'
);
// Webhook Settings Section
add_settings_section(
CARRYBEE_WP_COURIER_SLUG . '_webhook_settings',
__('Webhook Configuration', 'carrybee'),
array($this, 'webhook_settings_section_callback'),
CARRYBEE_WP_MENU_SLUG
);
add_settings_field(
CARRYBEE_WP_COURIER_SLUG . '_webhook_endpoint',
__('Webhook Endpoint', 'carrybee'),
array($this, 'webhook_endpoint_field_callback'),
CARRYBEE_WP_MENU_SLUG,
CARRYBEE_WP_COURIER_SLUG . '_webhook_settings'
);
add_settings_field(
CARRYBEE_WP_COURIER_SLUG . '_webhook_secret',
__('Webhook Secret', 'carrybee'),
array($this, 'webhook_secret_field_callback'),
CARRYBEE_WP_MENU_SLUG,
CARRYBEE_WP_COURIER_SLUG . '_webhook_settings'
);
// Default Settings Section
add_settings_section(
CARRYBEE_WP_COURIER_SLUG . '_default_settings',
__('Default Values', 'carrybee'),
array($this, 'default_settings_section_callback'),
CARRYBEE_WP_MENU_SLUG
);
add_settings_field(
CARRYBEE_WP_COURIER_SLUG . '_default_product_type',
__('Default Product Type', 'carrybee'),
array($this, 'default_product_type_field_callback'),
CARRYBEE_WP_MENU_SLUG,
CARRYBEE_WP_COURIER_SLUG . '_default_settings'
);
add_settings_field(
CARRYBEE_WP_COURIER_SLUG . '_default_store_id',
__('Default Store', 'carrybee'),
array($this, 'default_store_id_field_callback'),
CARRYBEE_WP_MENU_SLUG,
CARRYBEE_WP_COURIER_SLUG . '_default_settings'
);
}
/**
* Sanitize settings
*
* @param array $input
* @return array
*/
public function sanitize_settings($input) {
// Get existing settings to preserve values not present in the submitted form.
$existing = get_option(CARRYBEE_WP_SETTINGS_OPTION, array());
$sanitized = is_array($existing) ? $existing : array();
$existing_environment = isset($existing[CARRYBEE_WP_SETTING_ENVIRONMENT])
? sanitize_key($existing[CARRYBEE_WP_SETTING_ENVIRONMENT])
: CARRYBEE_WP_DEFAULT_ENVIRONMENT;
$submitted_environment = isset($input[CARRYBEE_WP_SETTING_ENVIRONMENT])
? sanitize_key($input[CARRYBEE_WP_SETTING_ENVIRONMENT])
: $existing_environment;
if (!in_array($submitted_environment, array(CARRYBEE_WP_ENVIRONMENT_PRODUCTION, CARRYBEE_WP_ENVIRONMENT_SANDBOX), true)) {
$submitted_environment = CARRYBEE_WP_DEFAULT_ENVIRONMENT;
}
$sanitized[CARRYBEE_WP_SETTING_ENVIRONMENT] = $submitted_environment;
$environment_changed = $submitted_environment !== $existing_environment;
if (isset($input['client_id'])) {
$sanitized['client_id'] = sanitize_text_field($input['client_id']);
}
if (isset($input['client_secret'])) {
$sanitized['client_secret'] = sanitize_text_field($input['client_secret']);
}
if (isset($input['client_context'])) {
$sanitized['client_context'] = sanitize_text_field($input['client_context']);
}
if (isset($input['webhook_secret'])) {
$sanitized['webhook_secret'] = sanitize_text_field($input['webhook_secret']);
}
if (isset($input['default_product_type'])) {
$default_product_type = absint($input['default_product_type']);
// Validate product type is 1 (Document), 2 (Parcel), or 3 (Book)
if (in_array($default_product_type, array(1, 2, 3))) {
$sanitized['default_product_type'] = $default_product_type;
} else {
$sanitized['default_product_type'] = 2; // Default to Parcel
}
} else {
$sanitized['default_product_type'] = 2; // Default to Parcel
}
if (isset($input[CARRYBEE_WP_SETTING_DEFAULT_STORE_ID])) {
$sanitized[CARRYBEE_WP_SETTING_DEFAULT_STORE_ID] = sanitize_text_field($input[CARRYBEE_WP_SETTING_DEFAULT_STORE_ID]);
}
// Token-based auth is no longer used, keep key clean.
$sanitized['access_token'] = '';
// When the environment or any client credential changes, the store list comes
// from a different account, so the saved default store and the cached list are
// no longer valid. Reset both (overriding whatever the form submitted — it was
// rendered against the old credentials).
$credentials_changed = $environment_changed;
foreach (array('client_id', 'client_secret', 'client_context') as $credential_key) {
$existing_value = isset($existing[$credential_key]) ? (string) $existing[$credential_key] : '';
$new_value = isset($sanitized[$credential_key]) ? (string) $sanitized[$credential_key] : '';
if ($existing_value !== $new_value) {
$credentials_changed = true;
break;
}
}
if ($credentials_changed) {
$had_default_store = !empty($existing[CARRYBEE_WP_SETTING_DEFAULT_STORE_ID]);
$sanitized[CARRYBEE_WP_SETTING_DEFAULT_STORE_ID] = '';
// All cached API data (stores, cities, zones) belongs to the old
// account/environment — cities and zones are cached for 24 hours, so
// clearing only the stores cache would leave stale geo data behind.
$this->delete_api_caches();
if ($had_default_store) {
add_settings_error(
CARRYBEE_WP_SETTINGS_OPTION,
'carrybee_wp_default_store_reset',
__('API credentials changed, so the saved default store was reset. Please review the Default Store setting.', 'carrybee'),
'warning'
);
}
}
if ($environment_changed) {
add_settings_error(
CARRYBEE_WP_SETTINGS_OPTION,
'carrybee_wp_environment_changed',
__('Environment changed successfully. API requests will now use the selected environment.', 'carrybee'),
'success'
);
}
return $sanitized;
}
/**
* API settings section callback
*/
public function api_settings_section_callback() {
echo '
' . esc_html__('Configure your CarryBee API credentials.', 'carrybee') . '
';
}
/**
* Environment field callback
*/
public function environment_field_callback() {
$options = get_option(CARRYBEE_WP_SETTINGS_OPTION, array());
$environment = isset($options[CARRYBEE_WP_SETTING_ENVIRONMENT])
? sanitize_key($options[CARRYBEE_WP_SETTING_ENVIRONMENT])
: CARRYBEE_WP_DEFAULT_ENVIRONMENT;
if (!in_array($environment, array(CARRYBEE_WP_ENVIRONMENT_PRODUCTION, CARRYBEE_WP_ENVIRONMENT_SANDBOX), true)) {
$environment = CARRYBEE_WP_DEFAULT_ENVIRONMENT;
}
?>
>
>
' . esc_html__('Configure webhook settings to receive status updates from CarryBee.', 'carrybee') . '';
}
/**
* Webhook endpoint field callback
*/
public function webhook_endpoint_field_callback() {
$webhook_url = rest_url(CARRYBEE_WP_REST_NAMESPACE . '/webhook');
?>
' . esc_html__('Configure default values for new orders.', 'carrybee') . '';
}
/**
* Default product type field callback
*/
public function default_product_type_field_callback() {
$options = get_option(CARRYBEE_WP_SETTINGS_OPTION, array());
$default_product_type = isset($options['default_product_type']) ? $options['default_product_type'] : 2;
?>
>
>
>
100) $per_page = 100;
// Get filter parameters
$date_from = isset($_GET['date_from']) ? sanitize_text_field(wp_unslash($_GET['date_from'])) : '';
$date_to = isset($_GET['date_to']) ? sanitize_text_field(wp_unslash($_GET['date_to'])) : '';
$order_status = isset($_GET['order_status']) ? sanitize_text_field(wp_unslash($_GET['order_status'])) : '';
$consignment_search = isset($_GET['consignment_search']) ? sanitize_text_field(wp_unslash($_GET['consignment_search'])) : '';
// Combined courier filter: not_sent (default), sent, all, or a specific courier status.
// Status options mirror the published webhook events list, plus the API's Pending state.
$courier_status_options = $this->get_courier_status_filter_options();
// When searching by consignment ID without an explicit choice, fall back to "all"
// so the search isn't hidden by the not-sent default.
$courier_filter = isset($_GET['cbwp_courier'])
? sanitize_text_field(wp_unslash($_GET['cbwp_courier']))
// phpcs:enable WordPress.Security.NonceVerification.Recommended
: (!empty($consignment_search) ? 'all' : 'not_sent');
if (!in_array($courier_filter, array('all', 'sent', 'not_sent'), true)
&& !in_array($courier_filter, $courier_status_options, true)) {
$courier_filter = 'not_sent';
}
// Build query args
$args = array(
'limit' => $per_page,
'paged' => $paged,
'orderby' => 'date',
'order' => 'DESC',
);
// Add date range filter
if (!empty($date_from) || !empty($date_to)) {
$date_query = array();
if (!empty($date_from)) {
$date_query['after'] = $date_from . ' 00:00:00';
}
if (!empty($date_to)) {
$date_query['before'] = $date_to . ' 23:59:59';
}
if (!empty($date_query)) {
$args['date_created'] = implode('...', array(
!empty($date_from) ? $date_from : '',
!empty($date_to) ? $date_to : ''
));
}
}
// Add order status filter
if (!empty($order_status)) {
$args['status'] = array($order_status);
}
// Build meta query from consignment search and courier sent/not-sent filter
$meta_query = array();
// Add consignment ID search filter
if (!empty($consignment_search)) {
$meta_query[] = array(
'key' => CARRYBEE_WP_META_CONSIGNMENT_ID,
'value' => $consignment_search,
'compare' => 'LIKE'
);
}
// Add the combined courier filter: sent/not-sent keywords or a specific status
// (status matching is case-insensitive at the DB level, so legacy uppercase values match too)
if ($courier_filter === 'sent') {
// Sent = has a consignment ID, or a bulk send was accepted and the ID is on its way
$meta_query[] = $this->build_courier_sent_meta_clause('sent');
} elseif ($courier_filter === 'not_sent') {
$meta_query[] = $this->build_courier_sent_meta_clause('not_sent');
} elseif ($courier_filter !== 'all') {
// A specific courier status implies the order was sent
$meta_query[] = array(
'key' => CARRYBEE_WP_META_COURIER_STATUS,
'value' => $courier_filter,
'compare' => '='
);
}
if (!empty($meta_query)) {
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Orders are looked up by CarryBee courier meta; there is no indexed alternative.
$args['meta_query'] = $meta_query;
$args['cbwp_meta_query'] = true;
}
// Fetch orders
$orders = wc_get_orders($args);
// Get total count for pagination (with same filters)
$count_args = $args;
$count_args['limit'] = -1;
$count_args['return'] = 'ids';
unset($count_args['paged']);
$total_orders = wc_get_orders($count_args);
$total_count = count($total_orders);
$total_pages = ceil($total_count / $per_page);
?>
0 ? (($paged - 1) * $per_page) + 1 : 0),
absint(min($paged * $per_page, $total_count)),
absint($total_count)
);
?>
render_courier_modals_html();
?>
orders_hook !== '' && $hook === $this->orders_hook);
$is_plugin_page = $is_orders_page || ($this->settings_hook !== '' && $hook === $this->settings_hook);
$is_wc_orders_page = ($screen && ($screen->id === 'edit-shop_order' || $screen->id === 'woocommerce_page_wc-orders'));
if (!$is_plugin_page && !$is_wc_orders_page) {
return;
}
$admin_css_path = CARRYBEE_WP_PLUGIN_DIR . 'assets/css/admin.css';
$admin_js_path = CARRYBEE_WP_PLUGIN_DIR . 'assets/js/admin.js';
$admin_css_version = file_exists($admin_css_path) ? (string) filemtime($admin_css_path) : CARRYBEE_WP_VERSION;
$admin_js_version = file_exists($admin_js_path) ? (string) filemtime($admin_js_path) : CARRYBEE_WP_VERSION;
// Enqueue CSS
wp_enqueue_style(
'cbwp-admin-css',
CARRYBEE_WP_PLUGIN_URL . 'assets/css/admin.css',
$this->register_select2_style(),
$admin_css_version
);
// Enqueue JS
wp_enqueue_script(
'cbwp-admin-js',
CARRYBEE_WP_PLUGIN_URL . 'assets/js/admin.js',
$this->register_select_woo_script() ? array('jquery', 'selectWoo') : array('jquery'),
$admin_js_version,
true
);
// Flag indicating whether saved API credentials are present (used by settings page JS)
$settings_options = get_option(CARRYBEE_WP_SETTINGS_OPTION, array());
$has_api_credentials = !empty($settings_options['client_id'])
&& !empty($settings_options['client_secret'])
&& !empty($settings_options['client_context']);
// Localize script
wp_localize_script('cbwp-admin-js', 'cbwpAdmin', array(
'ajaxUrl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('CARRYBEE_WP_admin_nonce'),
'pluginUrl' => CARRYBEE_WP_PLUGIN_URL,
'hasApiCredentials' => $has_api_credentials,
'actions' => array(
'login' => CARRYBEE_WP_AJAX_LOGIN,
'checkAccessToken' => CARRYBEE_WP_AJAX_CHECK_ACCESS_TOKEN,
'testApiConnection' => CARRYBEE_WP_AJAX_TEST_API_CONNECTION,
'sendOrder' => CARRYBEE_WP_AJAX_SEND_ORDER,
'bulkSend' => CARRYBEE_WP_AJAX_BULK_SEND,
'getOrderData' => CARRYBEE_WP_AJAX_GET_ORDER_DATA,
'getBulkOrderData' => CARRYBEE_WP_AJAX_GET_BULK_ORDER_DATA,
'getStores' => CARRYBEE_WP_AJAX_GET_STORES,
'getCities' => CARRYBEE_WP_AJAX_GET_CITIES,
'getZones' => CARRYBEE_WP_AJAX_GET_ZONES,
'getAreas' => CARRYBEE_WP_AJAX_GET_AREAS,
'getAllZones' => CARRYBEE_WP_AJAX_GET_ALL_ZONES,
'parseAddress' => CARRYBEE_WP_AJAX_PARSE_ADDRESS,
'parseAddressesBulk' => CARRYBEE_WP_AJAX_PARSE_ADDRESSES_BULK,
'clearCitiesCache' => CARRYBEE_WP_AJAX_CLEAR_CITIES_CACHE,
'clearStoresCache' => CARRYBEE_WP_AJAX_CLEAR_STORES_CACHE,
'clearAllCache' => CARRYBEE_WP_AJAX_CLEAR_ALL_CACHE,
'refreshOrderStatus' => CARRYBEE_WP_AJAX_REFRESH_ORDER_STATUS,
'updateDefaultStore' => CARRYBEE_WP_AJAX_UPDATE_DEFAULT_STORE,
'directSendToCourier' => CARRYBEE_WP_AJAX_DIRECT_SEND_TO_COURIER,
'directBulkSendToCourier' => CARRYBEE_WP_AJAX_DIRECT_BULK_SEND_TO_COURIER,
'printPod' => CARRYBEE_WP_AJAX_PRINT_POD,
),
'assets' => array(
'jsbarcode' => CARRYBEE_WP_PLUGIN_URL . 'assets/vendor/jsbarcode/JsBarcode.all.min.js',
'qrcode' => CARRYBEE_WP_PLUGIN_URL . 'assets/vendor/qrcode-generator/qrcode.js',
'fontRegular' => CARRYBEE_WP_PLUGIN_URL . 'assets/fonts/noto-sans-bengali-bengali-400-normal.woff2',
'fontBold' => CARRYBEE_WP_PLUGIN_URL . 'assets/fonts/noto-sans-bengali-bengali-700-normal.woff2',
),
'strings' => array(
'testing' => __('Testing...', 'carrybee'),
'success' => __('Connection successful!', 'carrybee'),
'error' => __('Connection failed!', 'carrybee'),
'saving' => __('Saving…', 'carrybee'),
'reloading' => __('Reloading…', 'carrybee'),
'loading' => __('Loading…', 'carrybee'),
'fieldRequired' => __('This is required', 'carrybee'),
'listsReloaded' => __('Lists reloaded', 'carrybee'),
'printPod' => __('Print POD', 'carrybee'),
'copyConsignment' => __('Copy consignment ID', 'carrybee'),
'refreshStatus' => __('Refresh status from CarryBee', 'carrybee'),
'searchNoResults' => __('No match. Try another spelling.', 'carrybee'),
'summaryMissing' => __('Missing', 'carrybee'),
/* translators: %s: number of packages */
'summaryPackages' => __('%s package(s)', 'carrybee'),
'selectedOne' => __('1 order selected', 'carrybee'),
/* translators: %d: number of selected orders */
'selectedMany' => __('%d orders selected', 'carrybee'),
'fieldInvalid' => __('Check this value', 'carrybee'),
'sending' => __('Sending…', 'carrybee'),
'sent' => __('Sent to Courier', 'carrybee'),
'sendError' => __('Failed to send', 'carrybee'),
'confirmSend' => __('Are you sure you want to send this order to courier?', 'carrybee'),
'fillHeadersFirst' => __('Fill in Client ID, Client Secret and Client Context first.', 'carrybee'),
'show' => __('Show', 'carrybee'),
'hide' => __('Hide', 'carrybee'),
'copied' => __('Copied', 'carrybee'),
/* translators: %s: environment name, Production or Sandbox */
'connectedTo' => __('Connected · %s', 'carrybee'),
'checking' => __('Checking connection…', 'carrybee'),
'checkingShort' => __('Checking…', 'carrybee'),
'notConnected' => __('Not connected', 'carrybee'),
'couldNotConnect' => __('Couldn\'t connect', 'carrybee'),
'connectedChip' => __('Connected', 'carrybee'),
'fixKeysChip' => __('Check keys', 'carrybee'),
'keysRejected' => __('CarryBee didn\'t accept these keys. Check them, and that the environment matches.', 'carrybee'),
// Bulk send table.
'bulkModalMissing' => __('The bulk send window could not be found. Refresh the page and try again.', 'carrybee'),
'bulkNoOrders' => __('No orders to send. All selected orders are already with the courier.', 'carrybee'),
'bulkStoresMissing' => __('Stores could not be loaded. Refresh the page and try again.', 'carrybee'),
'bulkCitiesMissing' => __('Cities could not be loaded. Refresh the page and try again.', 'carrybee'),
/* translators: %s: error message */
'bulkLoadFailed' => __('Could not load order data: %s', 'carrybee'),
'bulkOrdersLoadFailed' => __('Failed to load orders', 'carrybee'),
'bulkColProductType' => __('Product Type', 'carrybee'),
'bulkColMerchantOrderId' => __('Merchant Order ID', 'carrybee'),
'bulkColStore' => __('Store', 'carrybee'),
'bulkColRecipientName' => __('Recipient Name', 'carrybee'),
'bulkColPhone' => __('Phone', 'carrybee'),
'bulkColPhoneSecondary' => __('Phone (Secondary)', 'carrybee'),
'bulkColAddress' => __('Address', 'carrybee'),
'bulkColCity' => __('City', 'carrybee'),
'bulkColZone' => __('Zone', 'carrybee'),
'bulkColQuantity' => __('Quantity', 'carrybee'),
'bulkColWeight' => __('Weight (kg)', 'carrybee'),
'bulkColAmount' => __('Amount to Collect', 'carrybee'),
'bulkColItemDesc' => __('Package Description', 'carrybee'),
'bulkColSpecialInstruction' => __('Special Instruction', 'carrybee'),
'productTypeDocument' => __('Document', 'carrybee'),
'productTypeParcel' => __('Parcel', 'carrybee'),
'productTypeBook' => __('Book', 'carrybee'),
'bulkRowHeader' => __('#', 'carrybee'),
/* translators: 1: column name, 2: row number */
'bulkCellLabel' => __('%1$s, row %2$s', 'carrybee'),
'bulkRequired' => __('(required)', 'carrybee'),
'bulkSelectPlaceholder' => __('Select…', 'carrybee'),
'bulkSelectCityFirst' => __('Select city first', 'carrybee'),
'bulkNoZones' => __('No zones for this city', 'carrybee'),
'bulkLoadingZones' => __('Loading zones…', 'carrybee'),
'bulkParsingAll' => __('Reading addresses to fill in city and zone…', 'carrybee'),
/* translators: 1: rows filled, 2: rows with an address */
'bulkParseDone' => __('City and zone filled in for %1$s of %2$s orders. Check the table, then click "Send Bulk Orders".', 'carrybee'),
/* translators: %s: number of orders */
'bulkParsedNotice' => __('City and zone filled in for %s order(s).', 'carrybee'),
/* translators: %s: error message */
'bulkParseFailed' => __('Could not read the addresses: %s', 'carrybee'),
'bulkParseFailedDefault' => __('Failed to parse addresses. Fill in city and zone by hand.', 'carrybee'),
'bulkParseInvalid' => __('The address reader sent an unexpected reply. Fill in city and zone by hand.', 'carrybee'),
'bulkParseTimeout' => __('Reading addresses took too long. Fill in city and zone by hand.', 'carrybee'),
'bulkErrRequired' => __('required', 'carrybee'),
'bulkErrPositive' => __('must be greater than 0', 'carrybee'),
'bulkErrNonNegative' => __('must be 0 or more', 'carrybee'),
'bulkValidationHeading' => __('Fix the highlighted cells, then send again:', 'carrybee'),
/* translators: 1: row number, 2: order number, 3: column name, 4: problem */
'bulkErrorLine' => __('Row %1$s (order #%2$s), %3$s: %4$s', 'carrybee'),
'bulkServerHeading' => __('CarryBee could not accept some orders (cells highlighted):', 'carrybee'),
/* translators: 1: row number, 2: column name, 3: error message */
'bulkServerCellLine' => __('Row %1$s, column "%2$s": %3$s', 'carrybee'),
/* translators: 1: row number, 2: error message */
'bulkServerRowLine' => __('Row %1$s: %2$s', 'carrybee'),
'bulkValidationFailed' => __('Validation failed', 'carrybee'),
'bulkNoData' => __('There is nothing to send.', 'carrybee'),
'bulkSending' => __('Sending bulk orders…', 'carrybee'),
'bulkSendFailed' => __('Failed to send bulk orders.', 'carrybee'),
'bulkSendTimeout' => __('The request timed out. The orders may still be processing; refresh the page before trying again.', 'carrybee'),
),
));
}
/**
* Add order actions
*
* @param array $actions
* @return array
*/
public function add_order_actions($actions) {
$actions['carrybee_wp_send_to_courier'] = __('Send to CarryBee', 'carrybee');
return $actions;
}
/**
* The search-dropdown script that ships with WooCommerce (no CDN).
*
* @return bool Whether selectWoo is registered.
*/
private function register_select_woo_script() {
// WooCommerce registers selectWoo on its own hook, which can run after ours.
if (!wp_script_is('selectWoo', 'registered') && function_exists('WC')) {
wp_register_script('selectWoo', WC()->plugin_url() . '/assets/js/selectWoo/selectWoo.full.min.js', array('jquery'), '1.0.6', true);
}
return wp_script_is('selectWoo', 'registered');
}
/**
* The search-dropdown stylesheet that ships with WooCommerce (no CDN).
*
* @return array Style handle to depend on, or none.
*/
private function register_select2_style() {
if (!wp_style_is('select2', 'registered') && function_exists('WC')) {
wp_register_style('select2', WC()->plugin_url() . '/assets/css/select2.css', array(), defined('WC_VERSION') ? WC_VERSION : false);
}
return wp_style_is('select2', 'registered') ? array('select2') : array();
}
/**
* Colour group for a courier status badge.
*
* @param string $status Status text from CarryBee.
* @param bool $is_sent Whether the order has a consignment.
* @return string neutral|progress|success|warning|danger
*/
private function courier_status_tone($status, $is_sent) {
$s = strtolower((string) $status);
if (!$is_sent) {
return 'neutral';
}
if (preg_match('/(^|[^a-z])(not|non|un)[\s_-]?deliver/', $s) || preg_match('/hold|reschedul|pending|partial/', $s)) {
return 'warning';
}
if (preg_match('/fail|cancel|return|reject|lost|damage/', $s)) {
return 'danger';
}
if (preg_match('/(^|[^a-z])delivered/', $s)) {
return 'success';
}
return 'progress';
}
/**
* Without HPOS, wc_get_orders() drops 'meta_query', so the consignment search,
* the courier filter and the webhook fallback lookup would match every order.
* Pass it through to WP_Query, only for this plugin's own queries.
*
* @param array $query WP_Query args.
* @param array $query_vars wc_get_orders() args.
* @return array
*/
public function apply_cpt_meta_query($query, $query_vars) {
if (empty($query_vars['cbwp_meta_query']) || empty($query_vars['meta_query']) || !is_array($query_vars['meta_query'])) {
return $query;
}
if (!isset($query['meta_query']) || !is_array($query['meta_query'])) {
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Orders are looked up by CarryBee courier meta; there is no indexed alternative.
$query['meta_query'] = array();
}
$query['meta_query'][] = $query_vars['meta_query'];
return $query;
}
/**
* Capability needed to save the settings form.
*
* @return string
*/
public function settings_capability() {
return 'manage_woocommerce';
}
/**
* Keep a message for the next admin page load (order actions redirect after running).
*
* @param string $message Message text.
* @param string $type success|error.
*/
private function queue_admin_notice($message, $type = 'success') {
set_transient('cbwp_notice_' . get_current_user_id(), array(
'message' => (string) $message,
'type' => $type === 'error' ? 'error' : 'success',
), MINUTE_IN_SECONDS);
}
/**
* Show a message saved by queue_admin_notice().
*/
public function render_queued_admin_notice() {
$key = 'cbwp_notice_' . get_current_user_id();
$notice = get_transient($key);
if (!is_array($notice) || empty($notice['message'])) {
return;
}
delete_transient($key);
printf(
'',
esc_attr($notice['type']),
esc_html($notice['message'])
);
}
/**
* Stop two sends of the same order running at once (double click, two tabs).
*
* @param int $order_id Order ID.
* @return bool True when this request may send.
*/
private function default_courier_status($consignment_id, $is_sent) {
if ($consignment_id) {
return __('Sent', 'carrybee');
}
return $is_sent ? __('Sent, waiting for ID', 'carrybee') : __('Not Sent', 'carrybee');
}
/**
* Whether the order went to CarryBee: it has a consignment ID, or a bulk send was
* accepted and the ID has not arrived yet. Every "never send twice" check uses this.
*
* @param WC_Order|false $order Order.
* @return bool
*/
private function is_order_sent($order) {
return $order && (CARRYBEE_WP_get_order_meta($order, 'consignment_id') || CARRYBEE_WP_get_order_meta($order, 'sent_to_courier') === 'yes');
}
/**
* Re-read the order after taking the send lock, so a send that finished meanwhile is seen.
*
* @param int $order_id Order ID.
* @return bool
*/
private function is_order_sent_fresh($order_id) {
clean_post_cache($order_id);
if (function_exists('wc_get_container') && class_exists('\Automattic\WooCommerce\Caches\OrderCache')) {
wc_get_container()->get(\Automattic\WooCommerce\Caches\OrderCache::class)->remove($order_id);
}
return $this->is_order_sent(wc_get_order($order_id));
}
private function acquire_send_lock($order_id) {
// add_option() is a single INSERT on a unique key, so only one request can win.
$key = CARRYBEE_WP_SEND_LOCK_PREFIX . absint($order_id);
if (add_option($key, time(), '', false)) {
return true;
}
// A lock older than the timeout was left by a request that died; take it over.
$since = (int) get_option($key, 0);
if ($since && (time() - $since) > CARRYBEE_WP_SEND_LOCK_TIMEOUT) {
delete_option($key);
return add_option($key, time(), '', false);
}
return false;
}
/**
* Release the lock taken by acquire_send_lock().
*
* @param int $order_id Order ID.
*/
private function release_send_lock($order_id) {
delete_option(CARRYBEE_WP_SEND_LOCK_PREFIX . absint($order_id));
}
/**
* Process send to courier action
*
* @param WC_Order $order
*/
public function process_send_to_courier($order) {
if (!$order) {
return;
}
// Never send an order twice.
if ($this->is_order_sent($order)) {
$this->queue_admin_notice(__('This order was already sent to CarryBee.', 'carrybee'), 'error');
return;
}
if (!$this->acquire_send_lock($order->get_id())) {
$this->queue_admin_notice(__('This order is already being sent. Please wait a moment.', 'carrybee'), 'error');
return;
}
if ($this->is_order_sent_fresh($order->get_id())) {
$this->release_send_lock($order->get_id());
$this->queue_admin_notice(__('This order was already sent to CarryBee.', 'carrybee'), 'error');
return;
}
// Prepare order data
$order_data = $this->prepare_order_data($order);
// Send to API
$response = $this->api->create_parcel($order_data);
if (is_wp_error($response)) {
// Add error notice
$order->add_order_note(
sprintf(
/* translators: %s: error message from CarryBee */
__('Failed to send order to courier: %s', 'carrybee'),
$response->get_error_message()
)
);
$this->queue_admin_notice($response->get_error_message(), 'error');
} elseif (isset($response['error']) && $response['error'] === true) {
$error_message = isset($response['message']) ? $response['message'] : __('Failed to send order to courier.', 'carrybee');
$order->add_order_note(
sprintf(
/* translators: %s: error message */
__('Failed to send order to courier: %s', 'carrybee'),
$error_message
)
);
$this->queue_admin_notice($error_message, 'error');
} else {
// Success
$tracking_id = isset($response['tracking_id']) ? $response['tracking_id'] : '';
$consignment_id = '';
if (isset($response['data']['order']['consignment_id'])) {
$consignment_id = sanitize_text_field($response['data']['order']['consignment_id']);
} elseif (isset($response['data']['consignment_id'])) {
$consignment_id = sanitize_text_field($response['data']['consignment_id']);
} elseif (isset($response['consignment_id'])) {
$consignment_id = sanitize_text_field($response['consignment_id']);
}
if (empty($consignment_id)) {
$order->add_order_note(
__('Order send response did not include a consignment ID. The order was not marked as sent.', 'carrybee')
);
$this->queue_admin_notice(__('Courier did not return a consignment ID. Please try again.', 'carrybee'), 'error');
$this->release_send_lock($order->get_id());
return;
}
// Update order meta
if ($consignment_id) {
$order->update_meta_data(CARRYBEE_WP_META_CONSIGNMENT_ID, $consignment_id);
}
if ($tracking_id) {
$order->update_meta_data(CARRYBEE_WP_META_TRACKING_ID, $tracking_id);
}
$order->update_meta_data(CARRYBEE_WP_META_SENT_TO_COURIER, 'yes');
$order->update_meta_data(CARRYBEE_WP_META_SENT_DATE, current_time('mysql'));
$order->save();
// Add order note
$order->add_order_note(
sprintf(
/* translators: 1: courier name, 2: consignment id */
__('Order sent to %1$s successfully. Consignment ID: %2$s', 'carrybee'),
CARRYBEE_WP_COURIER_FULL_NAME,
$consignment_id
)
);
$this->queue_admin_notice(__('Order sent to courier successfully!', 'carrybee'), 'success');
}
$this->release_send_lock($order->get_id());
}
/**
* Prepare order data for API
*
* @param WC_Order $order
* @return array
*/
private function prepare_order_data($order) {
// Get default store from settings. Store IDs can be alphanumeric.
$options = get_option(CARRYBEE_WP_SETTINGS_OPTION, array());
$default_store_id = isset($options['default_store_id']) ? sanitize_text_field($options['default_store_id']) : '';
// Calculate total weight and quantity from order items
$total_quantity = 0;
$total_weight = 0;
$item_descriptions = array();
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$quantity = $item->get_quantity();
$total_quantity += $quantity;
if ($product && $product->get_weight()) {
$total_weight += floatval($product->get_weight()) * $quantity;
}
$item_descriptions[] = $item->get_name() . ' x ' . $quantity;
}
// Default weight if none calculated
if ($total_weight <= 0) {
$total_weight = 0.5;
}
// Get billing phone
$recipient_phone = $order->get_billing_phone();
// Try to get secondary phone from order meta
$recipient_phone_secondary = $order->get_meta('_billing_phone_2');
if (empty($recipient_phone_secondary)) {
$recipient_phone_secondary = $order->get_meta('_shipping_phone');
}
// Ensure secondary phone is different from primary phone
if (!empty($recipient_phone_secondary) && $recipient_phone_secondary === $recipient_phone) {
$recipient_phone_secondary = '';
}
// Get special instructions from order notes or customer note
$special_instruction = $order->get_customer_note();
if (empty($special_instruction)) {
$special_instruction = $order->get_meta('_order_special_instructions');
}
// Get default product type from settings (fallback to 2 = Parcel)
$default_product_type = CARRYBEE_WP_get_setting('default_product_type', 2);
// Prepare data in API format
$data = array(
'store_id' => $default_store_id,
'merchant_order_id' => $order->get_order_number(),
'recipient_name' => trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name()),
'recipient_phone' => $recipient_phone,
'recipient_phone_secondary' => $recipient_phone_secondary,
'recipient_address' => trim($order->get_billing_address_1() . ' ' . $order->get_billing_address_2()),
'city_id' => 0, // Will need to be mapped or set manually
'zone_id' => 0, // Will need to be mapped or set manually
'area_id' => 0, // Will need to be mapped or set manually
'delivery_type' => 1,
'product_type' => $default_product_type,
'special_instruction' => $special_instruction,
'quantity' => $total_quantity > 0 ? $total_quantity : 1,
'weight' => $total_weight,
'amount_collect' => floatval($order->get_total()),
'item_desc' => !empty($item_descriptions) ? implode(', ', $item_descriptions) : 'Order Items',
);
return apply_filters('CARRYBEE_WP_order_data', $data, $order);
}
/**
* Prepare order data for the send form and bulk table
*
* @param WC_Order $order
* @return array
*/
private function prepare_order_data_for_form($order) {
$base_data = $this->prepare_order_data($order);
// Return data with all fields needed for the form
return array(
'store_id' => $base_data['store_id'],
'merchant_order_id' => $base_data['merchant_order_id'],
'recipient_name' => $base_data['recipient_name'],
'recipient_phone' => $base_data['recipient_phone'],
'recipient_phone_secondary' => $base_data['recipient_phone_secondary'],
'recipient_address' => $base_data['recipient_address'],
'city_id' => $base_data['city_id'],
'zone_id' => $base_data['zone_id'],
'area_id' => $base_data['area_id'],
'delivery_type' => $base_data['delivery_type'],
'product_type' => $base_data['product_type'],
'special_instruction' => $base_data['special_instruction'],
'quantity' => $base_data['quantity'],
'weight' => $base_data['weight'],
'amount_collect' => $base_data['amount_collect'],
'item_desc' => $base_data['item_desc'],
);
}
/**
* Test API connection
*/
public function test_api_connection() {
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
$response = $this->api->test_connection();
if (is_wp_error($response)) {
wp_send_json_error(array('message' => $response->get_error_message()));
} else {
wp_send_json_success(array('message' => __('Connection successful!', 'carrybee')));
}
}
/**
* Handle legacy login AJAX request
*/
public function handle_login() {
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Keep endpoint for backward compatibility with existing admin JS.
$api = new CARRYBEE_WP_API();
$response = $api->test_connection();
if (is_wp_error($response)) {
wp_send_json_error(array('message' => $response->get_error_message()));
} else {
wp_send_json_success(array('message' => __('Connection successful. Token is not required for this API.', 'carrybee')));
}
}
/**
* Handle legacy token-check AJAX request
*/
public function handle_check_access_token() {
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP: handle_check_access_token CALLED');
}
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
if (!current_user_can('manage_woocommerce')) {
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP: Check token FAILED - user unauthorized');
}
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Validate configured headers by testing API connectivity.
$options = get_option(CARRYBEE_WP_SETTINGS_OPTION, array());
$has_headers = !empty($options['client_id']) && !empty($options['client_secret']) && !empty($options['client_context']);
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP: Has headers: ' . ($has_headers ? 'YES' : 'NO'));
}
if (!$has_headers) {
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP: Check headers FAILED - missing client headers');
}
wp_send_json_error(array('message' => __('Client headers are missing. Please save Client-ID, Client-Secret, and Client-Context.', 'carrybee')));
return;
}
// Test connection with configured headers.
$api = new CARRYBEE_WP_API();
$response = $api->test_connection();
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP: Test connection result: ' . (is_wp_error($response) ? 'ERROR - ' . $response->get_error_message() : 'SUCCESS'));
}
if (is_wp_error($response)) {
wp_send_json_error(array('message' => __('API headers are invalid: ', 'carrybee') . $response->get_error_message()));
} else {
wp_send_json_success(array('message' => __('API headers are valid and working!', 'carrybee')));
}
}
/**
* Handle get order data AJAX request
*/
public function handle_get_order_data() {
// Get order ID
$order_id = isset($_POST['order_id']) ? absint($_POST['order_id']) : 0;
if (!$order_id) {
wp_send_json_error(array('message' => __('Invalid order ID', 'carrybee')));
}
// Verify nonce
$nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
if (!wp_verify_nonce($nonce, 'CARRYBEE_WP_send_to_courier_' . $order_id)) {
wp_send_json_error(array('message' => __('Security check failed', 'carrybee')));
}
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Get order
$order = wc_get_order($order_id);
if (!$order) {
wp_send_json_error(array('message' => __('Order not found', 'carrybee')));
}
// Prepare order data for the form
$billing_phone = $order->get_billing_phone();
$customer_name = trim($order->get_billing_first_name() . ' ' . $order->get_billing_last_name());
$address = trim($order->get_billing_address_1() . ' ' . $order->get_billing_address_2());
// Calculate total weight
$total_weight = 0;
$item_descriptions = array();
$total_quantity = 0;
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$quantity = $item->get_quantity();
$total_quantity += $quantity;
if ($product && $product->get_weight()) {
$total_weight += (float) $product->get_weight() * $quantity;
}
$item_descriptions[] = $item->get_name() . ' x ' . $quantity;
}
// Default weight if not set
if ($total_weight <= 0) {
$total_weight = 0.5;
}
// Get default product type from settings (fallback to 2 = Parcel)
$default_product_type = CARRYBEE_WP_get_setting('default_product_type', 2);
$form_data = array(
'store_id' => CARRYBEE_WP_get_setting('default_store_id', ''),
'merchant_order_id' => $order->get_order_number(),
'recipient_name' => $customer_name,
'recipient_phone' => $billing_phone,
'recipient_phone_secondary' => '',
'recipient_address' => $address,
'city_id' => '',
'zone_id' => '',
'area_id' => '',
'delivery_type' => 1,
'product_type' => $default_product_type,
'special_instruction' => $order->get_customer_note(),
'quantity' => $total_quantity,
'weight' => $total_weight,
'amount_collect' => $order->get_total(),
'item_desc' => implode(', ', $item_descriptions),
);
wp_send_json_success(array('data' => $form_data));
}
/**
* Resolve WooCommerce order ID from merchant order ID.
*
* @param string $merchant_order_id
* @return int
*/
private function find_order_id_by_merchant_order_id($merchant_order_id) {
$merchant_order_id = sanitize_text_field($merchant_order_id);
if ($merchant_order_id === '') {
return 0;
}
$order_id = absint($merchant_order_id);
if ($order_id > 0) {
$order = wc_get_order($order_id);
if ($order && (string) $order->get_order_number() === (string) $merchant_order_id) {
return $order_id;
}
}
$orders_by_number = wc_get_orders(array(
'limit' => 1,
'return' => 'ids',
// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Orders are looked up by CarryBee courier meta; there is no indexed alternative.
'meta_key' => '_order_number',
'meta_value' => $merchant_order_id,
// phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value
));
if (!empty($orders_by_number)) {
return absint($orders_by_number[0]);
}
return 0;
}
/**
* Handle get stores AJAX request
*/
private function normalize_stores_for_frontend($stores) {
if (!is_array($stores)) {
return array();
}
return array_values(array_filter(array_map(function($store) {
if (!is_array($store)) {
return null;
}
$store_id = '';
if (isset($store['store_id'])) {
$store_id = sanitize_text_field($store['store_id']);
} elseif (isset($store['id'])) {
$store_id = sanitize_text_field($store['id']);
}
if ($store_id === '') {
return null;
}
$store_name = '';
if (isset($store['store_name'])) {
$store_name = sanitize_text_field($store['store_name']);
} elseif (isset($store['name'])) {
$store_name = sanitize_text_field($store['name']);
}
$is_active_raw = null;
if (array_key_exists('is_active', $store)) {
$is_active_raw = $store['is_active'];
}
$is_default_pickup_raw = null;
if (array_key_exists('is_default_pickup', $store)) {
$is_default_pickup_raw = $store['is_default_pickup'];
} elseif (array_key_exists('is_default_pickup_store', $store)) {
$is_default_pickup_raw = $store['is_default_pickup_store'];
}
$is_active = filter_var($is_active_raw, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
$is_default_pickup = filter_var($is_default_pickup_raw, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($is_active === null) {
$is_active = false;
}
if ($is_default_pickup === null) {
$is_default_pickup = false;
}
return array(
'id' => $store_id,
'name' => $store_name,
'store_id' => $store_id,
'store_name' => $store_name,
'is_active' => $is_active,
'is_default_pickup_store' => $is_default_pickup,
'is_default_pickup' => $is_default_pickup,
);
}, $stores)));
}
public function handle_get_stores() {
// Check nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Check for cached stores (30 minutes cache)
$cache_key = CARRYBEE_WP_cache_key(CARRYBEE_WP_CACHE_KEY_STORES);
$cached_stores = get_transient($cache_key);
if ($cached_stores !== false) {
$cached_stores = $this->normalize_stores_for_frontend($cached_stores);
// Return cached data
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Stores: Returning cached data');
}
wp_send_json_success(array('stores' => $cached_stores));
return;
}
// Get stores from API using endpoint constant
$response = $this->api->get(CARRYBEE_WP_API_Endpoints::STORES);
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
// Log detailed error for debugging
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Stores Error: ' . $error_message);
}
wp_send_json_error(array('message' => $error_message));
}
$response_code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
// Log response for debugging
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Stores Response Code: ' . $response_code);
}
// Support new response shape: { error: false, data: { stores: [...] } }
// and keep backward compatibility with previous shape.
$stores = null;
if (
$response_code === 200 &&
isset($data['error']) &&
$data['error'] === false &&
isset($data['data']['stores']) &&
is_array($data['data']['stores'])
) {
$stores = $data['data']['stores'];
} elseif (
$response_code === 200 &&
isset($data['success']) &&
$data['success'] === true &&
isset($data['data']) &&
is_array($data['data'])
) {
$stores = $data['data'];
}
if (is_array($stores)) {
$stores = $this->normalize_stores_for_frontend($stores);
// Cache stores for 30 minutes (1800 seconds)
set_transient($cache_key, $stores, CARRYBEE_WP_CACHE_STORES_TTL);
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Stores: Cached ' . count($stores) . ' stores for 30 minutes');
}
wp_send_json_success(array('stores' => $stores));
} else {
// Provide detailed error message
$message = __('Failed to fetch stores', 'carrybee');
if (isset($data['message'])) {
$message = $data['message'];
} elseif ($response_code !== 200) {
$message .= ' (HTTP ' . $response_code . ')';
}
// Log error
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Stores Failed: ' . $message);
}
wp_send_json_error(array('message' => $message));
}
}
/**
* Handle get cities AJAX request
*/
public function handle_get_cities() {
// Check nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Check for cached cities (daily cache)
$cache_key = CARRYBEE_WP_cache_key(CARRYBEE_WP_CACHE_KEY_CITIES);
$cached_cities = get_transient($cache_key);
if ($cached_cities !== false) {
// Return cached data
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Cities: Returning cached data');
}
wp_send_json_success(array('cities' => $cached_cities));
return;
}
// Get cities from API using endpoint constant
$response = $this->api->get(CARRYBEE_WP_API_Endpoints::CITIES);
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Cities Error: ' . $error_message);
}
wp_send_json_error(array('message' => $error_message));
}
$response_code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Cities Response Code: ' . $response_code);
}
// New response shape: { error: false, data: { cities: [...] } }
// Keep backward compatibility with previous formats.
$cities = null;
if ($response_code === 200 && isset($data['error']) && $data['error'] === false && isset($data['data']['cities']) && is_array($data['data']['cities'])) {
$cities = $data['data']['cities'];
} elseif ($response_code === 200 && isset($data['success']) && $data['success'] === true && isset($data['data']['data']) && is_array($data['data']['data'])) {
$cities = $data['data']['data'];
}
if (is_array($cities)) {
// Normalize to legacy frontend schema to avoid broad JS changes.
$cities = array_map(function($city) {
return array(
'city_id' => isset($city['city_id']) ? absint($city['city_id']) : (isset($city['id']) ? absint($city['id']) : 0),
'city_name' => isset($city['city_name']) ? sanitize_text_field($city['city_name']) : (isset($city['name']) ? sanitize_text_field($city['name']) : ''),
);
}, $cities);
// Cache cities for 24 hours (DAY_IN_SECONDS = 86400)
set_transient($cache_key, $cities, CARRYBEE_WP_CACHE_CITIES_TTL);
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Cities: Cached ' . count($cities) . ' cities for 24 hours');
}
wp_send_json_success(array('cities' => $cities));
} else {
$message = __('Failed to fetch cities', 'carrybee');
if (isset($data['message'])) {
$message = $data['message'];
} elseif ($response_code !== 200) {
$message .= ' (HTTP ' . $response_code . ')';
}
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Cities Failed: ' . $message);
}
wp_send_json_error(array('message' => $message));
}
}
/**
* Handle get zones AJAX request
*/
public function handle_get_zones() {
// Check nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Get city ID
$city_id = isset($_POST['city_id']) ? absint($_POST['city_id']) : 0;
if (!$city_id) {
wp_send_json_error(array('message' => __('Invalid city ID', 'carrybee')));
}
// Get all zones from API and filter by city for this request.
$endpoint = CARRYBEE_WP_API_Endpoints::ZONES;
$response = $this->api->get($endpoint);
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Zones Error: ' . $error_message);
}
wp_send_json_error(array('message' => $error_message));
}
$response_code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Zones Response Code: ' . $response_code);
}
// Supported response shapes:
// - { error: false, data: { zones: [...] } }
// - { success: true, data: [...] } (legacy)
$zones = null;
if ($response_code === 200 && isset($data['error']) && $data['error'] === false && isset($data['data']['zones']) && is_array($data['data']['zones'])) {
$zones = $data['data']['zones'];
} elseif ($response_code === 200 && isset($data['success']) && $data['success'] === true && isset($data['data']) && is_array($data['data'])) {
$zones = $data['data'];
}
if (is_array($zones)) {
$has_city_id = false;
foreach ($zones as $zone_item) {
if (isset($zone_item['city_id'])) {
$has_city_id = true;
break;
}
}
if ($has_city_id) {
$zones = array_values(array_filter($zones, function($zone) use ($city_id) {
return isset($zone['city_id']) && absint($zone['city_id']) === $city_id;
}));
}
$zones = array_map(function($zone) {
return array(
'zone_id' => isset($zone['zone_id']) ? absint($zone['zone_id']) : (isset($zone['id']) ? absint($zone['id']) : 0),
'zone_name' => isset($zone['zone_name']) ? sanitize_text_field($zone['zone_name']) : (isset($zone['name']) ? sanitize_text_field($zone['name']) : ''),
'city_id' => isset($zone['city_id']) ? absint($zone['city_id']) : 0,
);
}, $zones);
wp_send_json_success(array('zones' => $zones));
} else {
$message = __('Failed to fetch zones', 'carrybee');
if (isset($data['message'])) {
$message = $data['message'];
} elseif ($response_code !== 200) {
$message .= ' (HTTP ' . $response_code . ')';
}
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Zones Failed: ' . $message);
}
wp_send_json_error(array('message' => $message));
}
}
/**
* Handle get areas AJAX request
*/
public function handle_get_areas() {
// Check nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Get city and zone IDs
$city_id = isset($_POST['city_id']) ? absint($_POST['city_id']) : 0;
$zone_id = isset($_POST['zone_id']) ? absint($_POST['zone_id']) : 0;
if (!$city_id) {
wp_send_json_error(array('message' => __('Invalid city ID', 'carrybee')));
}
if (!$zone_id) {
wp_send_json_error(array('message' => __('Invalid zone ID', 'carrybee')));
}
// Get areas from API
$endpoint = CARRYBEE_WP_API_Endpoints::get_areas($city_id, $zone_id);
$response = $this->api->get($endpoint);
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Areas Error: ' . $error_message);
}
wp_send_json_error(array('message' => $error_message));
}
$response_code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Areas Response Code: ' . $response_code);
}
// New response shape: { error: false, data: { areas: [...] } }
$areas = null;
if ($response_code === 200 && isset($data['error']) && $data['error'] === false && isset($data['data']['areas']) && is_array($data['data']['areas'])) {
$areas = $data['data']['areas'];
}
if (is_array($areas)) {
$areas = array_map(function($area) {
return array(
'area_id' => isset($area['area_id']) ? absint($area['area_id']) : (isset($area['id']) ? absint($area['id']) : 0),
'area_name' => isset($area['area_name']) ? sanitize_text_field($area['area_name']) : (isset($area['name']) ? sanitize_text_field($area['name']) : ''),
'zone_id' => isset($area['zone_id']) ? absint($area['zone_id']) : 0,
);
}, $areas);
wp_send_json_success(array('areas' => $areas));
} else {
$message = __('Failed to fetch areas', 'carrybee');
if (isset($data['message'])) {
$message = $data['message'];
} elseif ($response_code !== 200) {
$message .= ' (HTTP ' . $response_code . ')';
}
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get Areas Failed: ' . $message);
}
wp_send_json_error(array('message' => $message));
}
}
/**
* Handle get all zones AJAX request (for bulk operations)
*/
public function handle_get_all_zones() {
// Check nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Check for cached zones (24 hours cache)
$cache_key = CARRYBEE_WP_cache_key(CARRYBEE_WP_CACHE_KEY_ZONES);
$cached_zones = get_transient($cache_key);
if ($cached_zones !== false) {
// Return cached data
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get All Zones: Returning cached data');
}
wp_send_json_success(array('zones' => $cached_zones));
return;
}
// Get all zones from API
$endpoint = CARRYBEE_WP_API_Endpoints::ZONES;
$response = $this->api->get($endpoint);
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get All Zones Error: ' . $error_message);
}
wp_send_json_error(array('message' => $error_message));
}
$response_code = wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get All Zones Response Code: ' . $response_code);
}
// API v2 shape: { error: false, data: { zones: [...] } }
// Keep legacy fallback: { success: true, data: [...] }
$zones = null;
if ($response_code === 200 && isset($data['error']) && $data['error'] === false && isset($data['data']['zones']) && is_array($data['data']['zones'])) {
$zones = $data['data']['zones'];
} elseif ($response_code === 200 && isset($data['success']) && $data['success'] === true && isset($data['data']) && is_array($data['data'])) {
$zones = $data['data'];
}
if (is_array($zones)) {
// Normalize payload for existing JS consumers in bulk send UI.
$zones = array_map(function($zone) {
return array(
'zone_id' => isset($zone['zone_id']) ? absint($zone['zone_id']) : (isset($zone['id']) ? absint($zone['id']) : 0),
'zone_name' => isset($zone['zone_name']) ? sanitize_text_field($zone['zone_name']) : (isset($zone['name']) ? sanitize_text_field($zone['name']) : ''),
'city_id' => isset($zone['city_id']) ? absint($zone['city_id']) : 0,
);
}, $zones);
// Cache zones for 24 hours
set_transient($cache_key, $zones, CARRYBEE_WP_CACHE_ZONES_TTL);
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get All Zones: Cached ' . count($zones) . ' zones for 24 hours');
}
wp_send_json_success(array('zones' => $zones));
} else {
$message = __('Failed to fetch all zones', 'carrybee');
if (isset($data['message'])) {
$message = $data['message'];
} elseif ($response_code !== 200) {
$message .= ' (HTTP ' . $response_code . ')';
}
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Get All Zones Failed: ' . $message);
}
wp_send_json_error(array('message' => $message));
}
}
/**
* Handle parse address AJAX request
*/
public function handle_parse_address() {
// Check nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Get address
$address = isset($_POST['address']) ? sanitize_textarea_field(wp_unslash($_POST['address'])) : '';
if (empty($address)) {
wp_send_json_error(array('message' => __('Address is required', 'carrybee')));
}
// Parse address using API
$response = $this->api->parse_address($address);
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Parse Address Error: ' . $error_message);
}
wp_send_json_error(array('message' => $error_message));
}
if (CARRYBEE_WP_debug_enabled()) {
}
// New API response format: { error: bool, message: string, data?: {...}, causes?: {...} }
if (isset($response['error']) && $response['error'] === false && isset($response['data']) && is_array($response['data'])) {
wp_send_json_success(array('parsed_address' => $response['data']));
}
// Backward compatibility for any older response shape.
if (isset($response['success']) && $response['success'] === true && isset($response['data'])) {
wp_send_json_success(array('parsed_address' => $response['data']));
}
$message = __('Failed to parse address', 'carrybee');
if (isset($response['message']) && !empty($response['message'])) {
$message = sanitize_text_field($response['message']);
}
// Bubble up validation details when present (e.g. causes.query[].type=min).
if (!empty($response['causes']) && is_array($response['causes'])) {
$first_cause = '';
foreach ($response['causes'] as $field => $items) {
if (is_array($items) && !empty($items[0]['type'])) {
$first_cause = sprintf('%s: %s', sanitize_text_field((string) $field), sanitize_text_field((string) $items[0]['type']));
break;
}
}
if ($first_cause !== '') {
$message .= ' (' . $first_cause . ')';
}
}
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Parse Address Failed: ' . $message);
}
wp_send_json_error(array('message' => $message));
}
/**
* Handle parse multiple addresses AJAX request
*/
public function handle_parse_addresses_bulk() {
// Check nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Get addresses array
// Decode first, then sanitize each field: sanitizing the raw JSON string strips "<...>" and "%xx" across fields and breaks it.
$addresses = isset($_POST['addresses']) ? json_decode(wp_unslash($_POST['addresses']), true) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- every decoded field is sanitized on the next line.
$addresses = is_array($addresses) ? map_deep($addresses, 'sanitize_textarea_field') : array();
if (empty($addresses) || !is_array($addresses)) {
wp_send_json_error(array('message' => __('Addresses array is required', 'carrybee')));
}
// Sanitize addresses
$sanitized_addresses = array_map('sanitize_textarea_field', $addresses);
// Parse addresses using API
$response = $this->api->parse_addresses_bulk($sanitized_addresses);
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Parse Addresses Bulk Error: ' . $error_message);
}
wp_send_json_error(array('message' => $error_message));
}
if (CARRYBEE_WP_debug_enabled()) {
}
// Check for successful response and normalize known payload shapes.
$is_success = (isset($response['error']) && $response['error'] === false) || (isset($response['success']) && $response['success'] === true);
if ($is_success && isset($response['data']) && is_array($response['data'])) {
$parsed_data = array();
// Current API v2 shape: data.addresses
if (isset($response['data']['addresses']) && is_array($response['data']['addresses'])) {
$parsed_data = $response['data']['addresses'];
// Legacy shape: data.parsed_addresses.batch_response
} elseif (isset($response['data']['parsed_addresses']['batch_response']) && is_array($response['data']['parsed_addresses']['batch_response'])) {
$parsed_data = $response['data']['parsed_addresses']['batch_response'];
// Legacy shape: data.parsed_addresses is already a list
} elseif (isset($response['data']['parsed_addresses']) && is_array($response['data']['parsed_addresses'])) {
$parsed_data = $response['data']['parsed_addresses'];
}
if (!is_array($parsed_data)) {
$parsed_data = array();
}
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Parse Addresses Bulk - Extracted Data Count: ' . count($parsed_data));
}
wp_send_json_success(array('parsed_addresses' => $parsed_data));
} else {
$message = __('Failed to parse addresses in bulk', 'carrybee');
if (isset($response['message'])) {
$message = $response['message'];
}
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP Parse Addresses Bulk Failed: ' . $message);
}
wp_send_json_error(array('message' => $message));
}
}
/**
* Handle clear cities cache AJAX request
*/
public function handle_clear_cities_cache() {
// Check nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Clear the cities cache
$cache_key = CARRYBEE_WP_cache_key(CARRYBEE_WP_CACHE_KEY_CITIES);
$deleted = delete_transient($cache_key);
if ($deleted) {
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP: Cities cache cleared manually');
}
wp_send_json_success(array('message' => __('Cities cache cleared successfully', 'carrybee')));
} else {
wp_send_json_success(array('message' => __('No cache to clear', 'carrybee')));
}
}
/**
* Handle AJAX request to persist the auto-selected default store from the settings page.
* Only writes when no default store is currently saved, so an admin's explicit choice is never overwritten.
*/
public function handle_update_default_store() {
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
$store_id = isset($_POST['store_id']) ? sanitize_text_field(wp_unslash($_POST['store_id'])) : '';
if ($store_id === '') {
wp_send_json_error(array('message' => __('Store ID is required', 'carrybee')));
}
$options = get_option(CARRYBEE_WP_SETTINGS_OPTION, array());
$existing_default = isset($options[CARRYBEE_WP_SETTING_DEFAULT_STORE_ID])
? sanitize_text_field($options[CARRYBEE_WP_SETTING_DEFAULT_STORE_ID])
: '';
if ($existing_default !== '') {
wp_send_json_success(array(
'updated' => false,
'store_id' => $existing_default,
));
}
CARRYBEE_WP_update_setting(CARRYBEE_WP_SETTING_DEFAULT_STORE_ID, $store_id);
wp_send_json_success(array(
'updated' => true,
'store_id' => $store_id,
));
}
/**
* Handle print POD AJAX request: fetch POD data from the API for the given consignments.
*/
public function handle_print_pod() {
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
$consignment_ids = isset($_POST['consignment_ids']) ? sanitize_text_field(wp_unslash($_POST['consignment_ids'])) : '';
if ($consignment_ids === '') {
wp_send_json_error(array('message' => __('Consignment ID is required', 'carrybee')));
}
$response = $this->api->get_order_print_pod($consignment_ids);
if (is_wp_error($response)) {
wp_send_json_error(array('message' => $response->get_error_message()));
}
wp_send_json_success($response);
}
/**
* Handle clear stores cache AJAX request
*/
public function handle_clear_stores_cache() {
// Check nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Clear the stores cache
$cache_key = CARRYBEE_WP_cache_key(CARRYBEE_WP_CACHE_KEY_STORES);
$deleted = delete_transient($cache_key);
if ($deleted) {
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP: Stores cache cleared manually');
}
wp_send_json_success(array('message' => __('Stores cache cleared successfully', 'carrybee')));
} else {
wp_send_json_success(array('message' => __('No cache to clear', 'carrybee')));
}
}
/**
* Delete all cached API data (cities, stores, zones, areas).
*
* @return int Number of cache items removed.
*/
private function delete_api_caches() {
$cache_keys = array(
CARRYBEE_WP_cache_key(CARRYBEE_WP_CACHE_KEY_CITIES),
CARRYBEE_WP_cache_key(CARRYBEE_WP_CACHE_KEY_STORES),
CARRYBEE_WP_cache_key(CARRYBEE_WP_CACHE_KEY_ZONES),
CARRYBEE_WP_cache_key(CARRYBEE_WP_CACHE_KEY_AREAS)
);
$cleared_count = 0;
foreach ($cache_keys as $key) {
if (delete_transient($key)) {
$cleared_count++;
}
}
return $cleared_count;
}
/**
* Handle clear all cache AJAX request (cities, stores, zones, areas)
*/
public function handle_clear_all_cache() {
// Check nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
$cleared_count = $this->delete_api_caches();
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CBWP: All caches cleared manually (' . $cleared_count . ' caches)');
}
wp_send_json_success(array(
'message' => __('CarryBee data reloaded. Stores, cities and zones will load fresh.', 'carrybee'),
));
}
/**
* Handle refresh order status AJAX request
*/
public function handle_refresh_order_status() {
// Check nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Get order ID
$order_id = isset($_POST['order_id']) ? absint($_POST['order_id']) : 0;
if (!$order_id) {
wp_send_json_error(array('message' => __('Invalid order ID', 'carrybee')));
}
// Get order
$order = wc_get_order($order_id);
if (!$order) {
wp_send_json_error(array('message' => __('Order not found', 'carrybee')));
}
// Get consignment ID
$consignment_id = CARRYBEE_WP_get_order_meta($order, 'consignment_id');
if (empty($consignment_id)) {
wp_send_json_error(array('message' => __('Order has not been sent to courier yet', 'carrybee')));
}
// Fetch order info from API
$response = $this->api->get_order_info($consignment_id);
if (is_wp_error($response)) {
wp_send_json_error(array('message' => $response->get_error_message()));
}
// Extract data from response
// Expected v2: { error: false, data: { transfer_status, ... } }
if (!isset($response['data'])) {
wp_send_json_error(array('message' => __('Invalid response from API', 'carrybee')));
}
$data = $response['data'];
$transfer_status = isset($data['transfer_status']) ? sanitize_text_field($data['transfer_status']) : '';
$order_status = isset($data['order_status']) ? sanitize_text_field($data['order_status']) : $transfer_status;
$updated_at = isset($data['updated_at']) ? sanitize_text_field($data['updated_at']) : '';
$invoice_id = isset($data['invoice_id']) ? sanitize_text_field($data['invoice_id']) : '';
// Update order meta
if ($order_status) {
CARRYBEE_WP_update_order_meta($order, 'courier_status', $order_status);
}
if ($updated_at) {
CARRYBEE_WP_update_order_meta($order, 'status_updated_at', $updated_at);
}
if ($invoice_id) {
CARRYBEE_WP_update_order_meta($order, 'invoice_id', $invoice_id);
}
$order->save();
// Add order note
$note = sprintf(
/* translators: 1: line break, 2: order status, 3: line break, 4: updated at */
__('Order status refreshed from courier.%1$sStatus: %2$s%3$sUpdated At: %4$s', 'carrybee'),
"\n",
$order_status,
"\n",
$updated_at
);
if ($invoice_id) {
/* translators: %s: invoice id */
$note .= "\n" . sprintf(__('Invoice ID: %s', 'carrybee'), $invoice_id);
}
$order->add_order_note($note);
// Return success with data
wp_send_json_success(array(
'message' => __('Order status updated successfully', 'carrybee'),
'order_status' => $order_status,
'transfer_status' => $transfer_status,
'updated_at' => $updated_at,
'invoice_id' => $invoice_id,
));
}
/**
* Handle send order to courier AJAX request
*/
public function handle_send_order_to_courier() {
// Check permissions first — the merchant-order-ID fallback below runs order
// lookups, which must not be reachable by unauthorized callers. The nonce is
// per-order so it can only be verified after the order ID is resolved.
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Try to get order ID directly first (preferred method)
$order_id = isset($_POST['order_id']) ? absint($_POST['order_id']) : 0;
// If not provided, fall back to finding by merchant order ID
if (!$order_id) {
$merchant_order_id = isset($_POST['merchant_order_id']) ? sanitize_text_field(wp_unslash($_POST['merchant_order_id'])) : '';
if (!$merchant_order_id) {
wp_send_json_error(array('message' => __('Invalid order ID', 'carrybee')));
}
// Find order by merchant order ID (order number)
$orders = wc_get_orders(array(
'limit' => 1,
'return' => 'ids',
// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Orders are looked up by CarryBee courier meta; there is no indexed alternative.
'meta_key' => '_order_number',
'meta_value' => $merchant_order_id,
// phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value
));
// If not found by meta, try to find by order number directly
if (empty($orders)) {
$orders = wc_get_orders(array(
'limit' => 1,
'return' => 'ids',
'cbwp_meta_query' => true,
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Orders are looked up by CarryBee courier meta; there is no indexed alternative.
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_order_key',
'value' => 'wc_order_' . $merchant_order_id,
'compare' => 'LIKE',
),
),
));
}
// Try parsing as integer if still not found
if (empty($orders)) {
$order_id = absint($merchant_order_id);
if ($order_id > 0) {
$order = wc_get_order($order_id);
if ($order && $order->get_order_number() == $merchant_order_id) {
$orders = array($order_id);
}
}
}
if (empty($orders)) {
wp_send_json_error(array('message' => __('Order not found', 'carrybee')));
}
$order_id = $orders[0];
}
if (!$order_id) {
wp_send_json_error(array('message' => __('Invalid order ID', 'carrybee')));
}
// Verify nonce
$nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
if (!wp_verify_nonce($nonce, 'CARRYBEE_WP_send_to_courier_' . $order_id)) {
wp_send_json_error(array('message' => __('Security check failed', 'carrybee')));
}
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Get order
$order = wc_get_order($order_id);
if (!$order) {
wp_send_json_error(array('message' => __('Order not found', 'carrybee')));
}
// Check if already sent
if ($this->is_order_sent($order)) {
wp_send_json_error(array('message' => __('Order already sent to courier', 'carrybee')));
}
if (!$this->acquire_send_lock($order_id)) {
wp_send_json_error(array('message' => __('This order is already being sent. Please wait a moment.', 'carrybee')));
}
// wp_send_json_* exits, so free the lock when the request ends.
add_action('shutdown', function () use ($order_id) {
$this->release_send_lock($order_id);
});
if ($this->is_order_sent_fresh($order_id)) {
wp_send_json_error(array('message' => __('Order already sent to courier', 'carrybee')));
}
// Get form data from modal
$form_data = array(
'store_id' => isset($_POST['store_id']) ? sanitize_text_field(wp_unslash($_POST['store_id'])) : '',
'merchant_order_id' => isset($_POST['merchant_order_id']) ? sanitize_text_field(wp_unslash($_POST['merchant_order_id'])) : '',
'recipient_name' => isset($_POST['recipient_name']) ? sanitize_text_field(wp_unslash($_POST['recipient_name'])) : '',
'recipient_phone' => isset($_POST['recipient_phone']) ? sanitize_text_field(wp_unslash($_POST['recipient_phone'])) : '',
'recipient_phone_secondary' => isset($_POST['recipient_phone_secondary']) ? sanitize_text_field(wp_unslash($_POST['recipient_phone_secondary'])) : '',
'recipient_address' => isset($_POST['recipient_address']) ? sanitize_text_field(wp_unslash($_POST['recipient_address'])) : '',
'city_id' => isset($_POST['city_id']) ? sanitize_text_field(wp_unslash($_POST['city_id'])) : '',
'zone_id' => isset($_POST['zone_id']) ? sanitize_text_field(wp_unslash($_POST['zone_id'])) : '',
'area_id' => isset($_POST['area_id']) ? sanitize_text_field(wp_unslash($_POST['area_id'])) : '',
'delivery_type' => isset($_POST['delivery_type']) ? absint($_POST['delivery_type']) : 1,
'product_type' => isset($_POST['product_type']) ? absint($_POST['product_type']) : 2,
'special_instruction' => isset($_POST['special_instruction']) ? sanitize_textarea_field(wp_unslash($_POST['special_instruction'])) : '',
'quantity' => isset($_POST['quantity']) ? absint($_POST['quantity']) : 1,
'weight' => isset($_POST['weight']) ? floatval($_POST['weight']) : 0.5,
'amount_collect' => isset($_POST['amount_collect']) ? floatval($_POST['amount_collect']) : 0,
'item_desc' => isset($_POST['item_desc']) ? sanitize_text_field(wp_unslash($_POST['item_desc'])) : '',
);
// Validate required fields (area_id is optional)
$required_fields = array('store_id', 'recipient_name', 'recipient_phone', 'recipient_address', 'city_id', 'zone_id');
foreach ($required_fields as $field) {
if (empty($form_data[$field])) {
/* translators: %s: field */
wp_send_json_error(array('message' => sprintf(__('Required field missing: %s', 'carrybee'), $field)));
}
}
// Send to API with form data
$this->send_parcel_and_respond($order, $form_data);
}
/**
* Handle direct send to courier AJAX request.
* Builds order data server-side and creates the parcel without city/zone/area —
* the courier resolves the location from the recipient address.
*/
public function handle_direct_send_to_courier() {
$order_id = isset($_POST['order_id']) ? absint($_POST['order_id']) : 0;
if (!$order_id) {
wp_send_json_error(array('message' => __('Invalid order ID', 'carrybee')));
}
// Verify nonce (same per-order nonce as the Send to CarryBee button)
$nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
if (!wp_verify_nonce($nonce, 'CARRYBEE_WP_send_to_courier_' . $order_id)) {
wp_send_json_error(array('message' => __('Security check failed', 'carrybee')));
}
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Get order
$order = wc_get_order($order_id);
if (!$order) {
wp_send_json_error(array('message' => __('Order not found', 'carrybee')));
}
// Check if already sent
if ($this->is_order_sent($order)) {
wp_send_json_error(array('message' => __('Order already sent to courier', 'carrybee')));
}
if (!$this->acquire_send_lock($order_id)) {
wp_send_json_error(array('message' => __('This order is already being sent. Please wait a moment.', 'carrybee')));
}
// wp_send_json_* exits, so free the lock when the request ends.
add_action('shutdown', function () use ($order_id) {
$this->release_send_lock($order_id);
});
if ($this->is_order_sent_fresh($order_id)) {
wp_send_json_error(array('message' => __('Order already sent to courier', 'carrybee')));
}
// Build order data from the order itself; omit city/zone/area for direct send.
$form_data = $this->prepare_order_data($order);
unset($form_data['city_id'], $form_data['zone_id'], $form_data['area_id']);
// Optional override from the orders table "Amount to Collect" input.
if (isset($_POST['amount_collect']) && $_POST['amount_collect'] !== '') {
$form_data['amount_collect'] = floatval($_POST['amount_collect']);
}
if (empty($form_data['store_id'])) {
wp_send_json_error(array('message' => __('No default store configured. Set a Default Store in settings or use Send to CarryBee instead.', 'carrybee')));
}
if (empty($form_data['recipient_name']) || empty($form_data['recipient_phone']) || empty($form_data['recipient_address'])) {
wp_send_json_error(array('message' => __('Order is missing recipient name, phone or address. Use Send to CarryBee instead.', 'carrybee')));
}
$this->send_parcel_and_respond($order, $form_data);
}
/**
* Create the parcel via API, update order meta and emit the JSON response.
* Shared by the modal send and direct send handlers.
*
* @param WC_Order $order
* @param array $form_data
*/
private function send_parcel_and_respond($order, $form_data) {
$response = $this->api->create_parcel($form_data);
if (is_wp_error($response)) {
// Add error note to order
$order->add_order_note(
sprintf(
/* translators: %s: error message from CarryBee */
__('Failed to send order to courier: %s', 'carrybee'),
$response->get_error_message()
)
);
wp_send_json_error(array('message' => $response->get_error_message()));
}
// Check if response has validation errors
if ((isset($response['error']) && $response['error'] === true) || (isset($response['success']) && $response['success'] === false)) {
// Add error note to order
$error_message = isset($response['message']) ? $response['message'] : __('Validation failed', 'carrybee');
$order->add_order_note(
sprintf(
/* translators: %s: error message */
__('Failed to send order to courier: %s', 'carrybee'),
$error_message
)
);
// Return validation errors for field-level display
$error_response = array('message' => $error_message);
if (isset($response['causes']) && is_array($response['causes'])) {
$normalized_errors = array();
foreach ($response['causes'] as $field_name => $causes) {
$messages = array();
if (is_array($causes)) {
foreach ($causes as $cause) {
if (is_array($cause) && isset($cause['type'])) {
/* translators: %s: type */
$messages[] = sprintf(__('Validation failed (%s)', 'carrybee'), sanitize_text_field($cause['type']));
} elseif (is_string($cause) && $cause !== '') {
$messages[] = sanitize_text_field($cause);
}
}
}
if (empty($messages)) {
$messages[] = __('Validation failed', 'carrybee');
}
$normalized_errors[$field_name] = $messages;
}
$error_response['errors'] = $normalized_errors;
} elseif (isset($response['errors']) && is_array($response['errors'])) {
$error_response['errors'] = $response['errors'];
}
wp_send_json_error($error_response);
}
// Success - extract data from API v2 response structure.
// Expected response: { error: false, message, data: { order: { consignment_id, delivery_fee, ... } } }
$consignment_id = '';
$order_status = 'Created';
$delivery_fee = 0;
// Extract from API v2 response structure
if (isset($response['data']['order']['consignment_id'])) {
$consignment_id = sanitize_text_field($response['data']['order']['consignment_id']);
} elseif (isset($response['data']['consignment_id'])) {
// Backward compatibility for older response shape.
$consignment_id = sanitize_text_field($response['data']['consignment_id']);
}
if (empty($consignment_id)) {
wp_send_json_error(array(
'message' => __('Courier did not return a consignment ID. The order was not marked as sent.', 'carrybee'),
));
}
if (isset($response['data']['order']['order_status'])) {
$order_status = sanitize_text_field($response['data']['order']['order_status']);
} elseif (isset($response['data']['order_status'])) {
$order_status = sanitize_text_field($response['data']['order_status']);
}
if (isset($response['data']['order']['delivery_fee'])) {
$delivery_fee = floatval($response['data']['order']['delivery_fee']);
} elseif (isset($response['data']['delivery_fee'])) {
$delivery_fee = floatval($response['data']['delivery_fee']);
}
// Update order meta with new data
if ($consignment_id) {
CARRYBEE_WP_update_order_meta($order, 'consignment_id', $consignment_id);
}
if ($order_status) {
CARRYBEE_WP_update_order_meta($order, 'courier_status', $order_status);
}
if ($delivery_fee) {
CARRYBEE_WP_update_order_meta($order, 'delivery_fee', $delivery_fee);
}
CARRYBEE_WP_update_order_meta($order, 'sent_to_courier', 'yes');
CARRYBEE_WP_update_order_meta($order, 'sent_date', current_time('mysql'));
$order->save();
// Add order note with all details
$note = sprintf(
/* translators: 1: courier name, 2: line break, 3: consignment id, 4: line break, 5: order status, 6: line break, 7: delivery fee */
__('Order sent to %1$s successfully.%2$sConsignment ID: %3$s%4$sOrder Status: %5$s%6$sDelivery Fee: %7$s', 'carrybee'),
CARRYBEE_WP_COURIER_FULL_NAME,
"\n",
$consignment_id,
"\n",
$order_status,
"\n",
wc_price($delivery_fee)
);
$order->add_order_note($note);
// Return success with data for frontend update
wp_send_json_success(array(
'message' => isset($response['message']) ? $response['message'] : __('Order sent to courier successfully!', 'carrybee'),
'consignment_id' => $consignment_id,
'courier_status' => $order_status,
'delivery_fee' => $delivery_fee,
'currency_symbol' => get_woocommerce_currency_symbol($order->get_currency()),
));
}
/**
* Handle bulk send orders to courier AJAX request
*/
public function handle_bulk_send_to_courier() {
// Verify nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Get orders data array from POST
// Decode first, then sanitize each field: sanitizing the raw JSON string strips "<...>" and "%xx" across fields and breaks it.
$orders_data = isset($_POST['orders_data']) ? json_decode(wp_unslash($_POST['orders_data']), true) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- every decoded field is sanitized on the next line.
$orders_data = is_array($orders_data) ? map_deep($orders_data, 'sanitize_textarea_field') : array();
if (empty($orders_data) || !is_array($orders_data)) {
wp_send_json_error(array('message' => __('No order data provided', 'carrybee')));
}
// Validate and prepare orders for bulk submission
$prepared_orders = array();
$validation_errors = array();
foreach ($orders_data as $index => $order_data) {
// Validate required fields
$required_fields = array('product_type', 'store_id', 'recipient_name', 'recipient_phone', 'recipient_address', 'city_id', 'zone_id', 'weight');
$missing_fields = array();
foreach ($required_fields as $field) {
$field_value = isset($order_data[$field]) ? $order_data[$field] : null;
if (empty($field_value) && $field_value !== '0' && $field_value !== 0) {
$missing_fields[] = $field;
}
}
if (!empty($missing_fields)) {
$validation_errors[$index] = sprintf(
/* translators: 1: merchant order id, 2: missing fields */
__('Order #%1$s: Missing required fields: %2$s', 'carrybee'),
isset($order_data['merchant_order_id']) ? $order_data['merchant_order_id'] : ($index + 1),
implode(', ', $missing_fields)
);
continue;
}
// Prepare order data for API
// Note: We use standard keys here because CARRYBEE_WP_API::create_bulk_parcels() will handle the mapping to API typos
$api_order_data = array(
'store_id' => sanitize_text_field($order_data['store_id']),
'merchant_order_id' => isset($order_data['merchant_order_id']) ? sanitize_text_field($order_data['merchant_order_id']) : '',
'recipient_name' => sanitize_text_field($order_data['recipient_name']),
'recipient_phone' => sanitize_text_field($order_data['recipient_phone']),
'recipient_secendary_phone' => isset($order_data['recipient_phone_secondary']) ? sanitize_text_field($order_data['recipient_phone_secondary']) : '',
'recipient_address' => sanitize_text_field($order_data['recipient_address']),
'city_id' => absint($order_data['city_id']),
'zone_id' => absint($order_data['zone_id']),
'delivery_type' => isset($order_data['delivery_type']) ? absint($order_data['delivery_type']) : 1,
'product_type' => isset($order_data['product_type']) ? absint($order_data['product_type']) : 2,
'special_instruction' => isset($order_data['special_instruction']) ? sanitize_textarea_field($order_data['special_instruction']) : '',
'item_quantity' => isset($order_data['quantity']) ? absint($order_data['quantity']) : 1,
'item_weight' => isset($order_data['weight']) ? absint(round(floatval($order_data['weight']) * 1000)) : 500,
'collectable_amount' => isset($order_data['amount_collect']) ? max(0, absint(round(floatval($order_data['amount_collect'])))) : 0,
'product_description' => isset($order_data['item_desc']) ? sanitize_text_field($order_data['item_desc']) : '',
);
if (empty($api_order_data['merchant_order_id'])) {
unset($api_order_data['merchant_order_id']);
}
if (empty($api_order_data['recipient_secendary_phone'])) {
unset($api_order_data['recipient_secendary_phone']);
}
if (empty($api_order_data['special_instruction'])) {
unset($api_order_data['special_instruction']);
}
if (empty($api_order_data['product_description'])) {
unset($api_order_data['product_description']);
}
// Only include area_id if it has a valid value (optional field, same as single order)
if (!empty($order_data['area_id']) && absint($order_data['area_id']) > 0) {
$api_order_data['area_id'] = absint($order_data['area_id']);
}
// Resolve WooCommerce order by merchant_order_id for internal tracking.
$merchant_order_id = isset($order_data['merchant_order_id']) ? sanitize_text_field($order_data['merchant_order_id']) : '';
$order_id = $this->find_order_id_by_merchant_order_id($merchant_order_id);
// Never send an order twice (it has a consignment ID, or an earlier bulk send was accepted).
if ($order_id && $this->is_order_sent(wc_get_order($order_id))) {
$validation_errors[] = sprintf(
/* translators: %s: order number */
__('Order #%s was already sent to CarryBee', 'carrybee'),
$merchant_order_id
);
continue;
}
$prepared_orders[] = array(
'order_id' => $order_id,
'merchant_order_id' => $merchant_order_id,
'api_data' => $api_order_data
);
}
// If there are validation errors, return them
if (!empty($validation_errors)) {
wp_send_json_error(array(
'message' => __('Some orders have validation errors', 'carrybee'),
'validation_errors' => $validation_errors
));
}
// Send bulk orders to API
$api_orders = array_map(function($item) {
return $item['api_data'];
}, $prepared_orders);
$this->process_bulk_send_response($this->api->create_bulk_parcels($api_orders), $prepared_orders);
}
/**
* Handle direct bulk send to courier AJAX request.
* Builds order data server-side for the selected orders and creates the parcels
* without city/zone/area — the courier resolves the location from each address.
*/
public function handle_direct_bulk_send_to_courier() {
// Verify nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
$order_ids = isset($_POST['order_ids']) ? array_map('absint', (array) $_POST['order_ids']) : array();
if (empty($order_ids)) {
wp_send_json_error(array('message' => __('No orders selected', 'carrybee')));
}
// Optional per-order overrides from the orders table "Amount to Collect" inputs.
$amounts = isset($_POST['amounts']) && is_array($_POST['amounts']) ? map_deep(wp_unslash($_POST['amounts']), 'sanitize_text_field') : array();
$result = $this->prepare_direct_send_orders($order_ids, $amounts);
if (!empty($result['error'])) {
wp_send_json_error(array('message' => $result['error']));
}
if (empty($result['prepared'])) {
wp_send_json_error(array(
'message' => sprintf(
/* translators: %s: skipped */
__('No orders could be sent. %s', 'carrybee'),
implode('; ', $result['skipped'])
),
));
}
$api_orders = array_map(function($item) {
return $item['api_data'];
}, $result['prepared']);
$this->process_bulk_send_response($this->api->create_bulk_parcels($api_orders), $result['prepared'], $result['skipped']);
}
/**
* Prepare orders for a direct (no city/zone/area) bulk send.
*
* @param array $order_ids Order IDs to prepare.
* @param array $amounts Optional per-order amount overrides keyed by order ID.
* @return array {prepared: array, skipped: string[], error: string} error is set for
* global failures (e.g. no default store) that should abort the whole batch.
*/
private function prepare_direct_send_orders($order_ids, $amounts = array()) {
$prepared = array();
$skipped = array();
foreach ($order_ids as $order_id) {
$order = wc_get_order($order_id);
if (!$order) {
/* translators: %d: order id */
$skipped[] = sprintf(__('Order %d not found', 'carrybee'), $order_id);
continue;
}
// Skip orders that already have a consignment
if ($this->is_order_sent($order)) {
/* translators: %s: order number */
$skipped[] = sprintf(__('Order #%s already sent to courier', 'carrybee'), $order->get_order_number());
continue;
}
// Build order data from the order itself; omit city/zone/area for direct send.
$form_data = $this->prepare_order_data($order);
unset($form_data['city_id'], $form_data['zone_id'], $form_data['area_id']);
if (isset($amounts[$order_id]) && $amounts[$order_id] !== '') {
$form_data['amount_collect'] = floatval($amounts[$order_id]);
}
if (empty($form_data['store_id'])) {
return array(
'prepared' => array(),
'skipped' => $skipped,
'error' => __('No default store configured. Set a Default Store in settings or use Review & send selected instead.', 'carrybee'),
);
}
if (empty($form_data['recipient_name']) || empty($form_data['recipient_phone']) || empty($form_data['recipient_address'])) {
/* translators: %s: order number */
$skipped[] = sprintf(__('Order #%s is missing recipient name, phone or address', 'carrybee'), $order->get_order_number());
continue;
}
$prepared[] = array(
'order_id' => $order_id,
'merchant_order_id' => $form_data['merchant_order_id'],
'api_data' => $form_data,
);
}
return array(
'prepared' => $prepared,
'skipped' => $skipped,
'error' => '',
);
}
/**
* Process the bulk-create API response: map validation errors back to rows,
* mark sent orders and emit the JSON response. Shared by the bulk modal and
* direct bulk send handlers.
*
* @param array|WP_Error $response Raw response from create_bulk_parcels().
* @param array $prepared_orders Items of shape {order_id, merchant_order_id, api_data}.
* @param array $skipped Optional human-readable skip notices appended to the success message.
*/
private function process_bulk_send_response($response, $prepared_orders, $skipped = array()) {
if (is_wp_error($response)) {
wp_send_json_error(array('message' => $response->get_error_message()));
}
// Check for API validation errors (v2 format: 0.field_name, legacy format: orders.0.field_name)
if (
((isset($response['error']) && $response['error'] === true) || (isset($response['success']) && $response['success'] === false)) &&
(isset($response['causes']) || isset($response['errors']))
) {
$api_errors = isset($response['causes']) && is_array($response['causes']) ? $response['causes'] : $response['errors'];
$parsed_errors = array();
// Parse errors like "0.collectable_amount" or "orders.0.collectable_amount".
foreach ($api_errors as $error_key => $error_messages) {
if (preg_match('/^(?:orders\.)?(\d+)\.(.+)$/', $error_key, $matches)) {
$row_index = intval($matches[1]);
$field_name = $matches[2];
// Get merchant order ID for better error message
$merchant_order_id = isset($prepared_orders[$row_index]['merchant_order_id']) ? $prepared_orders[$row_index]['merchant_order_id'] : ($row_index + 1);
// Format error message
$error_text = '';
if (is_array($error_messages)) {
$formatted_messages = array();
foreach ($error_messages as $message_item) {
if (is_array($message_item) && isset($message_item['type'])) {
/* translators: %s: type */
$formatted_messages[] = sprintf(__('Validation failed (%s)', 'carrybee'), sanitize_text_field($message_item['type']));
} elseif (is_string($message_item) && $message_item !== '') {
$formatted_messages[] = sanitize_text_field($message_item);
}
}
$error_text = implode(', ', $formatted_messages);
} else {
$error_text = sanitize_text_field((string) $error_messages);
}
if ($error_text === '') {
$error_text = __('Validation failed', 'carrybee');
}
$field_display = str_replace('_', ' ', $field_name);
if (!isset($parsed_errors[$row_index])) {
$parsed_errors[$row_index] = sprintf(
/* translators: 1: merchant order id, 2: field display, 3: error text */
__('Order #%1$s: %2$s - %3$s', 'carrybee'),
$merchant_order_id,
ucfirst($field_display),
$error_text
);
} else {
$parsed_errors[$row_index] .= sprintf(
/* translators: 1: field display, 2: error text */
__('; %1$s - %2$s', 'carrybee'),
ucfirst($field_display),
$error_text
);
}
}
}
if (!empty($parsed_errors)) {
wp_send_json_error(array(
'message' => isset($response['message']) ? $response['message'] : __('API validation failed', 'carrybee'),
'validation_errors' => $parsed_errors
));
}
wp_send_json_error(array(
'message' => isset($response['message']) ? $response['message'] : __('API validation failed', 'carrybee'),
));
}
// Process response and update orders
// Note: Per requirements, we ignore individual order data in response and verify success via webhook later
$success_count = $this->mark_bulk_orders_sent($prepared_orders);
// Send simple success message
$final_message = sprintf(
/* translators: %d: success count */
__('%d orders sent to courier successfully. Consignment details will be updated via webhook.', 'carrybee'),
$success_count
);
if (!empty($skipped)) {
$final_message .= ' ' . sprintf(
/* translators: 1: number of skipped orders, 2: reasons */
_n('%1$d order was skipped: %2$s', '%1$d orders were skipped: %2$s', count($skipped), 'carrybee'),
count($skipped),
implode('; ', $skipped)
);
}
wp_send_json_success(array(
'message' => $final_message,
'sent_count' => $success_count,
));
}
/**
* Mark bulk-sent orders as sent to courier (meta + order note).
* Consignment details arrive later via webhook.
*
* @param array $prepared_orders Items of shape {order_id, merchant_order_id, api_data}.
* @return int Number of orders marked as sent.
*/
private function mark_bulk_orders_sent($prepared_orders) {
$success_count = 0;
foreach ($prepared_orders as $order_item) {
$order = wc_get_order($order_item['order_id']);
if (!$order) {
continue;
}
// Update order meta to indicate we sent it
CARRYBEE_WP_update_order_meta($order, 'sent_to_courier', 'yes');
CARRYBEE_WP_update_order_meta($order, 'sent_date', current_time('mysql'));
$order->save();
// Add order note
$order->add_order_note(
/* translators: %s: courier name */
sprintf(__('Order sent to %s via bulk action. Waiting for courier details (Consignment ID) via webhook.', 'carrybee'), CARRYBEE_WP_COURIER_FULL_NAME)
);
$success_count++;
}
return $success_count;
}
/**
* Handle get bulk order data AJAX request
*/
public function handle_get_bulk_order_data() {
// Verify nonce
check_ajax_referer('CARRYBEE_WP_admin_nonce', 'nonce');
// Check permissions
if (!current_user_can('manage_woocommerce')) {
wp_send_json_error(array('message' => __('Unauthorized', 'carrybee')));
}
// Get order IDs
$order_ids = isset($_POST['order_ids']) ? array_map('absint', (array) $_POST['order_ids']) : array();
if (empty($order_ids)) {
wp_send_json_error(array('message' => __('No orders selected', 'carrybee')));
}
$orders_data = array();
$skipped = array();
foreach ($order_ids as $order_id) {
$order = wc_get_order($order_id);
if (!$order) {
$skipped[] = array(
'order_id' => $order_id,
'reason' => __('Order not found', 'carrybee')
);
continue;
}
// Check if already sent to courier
if ($this->is_order_sent($order)) {
$skipped[] = array(
'order_id' => $order_id,
'order_number' => $order->get_order_number(),
'reason' => __('Already sent to courier', 'carrybee')
);
continue;
}
// Prepare order data
$order_data = $this->prepare_order_data_for_form($order);
$order_data['order_id'] = $order_id;
$orders_data[] = $order_data;
}
if (empty($orders_data)) {
wp_send_json_error(array(
'message' => __('No orders available to send. All selected orders have already been sent to courier.', 'carrybee'),
'skipped' => $skipped
));
}
wp_send_json_success(array(
'orders' => $orders_data,
'skipped' => $skipped
));
}
/**
* Reload API credentials after settings update
* Ensures the API instance has the latest token
*
* @param array $old_value
* @param array $value
*/
public function reload_api_credentials($old_value, $value) {
if ($this->api) {
$this->api->reload_credentials();
}
}
/**
* Register webhook REST API endpoint
*/
public function register_webhook_endpoint() {
register_rest_route(CARRYBEE_WP_REST_NAMESPACE, '/webhook', array(
'methods' => 'POST',
'callback' => array($this, 'handle_webhook'),
// Called by CarryBee's servers, so there is no logged-in user.
// Every request must prove it knows the webhook secret.
'permission_callback' => array($this, 'authorize_webhook'),
));
}
/**
* Allow a webhook request only when it proves it knows the webhook secret.
*
* - No secret saved on this store: every request is refused (503), so a
* fresh install is never open to fake status updates.
* - CarryBee's {"event":"webhook.integration"} handshake changes no data,
* so it only needs a secret to be configured.
* - Every other request must carry X-BEE-Signature, either:
* sha256=."> (signed, preferred)
* (legacy plain secret)
*
* @param WP_REST_Request $request
* @return true|WP_Error
*/
public function authorize_webhook($request) {
$webhook_secret = trim((string) CARRYBEE_WP_get_setting(CARRYBEE_WP_SETTING_WEBHOOK_SECRET, ''));
if ($webhook_secret === '') {
return new WP_Error(
'carrybee_webhook_not_configured',
'Webhook secret is not configured on this store.',
array('status' => 503)
);
}
$body = $request->get_json_params();
if (is_array($body) && isset($body['event']) && $body['event'] === CARRYBEE_WP_WEBHOOK_INTEGRATION_EVENT) {
return true;
}
if ($this->is_valid_webhook_signature($request, $webhook_secret)) {
return true;
}
return new WP_Error(
'carrybee_webhook_unauthorized',
'Invalid webhook signature.',
array('status' => 401)
);
}
/**
* Check X-BEE-Signature against the webhook secret (signed HMAC or legacy plain secret).
*
* @param WP_REST_Request $request
* @param string $webhook_secret
* @return bool
*/
private function is_valid_webhook_signature($request, $webhook_secret) {
$signature = trim((string) $request->get_header(CARRYBEE_WP_WEBHOOK_SIGNATURE_HEADER));
if ($signature === '') {
return false;
}
if (strpos($signature, CARRYBEE_WP_WEBHOOK_SIGNATURE_PREFIX) !== 0) {
// Legacy: the secret itself is sent in the header.
return hash_equals($webhook_secret, $signature);
}
$timestamp_header = trim((string) $request->get_header(CARRYBEE_WP_WEBHOOK_TIMESTAMP_HEADER));
$timestamp = ctype_digit($timestamp_header) ? (int) $timestamp_header : strtotime($timestamp_header);
if (!$timestamp || abs(time() - $timestamp) > CARRYBEE_WP_WEBHOOK_MAX_AGE) {
return false;
}
$expected = hash_hmac('sha256', $timestamp_header . '.' . $request->get_body(), $webhook_secret);
$received = strtolower(substr($signature, strlen(CARRYBEE_WP_WEBHOOK_SIGNATURE_PREFIX)));
return hash_equals($expected, $received);
}
/**
* Handle incoming webhook from courier service
*
* Supports event-based payload (event/timestamptz) and legacy payload.
*
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function handle_webhook($request) {
// The request is already authorized by authorize_webhook().
// Handle CarryBee's webhook integration handshake.
// CarryBee verifies the endpoint before registering by POSTing
// {"event": "webhook.integration"}. The endpoint must respond with
// HTTP 202 and the X-CB-Webhook-Integration-Header header set to the
// verification token (webhook_response() adds it to every other reply too).
$integration_body = $request->get_json_params();
if (is_array($integration_body) && isset($integration_body['event']) && $integration_body['event'] === CARRYBEE_WP_WEBHOOK_INTEGRATION_EVENT) {
$response = new WP_REST_Response(null, 202);
$response->header(CARRYBEE_WP_WEBHOOK_INTEGRATION_HEADER, CARRYBEE_WP_WEBHOOK_INTEGRATION_TOKEN);
return $response;
}
// Get webhook data
$data = $request->get_json_params();
if (!is_array($data)) {
return $this->webhook_response(array(
'success' => false,
'message' => 'Invalid JSON payload'
), 400);
}
$payload = $this->normalize_webhook_payload($data);
// Log webhook for debugging
$this->log_webhook($payload);
if (empty($payload['event'])) {
return $this->webhook_response(array(
'success' => false,
'message' => 'Missing required field: event'
), 400);
}
if (empty($payload['timestamp'])) {
return $this->webhook_response(array(
'success' => false,
'message' => 'Missing required field: timestamptz'
), 400);
}
// Validate required fields - check if at least one identifier is present
if (empty($payload['consignment_id']) && empty($payload['merchant_order_id'])) {
return $this->webhook_response(array(
'success' => false,
'message' => 'Missing required fields: consignment_id or merchant_order_id'
), 400);
}
// Process webhook
$result = $this->process_webhook_event($payload);
if ($result) {
// 202 Accepted: event received and successfully processed.
return $this->webhook_response(array(
'success' => true,
'message' => 'Webhook processed successfully',
'order_id' => $result
), 202);
}
return $this->webhook_response(array(
'success' => false,
'message' => 'Order not found or update failed'
), 404);
}
/**
* Build a webhook REST response with the CarryBee integration header attached.
*
* Every webhook response carries the X-CB-Webhook-Integration-Header so the
* endpoint passes CarryBee's verification on any event.
*
* @param mixed $data Response body.
* @param int $status HTTP status code.
* @return WP_REST_Response
*/
private function webhook_response($data, $status) {
$response = new WP_REST_Response($data, $status);
$response->header(CARRYBEE_WP_WEBHOOK_INTEGRATION_HEADER, CARRYBEE_WP_WEBHOOK_INTEGRATION_TOKEN);
return $response;
}
/**
* Process webhook event
*
* @param array $data
* @return int|bool Order ID if successful, false otherwise
*/
private function process_webhook_event($data) {
$consignment_id = isset($data['consignment_id']) ? sanitize_text_field($data['consignment_id']) : '';
$merchant_order_id = isset($data['merchant_order_id']) ? sanitize_text_field((string) $data['merchant_order_id']) : '';
$event = isset($data['event']) ? sanitize_text_field($data['event']) : '';
$courier_status = isset($data['courier_status']) ? sanitize_text_field($data['courier_status']) : '';
$updated_at = isset($data['timestamp']) ? sanitize_text_field($data['timestamp']) : '';
$invoice_id = isset($data['invoice_id']) ? sanitize_text_field($data['invoice_id']) : '';
$store_id = isset($data['store_id']) ? sanitize_text_field($data['store_id']) : '';
$reason = isset($data['reason']) ? sanitize_text_field($data['reason']) : '';
$attempt = isset($data['attempt']) ? absint($data['attempt']) : 0;
$collectable_amount = isset($data['collectable_amount']) ? sanitize_text_field($data['collectable_amount']) : '';
$collected_amount = isset($data['collected_amount']) ? sanitize_text_field($data['collected_amount']) : '';
$cod_fee = isset($data['cod_fee']) ? floatval($data['cod_fee']) : null;
$delivery_fee = isset($data['delivery_fee']) ? floatval($data['delivery_fee']) : null;
$order = false;
// 1. Find order by consignment ID first
if (!empty($consignment_id)) {
$orders = wc_get_orders(array(
// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Orders are looked up by CarryBee courier meta; there is no indexed alternative.
'meta_key' => CARRYBEE_WP_META_CONSIGNMENT_ID,
'meta_value' => $consignment_id,
// phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value
'limit' => 1,
));
if (!empty($orders)) {
$order = $orders[0];
}
}
// 2. If still not found, try by merchant order ID
if (!$order && !empty($merchant_order_id)) {
// Case A: Try as standard WC Order ID
$order_by_id = wc_get_order($merchant_order_id);
if ($order_by_id) {
$order = $order_by_id;
}
// Case B: Try as custom order number (if plugins store it in _order_number meta)
else {
$orders_by_number = wc_get_orders(array(
// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Orders are looked up by CarryBee courier meta; there is no indexed alternative.
'meta_key' => '_order_number',
'meta_value' => $merchant_order_id,
// phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value
'limit' => 1,
));
if (!empty($orders_by_number)) {
$order = $orders_by_number[0];
}
}
}
if (!$order) {
$this->log_webhook_message('Webhook: Order not found - Event: ' . $event . ', Consignment ID: ' . $consignment_id . ', Merchant Order ID: ' . $merchant_order_id);
return false;
}
// Update courier status using helper functions
if (!empty($courier_status)) {
CARRYBEE_WP_update_order_meta($order, 'courier_status', $courier_status);
}
if (!empty($updated_at)) {
CARRYBEE_WP_update_order_meta($order, 'status_updated_at', $updated_at);
} else {
CARRYBEE_WP_update_order_meta($order, 'status_updated_at', current_time('mysql'));
}
// Ensure consignment ID is saved if matched by merchant ID
if (!empty($consignment_id)) {
$current_consignment = CARRYBEE_WP_get_order_meta($order, 'consignment_id');
if (empty($current_consignment) || $current_consignment !== $consignment_id) {
CARRYBEE_WP_update_order_meta($order, 'consignment_id', $consignment_id);
}
}
// Update invoice ID if provided
if (!empty($invoice_id)) {
CARRYBEE_WP_update_order_meta($order, 'invoice_id', $invoice_id);
}
if ($delivery_fee !== null) {
CARRYBEE_WP_update_order_meta($order, 'delivery_fee', $delivery_fee);
}
// Save order
$order->save();
// Add order note with status update
$note_parts = array();
/* translators: 1: courier name, 2: event */
$note_parts[] = sprintf(__('%1$s webhook event: %2$s', 'carrybee'), CARRYBEE_WP_COURIER_FULL_NAME, $event);
if (!empty($courier_status)) {
/* translators: %s: courier status */
$note_parts[] = sprintf(__('Status: %s', 'carrybee'), $courier_status);
}
if (!empty($store_id)) {
/* translators: %s: store id */
$note_parts[] = sprintf(__('Store ID: %s', 'carrybee'), $store_id);
}
if (!empty($invoice_id)) {
/* translators: %s: invoice id */
$note_parts[] = sprintf(__('Invoice ID: %s', 'carrybee'), $invoice_id);
}
if (!empty($updated_at)) {
/* translators: %s: updated at */
$note_parts[] = sprintf(__('Event time: %s', 'carrybee'), $updated_at);
}
if (!empty($collectable_amount)) {
/* translators: %s: collectable amount */
$note_parts[] = sprintf(__('Collectable amount (BDT): %s', 'carrybee'), $collectable_amount);
}
if (!empty($collected_amount)) {
/* translators: %s: collected amount */
$note_parts[] = sprintf(__('Collected amount (BDT): %s', 'carrybee'), $collected_amount);
}
if ($cod_fee !== null) {
/* translators: %s: cod fee */
$note_parts[] = sprintf(__('COD fee (BDT): %s', 'carrybee'), wc_format_decimal($cod_fee, 2));
}
if ($delivery_fee !== null) {
/* translators: %s: delivery fee */
$note_parts[] = sprintf(__('Delivery fee (BDT): %s', 'carrybee'), wc_format_decimal($delivery_fee, 2));
}
if (!empty($attempt)) {
/* translators: %d: attempt */
$note_parts[] = sprintf(__('Attempt: %d', 'carrybee'), $attempt);
}
if (!empty($reason)) {
/* translators: %s: reason */
$note_parts[] = sprintf(__('Reason: %s', 'carrybee'), $reason);
}
$order->add_order_note(implode(' | ', $note_parts));
// Log successful update
$this->log_webhook_message('Webhook: Order #' . $order->get_id() . ' updated - Event: ' . $event . ', Status: ' . $courier_status . ', Consignment: ' . $consignment_id);
// Handle specific status changes (auto-complete order if delivered)
$this->handle_status_change($order, $event, $courier_status);
return $order->get_id();
}
/**
* Normalize webhook payload from event-based and legacy contracts.
*
* @param array $data
* @return array
*/
private function normalize_webhook_payload($data) {
$event = isset($data['event']) ? sanitize_text_field((string) $data['event']) : '';
$legacy_status = isset($data['order_status']) ? sanitize_text_field((string) $data['order_status']) : '';
$legacy_status_slug = isset($data['order_status_slug']) ? sanitize_text_field((string) $data['order_status_slug']) : '';
if (empty($event) && !empty($legacy_status)) {
$event = 'order.updated';
}
$timestamp = '';
if (!empty($data['timestamptz'])) {
$timestamp = sanitize_text_field((string) $data['timestamptz']);
} elseif (!empty($data['timestampz'])) {
$timestamp = sanitize_text_field((string) $data['timestampz']);
} elseif (!empty($data['updated_at'])) {
$timestamp = sanitize_text_field((string) $data['updated_at']);
}
$courier_status = $this->resolve_courier_status_label($event, $legacy_status, $legacy_status_slug);
return array(
'event' => $event,
'store_id' => isset($data['store_id']) ? sanitize_text_field((string) $data['store_id']) : '',
'consignment_id' => isset($data['consignment_id']) ? sanitize_text_field((string) $data['consignment_id']) : '',
'merchant_order_id' => isset($data['merchant_order_id']) && $data['merchant_order_id'] !== null
? sanitize_text_field((string) $data['merchant_order_id'])
: '',
'timestamp' => $timestamp,
'invoice_id' => isset($data['invoice_id']) ? sanitize_text_field((string) $data['invoice_id']) : '',
'collectable_amount' => isset($data['collectable_amount']) ? sanitize_text_field((string) $data['collectable_amount']) : '',
'collected_amount' => isset($data['collected_amount']) ? sanitize_text_field((string) $data['collected_amount']) : '',
'cod_fee' => isset($data['cod_fee']) && is_numeric($data['cod_fee']) ? floatval($data['cod_fee']) : null,
'delivery_fee' => isset($data['delivery_fee']) && is_numeric($data['delivery_fee']) ? floatval($data['delivery_fee']) : null,
'attempt' => isset($data['attempt']) ? absint($data['attempt']) : 0,
'reason' => isset($data['reason']) && $data['reason'] !== null ? sanitize_text_field((string) $data['reason']) : '',
'courier_status' => $courier_status,
);
}
/**
* Convert webhook event code into a human-readable status label.
*
* @param string $event
* @param string $legacy_status
* @param string $legacy_status_slug
* @return string
*/
private function resolve_courier_status_label($event, $legacy_status, $legacy_status_slug) {
if (!empty($legacy_status)) {
return $legacy_status;
}
$event_labels = $this->get_webhook_event_labels();
if (!empty($event) && isset($event_labels[$event])) {
return $event_labels[$event];
}
if (!empty($legacy_status_slug)) {
return ucwords(str_replace('_', ' ', strtolower($legacy_status_slug)));
}
if (!empty($event)) {
$raw_status = preg_replace('/^order\./', '', $event);
return ucwords(str_replace('-', ' ', $raw_status));
}
return '';
}
/**
* Webhook event => human-readable status label map.
* Mirrors the events list published at https://merchant.carrybee.com/webhook/events.
*
* @return array
*/
private function get_webhook_event_labels() {
return array(
'order.created' => __('Order created', 'carrybee'),
'order.updated' => __('Order updated', 'carrybee'),
'order.pickup-requested' => __('Pickup requested', 'carrybee'),
'order.assigned-for-pickup' => __('Assigned for pickup', 'carrybee'),
'order.picked' => __('Picked', 'carrybee'),
'order.pickup-failed' => __('Pickup failed', 'carrybee'),
'order.pickup-cancelled' => __('Pickup cancelled', 'carrybee'),
'order.at-the-sorting-hub' => __('At the sorting hub', 'carrybee'),
'order.on-the-way-to-central-warehouse' => __('On the way to central warehouse', 'carrybee'),
'order.at-central-warehouse' => __('At central warehouse', 'carrybee'),
'order.in-transit' => __('In transit', 'carrybee'),
'order.received-at-last-mile-hub' => __('Received at last mile hub', 'carrybee'),
'order.assigned-for-delivery' => __('Assigned for delivery', 'carrybee'),
'order.delivery-on-hold' => __('Delivery on hold', 'carrybee'),
'order.delivered' => __('Delivered', 'carrybee'),
'order.partial-delivery' => __('Partial delivery', 'carrybee'),
'order.delivery-failed' => __('Delivery failed', 'carrybee'),
'order.returned' => __('Returned', 'carrybee'),
'order.paid-return' => __('Paid return', 'carrybee'),
'order.exchange' => __('Exchange', 'carrybee'),
'order.paid' => __('Paid', 'carrybee'),
'order.returned-at-sorting' => __('Returned at sorting', 'carrybee'),
'order.returned-in-transit' => __('Returned in transit', 'carrybee'),
'order.returned-to-merchant' => __('Returned to merchant', 'carrybee'),
);
}
/**
* Handle specific courier status changes
*
* @param WC_Order $order
* @param string $event
* @param string $status
*/
private function handle_status_change($order, $event, $status) {
$event_lower = strtolower((string) $event);
$status_lower = strtolower($status);
$is_delivered = $event_lower === 'order.delivered'
|| ((bool) preg_match('/(^|[^a-z])delivered([^a-z]|$)/', $status_lower)
&& !preg_match('/(^|[^a-z])(not|non)[\s_-]?delivered/', $status_lower)
&& !preg_match('/partial/', $status_lower));
$is_failed = in_array($event_lower, array('order.delivery-failed', 'order.pickup-failed'), true) || strpos($status_lower, 'failed') !== false;
$is_cancelled_or_returned = in_array($event_lower, array(
'order.pickup-cancelled',
'order.returned',
'order.paid-return',
'order.returned-at-sorting',
'order.returned-in-transit',
'order.returned-to-merchant',
), true) || strpos($status_lower, 'cancelled') !== false || strpos($status_lower, 'returned') !== false;
// Change WooCommerce order status based on courier status
if ($is_delivered) {
// Mark order as completed when delivered
if ($order->get_status() !== 'completed') {
/* translators: %s: courier name */
$order->update_status('completed', sprintf(__('Order delivered by %s', 'carrybee'), CARRYBEE_WP_COURIER_FULL_NAME));
}
} elseif ($is_cancelled_or_returned) {
// Add note for cancelled/returned orders but don't change WC status automatically
$order->add_order_note(__('Courier delivery was cancelled or returned. Please review order status.', 'carrybee'));
} elseif ($is_failed) {
// Add note for failed delivery
$order->add_order_note(__('Courier delivery failed. Please contact customer.', 'carrybee'));
}
}
/**
* Log webhook message for debugging.
*
* @param string $message
*/
private function log_webhook_message($message) {
if (CARRYBEE_WP_debug_enabled()) {
CARRYBEE_WP_debug_log('CarryBee Webhook: ' . $message);
}
}
/**
* Log webhook data for debugging
*
* @param array $data
*/
private function log_webhook($data) {
if (CARRYBEE_WP_debug_enabled()) {
}
}
/**
* Add order meta box
*/
public function add_order_meta_box() {
add_meta_box(
'CARRYBEE_WP_order_details',
esc_html(CARRYBEE_WP_COURIER_NAME),
array($this, 'render_order_meta_box'),
'shop_order',
'side',
'default'
);
// For HPOS compatibility
if (class_exists('Automattic\WooCommerce\Utilities\OrderUtil') &&
\Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled()) {
add_meta_box(
'CARRYBEE_WP_order_details',
esc_html(CARRYBEE_WP_COURIER_NAME),
array($this, 'render_order_meta_box'),
'woocommerce_page_wc-orders',
'side',
'default'
);
}
}
/**
* Render order meta box
*
* @param WP_Post|WC_Order $post_or_order
*/
public function render_order_meta_box($post_or_order) {
$order = ($post_or_order instanceof WC_Order) ? $post_or_order : wc_get_order($post_or_order->ID);
if (!$order) {
return;
}
// Get courier meta data using helper function
$sent_to_courier = CARRYBEE_WP_get_order_meta($order, 'sent_to_courier');
$consignment_id = CARRYBEE_WP_get_order_meta($order, 'consignment_id');
$tracking_id = CARRYBEE_WP_get_order_meta($order, 'tracking_id');
$sent_date = CARRYBEE_WP_get_order_meta($order, 'sent_date');
?>
%s',
admin_url('admin.php?page=carrybee-courier-settings'),
__('Settings', 'carrybee')
);
array_unshift($links, $settings_link);
return $links;
}
/**
* Add custom columns to WooCommerce orders list
*
* @param array $columns
* @return array
*/
public function add_order_columns($columns) {
$new_columns = array();
foreach ($columns as $key => $column) {
$new_columns[$key] = $column;
// Add our columns after the 'order_status' column
if ($key === 'order_status') {
$new_columns[CARRYBEE_WP_COURIER_SLUG . '_amount_collect'] = __('COD Amount', 'carrybee');
$new_columns[CARRYBEE_WP_COURIER_SLUG . '_consignment'] = __('CarryBee', 'carrybee');
$new_columns[CARRYBEE_WP_COURIER_SLUG . '_courier_status'] = __('Courier Status', 'carrybee');
$new_columns[CARRYBEE_WP_COURIER_SLUG . '_delivery_fee'] = __('Delivery Fee', 'carrybee');
}
}
return $new_columns;
}
/**
* Render custom columns content for orders (Legacy)
*
* @param string $column
* @param int $post_id
*/
public function render_order_columns($column, $post_id) {
$order = wc_get_order($post_id);
if (!$order) {
return;
}
$this->render_column_content($column, $order);
}
/**
* Render custom columns content for orders (HPOS)
*
* @param string $column
* @param WC_Order $order
*/
public function render_order_columns_hpos($column, $order) {
if (!$order instanceof WC_Order) {
return;
}
$this->render_column_content($column, $order);
}
/**
* Render column content
*
* @param string $column
* @param WC_Order $order
*/
private function render_column_content($column, $order) {
switch ($column) {
case CARRYBEE_WP_COURIER_SLUG . '_amount_collect':
if ($this->is_order_sent($order)) {
echo '— ';
} else {
// name attr submits the override with the native bulk actions form (direct send bulk action)
echo ' ';
}
break;
case CARRYBEE_WP_COURIER_SLUG . '_consignment':
$consignment_id = CARRYBEE_WP_get_order_meta($order, 'consignment_id');
$order_id = $order->get_id();
$nonce = wp_create_nonce('CARRYBEE_WP_send_to_courier_' . $order_id);
// Same buttons as the CarryBee Orders page (WooCommerce has its own "open order" link).
echo '';
if (!$consignment_id && $this->is_order_sent($order)) {
echo '' . esc_html__('Waiting for consignment ID', 'carrybee') . ' ';
} elseif ($consignment_id) {
echo '';
echo '' . esc_html($consignment_id) . ' ';
echo ' ';
echo '' . esc_html__('Copy', 'carrybee') . ' ';
echo ' ';
echo '';
echo ' ' . esc_html__('Print POD', 'carrybee');
echo ' ';
} else {
echo '';
echo esc_html__('Review & send', 'carrybee');
echo ' ';
echo '';
echo esc_html__('Quick send', 'carrybee');
echo ' ';
}
echo '
';
break;
case CARRYBEE_WP_COURIER_SLUG . '_courier_status':
$consignment_id = CARRYBEE_WP_get_order_meta($order, 'consignment_id');
$courier_status = CARRYBEE_WP_get_order_meta($order, 'courier_status');
if (empty($courier_status)) {
$courier_status = $this->default_courier_status($consignment_id, $this->is_order_sent($order));
}
echo '';
echo '' . esc_html($courier_status) . ' ';
if ($consignment_id) {
echo '';
echo ' ';
echo ' ';
}
echo '
';
break;
case CARRYBEE_WP_COURIER_SLUG . '_delivery_fee':
$delivery_fee = CARRYBEE_WP_get_order_meta($order, 'delivery_fee');
if ($delivery_fee) {
echo '';
echo wp_kses_post(wc_price($delivery_fee));
echo ' ';
} else {
echo '— ';
}
break;
}
}
/**
* Register the direct send bulk action on WooCommerce orders pages.
*
* @param array $actions
* @return array
*/
public function register_wc_orders_bulk_actions($actions) {
/* translators: %s: CarryBee */
$actions['cbwp_direct_send_to_courier'] = sprintf(__('%s: Quick send', 'carrybee'), CARRYBEE_WP_COURIER_NAME);
return $actions;
}
/**
* Handle the direct send bulk action from WooCommerce orders pages.
* Sends the selected orders to the bulk create API without city/zone/area and
* redirects back with result counts for the admin notice.
*
* @param string $redirect_to
* @param string $action
* @param array $ids Selected order IDs.
* @return string
*/
public function handle_wc_orders_bulk_action($redirect_to, $action, $ids) {
if ($action !== 'cbwp_direct_send_to_courier') {
return $redirect_to;
}
$redirect_to = remove_query_arg(array('cbwp_direct_sent', 'cbwp_direct_skipped', 'cbwp_direct_error'), $redirect_to);
if (!current_user_can('manage_woocommerce')) {
return add_query_arg('cbwp_direct_error', rawurlencode(__('Unauthorized', 'carrybee')), $redirect_to);
}
// Optional per-order overrides from the orders table "Amount to Collect" inputs,
// submitted along with the bulk action form.
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- WooCommerce/WordPress verified the bulk-action nonce before calling handle_bulk_actions-*.
$amounts = isset($_REQUEST['cbwp_amounts']) && is_array($_REQUEST['cbwp_amounts'])
? map_deep(wp_unslash($_REQUEST['cbwp_amounts']), 'sanitize_text_field')
: array();
// phpcs:enable WordPress.Security.NonceVerification.Recommended
$result = $this->prepare_direct_send_orders(array_map('absint', (array) $ids), $amounts);
if (!empty($result['error'])) {
return add_query_arg('cbwp_direct_error', rawurlencode($result['error']), $redirect_to);
}
if (empty($result['prepared'])) {
return add_query_arg(array(
'cbwp_direct_sent' => 0,
'cbwp_direct_skipped' => count($result['skipped']),
), $redirect_to);
}
$api_orders = array_map(function($item) {
return $item['api_data'];
}, $result['prepared']);
$response = $this->api->create_bulk_parcels($api_orders);
if (is_wp_error($response)) {
return add_query_arg('cbwp_direct_error', rawurlencode($response->get_error_message()), $redirect_to);
}
if ((isset($response['error']) && $response['error'] === true) || (isset($response['success']) && $response['success'] === false)) {
$message = isset($response['message']) ? $response['message'] : __('Failed to send orders to courier.', 'carrybee');
return add_query_arg('cbwp_direct_error', rawurlencode($message), $redirect_to);
}
$sent = $this->mark_bulk_orders_sent($result['prepared']);
return add_query_arg(array(
'cbwp_direct_sent' => $sent,
'cbwp_direct_skipped' => count($result['skipped']),
), $redirect_to);
}
/**
* Warn on CarryBee and WooCommerce order screens while no webhook secret is set,
* because every order status update from CarryBee is refused until it is.
*/
public function render_missing_webhook_secret_notice() {
if (!current_user_can('manage_woocommerce')) {
return;
}
if (trim((string) CARRYBEE_WP_get_setting(CARRYBEE_WP_SETTING_WEBHOOK_SECRET, '')) !== '') {
return;
}
$screen = function_exists('get_current_screen') ? get_current_screen() : null;
$screen_id = $screen ? (string) $screen->id : '';
$is_plugin_screen = strpos($screen_id, CARRYBEE_WP_MENU_SLUG) !== false || strpos($screen_id, CARRYBEE_WP_ORDERS_SLUG) !== false;
$is_orders_screen = in_array($screen_id, array('edit-shop_order', 'woocommerce_page_wc-orders'), true);
if (!$is_plugin_screen && !$is_orders_screen) {
return;
}
$settings_url = admin_url('admin.php?page=' . CARRYBEE_WP_MENU_SLUG . '#' . CARRYBEE_WP_SETTINGS_OPTION . '_webhook_secret');
?>
%s
',
esc_html(sanitize_text_field(wp_unslash($_GET['cbwp_direct_error'])))
);
return;
}
if (!isset($_GET['cbwp_direct_sent'])) {
return;
}
$sent = absint($_GET['cbwp_direct_sent']);
$skipped = isset($_GET['cbwp_direct_skipped']) ? absint($_GET['cbwp_direct_skipped']) : 0;
// phpcs:enable WordPress.Security.NonceVerification.Recommended
if ($sent > 0) {
$message = sprintf(
/* translators: %d: number of orders sent */
_n('%d order sent to courier successfully. Consignment details will be updated via webhook.', '%d orders sent to courier successfully. Consignment details will be updated via webhook.', $sent, 'carrybee'),
$sent
);
if ($skipped > 0) {
$message .= ' ' . sprintf(
/* translators: %d: number of skipped orders */
_n('%d order was skipped (already sent or missing recipient details).', '%d orders were skipped (already sent or missing recipient details).', $skipped, 'carrybee'),
$skipped
);
}
printf('', esc_html($message));
} else {
printf(
'',
esc_html(sprintf(
/* translators: %d: number of skipped orders */
_n('No orders were sent. %d order was skipped (already sent or missing recipient details).', 'No orders were sent. %d orders were skipped (already sent or missing recipient details).', max(1, $skipped), 'carrybee'),
$skipped
))
);
}
}
/**
* Courier status options for the filters: the API's Pending state plus the
* published webhook event statuses.
*
* @return array
*/
private function get_courier_status_filter_options() {
$options = array_merge(
array(__('Pending', 'carrybee')),
array_values($this->get_webhook_event_labels())
);
// Add statuses saved on orders that the list words differently (e.g. the API's "Created").
$seen = get_option(CARRYBEE_WP_SEEN_STATUSES_OPTION, array());
$known = array_map('strtolower', $options);
foreach (is_array($seen) ? $seen : array() as $status) {
if (is_string($status) && $status !== '' && !in_array(strtolower($status), $known, true)) {
$options[] = $status;
$known[] = strtolower($status);
}
}
return $options;
}
/**
* Get the current courier filter value from the request:
* sent, not_sent, a specific courier status, or '' for all.
*
* @return string
*/
private function get_wc_orders_courier_filter() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only list filters and pagination; values are sanitized and nothing is changed.
$filter = isset($_GET['cbwp_courier_filter']) ? sanitize_text_field(wp_unslash($_GET['cbwp_courier_filter'])) : '';
if (in_array($filter, array('sent', 'not_sent'), true)) {
return $filter;
}
return in_array($filter, $this->get_courier_status_filter_options(), true) ? $filter : '';
}
/**
* Build a meta query clause for the courier filter: sent/not_sent keywords
* or a specific courier status (case-insensitive at the DB level).
*
* @param string $filter sent|not_sent|
* @return array
*/
private function build_courier_sent_meta_clause($filter) {
if ($filter === 'sent') {
return array(
'relation' => 'OR',
array('key' => CARRYBEE_WP_META_CONSIGNMENT_ID, 'value' => '', 'compare' => '!='),
array('key' => CARRYBEE_WP_META_SENT_TO_COURIER, 'value' => 'yes', 'compare' => '='),
);
}
if ($filter === 'not_sent') {
return array(
'relation' => 'AND',
array(
'relation' => 'OR',
array('key' => CARRYBEE_WP_META_CONSIGNMENT_ID, 'compare' => 'NOT EXISTS'),
array('key' => CARRYBEE_WP_META_CONSIGNMENT_ID, 'value' => '', 'compare' => '='),
),
array(
'relation' => 'OR',
array('key' => CARRYBEE_WP_META_SENT_TO_COURIER, 'compare' => 'NOT EXISTS'),
array('key' => CARRYBEE_WP_META_SENT_TO_COURIER, 'value' => 'yes', 'compare' => '!='),
),
);
}
// A specific courier status implies the order was sent
return array(
'key' => CARRYBEE_WP_META_COURIER_STATUS,
'value' => $filter,
'compare' => '='
);
}
/**
* Render the courier filter dropdown. Defaults to all orders.
*/
private function render_courier_filter_dropdown() {
$current = $this->get_wc_orders_courier_filter();
?>
>
>
>
get_courier_status_filter_options() as $status_option) : ?>
>
render_courier_filter_dropdown();
}
/**
* Render the courier filter on the HPOS WooCommerce orders page.
*
* @param string $order_type
* @param string $which top|bottom
*/
public function render_wc_orders_courier_filter_hpos($order_type, $which) {
if ($which !== 'top') {
return;
}
$this->render_courier_filter_dropdown();
}
/**
* Apply the courier filter on the legacy WooCommerce orders list query.
*
* @param WP_Query $query
*/
public function apply_wc_orders_courier_filter_legacy($query) {
global $pagenow;
if (!is_admin() || $pagenow !== 'edit.php' || !$query->is_main_query() || $query->get('post_type') !== 'shop_order') {
return;
}
$filter = $this->get_wc_orders_courier_filter();
if ($filter === '') {
return;
}
$meta_query = $query->get('meta_query');
if (!is_array($meta_query)) {
$meta_query = array();
}
$meta_query[] = $this->build_courier_sent_meta_clause($filter);
$query->set('meta_query', $meta_query);
}
/**
* Apply the courier filter on the HPOS WooCommerce orders list query.
*
* @param array $query_args
* @return array
*/
public function apply_wc_orders_courier_filter_hpos($query_args) {
$filter = $this->get_wc_orders_courier_filter();
if ($filter === '') {
return $query_args;
}
$meta_query = isset($query_args['meta_query']) && is_array($query_args['meta_query'])
? $query_args['meta_query']
: array();
$meta_query[] = $this->build_courier_sent_meta_clause($filter);
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Orders are looked up by CarryBee courier meta; there is no indexed alternative.
$query_args['meta_query'] = $meta_query;
return $query_args;
}
/**
* Make custom columns sortable
*
* @param array $columns
* @return array
*/
public function make_columns_sortable($columns) {
$columns[CARRYBEE_WP_COURIER_SLUG . '_courier_status'] = CARRYBEE_WP_COURIER_SLUG . '_courier_status';
$columns[CARRYBEE_WP_COURIER_SLUG . '_delivery_fee'] = CARRYBEE_WP_COURIER_SLUG . '_delivery_fee';
return $columns;
}
/**
* Render modal on WooCommerce orders page
*/
public function render_modal_on_orders_page() {
$screen = get_current_screen();
// Check if we're on WooCommerce orders page (classic or HPOS)
if (!$screen || ($screen->id !== 'edit-shop_order' && $screen->id !== 'woocommerce_page_wc-orders')) {
return;
}
// Render the modal
$this->render_courier_modals_html();
}
/**
* Render courier modals HTML
* Used by both render_orders_page and render_modal_on_orders_page to avoid duplication
*/
private function render_courier_modals_html() {
?>