'permission_denied'), 403); } check_ajax_referer('aieo_trs_admin', 'nonce'); } public static function ajax_list() { self::gate(); $instance_id = (int) (sanitize_text_field( wp_unslash( $_REQUEST['instance_id'] ) ) ?? 0); if ($instance_id <= 0) { wp_send_json_success(array('rules' => array(), 'classes' => self::shipping_classes())); } $rows = AIEO_TRS_Rules::get_for_instance($instance_id); $classes = self::shipping_classes(); $table = self::rules_table(is_array($rows) ? $rows : array(), $classes); wp_send_json_success(array( 'rules' => $rows, 'classes' => $classes, 'table' => $table, 'icons' => '' !== $table ? \Rooster\Admin\Ui::icons_of($table) : '', )); } public static function rules_table(array $rules, array $classes) { if (!function_exists('rooster_admin_builders') || !rooster_admin_builders()) { return ''; } $weight_unit = (string) get_option('woocommerce_weight_unit', 'kg'); $symbol = function_exists('get_woocommerce_currency_symbol') ? html_entity_decode((string) get_woocommerce_currency_symbol(), ENT_QUOTES | ENT_HTML5, 'UTF-8') : (string) get_option('woocommerce_currency', ''); $pos = (string) get_option('woocommerce_currency_pos', 'left'); $num = static function ($n) { if (null === $n || '' === $n || !is_numeric($n)) { return ''; } return rtrim(rtrim(number_format((float) $n, 4, '.', ''), '0'), '.'); }; $money = static function ($n) use ($num, $symbol, $pos) { $s = $num($n); if ('' === $s) { return ''; } if (function_exists('wc_price')) { $own = false === strpos($s, '.') ? 0 : strlen($s) - strpos($s, '.') - 1; return trim(html_entity_decode(wp_strip_all_tags(wc_price((float) $n, array('decimals' => max((int) wc_get_price_decimals(), $own)))), ENT_QUOTES | ENT_HTML5, 'UTF-8')); } switch ($pos) { case 'right': return $s . $symbol; case 'right_space': return $s . ' ' . $symbol; case 'left': return $symbol . $s; default: return $symbol . ' ' . $s; } }; $names = array(); foreach ($classes as $c) { $names[(string) $c['slug']] = (string) $c['name']; } $class_label = static function ($slug) use ($names) { $slug = null === $slug ? '' : (string) $slug; if ('' === $slug) { return __('Any class', 'ai-eshop-optimizer'); } if ('0' === $slug) { return __('No class', 'ai-eshop-optimizer'); } return isset($names[$slug]) ? $names[$slug] : $slug; }; $conds = array( 'price' => __('Subtotal', 'ai-eshop-optimizer'), 'weight' => __('Weight', 'ai-eshop-optimizer'), 'items' => __('Items', 'ai-eshop-optimizer'), 'items_in_class' => __('Items in class', 'ai-eshop-optimizer'), ); $range = static function ($r) use ($num, $money, $conds, $symbol, $weight_unit) { $cond = (string) ($r['rate_condition'] ?? ''); $unit = 'weight' === $cond ? $weight_unit : ''; $label = '' === $cond ? __('Always matches', 'ai-eshop-optimizer') : ($conds[$cond] ?? $cond); $lo = 'price' === $cond ? $money($r['rate_min'] ?? null) : $num($r['rate_min'] ?? null); $hi = 'price' === $cond ? $money($r['rate_max'] ?? null) : $num($r['rate_max'] ?? null); $tail = '' !== $unit ? ' ' . $unit : ''; if ('' === $lo && '' === $hi) { return $label; } if ('' !== $lo && '' !== $hi) { return $label . ': ' . $lo . '–' . $hi . $tail; } return '' !== $lo ? $label . ' ≥ ' . $lo . $tail : $label . ' ≤ ' . $hi . $tail; }; $extras = static function ($r) use ($num, $money, $conds, $weight_unit) { $bits = array(); $pi = $num($r['rate_cost_per_item'] ?? null); $pw = $num($r['rate_cost_per_weight_unit'] ?? null); $pc = $num($r['rate_cost_percent'] ?? null); if ('' !== $pi && 0.0 !== (float) $pi) { $bits[] = '+' . $money($pi) . '/' . strtok(mb_strtolower($conds['items']), ' '); } if ('' !== $pw && 0.0 !== (float) $pw) { $bits[] = '+' . $money($pw) . '/' . $weight_unit; } if ('' !== $pc && 0.0 !== (float) $pc) { $bits[] = '+' . $pc . '% ' . mb_strtolower($conds['price']); } return $bits ? implode(' ', $bits) : '—'; }; $ui = '\Rooster\Admin\Ui'; $rows = array(); foreach (array_values($rules) as $i => $r) { $r = (array) $r; $id = (int) ($r['id'] ?? 0); $class = $class_label($r['rate_class'] ?? ''); $rule = $range($r); $marks = (1 === (int) ($r['rate_priority'] ?? 0) ? ' ' . $ui::badge(__('Stop after match', 'ai-eshop-optimizer'), 'warning', array('sm' => true)) : '') . (1 === (int) ($r['rate_abort'] ?? 0) ? ' ' . $ui::badge(__('Abort method', 'ai-eshop-optimizer'), 'destructive', array('sm' => true)) : ''); $label = (string) ($r['rate_label'] ?? ''); $extra = $extras($r); $rows[] = array( '_id' => (string) $id, '_name' => $class . ', ' . $rule, '_attrs' => array( 'data-ra-s' => array( 'ord' => $i + 1, 'class' => $class, 'rule' => $rule, 'cost' => (float) ($r['rate_cost'] ?? 0), 'extras' => $extra, 'label' => $label, '_id' => $id, ), 'data-ra-text' => $label, ), 'ord' => (string) ($i + 1), 'class' => $class, 'rule' => array('html' => esc_html($rule) . $marks), 'cost' => $money($r['rate_cost'] ?? null), 'extras' => $extra, 'label' => '' !== $label ? $label : array('html' => '' . esc_html__('(uses method title)', 'ai-eshop-optimizer') . ''), 'enabled' => array('value' => 1 === (int) ($r['enabled'] ?? 0) ? 1 : 0, 'label' => 1 === (int) ($r['enabled'] ?? 0) ? __('Enabled', 'ai-eshop-optimizer') : __('Disabled', 'ai-eshop-optimizer')), 'act' => array( array('label' => __('Edit', 'ai-eshop-optimizer'), 'icon' => 'pencil', 'attrs' => array('data-aieo-trs' => 'edit', 'data-id' => $id)), array('label' => __('Duplicate', 'ai-eshop-optimizer'), 'icon' => 'copy', 'attrs' => array('data-aieo-trs' => 'duplicate', 'data-id' => $id)), array('label' => __('Delete', 'ai-eshop-optimizer'), 'destructive' => true, 'attrs' => array('data-aieo-trs' => 'delete', 'data-id' => $id)), ), ); } $id = 'aieo-trs-table'; $sort = static function ($key, $type) { return array('sort' => 'none', 'sort_type' => $type, 'sort_url' => '#trs_orderby=' . $key); }; $columns = array( array('key' => 'ord', 'label' => '#', 'type' => 'num', 'width' => 'min') + $sort('ord', 'number'), array('key' => 'class', 'label' => _x('Class', 'a shipping class', 'ai-eshop-optimizer'), 'type' => 'text') + $sort('class', 'text'), array('key' => 'rule', 'label' => __('Rule', 'ai-eshop-optimizer'), 'type' => 'text') + $sort('rule', 'text'), array('key' => 'cost', 'label' => __('Base cost', 'ai-eshop-optimizer'), 'type' => 'num') + $sort('cost', 'number'), array('key' => 'extras', 'label' => __('Extras', 'ai-eshop-optimizer'), 'type' => 'text') + $sort('extras', 'text'), array('key' => 'label', 'label' => __('Label', 'ai-eshop-optimizer'), 'type' => 'text') + $sort('label', 'text'), array('key' => 'enabled', 'label' => __('Enabled', 'ai-eshop-optimizer'), 'type' => 'boolean'), array('key' => 'act', 'label' => __('Actions', 'ai-eshop-optimizer'), 'type' => 'actions'), ); return $ui::table($columns, $rows, array( 'id' => $id, 'caption' => __('Shipping rate rules', 'ai-eshop-optimizer'), 'move' => array('label' => __('Shipping rate rules', 'ai-eshop-optimizer')), 'local' => array('size' => 25, 'sizes' => array(25, 50, 100), 'words' => true, 'prefix' => 'trs_'), 'toolbar' => \Rooster\Admin\Filters::bar($id, array(), array(), array( 'prefix' => 'trs_', 'search' => array('label' => __('Search', 'ai-eshop-optimizer'), 'placeholder' => __('Labels', 'ai-eshop-optimizer')), 'keys' => array('s' => 'trs_s'), )), 'chooser' => true, 'cards' => true, 'empty' => \Rooster\Admin\States::state('first-use', array( 'title' => __('No rules yet. Click "Add rule" to create your first one.', 'ai-eshop-optimizer'), 'compact' => true, )), )); } public static function ajax_save() { self::gate(); $payload = isset($_POST['rule']) && is_array( wp_unslash( $_POST['rule'] ) ) ? wp_unslash($_POST['rule']) : array(); $check = AIEO_TRS_Validator::validate($payload); if (empty($check['ok'])) { wp_send_json_error(array('errors' => $check['errors']), 422); } $clean = $check['data']; $rule_id = (int) (sanitize_text_field( wp_unslash( $_POST['rule_id'] ) ) ?? 0); if ($rule_id > 0) { $r = AIEO_TRS_Rules::update($rule_id, $clean); if (empty($r['ok'])) { wp_send_json_error(array('errors' => array($r['error'] ?? 'update failed'))); } wp_send_json_success(array('id' => $rule_id, 'updated' => true)); } $r = AIEO_TRS_Rules::create($clean); if (empty($r['ok'])) { wp_send_json_error(array('errors' => array($r['error'] ?? 'create failed'))); } wp_send_json_success(array('id' => (int) $r['id'], 'created' => true)); } public static function ajax_delete() { self::gate(); $rule_id = (int) (sanitize_text_field( wp_unslash( $_POST['rule_id'] ) ) ?? 0); if ($rule_id <= 0) { wp_send_json_error(array('message' => 'bad_id'), 400); } $ok = AIEO_TRS_Rules::delete($rule_id); wp_send_json_success(array('deleted' => (bool) $ok)); } public static function ajax_reorder() { self::gate(); $ids = isset($_POST['ids']) ? array_map('intval', (array) wp_unslash($_POST['ids'])) : array(); $ids = array_values(array_filter($ids)); $n = AIEO_TRS_Rules::reorder($ids); wp_send_json_success(array('reordered' => (int) $n)); } public static function ajax_csv_export() { self::gate(); $instance_id = isset($_REQUEST['instance_id']) && $_REQUEST['instance_id'] !== '' ? (int) $_REQUEST['instance_id'] : null; $csv = AIEO_TRS_CSV::export($instance_id); nocache_headers(); header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="aieo-shipping-rates-' . gmdate('Ymd-His') . '.csv"'); echo $csv; exit; } public static function ajax_csv_import() { self::gate(); if (empty($_FILES['file']) || !is_array($_FILES['file'])) { wp_send_json_error(array('message' => 'no_file'), 400); } if ((int) $_FILES['file']['size'] > 2 * 1024 * 1024) { wp_send_json_error(array('message' => 'file_too_large'), 413); } $tmp = (string) $_FILES['file']['tmp_name']; if (!is_uploaded_file($tmp)) { wp_send_json_error(array('message' => 'bad_upload'), 400); } $body = file_get_contents($tmp); $default_instance = (int) (sanitize_text_field( wp_unslash( $_POST['instance_id'] ) ) ?? 0); $r = AIEO_TRS_CSV::import((string) $body, $default_instance); if (empty($r['ok'])) { wp_send_json_error($r, 422); } wp_send_json_success($r); } public static function ajax_flip_method() { self::gate(); global $wpdb; $instance_id = (int) (sanitize_text_field( wp_unslash( $_POST['instance_id'] ) ) ?? 0); $target = (string) (sanitize_text_field( wp_unslash( $_POST['target'] ) ) ?? ''); if ($instance_id <= 0) { wp_send_json_error(array('message' => 'bad_instance'), 400); } if (!in_array($target, array('table_rate', 'aieo_table_rate'), true)) { wp_send_json_error(array('message' => 'bad_target'), 400); } $table = $wpdb->prefix . 'woocommerce_shipping_zone_methods'; $current = $wpdb->get_row( $wpdb->prepare("SELECT zone_id, method_id FROM {$table} WHERE instance_id = %d LIMIT 1", $instance_id), ARRAY_A ); if (!$current) { wp_send_json_error(array('message' => 'instance_not_found'), 404); } $previous = (string) $current['method_id']; if (!in_array($previous, array('table_rate', 'aieo_table_rate'), true)) { wp_send_json_error(array('message' => 'not_a_table_rate_instance'), 400); } if ($previous === $target) { wp_send_json_success(array('changed' => false, 'method_id' => $target)); } self::copy_instance_settings($previous, $target, $instance_id); $r = $wpdb->update( $table, array('method_id' => $target), array('instance_id' => $instance_id), array('%s'), array('%d') ); if ($r === false) { wp_send_json_error(array('message' => 'update_failed: ' . $wpdb->last_error), 500); } if (class_exists('WC_Cache_Helper') && method_exists('WC_Cache_Helper', 'get_transient_version')) { WC_Cache_Helper::get_transient_version('shipping', true); } if (class_exists('AIEO_Runtime_TRS_Cache') && method_exists('AIEO_Runtime_TRS_Cache', 'flush_request_cache')) { AIEO_Runtime_TRS_Cache::flush_request_cache(); } do_action('aieo_trs_method_flipped', $instance_id, $target, $previous); wp_send_json_success(array( 'changed' => true, 'method_id' => $target, 'previous' => $previous, )); } private static function copy_instance_settings($from_method_id, $to_method_id, $instance_id) { $from_key = sprintf('woocommerce_%s_%d_settings', $from_method_id, (int) $instance_id); $to_key = sprintf('woocommerce_%s_%d_settings', $to_method_id, (int) $instance_id); $src = get_option($from_key, array()); $dst = get_option($to_key, array()); if (!is_array($src)) { $src = array(); } if (!is_array($dst)) { $dst = array(); } $carry = array('title', 'tax_status', 'enabled'); foreach ($carry as $k) { $src_val = isset($src[$k]) ? $src[$k] : null; if ($src_val === null || $src_val === '') { continue; } $dst_val = isset($dst[$k]) ? $dst[$k] : null; if ($dst_val === null || $dst_val === '') { $dst[$k] = $src_val; } } if (!isset($dst['enabled']) || $dst['enabled'] === '') { $dst['enabled'] = 'yes'; } update_option($to_key, $dst, false); } public static function shipping_classes() { $out = array( array('slug' => '', 'name' => __('Any class', 'ai-eshop-optimizer')), array('slug' => '0', 'name' => __('No shipping class', 'ai-eshop-optimizer')), ); if (!class_exists('WC_Shipping')) { return $out; } $classes = WC_Shipping::instance()->get_shipping_classes(); if (!is_array($classes)) { return $out; } foreach ($classes as $c) { $out[] = array( 'slug' => (string) $c->slug, 'name' => (string) $c->name, ); } return $out; } }