api_client = $api_client;
$this->price_sync = $price_sync;
$this->stock_sync = $stock_sync;
$this->cron = $cron;
$this->logger = $logger;
$this->product_mapper = $product_mapper;
$this->product_importer = $product_importer;
$this->order_handler = $order_handler;
$this->auto_importer = $auto_importer;
// Admin hooks
add_action('admin_menu', [$this, 'register_menu']);
add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
add_action('admin_init', [$this, 'register_settings']);
// AJAX handlers
add_action('wp_ajax_dszsync_test_connection', [$this, 'ajax_test_connection']);
add_action('wp_ajax_dszsync_save_settings', [$this, 'ajax_save_settings']);
add_action('wp_ajax_dszsync_run_sync', [$this, 'ajax_run_sync']);
add_action('wp_ajax_dszsync_get_sync_status', [$this, 'ajax_get_sync_status']);
add_action('wp_ajax_dszsync_continue_sync', [$this, 'ajax_continue_sync']);
add_action('wp_ajax_dszsync_hide_setup', [$this, 'ajax_hide_setup']);
add_action('wp_ajax_dszsync_clear_logs', [$this, 'ajax_clear_logs']);
add_action('wp_ajax_dszsync_export_logs', [$this, 'ajax_export_logs']);
// Mapping AJAX handlers
add_action('wp_ajax_dszsync_search_wc_products', [$this, 'ajax_search_wc_products']);
add_action('wp_ajax_dszsync_search_catalog_products', [$this, 'ajax_search_catalog_products']);
add_action('wp_ajax_dszsync_map_product', [$this, 'ajax_map_product']);
add_action('wp_ajax_dszsync_unmap_product', [$this, 'ajax_unmap_product']);
add_action('wp_ajax_dszsync_auto_map', [$this, 'ajax_auto_map']);
// Import AJAX handlers
add_action('wp_ajax_dszsync_search_api_products', [$this, 'ajax_search_api_products']);
add_action('wp_ajax_dszsync_import_product', [$this, 'ajax_import_product']);
add_action('wp_ajax_dszsync_resync_product', [$this, 'ajax_resync_product']);
add_action('wp_ajax_dszsync_resync_all', [$this, 'ajax_resync_all']);
add_action('wp_ajax_dszsync_resync_images', [$this, 'ajax_resync_images']);
add_action('wp_ajax_dszsync_resync_categories', [$this, 'ajax_resync_categories']);
add_action('wp_ajax_dszsync_resync_never_synced', [$this, 'ajax_resync_never_synced']);
add_action('wp_ajax_dszsync_scan_unmapped_products', [$this, 'ajax_scan_unmapped_products']);
add_action('wp_ajax_dszsync_get_categories', [$this, 'ajax_get_categories']);
add_action('wp_ajax_dszsync_save_advanced_price_rules', [$this, 'ajax_save_advanced_price_rules']);
add_action('wp_ajax_dszsync_save_import_template', [$this, 'ajax_save_import_template']);
add_action('wp_ajax_dszsync_delete_import_template', [$this, 'ajax_delete_import_template']);
add_action('wp_ajax_dszsync_export_mappings', [$this, 'ajax_export_mappings']);
// Order AJAX handlers
add_action('wp_ajax_dszsync_submit_order', [$this, 'ajax_submit_order']);
add_action('wp_ajax_dszsync_submit_pending_orders', [$this, 'ajax_submit_pending_orders']);
add_action('wp_ajax_dszsync_run_tracking_sync', [$this, 'ajax_run_tracking_sync']);
// Orders list bulk action (HPOS + legacy)
add_filter('bulk_actions-woocommerce_page_wc-orders', [$this, 'register_order_bulk_action']);
add_filter('bulk_actions-edit-shop_order', [$this, 'register_order_bulk_action']);
add_filter('handle_bulk_actions-woocommerce_page_wc-orders', [$this, 'handle_order_bulk_action'], 10, 3);
add_filter('handle_bulk_actions-edit-shop_order', [$this, 'handle_order_bulk_action'], 10, 3);
add_action('admin_notices', [$this, 'order_bulk_action_notice']);
// Product list margin column (from _dszsync_cost supplier cost meta)
add_filter('manage_edit-product_columns', [$this, 'add_product_margin_column'], 20);
add_action('manage_product_posts_custom_column', [$this, 'render_product_margin_column'], 10, 2);
// Auto Import AJAX handlers
add_action('wp_ajax_dszsync_run_auto_import', [$this, 'ajax_run_auto_import']);
add_action('wp_ajax_dszsync_save_auto_import_settings', [$this, 'ajax_save_auto_import_settings']);
// WooCommerce order integration
add_action('add_meta_boxes', [$this, 'add_order_meta_box']);
}
/**
* Register admin menu
*/
public function register_menu() {
// Main menu
add_menu_page(
__('Dropshipzone Sync', '3s-soft-price-stock-sync-for-dropshipzone'),
__('DSZ Sync', '3s-soft-price-stock-sync-for-dropshipzone'),
'manage_woocommerce',
'dsz-sync',
[$this, 'render_dashboard'],
'dashicons-update',
56
);
// Submenu order, labels and callbacks all come from the same
// definition as the in-page nav bar. Registering them by hand let the
// two drift: the sidebar was in the order the calls happened to be
// written (Logs above Product Mapping), while the nav bar was in
// workflow order, so the same nine screens appeared in two different
// sequences depending on where you looked.
foreach ($this->get_nav_groups() as $group) {
foreach ($group['items'] as $page_slug => $item) {
add_submenu_page(
'dsz-sync',
$item['label'],
$item['label'],
'manage_woocommerce',
$page_slug,
[$this, $item['callback']]
);
}
}
}
/**
* Enqueue admin assets
*/
public function enqueue_assets($hook) {
// Load on our pages and on order edit screens (DSZ order meta box)
$screen = function_exists('get_current_screen') ? get_current_screen() : null;
$is_order_screen = $screen && in_array($screen->id, ['shop_order', 'woocommerce_page_wc-orders'], true);
if (strpos($hook, 'dsz-sync') === false && !$is_order_screen) {
return;
}
// Use timestamp in dev mode to bust cache
$asset_version = defined('WP_DEBUG') && WP_DEBUG ? DSZSYNC_VERSION . '.' . time() : DSZSYNC_VERSION;
wp_enqueue_style(
'dsz-admin-css',
DSZSYNC_PLUGIN_URL . 'assets/admin.css',
[],
$asset_version
);
wp_enqueue_script(
'dsz-admin-js',
DSZSYNC_PLUGIN_URL . 'assets/admin.js',
['jquery'],
$asset_version,
true
);
wp_localize_script('dsz-admin-js', 'dszsync_admin', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('dszsync_admin_nonce'),
'import_templates' => (object) get_option('dszsync_import_templates', []),
'strings' => [
'testing' => __('Testing connection...', '3s-soft-price-stock-sync-for-dropshipzone'),
'saving' => __('Saving...', '3s-soft-price-stock-sync-for-dropshipzone'),
'syncing' => __('Syncing...', '3s-soft-price-stock-sync-for-dropshipzone'),
'success' => __('Success!', '3s-soft-price-stock-sync-for-dropshipzone'),
'error' => __('Error occurred', '3s-soft-price-stock-sync-for-dropshipzone'),
'confirm_clear' => __('Are you sure you want to clear all logs?', '3s-soft-price-stock-sync-for-dropshipzone'),
'confirm_never_synced' => __('This will resync all never-synced products. Continue?', '3s-soft-price-stock-sync-for-dropshipzone'),
'confirm_scan' => __('This will check all unmapped products against Dropshipzone API. Products found will be linked; products not found will be marked as Non-DSZ. Continue?', '3s-soft-price-stock-sync-for-dropshipzone'),
'processing' => __('Processing...', '3s-soft-price-stock-sync-for-dropshipzone'),
'scanning' => __('Scanning products...', '3s-soft-price-stock-sync-for-dropshipzone'),
'resynced' => __('Resynced', '3s-soft-price-stock-sync-for-dropshipzone'),
'errors_word' => __('errors', '3s-soft-price-stock-sync-for-dropshipzone'),
'processed' => __('processed...', '3s-soft-price-stock-sync-for-dropshipzone'),
'linked' => __('linked', '3s-soft-price-stock-sync-for-dropshipzone'),
'non_dsz' => __('marked as non-DSZ', '3s-soft-price-stock-sync-for-dropshipzone'),
'scanned' => __('scanned...', '3s-soft-price-stock-sync-for-dropshipzone'),
'importing' => __('Importing...', '3s-soft-price-stock-sync-for-dropshipzone'),
'submitting' => __('Submitting...', '3s-soft-price-stock-sync-for-dropshipzone'),
'request_failed' => __('Request failed', '3s-soft-price-stock-sync-for-dropshipzone'),
'rate_wait' => __('Rate limit reached — retrying shortly...', '3s-soft-price-stock-sync-for-dropshipzone'),
'confirm_ok' => __('Confirm', '3s-soft-price-stock-sync-for-dropshipzone'),
'confirm_cancel' => __('Cancel', '3s-soft-price-stock-sync-for-dropshipzone'),
],
]);
}
/**
* Register settings
*/
public function register_settings() {
register_setting('dszsync_api', 'dszsync_api_email', [
'sanitize_callback' => 'sanitize_email'
]);
register_setting('dszsync_api', 'dszsync_api_password', [
'sanitize_callback' => 'sanitize_text_field'
]);
// Each option gets a callback that knows its own shape. A generic
// recursive sanitize_text_field() would let "banana" through as a
// markup type or a rounding rule, because it only guarantees the value
// is a harmless string — not that it is one this plugin can act on.
register_setting('dszsync_settings', 'dszsync_price_rules', [
'type' => 'array',
'sanitize_callback' => [$this, 'sanitize_price_rules'],
]);
register_setting('dszsync_settings', 'dszsync_stock_rules', [
'type' => 'array',
'sanitize_callback' => [$this, 'sanitize_stock_rules'],
]);
register_setting('dszsync_settings', 'dszsync_settings', [
'type' => 'array',
'sanitize_callback' => [$this, 'sanitize_sync_settings'],
]);
register_setting('dszsync_settings', 'dszsync_import_settings', [
'type' => 'array',
'sanitize_callback' => [$this, 'sanitize_import_settings'],
]);
}
/**
* Pick a value from a fixed set, falling back when it is not one of them.
*
* @param mixed $value Raw input
* @param array $allowed Permitted values
* @param string $fallback Value to use when the input is not permitted
* @return string
*/
private static function pick($value, array $allowed, $fallback) {
$value = is_scalar($value) ? (string) $value : '';
return in_array($value, $allowed, true) ? $value : $fallback;
}
/**
* Sanitize price rules.
*
* @param mixed $input Raw option value
* @return array
*/
public function sanitize_price_rules($input) {
$input = is_array($input) ? $input : [];
return [
'markup_type' => self::pick(
isset($input['markup_type']) ? $input['markup_type'] : '',
['percentage', 'fixed'],
'percentage'
),
// Negative markup would sell below cost; the upper bound is only
// there to stop a typo turning into an unsellable price.
'markup_value' => max(0, min(100000, (float) (isset($input['markup_value']) ? $input['markup_value'] : 30))),
'rounding_enabled' => !empty($input['rounding_enabled']),
'rounding_type' => self::pick(
isset($input['rounding_type']) ? $input['rounding_type'] : '',
['99', '95', 'nearest'],
'99'
),
'gst_enabled' => !empty($input['gst_enabled']),
'gst_type' => self::pick(
isset($input['gst_type']) ? $input['gst_type'] : '',
['include', 'exclude'],
'include'
),
];
}
/**
* Sanitize stock rules.
*
* @param mixed $input Raw option value
* @return array
*/
public function sanitize_stock_rules($input) {
$input = is_array($input) ? $input : [];
return [
'buffer_enabled' => !empty($input['buffer_enabled']),
'buffer_amount' => max(0, min(100000, (int) (isset($input['buffer_amount']) ? $input['buffer_amount'] : 0))),
'zero_on_unavailable' => !empty($input['zero_on_unavailable']),
'auto_out_of_stock' => !empty($input['auto_out_of_stock']),
'deactivate_if_not_found' => !empty($input['deactivate_if_not_found']),
'republish_on_restock' => !empty($input['republish_on_restock']),
];
}
/**
* Sanitize sync settings.
*
* This option holds both user configuration and the sync's own run state
* (offset, counters, timestamps). The run state is carried over from what
* is already stored rather than read from the input, so saving the form
* can never rewind an in-flight sync or fake its results.
*
* @param mixed $input Raw option value
* @return array
*/
public function sanitize_sync_settings($input) {
$input = is_array($input) ? $input : [];
$current = get_option('dszsync_settings', []);
$current = is_array($current) ? $current : [];
$frequencies = ['hourly', 'twicedaily', 'daily'];
$clean = [
'frequency' => self::pick(
isset($input['frequency']) ? $input['frequency'] : '',
$frequencies,
'hourly'
),
'batch_size' => max(10, min(200, (int) (isset($input['batch_size']) ? $input['batch_size'] : 100))),
'incremental_enabled' => !empty($input['incremental_enabled']),
'incremental_frequency' => self::pick(
isset($input['incremental_frequency']) ? $input['incremental_frequency'] : '',
$frequencies,
'hourly'
),
];
// Run state: preserved, and cast so a corrupted row cannot poison it
$clean['sync_in_progress'] = !empty($current['sync_in_progress']);
$clean['current_offset'] = max(0, (int) (isset($current['current_offset']) ? $current['current_offset'] : 0));
$clean['total_products'] = max(0, (int) (isset($current['total_products']) ? $current['total_products'] : 0));
$clean['products_updated'] = max(0, (int) (isset($current['products_updated']) ? $current['products_updated'] : 0));
$clean['errors_count'] = max(0, (int) (isset($current['errors_count']) ? $current['errors_count'] : 0));
$clean['last_products_updated'] = max(0, (int) (isset($current['last_products_updated']) ? $current['last_products_updated'] : 0));
$clean['last_errors_count'] = max(0, (int) (isset($current['last_errors_count']) ? $current['last_errors_count'] : 0));
$clean['last_batch_time'] = max(0, (int) (isset($current['last_batch_time']) ? $current['last_batch_time'] : 0));
$clean['last_sync'] = isset($current['last_sync']) && $current['last_sync']
? max(0, (int) $current['last_sync'])
: null;
return $clean;
}
/**
* Sanitize import settings.
*
* @param mixed $input Raw option value
* @return array
*/
public function sanitize_import_settings($input) {
$input = is_array($input) ? $input : [];
return [
'default_status' => self::pick(
isset($input['default_status']) ? $input['default_status'] : '',
['publish', 'draft', 'pending'],
'publish'
),
];
}
/**
* Render page header with navigation
*/
private function render_header($title, $subtitle = '', $actions = '') {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only screen state (current page, filter, pagination); nothing is created, changed or deleted here.
$current_page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : 'dsz-sync';
// Grouped in the order the plugin is actually set up and used. Labels
// match the WordPress submenu entries exactly so the two menus never
// disagree about what a screen is called.
$nav_groups = $this->get_nav_groups();
?>
$item):
$is_active = ($current_page === $page_slug);
?>
>
string, 'items' => [slug => [label, icon]]]
*/
private function get_nav_groups() {
return [
[
'label' => __('Overview', '3s-soft-price-stock-sync-for-dropshipzone'),
'items' => [
'dsz-sync' => [
'label' => __('Dashboard', '3s-soft-price-stock-sync-for-dropshipzone'),
'icon' => 'dashicons-dashboard',
'callback' => 'render_dashboard',
],
],
],
[
'label' => __('Setup', '3s-soft-price-stock-sync-for-dropshipzone'),
'items' => [
'dsz-sync-api' => [
'label' => __('API Settings', '3s-soft-price-stock-sync-for-dropshipzone'),
'icon' => 'dashicons-admin-network',
'callback' => 'render_api_settings',
],
],
],
[
'label' => __('Products', '3s-soft-price-stock-sync-for-dropshipzone'),
'items' => [
'dsz-sync-import' => [
'label' => __('Product Import', '3s-soft-price-stock-sync-for-dropshipzone'),
'icon' => 'dashicons-download',
'callback' => 'render_import',
],
'dsz-sync-auto-import' => [
'label' => __('Auto Import', '3s-soft-price-stock-sync-for-dropshipzone'),
'icon' => 'dashicons-controls-repeat',
'callback' => 'render_auto_import',
],
'dsz-sync-mapping' => [
'label' => __('Product Mapping', '3s-soft-price-stock-sync-for-dropshipzone'),
'icon' => 'dashicons-admin-links',
'callback' => 'render_mapping',
],
],
],
[
'label' => __('Rules', '3s-soft-price-stock-sync-for-dropshipzone'),
'items' => [
'dsz-sync-price' => [
'label' => __('Price Rules', '3s-soft-price-stock-sync-for-dropshipzone'),
'icon' => 'dashicons-money-alt',
'callback' => 'render_price_rules',
],
'dsz-sync-stock' => [
'label' => __('Stock Rules', '3s-soft-price-stock-sync-for-dropshipzone'),
'icon' => 'dashicons-archive',
'callback' => 'render_stock_rules',
],
],
],
[
'label' => __('Operations', '3s-soft-price-stock-sync-for-dropshipzone'),
'items' => [
'dsz-sync-control' => [
'label' => __('Sync Center', '3s-soft-price-stock-sync-for-dropshipzone'),
'icon' => 'dashicons-update',
'callback' => 'render_sync_center',
],
'dsz-sync-logs' => [
'label' => __('Logs', '3s-soft-price-stock-sync-for-dropshipzone'),
'icon' => 'dashicons-list-view',
'callback' => 'render_logs',
],
],
],
];
}
/**
* Resolve the setup steps and whether each is done.
*
* Reads only state the plugin already tracks — no new queries, and no
* new options. A step is "done" when the thing it configures exists,
* not when the user has visited the page.
*
* @return array Steps of ['label', 'done', 'url', 'cta', 'help']
*/
private function get_setup_steps() {
$token_status = $this->api_client->get_token_status();
$price_rules = get_option('dszsync_price_rules', []);
$stock_rules = get_option('dszsync_stock_rules', []);
$sync_status = $this->cron->get_sync_status();
$mapped = $this->product_mapper ? $this->product_mapper->get_syncable_count() : 0;
return [
[
'label' => __('Connect your Dropshipzone account', '3s-soft-price-stock-sync-for-dropshipzone'),
'help' => __('Nothing syncs until the plugin can authenticate.', '3s-soft-price-stock-sync-for-dropshipzone'),
'done' => !empty($token_status['is_valid']),
'url' => admin_url('admin.php?page=dsz-sync-api'),
'cta' => __('Add credentials', '3s-soft-price-stock-sync-for-dropshipzone'),
],
[
'label' => __('Set your pricing rules', '3s-soft-price-stock-sync-for-dropshipzone'),
'help' => __('Markup, GST and rounding decide your shelf price.', '3s-soft-price-stock-sync-for-dropshipzone'),
'done' => !empty($price_rules),
'url' => admin_url('admin.php?page=dsz-sync-price'),
'cta' => __('Set pricing', '3s-soft-price-stock-sync-for-dropshipzone'),
],
[
'label' => __('Set your stock rules', '3s-soft-price-stock-sync-for-dropshipzone'),
'help' => __('A stock buffer is what stops you overselling.', '3s-soft-price-stock-sync-for-dropshipzone'),
'done' => !empty($stock_rules),
'url' => admin_url('admin.php?page=dsz-sync-stock'),
'cta' => __('Set stock rules', '3s-soft-price-stock-sync-for-dropshipzone'),
],
[
'label' => __('Link products to Dropshipzone SKUs', '3s-soft-price-stock-sync-for-dropshipzone'),
'help' => $mapped > 0
? sprintf(
/* translators: %d: number of linked products */
_n('%d product linked.', '%d products linked.', $mapped, '3s-soft-price-stock-sync-for-dropshipzone'),
$mapped
)
: __('Only linked products are kept up to date.', '3s-soft-price-stock-sync-for-dropshipzone'),
'done' => $mapped > 0,
'url' => admin_url('admin.php?page=dsz-sync-mapping'),
'cta' => __('Link products', '3s-soft-price-stock-sync-for-dropshipzone'),
],
[
'label' => __('Run your first sync', '3s-soft-price-stock-sync-for-dropshipzone'),
'help' => __('Confirms everything above is wired up correctly.', '3s-soft-price-stock-sync-for-dropshipzone'),
'done' => !empty($sync_status['last_sync']),
'url' => admin_url('admin.php?page=dsz-sync-control'),
'cta' => __('Run sync', '3s-soft-price-stock-sync-for-dropshipzone'),
],
];
}
/**
* Render the setup checklist, unless every step is done or the user
* has dismissed it.
*
* @return void
*/
private function render_setup_checklist() {
if (get_user_meta(get_current_user_id(), 'dszsync_hide_setup', true)) {
return;
}
$steps = $this->get_setup_steps();
$done = count(array_filter(wp_list_pluck($steps, 'done')));
$total = count($steps);
if ($done === $total) {
return;
}
// The first unfinished step is the one to act on next
$next = null;
foreach ($steps as $i => $step) {
if (!$step['done']) {
$next = $i;
break;
}
}
?>
string, 'label' => string]
* @return void
*/
private function render_empty_state($icon, $title, $body, $action = []) {
?>
cron->get_sync_status();
$token_status = $this->api_client->get_token_status();
$error_count = $this->logger->get_count('error');
?>
render_header(__('Dropshipzone Sync Dashboard', '3s-soft-price-stock-sync-for-dropshipzone')); ?>
render_setup_checklist(); ?>
cron->get_progress())); ?>
api_client->get_token_status();
?>
render_header(__('API Settings', '3s-soft-price-stock-sync-for-dropshipzone'), __('Configure your Dropshipzone API credentials', '3s-soft-price-stock-sync-for-dropshipzone')); ?>
price_sync->get_rules();
?>
render_header(__('Price Rules', '3s-soft-price-stock-sync-for-dropshipzone'), __('Configure how prices are calculated from supplier cost', '3s-soft-price-stock-sync-for-dropshipzone')); ?>
stock_sync->get_rules();
?>
render_header(__('Stock Rules', '3s-soft-price-stock-sync-for-dropshipzone'), __('Configure how stock quantities are synced', '3s-soft-price-stock-sync-for-dropshipzone')); ?>
cron->get_sync_status();
$frequencies = $this->cron->get_frequencies();
$total_mapped = intval($this->product_mapper->get_count());
$unmapped_count = $this->product_mapper->get_unmapped_count();
$in_progress = !empty($sync_status['in_progress']);
?>
render_header(__('Sync Center', '3s-soft-price-stock-sync-for-dropshipzone'), __('All sync actions in one place', '3s-soft-price-stock-sync-for-dropshipzone')); ?>
__('Hourly', '3s-soft-price-stock-sync-for-dropshipzone'),
'twicedaily' => __('Twice Daily', '3s-soft-price-stock-sync-for-dropshipzone'),
'daily' => __('Daily', '3s-soft-price-stock-sync-for-dropshipzone'),
];
echo esc_html(isset($freq_labels[$sync_status['frequency']]) ? $freq_labels[$sync_status['frequency']] : ucfirst($sync_status['frequency']));
?>
cron->get_progress()); ?>%
logger->get_logs([
'level' => $level,
'limit' => $per_page,
'offset' => ($page - 1) * $per_page,
]);
$total = $this->logger->get_count($level);
$total_pages = ceil($total / $per_page);
// Get counts by level for stats cards
$total_all = $this->logger->get_count('');
$total_info = $this->logger->get_count('info');
$total_warning = $this->logger->get_count('warning');
$total_error = $this->logger->get_count('error');
?>
render_header(__('Activity Logs', '3s-soft-price-stock-sync-for-dropshipzone'), __('Monitor sync activity and troubleshoot issues', '3s-soft-price-stock-sync-for-dropshipzone')); ?>
render_empty_state(
'search',
__('No logs at this level', '3s-soft-price-stock-sync-for-dropshipzone'),
__('Nothing was recorded at this level. Clear the filter to see all activity.', '3s-soft-price-stock-sync-for-dropshipzone'),
[
'url' => admin_url('admin.php?page=dsz-sync-logs'),
'label' => __('Clear filter', '3s-soft-price-stock-sync-for-dropshipzone'),
]
);
} else {
$this->render_empty_state(
'yes-alt',
__('Nothing to report', '3s-soft-price-stock-sync-for-dropshipzone'),
__('Sync activity and any errors will appear here once a sync has run.', '3s-soft-price-stock-sync-for-dropshipzone'),
[
'url' => admin_url('admin.php?page=dsz-sync-control'),
'label' => __('Go to Sync Center', '3s-soft-price-stock-sync-for-dropshipzone'),
]
);
}
?>
1): ?>
__('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
// A password is opaque credential data, not display text. Sanitizing
// would corrupt valid passwords; it is never output and is only sent
// to the API over HTTPS or stored encrypted.
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- see comment above
$password = isset($_POST['password']) ? (string) wp_unslash($_POST['password']) : '';
// If password is empty, try to use stored password
if (empty($password)) {
$encrypted = get_option('dszsync_api_password', '');
$password = dszsync_decrypt($encrypted);
}
$result = $this->api_client->test_connection($email, $password);
if (is_wp_error($result)) {
wp_send_json_error(['message' => $result->get_error_message()]);
}
// Persist the verified credentials. Without this, a successful test
// stores a token but no password — once the token expires, scheduled
// refreshes fail with "missing credentials".
if (!empty($email)) {
update_option('dszsync_api_email', $email);
}
if (!empty($_POST['password'])) {
update_option('dszsync_api_password', dszsync_encrypt($password));
}
wp_send_json_success([
'message' => $result['message'],
'products' => $result['products_available'],
]);
}
/**
* AJAX: Save settings
*/
public function ajax_save_settings() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$type = isset($_POST['type']) ? sanitize_text_field(wp_unslash($_POST['type'])) : '';
// Each branch below sanitizes the individual fields it consumes with
// the function appropriate to that field's type.
$settings = isset($_POST['settings']) && is_array($_POST['settings'])
? wp_unslash($_POST['settings']) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized per field below
: [];
switch ($type) {
case 'api':
$email = isset($settings['email']) ? sanitize_email($settings['email']) : '';
// A password is opaque credential data, not display text.
// sanitize_text_field() would silently corrupt valid passwords
// (it collapses whitespace and strips tag-like sequences), so
// the value is only forced to a scalar string. It is never
// echoed, and is encrypted at rest via dszsync_encrypt().
$password = isset($settings['password']) && is_scalar($settings['password'])
? (string) $settings['password']
: '';
$email_changed = ($email !== get_option('dszsync_api_email', ''));
update_option('dszsync_api_email', $email);
if (!empty($password)) {
update_option('dszsync_api_password', dszsync_encrypt($password));
}
// Credentials changed, so the cached token was issued for the
// previous account. Drop it and let the next request re-auth,
// rather than leaving a stale token valid until it expires.
if ($email_changed || !empty($password)) {
$this->api_client->clear_token();
}
break;
case 'price_rules':
// Same validator the Settings API uses, so both entry points
// enforce one definition of what a valid rule set is.
$rules = $this->sanitize_price_rules($settings);
update_option('dszsync_price_rules', $rules);
$this->price_sync->reload_rules();
break;
case 'stock_rules':
$rules = $this->sanitize_stock_rules($settings);
update_option('dszsync_stock_rules', $rules);
$this->stock_sync->reload_rules();
break;
case 'sync_settings':
// Carries the sync run state through unchanged; only the
// scheduling fields come from the request.
$current = $this->sanitize_sync_settings($settings);
update_option('dszsync_settings', $current);
// Reschedule cron
$this->cron->schedule_sync($current['frequency']);
if ($current['incremental_enabled']) {
$this->cron->schedule_incremental($current['incremental_frequency']);
} else {
$this->cron->unschedule_incremental();
}
break;
case 'import_settings':
$import_settings = $this->sanitize_import_settings($settings);
update_option('dszsync_import_settings', $import_settings);
break;
case 'orders':
update_option('dszsync_order_settings', [
'auto_submit' => !empty($settings['auto_submit']),
'tracking_autocomplete' => !empty($settings['tracking_autocomplete']),
], false);
break;
default:
wp_send_json_error(['message' => __('Invalid settings type', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
wp_send_json_success(['message' => __('Settings saved successfully', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
/**
* AJAX: Run sync
*/
public function ajax_run_sync() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$result = $this->cron->manual_sync();
wp_send_json_success($result);
}
/**
* AJAX: Get sync status
*/
public function ajax_get_sync_status() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$status = $this->cron->get_sync_status();
$status['progress'] = $this->cron->get_progress();
wp_send_json_success($status);
}
/**
* AJAX: Continue sync batch
*/
public function ajax_continue_sync() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$result = $this->cron->continue_batch();
wp_send_json_success($result);
}
/**
* AJAX: Dismiss the setup checklist for the current user.
*
* Stored per user rather than per site: on a multi-author store one
* person dismissing it should not hide it from everyone else.
*/
public function ajax_hide_setup() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
update_user_meta(get_current_user_id(), 'dszsync_hide_setup', 1);
wp_send_json_success();
}
/**
* AJAX: Clear logs
*/
public function ajax_clear_logs() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$this->logger->clear_logs();
wp_send_json_success(['message' => __('Logs cleared successfully', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
/**
* AJAX: Export logs
*/
public function ajax_export_logs() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$level = isset($_POST['level']) ? sanitize_text_field(wp_unslash($_POST['level'])) : '';
$csv = $this->logger->export_csv(['level' => $level]);
wp_send_json_success([
'csv' => base64_encode($csv),
'filename' => 'dsz-sync-logs-' . gmdate('Y-m-d') . '.csv',
]);
}
/**
* AJAX: Export product mappings as CSV
*/
public function ajax_export_mappings() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$mappings = $this->product_mapper->get_mappings(['limit' => 100000, 'offset' => 0]);
$rows = [
['wc_product_id', 'wc_product_name', 'dsz_sku', 'sync_enabled', 'last_synced', 'last_resynced', 'created_at'],
];
foreach ($mappings as $m) {
$rows[] = [
$m['wc_product_id'],
isset($m['wc_product_name']) ? $m['wc_product_name'] : '',
$m['dsz_sku'],
$m['sync_enabled'],
isset($m['last_synced']) ? $m['last_synced'] : '',
isset($m['last_resynced']) ? $m['last_resynced'] : '',
isset($m['created_at']) ? $m['created_at'] : '',
];
}
// Built as a string rather than via a stream: no filesystem access is
// involved, so WP_Filesystem is not applicable here.
$csv = '';
foreach ($rows as $row) {
$escaped = [];
foreach ($row as $field) {
$escaped[] = '"' . str_replace('"', '""', (string) $field) . '"';
}
$csv .= implode(',', $escaped) . "\r\n";
}
wp_send_json_success([
'csv' => base64_encode($csv),
'filename' => 'dsz-mappings-' . gmdate('Y-m-d') . '.csv',
]);
}
/**
* AJAX: Save advanced price rules (ordered, first match wins)
*/
public function ajax_save_advanced_price_rules() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
// Each rule field is sanitized individually in the loop below.
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized per field below
$raw_rules = isset($_POST['rules']) ? (array) wp_unslash($_POST['rules']) : [];
$clean = [];
foreach ($raw_rules as $rule) {
if (!is_array($rule)) {
continue;
}
$match_type = isset($rule['match_type']) ? sanitize_text_field($rule['match_type']) : '';
$match_value = isset($rule['match_value']) ? sanitize_text_field($rule['match_value']) : '';
if (!in_array($match_type, ['category', 'supplier', 'sku_prefix'], true) || $match_value === '') {
continue;
}
$clean[] = [
'name' => isset($rule['name']) ? sanitize_text_field($rule['name']) : '',
'match_type' => $match_type,
'match_value' => $match_value,
'markup_type' => (isset($rule['markup_type']) && $rule['markup_type'] === 'fixed') ? 'fixed' : 'percentage',
'markup_value' => isset($rule['markup_value']) ? floatval($rule['markup_value']) : 0,
];
if (count($clean) >= 50) {
break;
}
}
update_option('dszsync_price_rules_v2', ['rules' => $clean], false);
wp_send_json_success([
/* translators: %d: number of rules */
'message' => sprintf(__('Saved %d advanced price rules.', '3s-soft-price-stock-sync-for-dropshipzone'), count($clean)),
]);
}
/**
* AJAX: Save an import filter template
*/
public function ajax_save_import_template() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$name = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
// Each filter field is sanitized individually when the template is built.
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized per field below
$filters = isset($_POST['filters']) ? (array) wp_unslash($_POST['filters']) : [];
if ($name === '') {
wp_send_json_error(['message' => __('Template name is required.', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$templates = get_option('dszsync_import_templates', []);
if (!isset($templates[$name]) && count($templates) >= 20) {
wp_send_json_error(['message' => __('Template limit reached (20). Delete one first.', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$sort = isset($filters['sort']) ? sanitize_text_field($filters['sort']) : '';
$templates[$name] = [
'category' => isset($filters['category']) ? sanitize_text_field($filters['category']) : '',
'sort' => in_array($sort, ['', 'price_asc', 'price_desc'], true) ? $sort : '',
'in_stock' => !empty($filters['in_stock']),
'free_shipping' => !empty($filters['free_shipping']),
'promotion' => !empty($filters['promotion']),
'new_arrival' => !empty($filters['new_arrival']),
];
update_option('dszsync_import_templates', $templates, false);
wp_send_json_success([
'message' => __('Template saved.', '3s-soft-price-stock-sync-for-dropshipzone'),
'templates' => (object) $templates,
]);
}
/**
* AJAX: Delete an import filter template
*/
public function ajax_delete_import_template() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$name = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
$templates = get_option('dszsync_import_templates', []);
if (!isset($templates[$name])) {
wp_send_json_error(['message' => __('Template not found.', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
unset($templates[$name]);
update_option('dszsync_import_templates', $templates, false);
wp_send_json_success([
'message' => __('Template deleted.', '3s-soft-price-stock-sync-for-dropshipzone'),
'templates' => (object) $templates,
]);
}
/**
* Render Product Mapping page
*/
public function render_mapping() {
if (!dszsync_current_user_can_manage()) {
wp_die(esc_html__('You do not have permission to access this page.', '3s-soft-price-stock-sync-for-dropshipzone'));
}
if (!$this->product_mapper) {
echo '' . esc_html__('Product Mapper not initialized.', '3s-soft-price-stock-sync-for-dropshipzone') . '
';
return;
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only screen state (current page, filter, pagination); nothing is created, changed or deleted here.
$search = isset($_GET['search']) ? sanitize_text_field(wp_unslash($_GET['search'])) : '';
$resync_filter = isset($_GET['resync_filter']) ? sanitize_text_field(wp_unslash($_GET['resync_filter'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only filter state.
$page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only pagination state.
$per_page = 30;
$mappings = $this->product_mapper->get_mappings([
'search' => $search,
'resync_filter' => $resync_filter,
'limit' => $per_page,
'offset' => ($page - 1) * $per_page,
]);
$total = $this->product_mapper->get_count(['search' => $search, 'resync_filter' => $resync_filter]);
$total_pages = ceil($total / $per_page);
$unmapped_count = $this->product_mapper->get_unmapped_count();
$never_synced_count = $this->product_mapper->get_count(['resync_filter' => 'never']);
?>
render_header(__('Product Mapping', '3s-soft-price-stock-sync-for-dropshipzone'), __('Map your WooCommerce products to Dropshipzone SKUs', '3s-soft-price-stock-sync-for-dropshipzone')); ?>
__('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
if (strlen($search) < 2) {
wp_send_json_success(['products' => []]);
}
$products = $this->product_mapper->search_wc_products($search, 20);
wp_send_json_success(['products' => $products]);
}
/**
* AJAX: Search Dropshipzone products
*/
public function ajax_search_catalog_products() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
if (strlen($search) < 2) {
wp_send_json_success(['products' => []]);
}
// Search Dropshipzone API by SKU
$response = $this->api_client->get_products(['skus' => $search, 'limit' => 40]);
if (is_wp_error($response)) {
wp_send_json_error(['message' => $response->get_error_message()]);
}
$products = isset($response['result']) ? $response['result'] : [];
wp_send_json_success(['products' => $products]);
}
/**
* AJAX: Map product
*/
public function ajax_map_product() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$wc_product_id = isset($_POST['wc_product_id']) ? intval($_POST['wc_product_id']) : 0;
$dsz_sku = isset($_POST['dsz_sku']) ? sanitize_text_field(wp_unslash($_POST['dsz_sku'])) : '';
if (!$wc_product_id || !$dsz_sku) {
wp_send_json_error(['message' => __('Product ID and SKU are required', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$result = $this->product_mapper->map($wc_product_id, $dsz_sku);
if ($result) {
wp_send_json_success(['message' => __('Mapping created successfully', '3s-soft-price-stock-sync-for-dropshipzone')]);
} else {
wp_send_json_error(['message' => __('Failed to create mapping', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
}
/**
* AJAX: Unmap product
*/
public function ajax_unmap_product() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$wc_product_id = isset($_POST['wc_product_id']) ? intval($_POST['wc_product_id']) : 0;
if (!$wc_product_id) {
wp_send_json_error(['message' => __('Product ID is required', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$result = $this->product_mapper->unmap($wc_product_id);
if ($result) {
wp_send_json_success(['message' => __('Mapping removed successfully', '3s-soft-price-stock-sync-for-dropshipzone')]);
} else {
wp_send_json_error(['message' => __('Failed to remove mapping', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
}
/**
* AJAX: Auto-map products
*/
public function ajax_auto_map() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$results = $this->product_mapper->auto_map_by_sku();
wp_send_json_success([
'message' => sprintf(
/* translators: %1$d: mapped count, %2$d: skipped count */
__('Auto-mapping complete! %1$d products mapped, %2$d skipped.', '3s-soft-price-stock-sync-for-dropshipzone'),
$results['mapped'],
$results['skipped']
),
'mapped' => $results['mapped'],
'skipped' => $results['skipped'],
]);
}
/**
* Render Product Import page
*/
public function render_import() {
if (!dszsync_current_user_can_manage()) {
wp_die(esc_html__('You do not have permission to access this page.', '3s-soft-price-stock-sync-for-dropshipzone'));
}
?>
render_header(__('Product Import', '3s-soft-price-stock-sync-for-dropshipzone'), __('Discover and import products from Dropshipzone catalog', '3s-soft-price-stock-sync-for-dropshipzone')); ?>
__('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
// Get search parameters
$search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : '';
$category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0;
$in_stock = isset($_POST['in_stock']) && $_POST['in_stock'] === 'true';
$free_shipping = isset($_POST['free_shipping']) && $_POST['free_shipping'] === 'true';
$on_promotion = isset($_POST['on_promotion']) && $_POST['on_promotion'] === 'true';
$new_arrival = isset($_POST['new_arrival']) && $_POST['new_arrival'] === 'true';
$sort = isset($_POST['sort']) ? sanitize_text_field(wp_unslash($_POST['sort'])) : '';
// Allow empty search to browse all products (will be limited by API limit param)
// Build API query parameters
$api_params = [
'limit' => 100,
];
// Add filters
if ($category_id > 0) $api_params['category_id'] = $category_id;
if ($in_stock) $api_params['in_stock'] = true;
if ($free_shipping) $api_params['au_free_shipping'] = true;
if ($on_promotion) $api_params['on_promotion'] = true;
if ($new_arrival) $api_params['new_arrival'] = true;
if (!empty($sort)) {
if ($sort === 'price_asc') {
$api_params['sort_by'] = 'price';
$api_params['sort_order'] = 'asc';
} elseif ($sort === 'price_desc') {
$api_params['sort_by'] = 'price';
$api_params['sort_order'] = 'desc';
}
}
$products = [];
$last_error = null;
// If we have a search term, try it as both SKU and keywords
if (!empty($search)) {
// 1. Try exact SKU match with ALL filters applied
$sku_params = $api_params;
$sku_params['skus'] = $search;
$sku_params['limit'] = 40; // API minimum limit
$sku_response = $this->api_client->get_products($sku_params);
if (is_wp_error($sku_response)) {
$last_error = $sku_response;
} elseif (!empty($sku_response['result'])) {
$products = $sku_response['result'];
}
// 2. If no SKU results (or we want to find similar items via keywords), use keyword search
if (empty($products)) {
$keyword_params = $api_params;
$keyword_params['keywords'] = str_replace([' ', '+'], ',', trim($search));
$response = $this->api_client->get_products($keyword_params);
if (is_wp_error($response)) {
$last_error = $response;
} elseif (!empty($response['result'])) {
$products = $response['result'];
}
}
} else {
// No search term, just use filters (browse mode)
$response = $this->api_client->get_products($api_params);
if (is_wp_error($response)) {
$last_error = $response;
} elseif (!empty($response['result'])) {
$products = $response['result'];
}
}
// Belt-and-braces for the In Stock filter: the API result is trimmed
// here as well. This used to run unconditionally, which both hid
// out-of-stock products from anyone browsing without the filter and
// masked the fact that in_stock was never being sent to the API.
if ($in_stock && !empty($products)) {
$products = array_filter($products, function($product) {
$stock_qty = isset($product['stock_qty']) ? intval($product['stock_qty']) : 0;
return $stock_qty > 0;
});
$products = array_values($products); // Re-index array
}
if (empty($products)) {
if ($last_error) {
wp_send_json_error(['message' => $last_error->get_error_message()]);
}
$message = __('No products found.', '3s-soft-price-stock-sync-for-dropshipzone');
if (!empty($search)) {
$message .= ' ' . __('Try different keywords or adjust filters.', '3s-soft-price-stock-sync-for-dropshipzone');
} else {
$message .= ' ' . __('Try adjusting your filters.', '3s-soft-price-stock-sync-for-dropshipzone');
}
wp_send_json_error(['message' => $message]);
}
// Pre-check if products are already mapped/imported
foreach ($products as &$product) {
$wc_product_id = wc_get_product_id_by_sku($product['sku']);
$product['is_imported'] = !empty($wc_product_id);
$product['wc_product_id'] = $wc_product_id ? $wc_product_id : null;
}
// Build response with metadata
$response_data = [
'products' => $products,
'total' => count($products),
'filters_applied' => array_filter([
'search' => $search ?: null,
'category_id' => $category_id ?: null,
'in_stock' => $in_stock ?: null,
'free_shipping' => $free_shipping ?: null,
'on_promotion' => $on_promotion ?: null,
'new_arrival' => $new_arrival ?: null,
'sort' => $sort ?: null,
]),
];
wp_send_json_success($response_data);
}
/**
* AJAX: Get categories from API
*/
public function ajax_get_categories() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$response = $this->api_client->get_categories();
if (is_wp_error($response)) {
$this->logger->error('Failed to fetch categories', [
'error' => $response->get_error_message(),
]);
wp_send_json_error(['message' => $response->get_error_message()]);
}
// Handle both direct array and result-wrapped response
$categories = [];
if (is_array($response)) {
if (isset($response['result']) && is_array($response['result'])) {
$categories = $response['result'];
} elseif (isset($response['categories']) && is_array($response['categories'])) {
$categories = $response['categories'];
} elseif (!isset($response['result']) && !isset($response['categories'])) {
// Response might be the categories array directly
$categories = $response;
}
}
if (empty($categories)) {
$this->logger->warning('No categories returned from API');
wp_send_json_error(['message' => __('No categories found from API.', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$this->logger->info('Categories loaded', ['count' => count($categories)]);
// Return the flat list of categories
wp_send_json_success(['categories' => $categories]);
}
/**
* AJAX: Import product
*/
public function ajax_import_product() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$sku = isset($_POST['sku']) ? sanitize_text_field(wp_unslash($_POST['sku'])) : '';
if (!$sku) {
wp_send_json_error(['message' => __('SKU is required', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
// Product data may be posted back from cached search results to avoid
// a second API call. It is client-supplied, so sanitize it fully.
$product_data = null;
if (!empty($_POST['product_data'])) {
$decoded = json_decode(wp_unslash($_POST['product_data']), true); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized below
if (is_array($decoded)) {
$product_data = dszsync_sanitize_api_product($decoded);
}
}
// If we have product data from search, use it directly; otherwise fetch by SKU
if ($product_data && isset($product_data['sku']) && $product_data['sku'] === $sku) {
$result = $this->product_importer->import_product($product_data);
} else {
$result = $this->product_importer->import_product($sku);
}
if (is_wp_error($result)) {
wp_send_json_error(['message' => $result->get_error_message()]);
}
wp_send_json_success([
'message' => __('Product imported successfully!', '3s-soft-price-stock-sync-for-dropshipzone'),
'product_id' => $result,
'edit_url' => get_edit_post_link($result, 'url')
]);
}
/**
* AJAX: Resync existing product from Dropshipzone API
*/
public function ajax_resync_product() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
$sku = isset($_POST['sku']) ? sanitize_text_field(wp_unslash($_POST['sku'])) : '';
if (!$product_id && !$sku) {
wp_send_json_error(['message' => __('Product ID or SKU is required', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
// If we only have SKU, try to find the product ID
if (!$product_id && $sku) {
$product_id = wc_get_product_id_by_sku($sku);
if (!$product_id) {
wp_send_json_error(['message' => __('Product not found in WooCommerce', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
}
// Get resync options from request
$options = [];
if (isset($_POST['update_images'])) {
$options['update_images'] = filter_var(wp_unslash($_POST['update_images']), FILTER_VALIDATE_BOOLEAN);
}
if (isset($_POST['update_description'])) {
$options['update_description'] = filter_var(wp_unslash($_POST['update_description']), FILTER_VALIDATE_BOOLEAN);
}
if (isset($_POST['update_price'])) {
$options['update_price'] = filter_var(wp_unslash($_POST['update_price']), FILTER_VALIDATE_BOOLEAN);
}
if (isset($_POST['update_stock'])) {
$options['update_stock'] = filter_var(wp_unslash($_POST['update_stock']), FILTER_VALIDATE_BOOLEAN);
}
if (isset($_POST['update_title'])) {
$options['update_title'] = filter_var(wp_unslash($_POST['update_title']), FILTER_VALIDATE_BOOLEAN);
}
// Product data may be posted back from cached search results to avoid
// a second API call. It is client-supplied, so sanitize it fully.
$product_data = null;
if (!empty($_POST['product_data'])) {
$decoded = json_decode(wp_unslash($_POST['product_data']), true); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized on the next line
if (is_array($decoded)) {
$product_data = dszsync_sanitize_api_product($decoded);
}
}
// Perform resync
$result = $this->product_importer->resync_product($product_id, $product_data, $options);
if (is_wp_error($result)) {
wp_send_json_error(['message' => $result->get_error_message()]);
}
wp_send_json_success([
'message' => __('Product resynced successfully!', '3s-soft-price-stock-sync-for-dropshipzone'),
'product_id' => $result,
'edit_url' => get_edit_post_link($result, 'url')
]);
}
/**
* Fetch API data for a chunk of mappings and resync each product.
*
* Chunks are bounded (≤100) so this issues a single API request.
*
* @param array $mappings Mapping rows (wc_product_id, dsz_sku)
* @param array $options Resync options passed to Product_Importer::resync_product()
* @return array|\WP_Error ['success' => int, 'errors' => int, 'error_details' => string[]]
*/
private function resync_mapping_chunk($mappings, $options) {
$skus = array_column($mappings, 'dsz_sku');
$response = $this->api_client->get_products_by_skus($skus);
if (is_wp_error($response)) {
return $response;
}
$api_products = [];
if (!empty($response['result'])) {
foreach ($response['result'] as $product_data) {
if (!empty($product_data['sku'])) {
$api_products[$product_data['sku']] = $product_data;
}
}
}
$success = 0;
$errors = 0;
$error_details = [];
foreach ($mappings as $mapping) {
$product_id = $mapping['wc_product_id'];
$sku = $mapping['dsz_sku'];
if (!isset($api_products[$sku])) {
$errors++;
$error_details[] = sprintf('%s: %s', $sku, __('Not found in Dropshipzone API', '3s-soft-price-stock-sync-for-dropshipzone'));
continue;
}
$result = $this->product_importer->resync_product($product_id, $api_products[$sku], $options);
if (is_wp_error($result)) {
$errors++;
$error_details[] = sprintf('%s: %s', $sku, $result->get_error_message());
} else {
$success++;
}
if (dszsync_is_memory_near_limit(85)) {
$this->logger->warning('Memory limit approaching, stopping chunk early');
break;
}
}
return [
'success' => $success,
'errors' => $errors,
'error_details' => $error_details,
];
}
/**
* Send a chunk-processing error, passing retry_after through so the
* client can wait out a rate limit and retry the same chunk.
*
* @param \WP_Error $error Error from the API client
*/
private function send_chunk_error($error) {
$payload = ['message' => $error->get_error_message()];
$data = $error->get_error_data();
if (is_array($data) && !empty($data['retry_after'])) {
$payload['retry_after'] = intval($data['retry_after']);
}
wp_send_json_error($payload);
}
/**
* AJAX: Resync all mapped products (one bounded chunk per request)
*
* The client passes `offset` and keeps calling until `done` is true, so
* large catalogs never hit PHP max_execution_time in a single request.
* Products that are already inactive (draft + out of stock) are skipped.
*/
public function ajax_resync_all() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$offset = isset($_POST['offset']) ? absint($_POST['offset']) : 0;
$chunk_size = 20; // Small: full resync downloads images per product
$total = $this->product_mapper->get_count();
if ($total === 0) {
wp_send_json_error(['message' => __('No mapped products found to resync.', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$mappings = $this->product_mapper->get_mappings([
'limit' => $chunk_size,
'offset' => $offset,
]);
if (empty($mappings)) {
wp_send_json_success([
'done' => true,
'next_offset' => $offset,
'total' => $total,
'processed' => 0,
'success' => 0,
'errors' => 0,
'skipped_inactive' => 0,
'error_details' => [],
]);
}
// Filter out products that are already inactive (draft + out of stock)
$active_mappings = [];
$skipped_inactive = 0;
foreach ($mappings as $mapping) {
$product = wc_get_product(intval($mapping['wc_product_id']));
if (!$product) {
$skipped_inactive++;
continue;
}
if ($product->get_status() === 'draft'
&& ($product->get_stock_quantity() <= 0 || $product->get_stock_status() === 'outofstock')) {
$skipped_inactive++;
continue;
}
$active_mappings[] = $mapping;
}
$result = ['success' => 0, 'errors' => 0, 'error_details' => []];
if (!empty($active_mappings)) {
$result = $this->resync_mapping_chunk($active_mappings, [
'update_price' => true,
'update_stock' => true,
'update_images' => true,
'update_description' => true,
'update_title' => true,
'update_categories' => true,
]);
if (is_wp_error($result)) {
$this->send_chunk_error($result);
}
}
$next_offset = $offset + count($mappings);
$done = (count($mappings) < $chunk_size) || ($next_offset >= $total);
$this->logger->info('Resync all chunk complete', [
'offset' => $offset,
'processed' => count($mappings),
'success' => $result['success'],
'errors' => $result['errors'],
'skipped_inactive' => $skipped_inactive,
'done' => $done,
]);
wp_send_json_success([
'done' => $done,
'next_offset' => $next_offset,
'total' => $total,
'processed' => count($mappings),
'success' => $result['success'],
'errors' => $result['errors'],
'skipped_inactive' => $skipped_inactive,
'error_details' => array_slice($result['error_details'], 0, 10),
]);
}
/**
* AJAX handler for resyncing ONLY product images
*/
public function ajax_resync_images() {
$this->resync_specific('images');
}
/**
* AJAX handler for resyncing ONLY product categories
*/
public function ajax_resync_categories() {
$this->resync_specific('categories');
}
/**
* Shared handler for specific resync types (images or categories)
*
* @param string $type 'images' or 'categories'
*/
private function resync_specific($type) {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$offset = isset($_POST['offset']) ? absint($_POST['offset']) : 0;
// Image refresh downloads files per product; categories are cheap
$chunk_size = ($type === 'images') ? 20 : 50;
$total = $this->product_mapper->get_count();
if ($total === 0) {
wp_send_json_error(['message' => __('No mapped products found.', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$mappings = $this->product_mapper->get_mappings([
'limit' => $chunk_size,
'offset' => $offset,
]);
if (empty($mappings)) {
wp_send_json_success([
'done' => true,
'next_offset' => $offset,
'total' => $total,
'processed' => 0,
'success' => 0,
'errors' => 0,
'error_details' => [],
]);
}
$result = $this->resync_mapping_chunk($mappings, [
'update_images' => ($type === 'images'),
'update_categories' => ($type === 'categories'),
'update_description' => false,
'update_price' => false,
'update_stock' => false,
'update_title' => false,
]);
if (is_wp_error($result)) {
$this->send_chunk_error($result);
}
$next_offset = $offset + count($mappings);
$done = (count($mappings) < $chunk_size) || ($next_offset >= $total);
$this->logger->info($type . ' resync chunk complete', [
'offset' => $offset,
'processed' => count($mappings),
'success' => $result['success'],
'errors' => $result['errors'],
'done' => $done,
]);
wp_send_json_success([
'done' => $done,
'next_offset' => $next_offset,
'total' => $total,
'processed' => count($mappings),
'success' => $result['success'],
'errors' => $result['errors'],
'error_details' => array_slice($result['error_details'], 0, 10),
]);
}
/**
* AJAX handler for resyncing products that have never been synced
*
* Processes one bounded chunk per request. Successfully synced products
* leave the "never" set (last_resynced gets stamped), so the client passes
* its cumulative error count as `offset` to step past persistent failures.
*/
public function ajax_resync_never_synced() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$offset = isset($_POST['offset']) ? absint($_POST['offset']) : 0;
$chunk_size = 50; // Price/stock only — no image downloads
$never_synced = $this->product_mapper->get_mappings([
'resync_filter' => 'never',
'limit' => $chunk_size,
'offset' => $offset,
]);
if (empty($never_synced)) {
wp_send_json_success([
'done' => true,
'processed' => 0,
'success' => 0,
'errors' => 0,
'error_details' => [],
]);
}
$result = $this->resync_mapping_chunk($never_synced, [
'update_title' => false,
'update_description' => false,
'update_images' => false,
'update_price' => true,
'update_stock' => true,
]);
if (is_wp_error($result)) {
$this->send_chunk_error($result);
}
$done = count($never_synced) < $chunk_size;
$this->logger->info('Never-synced resync chunk complete', [
'offset' => $offset,
'processed' => count($never_synced),
'success' => $result['success'],
'errors' => $result['errors'],
'done' => $done,
]);
wp_send_json_success([
'done' => $done,
'processed' => count($never_synced),
'success' => $result['success'],
'errors' => $result['errors'],
'error_details' => array_slice($result['error_details'], 0, 10),
]);
}
/**
* AJAX handler for scanning unmapped products against Dropshipzone API
*
* Checks if unmapped WC products exist in DSZ:
* - Found: creates mapping and resyncs
* - Not found: marks as non-DSZ product (_dszsync_not_available meta)
*/
public function ajax_scan_unmapped_products() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
// Get WC products that are NOT in our mapping table and not already
// flagged as non-DSZ. Processing consumes the set (products get mapped
// or flagged), so each request re-queries from the top — the client
// keeps calling until `done` is true.
global $wpdb;
$mapping_table = $wpdb->prefix . 'dsz_product_mapping';
$chunk_size = 50;
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.SlowDBQuery.slow_db_query_meta_key, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name is built from $wpdb->prefix and is not user input; all values are passed through prepare(). These are plugin-owned tables, so no core caching API applies.
$unmapped_products = $wpdb->get_results(
$wpdb->prepare(
"SELECT p.ID, pm.meta_value as sku
FROM {$wpdb->posts} p
INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_sku'
LEFT JOIN %i m ON p.ID = m.wc_product_id
LEFT JOIN {$wpdb->postmeta} pm2 ON p.ID = pm2.post_id AND pm2.meta_key = '_dszsync_not_available'
WHERE p.post_type IN ('product', 'product_variation')
AND p.post_status != 'trash'
AND pm.meta_value != ''
AND m.id IS NULL
AND pm2.post_id IS NULL
ORDER BY p.ID DESC
LIMIT %d",
$mapping_table,
$chunk_size
),
ARRAY_A
);
if (empty($unmapped_products)) {
wp_send_json_success([
'message' => __('No unmapped products to scan.', '3s-soft-price-stock-sync-for-dropshipzone'),
'done' => true,
'found' => 0,
'not_found' => 0,
]);
return;
}
$this->logger->info('Starting unmapped product scan', [
'products_to_scan' => count($unmapped_products),
]);
// Collect all SKUs for batch API lookup
$all_skus = [];
$sku_to_product = [];
foreach ($unmapped_products as $product) {
$sku = trim($product['sku']);
if (!empty($sku)) {
$all_skus[] = $sku;
$sku_to_product[$sku] = intval($product['ID']);
}
}
// Batch fetch from API (100 SKUs at a time)
$api_products = [];
$sku_chunks = array_chunk($all_skus, 100);
foreach ($sku_chunks as $chunk_index => $chunk) {
$this->logger->debug('Scanning API batch', [
'batch' => $chunk_index + 1,
'total_batches' => count($sku_chunks),
'skus_in_batch' => count($chunk),
]);
$response = $this->api_client->get_products_by_skus($chunk);
if (is_wp_error($response)) {
$this->logger->error('Scan batch fetch failed', [
'batch' => $chunk_index + 1,
'error' => $response->get_error_message(),
]);
continue;
}
if (!empty($response['result'])) {
foreach ($response['result'] as $product_data) {
if (!empty($product_data['sku'])) {
$api_products[$product_data['sku']] = $product_data;
}
}
}
}
$this->logger->info('Scan API fetch complete', [
'requested_skus' => count($all_skus),
'found_in_dsz' => count($api_products),
]);
$found_count = 0;
$not_found_count = 0;
$errors = [];
// Process each unmapped product
foreach ($all_skus as $sku) {
$product_id = $sku_to_product[$sku];
if (isset($api_products[$sku])) {
// Product FOUND in Dropshipzone - create mapping and resync
$api_data = $api_products[$sku];
// Create mapping
$title = isset($api_data['title']) ? $api_data['title'] : '';
$mapping_result = $this->product_mapper->map($product_id, $sku, $title);
if ($mapping_result) {
// Clear any previous "not available" flag
delete_post_meta($product_id, '_dszsync_not_available');
// Resync the product with DSZ data
$this->product_importer->resync_product($product_id, $api_data, [
'update_price' => true,
'update_stock' => true,
'update_images' => false, // Don't replace user's images
'update_description' => false, // Don't replace user's description
'update_title' => false, // Don't replace user's title
]);
$found_count++;
$this->logger->info('Unmapped product linked to DSZ', [
'product_id' => $product_id,
'sku' => $sku,
]);
} else {
$errors[] = sprintf('%s: %s', $sku, __('Failed to create mapping', '3s-soft-price-stock-sync-for-dropshipzone'));
}
} else {
// Product NOT FOUND in Dropshipzone - mark as non-DSZ product
update_post_meta($product_id, '_dszsync_not_available', '1');
$not_found_count++;
$this->logger->debug('Product marked as non-DSZ', [
'product_id' => $product_id,
'sku' => $sku,
]);
}
// Memory check
if (dszsync_is_memory_near_limit(85)) {
$this->logger->warning('Memory limit approaching, stopping scan early', [
'processed' => $found_count + $not_found_count,
'total' => count($all_skus),
]);
break;
}
}
$message = sprintf(
/* translators: %1$d: found count, %2$d: not found count */
__('Scan complete! %1$d products linked to Dropshipzone, %2$d marked as non-DSZ products.', '3s-soft-price-stock-sync-for-dropshipzone'),
$found_count,
$not_found_count
);
$this->logger->info('Unmapped product scan chunk complete', [
'total_scanned' => count($all_skus),
'found' => $found_count,
'not_found' => $not_found_count,
]);
// Done when the set is exhausted, or nothing progressed (mapping
// failures would otherwise be re-selected forever)
$done = (count($unmapped_products) < $chunk_size)
|| (($found_count + $not_found_count) === 0);
wp_send_json_success([
'message' => $message,
'done' => $done,
'found' => $found_count,
'not_found' => $not_found_count,
'errors' => array_slice($errors, 0, 10),
]);
}
/**
* AJAX handler for submitting order to Dropshipzone
*/
public function ajax_submit_order() {
check_ajax_referer('dszsync_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied.', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;
if (!$order_id) {
wp_send_json_error(['message' => __('Order ID required.', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
if (!$this->order_handler) {
wp_send_json_error(['message' => __('Order handler not initialized.', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$result = $this->order_handler->submit_order($order_id);
if (is_wp_error($result)) {
wp_send_json_error(['message' => $result->get_error_message()]);
}
wp_send_json_success($result);
}
/**
* AJAX: Submit pending (paid, unsubmitted) orders to DSZ — one chunk
* per request; the client keeps calling until `done`.
*/
public function ajax_submit_pending_orders() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
if (!$this->order_handler) {
wp_send_json_error(['message' => __('Order handler not initialized.', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$chunk_size = 5;
$pending = $this->order_handler->get_pending_order_ids($chunk_size);
if (empty($pending)) {
wp_send_json_success([
'done' => true,
'submitted' => 0,
'errors' => 0,
'error_details' => [],
]);
}
$submitted = 0;
$errors = 0;
$error_details = [];
foreach ($pending as $order_id) {
$result = $this->order_handler->submit_order($order_id);
if (is_wp_error($result)) {
if ($result->get_error_code() === 'rate_limited') {
$data = $result->get_error_data();
wp_send_json_error([
'message' => $result->get_error_message(),
'retry_after' => is_array($data) && !empty($data['retry_after']) ? intval($data['retry_after']) : 30,
]);
}
$errors++;
$error_details[] = sprintf('#%d: %s', $order_id, $result->get_error_message());
} else {
$submitted++;
}
}
// Failed orders stay pending, so stop when a whole chunk produced no
// submissions to avoid looping over the same failures forever
$done = (count($pending) < $chunk_size) || ($submitted === 0);
wp_send_json_success([
'done' => $done,
'submitted' => $submitted,
'errors' => $errors,
'error_details' => array_slice($error_details, 0, 10),
]);
}
/**
* AJAX: Run the tracking sync on demand
*/
public function ajax_run_tracking_sync() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
if (!$this->order_handler) {
wp_send_json_error(['message' => __('Order handler not initialized.', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$results = $this->order_handler->sync_tracking();
wp_send_json_success([
/* translators: %1$d: orders checked, %2$d: orders updated */
'message' => sprintf(__('Tracking checked for %1$d orders, %2$d updated.', '3s-soft-price-stock-sync-for-dropshipzone'), $results['checked'], $results['updated']),
'results' => $results,
]);
}
/**
* Register the orders-list bulk action
*
* @param array $actions Bulk actions
* @return array
*/
public function register_order_bulk_action($actions) {
$actions['dszsync_submit_orders'] = __('Submit to Dropshipzone', '3s-soft-price-stock-sync-for-dropshipzone');
return $actions;
}
/**
* Handle the orders-list bulk action
*
* @param string $redirect Redirect URL
* @param string $action Action name
* @param array $ids Selected order IDs
* @return string Redirect URL with result args
*/
public function handle_order_bulk_action($redirect, $action, $ids) {
if ($action !== 'dszsync_submit_orders' || !$this->order_handler) {
return $redirect;
}
$submitted = 0;
$errors = 0;
foreach (array_slice((array) $ids, 0, 25) as $order_id) {
$result = $this->order_handler->submit_order(intval($order_id));
if (is_wp_error($result)) {
$errors++;
} else {
$submitted++;
}
}
return add_query_arg([
'dszsync_bulk_submitted' => $submitted,
'dszsync_bulk_errors' => $errors,
], $redirect);
}
/**
* Show the result notice after the bulk submit action
*/
public function order_bulk_action_notice() {
if (!isset($_GET['dszsync_bulk_submitted'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
return;
}
$submitted = intval($_GET['dszsync_bulk_submitted']); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$errors = isset($_GET['dszsync_bulk_errors']) ? intval($_GET['dszsync_bulk_errors']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
printf(
'',
esc_attr($errors > 0 ? 'warning' : 'success'),
esc_html(sprintf(
/* translators: %1$d: submitted count, %2$d: error count */
__('Dropshipzone: %1$d orders submitted, %2$d failed (see order notes / logs).', '3s-soft-price-stock-sync-for-dropshipzone'),
$submitted,
$errors
))
);
}
/**
* Add the DSZ margin column to the products list
*
* @param array $columns Columns
* @return array
*/
public function add_product_margin_column($columns) {
$columns['dszsync_margin'] = __('DSZ Margin', '3s-soft-price-stock-sync-for-dropshipzone');
return $columns;
}
/**
* Render the DSZ margin column value
*
* @param string $column Column key
* @param int $post_id Product ID
*/
public function render_product_margin_column($column, $post_id) {
if ($column !== 'dszsync_margin') {
return;
}
$product = wc_get_product($post_id);
if (!$product) {
return;
}
$cost = $product->get_meta('_dszsync_cost');
if ($cost === '' || $cost === null) {
echo '— ';
return;
}
$price = floatval($product->get_price());
$margin = $price - floatval($cost);
printf(
'%2$s ',
esc_attr($margin >= 0 ? 'dsz-text-success' : 'dsz-text-error'),
wp_kses_post(wc_price($margin))
);
}
/**
* Add meta box to WooCommerce order page
*/
public function add_order_meta_box() {
$screen = 'shop_order';
if (class_exists(\Automattic\WooCommerce\Utilities\OrderUtil::class) && \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled()) {
$screen = wc_get_page_screen_id('shop-order');
} elseif (function_exists('wc_get_container') && class_exists(\Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController::class)) {
try {
if (wc_get_container()->get(\Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController::class)->custom_orders_table_usage_is_enabled()) {
$screen = wc_get_page_screen_id('shop-order');
}
} catch (\Throwable $e) {
$screen = 'shop_order';
}
}
add_meta_box(
'dsz-order-meta-box',
__('Dropshipzone Order', '3s-soft-price-stock-sync-for-dropshipzone'),
[$this, 'render_order_meta_box'],
$screen,
'side',
'high'
);
}
/**
* Render order meta box content
*
* @param WP_Post|WC_Order $post_or_order Post or Order object
*/
public function render_order_meta_box($post_or_order) {
// Get order object (HPOS compatible)
$order = $post_or_order instanceof \WP_Post ? wc_get_order($post_or_order->ID) : $post_or_order;
if (!$order) {
echo '' . esc_html__('Order not found.', '3s-soft-price-stock-sync-for-dropshipzone') . '
';
return;
}
$order_id = $order->get_id();
// Check if order has DSZ products
if (!$this->order_handler) {
echo '' . esc_html__('Order handler not available.', '3s-soft-price-stock-sync-for-dropshipzone') . '
';
return;
}
$has_dszsync_products = $this->order_handler->order_has_dszsync_products($order_id);
if (!$has_dszsync_products) {
echo '' . esc_html__('No Dropshipzone products in this order.', '3s-soft-price-stock-sync-for-dropshipzone') . '
';
return;
}
// Get DSZ order info
$dszsync_order = $this->order_handler->get_dszsync_order($order_id);
$dszsync_serial = $order->get_meta('_dszsync_serial_number');
wp_nonce_field('dszsync_nonce', 'dszsync_order_nonce');
?>
get_meta('_dszsync_tracking_number'); ?>
get_meta('_dszsync_courier'); ?>
get_items() as $profit_item) {
$profit_product = $profit_item->get_product();
if (!$profit_product || !$this->product_mapper || !$this->product_mapper->get_dsz_sku($profit_product->get_id())) {
continue;
}
$profit_revenue += floatval($profit_item->get_total());
$cost_meta = $profit_product->get_meta('_dszsync_cost');
if ($cost_meta === '' || $cost_meta === null) {
$profit_known = false;
}
$profit_cost += floatval($cost_meta) * $profit_item->get_quantity();
}
?>
0): ?>
auto_importer ? $this->auto_importer->get_settings() : [];
$status = $this->auto_importer ? $this->auto_importer->get_status() : [];
$next_scheduled = $this->auto_importer ? $this->auto_importer->get_next_scheduled() : false;
?>
render_header(__('Auto Import', '3s-soft-price-stock-sync-for-dropshipzone'), __('Automatically import new products from Dropshipzone', '3s-soft-price-stock-sync-for-dropshipzone')); ?>
__('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
if (!$this->auto_importer) {
wp_send_json_error(['message' => __('Auto importer not initialized', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
// Temporarily enable for manual run
$settings = $this->auto_importer->get_settings();
$was_enabled = $settings['enabled'];
if (!$was_enabled) {
$settings['enabled'] = true;
$this->auto_importer->save_settings($settings);
}
$result = $this->auto_importer->run_import();
// Restore original setting
if (!$was_enabled) {
$settings['enabled'] = false;
$this->auto_importer->save_settings($settings);
}
wp_send_json_success([
'message' => $result['message'],
'imported' => $result['imported'],
'skipped' => $result['skipped'],
'errors' => $result['errors'],
]);
}
/**
* AJAX handler: Save auto import settings
*/
public function ajax_save_auto_import_settings() {
check_ajax_referer('dszsync_admin_nonce', 'nonce');
if (!dszsync_current_user_can_manage()) {
wp_send_json_error(['message' => __('Permission denied', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
if (!$this->auto_importer) {
wp_send_json_error(['message' => __('Auto importer not initialized', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
$settings = [
'enabled' => !empty($_POST['enabled']),
'frequency' => isset($_POST['frequency']) ? sanitize_text_field(wp_unslash($_POST['frequency'])) : 'daily',
'max_products_per_run' => isset($_POST['max_products_per_run']) ? intval($_POST['max_products_per_run']) : 50,
'min_stock_qty' => isset($_POST['min_stock_qty']) ? intval($_POST['min_stock_qty']) : 10,
'default_product_status'=> isset($_POST['default_product_status']) ? sanitize_text_field(wp_unslash($_POST['default_product_status'])) : 'publish',
'filter_new_arrival' => !empty($_POST['filter_new_arrival']),
'filter_in_stock' => !empty($_POST['filter_in_stock']),
'filter_free_shipping' => !empty($_POST['filter_free_shipping']),
'filter_on_promotion' => !empty($_POST['filter_on_promotion']),
'filter_nz_available' => !empty($_POST['filter_nz_available']),
'exclude_supplier_ids' => isset($_POST['exclude_supplier_ids']) ? sanitize_text_field(wp_unslash($_POST['exclude_supplier_ids'])) : '',
];
$this->auto_importer->save_settings($settings);
// Update cron schedule
if ($settings['enabled']) {
$this->auto_importer->schedule_import($settings['frequency']);
} else {
$this->auto_importer->unschedule_import();
}
wp_send_json_success(['message' => __('Settings saved successfully', '3s-soft-price-stock-sync-for-dropshipzone')]);
}
}