render_template('complementary.php', array( 'rows' => $this->fetch_all_with_labels(), 'module' => $this, )); } public function enqueue_admin_assets() { } public function fetch_all_with_labels() { global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_complementary'; if (!aieo_dmm_table_exists($table)) { return array(); } $rows = $wpdb->get_results("SELECT * FROM {$table} ORDER BY enabled DESC, id DESC", ARRAY_A); if (!is_array($rows)) { return array(); } $out = array(); foreach ($rows as $row) { $out[] = $this->hydrate_row($row); } return $out; } private function hydrate_row(array $row) { $row = AIEO_DMM_Complementary_Sets::row($row); $row['product_names'] = array_map(array($this, 'resolve_product_name'), $row['product_ids']); $row['source_product_name'] = $this->resolve_product_name($row['source_product_id']); return $row; } private function resolve_product_name($product_id) { $product_id = (int) $product_id; if ($product_id <= 0) { return ''; } $title = get_the_title($product_id); return ($title !== '' && $title !== null) ? (string) $title : ('#' . $product_id); } private static function member_columns(array $members, int $source_id): array { $pids = array(); foreach ($members as $member) { if ((int) $member['p'] !== $source_id) { $pids[] = (int) $member['p']; } } return array( 'product_ids' => wp_json_encode($pids), 'members' => wp_json_encode(array_values($members)), ); } private static function row_formats(array $data): array { $formats = array(); foreach (array_keys($data) as $column) { $formats[] = in_array($column, array('enabled', 'source_product_id', 'offer_id'), true) ? '%d' : '%s'; } return $formats; } public static function form_url(int $set_id = 0): string { $args = array( 'page' => AIEO_DMM::MENU_SLUG, 'dmm_tab' => 'complementary', ); if ($set_id > 0) { $args['set'] = $set_id; } return add_query_arg($args, admin_url('admin.php')) . '#aieo-card-complementary-products'; } public static function schema_step_may_run(): bool { if ((defined('WP_CLI') && WP_CLI) || wp_doing_cron()) { return true; } return is_admin() && !wp_doing_ajax(); } public static function maybe_install(): void { if (!self::schema_step_may_run()) { return; } if ((string) get_option(self::SCHEMA_OPTION, '') === self::SCHEMA_VERSION) { return; } if (!AIEO_Schema_Lock::acquire(self::SCHEMA_OPTION)) { return; } if (!function_exists('aieo_dmm_ensure_complementary_bundle_columns')) { require_once AIEO_DIR . 'includes/dmm/sql/dmm-schema.php'; } if (!aieo_dmm_ensure_complementary_bundle_columns()) { AIEO_Schema_Lock::release(self::SCHEMA_OPTION); return; } update_option(self::SCHEMA_OPTION, self::SCHEMA_VERSION, true); } public function ajax_save() { AIEO_DMM::verify_ajax_request(); $in = self::posted_set(); $saved = $this->save_set($in); if (is_wp_error($saved)) { wp_send_json_error(self::refusal_answer($saved, $in)); } global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_complementary'; $row = $this->hydrate_row( $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE id = %d", $saved['id']), ARRAY_A) ?: array() ); wp_send_json_success(array( 'id' => $saved['id'], 'is_update' => $saved['is_update'], 'row' => $row, 'message' => __('Complementary set saved.', 'ai-eshop-optimizer'), )); } public function ajax_sums() { AIEO_DMM::verify_ajax_request(); wp_send_json_success($this->view_of(self::posted_set())); } public function ajax_load() { AIEO_DMM::verify_ajax_request(); global $wpdb; $id = isset($_POST['id']) ? absint(wp_unslash($_POST['id'])) : 0; $row = $id > 0 ? $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'aieo_dmm_complementary WHERE id = %d', $id), ARRAY_A) : null; if (!is_array($row)) { wp_send_json_error(array('message' => __('This set is not there any more: reload the page.', 'ai-eshop-optimizer'))); } $row = $this->hydrate_row($row); $together = self::together_of($row); $names = array(); foreach ($together['gift']['products'] as $pid) { $names[] = $this->resolve_product_name($pid); } $together['gift']['names'] = $names; wp_send_json_success(array( 'row' => $row, 'together' => $together, 'view' => $this->view_of(array( 'id' => $row['id'], 'source_product_id' => $row['source_product_id'], 'enabled' => $row['enabled'], 'label' => $row['label'], 'members' => $row['members'], 'together' => $together['together'], 'value' => $together['value'], 'per' => $together['per'], 'gift' => $together['gift'], )), )); } private static function posted_set(): array { $text = static function ($key) { return isset($_POST[$key]) ? sanitize_text_field(wp_unslash($_POST[$key])) : ''; }; $in = array( 'id' => isset($_POST['id']) ? absint(wp_unslash($_POST['id'])) : 0, 'source_product_id' => isset($_POST['source_product_id']) ? absint(wp_unslash($_POST['source_product_id'])) : 0, 'enabled' => !empty($_POST['enabled']) ? 1 : 0, 'label' => $text('label'), 'offer_title' => $text('offer_title'), 'button_text' => $text('button_text'), 'placement' => isset($_POST['placement']) ? sanitize_key(wp_unslash($_POST['placement'])) : '', 'checkboxes_state' => $text('checkboxes_state'), 'members' => array(), '_rows' => array(), ); $rows = (isset($_POST['members']) && is_array($_POST['members'])) ? wp_unslash($_POST['members']) : array(); foreach ($rows as $i => $member) { if (!is_array($member)) { continue; } $p = 0 === (int) $i ? $in['source_product_id'] : (isset($member['p']) ? absint($member['p']) : 0); if ($p <= 0) { continue; } $in['members'][] = array( 'p' => $p, 'min' => (isset($member['min']) && '' !== $member['min']) ? (int) $member['min'] : 1, 'max' => (isset($member['max']) && '' !== $member['max']) ? (int) $member['max'] : null, ); $in['_rows'][] = (int) $i; } $in['together'] = isset($_POST['together']) ? sanitize_key(wp_unslash($_POST['together'])) : ''; $in['value'] = in_array($in['together'], array('set_price', 'percent', 'amount'), true) ? $text($in['together']) : ''; $in['per'] = isset($_POST['per']) ? sanitize_key(wp_unslash($_POST['per'])) : ''; $in['gift'] = array( 'products' => (isset($_POST['gift_products']) && is_array($_POST['gift_products'])) ? array_map('absint', wp_unslash($_POST['gift_products'])) : array(), 'choose' => 1, ); $in['starts'] = $text('starts'); $in['ends'] = $text('ends'); return $in; } private static function refusal_answer(WP_Error $refusal, array $in): array { $data = $refusal->get_error_data(); $data = is_array($data) ? $data : array(); $field = isset($data['field']) ? (string) $data['field'] : ''; $rows = (isset($in['_rows']) && is_array($in['_rows'])) ? $in['_rows'] : array(); $control = ''; if (1 === preg_match('/^members\.(\d+)(?:\.(min|max))?$/', $field, $m)) { $row = isset($rows[(int) $m[1]]) ? (int) $rows[(int) $m[1]] : (int) $m[1]; $part = isset($m[2]) ? $m[2] : 'p'; $control = (0 === $row && 'p' === $part) ? 'source_product_id' : 'members[' . $row . '][' . $part . ']'; } elseif ('members' === $field) { $control = 'members[1][p]'; } elseif ('value' === $field) { $control = in_array($in['together'] ?? '', array('set_price', 'percent', 'amount'), true) ? (string) $in['together'] : 'together'; } elseif ('gift' === $field) { $control = 'gift_products[]'; } elseif (in_array($field, array('source_product_id', 'together', 'per', 'starts', 'ends'), true)) { $control = $field; } return array( 'message' => $refusal->get_error_message(), 'control' => $control, ) + $data; } public function save_set(array $in, array $args = array()) { global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_complementary'; if (!aieo_dmm_table_exists($table)) { return new WP_Error('aieo_complementary_no_table', __('Table missing.', 'ai-eshop-optimizer')); } $id = isset($in['id']) ? (int) $in['id'] : 0; $is_update = $id > 0; $dry = !empty($args['dry_run']); $source_id = isset($in['source_product_id']) ? (int) $in['source_product_id'] : 0; if ($source_id <= 0) { return new WP_Error('aieo_complementary_refused', __('Pick a source product.', 'ai-eshop-optimizer'), array('field' => 'source_product_id')); } $members = $this->members_for_save($source_id, $in); if (is_wp_error($members)) { return $members; } if (!$is_update) { $existing = (int) $wpdb->get_var($wpdb->prepare( "SELECT id FROM {$table} WHERE source_product_id = %d LIMIT 1", $source_id )); if ($existing > 0) { return new WP_Error( 'aieo_complementary_refused', __('A complementary set already exists for this source product. Edit it instead.', 'ai-eshop-optimizer'), array('field' => 'source_product_id', 'existing_id' => $existing) ); } } else { $existing = (int) $wpdb->get_var($wpdb->prepare( "SELECT id FROM {$table} WHERE source_product_id = %d AND id <> %d LIMIT 1", $source_id, $id )); if ($existing > 0) { return new WP_Error('aieo_complementary_refused', __('Another row already targets this source product.', 'ai-eshop-optimizer'), array('field' => 'source_product_id')); } } $together = self::together_for_save($in, $id); if (is_wp_error($together)) { return $together; } $placement = isset($in['placement']) ? (string) $in['placement'] : ''; if (!in_array($placement, array('before_add_to_cart', 'after_add_to_cart', 'after_summary'), true)) { $placement = 'before_add_to_cart'; } $data = array( 'enabled' => !empty($in['enabled']) ? 1 : 0, 'label' => isset($in['label']) ? (string) $in['label'] : '', 'source_product_id' => $source_id, 'offer_title' => isset($in['offer_title']) ? (string) $in['offer_title'] : '', 'button_text' => isset($in['button_text']) ? (string) $in['button_text'] : '', 'placement' => $placement, 'checkboxes_state' => (isset($in['checkboxes_state']) && 'checked' === $in['checkboxes_state']) ? 'checked' : 'unchecked', ) + self::member_columns($members, $source_id); $write = static function (int $offer_id) use ($wpdb, $table, $data, $id, $is_update) { $data['offer_id'] = $offer_id; if ($is_update) { $written = $wpdb->update($table, $data, array('id' => $id), self::row_formats($data), array('%d')); $row_id = $id; } else { $written = $wpdb->insert($table, $data, self::row_formats($data)); $row_id = (int) $wpdb->insert_id; } if (false === $written || $row_id <= 0) { return new WP_Error('aieo_complementary_not_saved', __('The set could not be saved: the database refused it.', 'ai-eshop-optimizer')); } return $row_id; }; $set = array( 'id' => $id, 'label' => $data['label'], 'enabled' => (bool) $data['enabled'], 'members' => $members, ) + $together; $answer = AIEO_DMM_Bundles::save_offer($set, $write, array('dry_run' => $dry)); if (is_wp_error($answer)) { return $this->offer_refusal($answer, $members, (string) $together['together']); } if (!$dry) { AIEO_DMM_Cache::bump_version('complementary'); } return array( 'id' => (int) ($answer['set_id'] ?? $id), 'is_update' => $is_update, 'offer_id' => (int) ($answer['offer_id'] ?? 0), 'definition' => (isset($answer['definition']) && is_array($answer['definition'])) ? $answer['definition'] : null, 'members' => $members, ); } private static function together_for_save(array $in, int $set_id) { $together = (isset($in['together']) && in_array($in['together'], AIEO_DMM_Bundles::RESULTS, true)) ? (string) $in['together'] : ''; $out = array('together' => $together); if ('' === $together) { return $out; } if ('gift' === $together) { $gift = (isset($in['gift']) && is_array($in['gift'])) ? $in['gift'] : array(); $products = (isset($gift['products']) && is_array($gift['products'])) ? array_values(array_unique(array_filter(array_map('intval', $gift['products'])))) : array(); if (!$products) { return new WP_Error('aieo_complementary_refused', __('Pick the gift the set comes with.', 'ai-eshop-optimizer'), array('field' => 'gift')); } $out['gift'] = array( 'products' => $products, 'choose' => max(1, (int) ($gift['choose'] ?? 1)), ); } else { $value = $in['value'] ?? ''; $out['value'] = (is_int($value) || is_float($value)) ? (float) $value : (float) wc_format_decimal((string) $value); } if (isset($in['per']) && in_array($in['per'], array('set', 'once'), true)) { $out['per'] = (string) $in['per']; } if (array_key_exists('starts', $in) || array_key_exists('ends', $in)) { $days = array(); foreach (array('starts', 'ends') as $end) { $day = isset($in[$end]) ? trim((string) $in[$end]) : ''; if ('' !== $day && (1 !== preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $day, $d) || !checkdate((int) $d[2], (int) $d[3], (int) $d[1]))) { return new WP_Error('aieo_complementary_refused', __('Give the day as year-month-day, like 2026-12-24.', 'ai-eshop-optimizer'), array('field' => $end)); } $days[$end] = $day; } if ('' !== $days['starts'] && '' !== $days['ends'] && $days['ends'] < $days['starts']) { return new WP_Error('aieo_complementary_refused', __('The last day cannot be before the first day.', 'ai-eshop-optimizer'), array('field' => 'ends')); } $offer = $set_id > 0 ? AIEO_DMM_Bundles::offer_of_set($set_id) : null; $stored = is_array($offer) ? array('starts' => self::day_of($offer['start_date'] ?? ''), 'ends' => self::day_of($offer['end_date'] ?? '')) : null; if ($days !== $stored) { $out += $days; } } return $out; } private static function day_of($date): string { $day = is_string($date) ? substr($date, 0, 10) : ''; return (1 === preg_match('/^\d{4}-\d{2}-\d{2}$/', $day) && '0000-00-00' !== $day) ? $day : ''; } private function offer_refusal(WP_Error $refusal, array $members, string $together): WP_Error { $data = $refusal->get_error_data(); $data = is_array($data) ? $data : array(); if (isset($data['field'])) { return $refusal; } $path = isset($data['path']) ? (string) $data['path'] : ''; $reason = isset($data['reason']) ? (string) $data['reason'] : ''; $name = ''; if (1 === preg_match('/^bundle\.(\d+)(?:\.(p|min|max))?/', $path, $m)) { $field = 'members.' . $m[1] . ((isset($m[2]) && 'p' !== $m[2]) ? '.' . $m[2] : ''); $name = isset($members[(int) $m[1]]) ? $this->resolve_product_name((int) $members[(int) $m[1]]['p']) : ''; } elseif ('bundle' === $path || 'target' === $path) { $field = 'members'; } elseif (in_array($path, array('effect.price', 'effect.value'), true)) { $field = 'value'; } elseif (in_array($path, array('effect.per', 'allocation'), true)) { $field = 'per'; } elseif (0 === strpos($path, 'effect.products') || 0 === strpos($path, 'effect.choose')) { $field = 'gift'; } else { $field = 'together'; } $message = $refusal->get_error_message(); if ('invalid_definition' === $refusal->get_error_code()) { $message = __('"Bought together" could not be saved as it is: check its fields, then save again.', 'ai-eshop-optimizer'); if ('' !== $name && 'not_exact' === $reason) { $message = sprintf(__('A set price is for exactly that many of %s: give one number, not a range.', 'ai-eshop-optimizer'), $name); } elseif ('' !== $name && 'duplicate' === $reason) { $message = sprintf(__('%s is in the set twice: keep one of its rows.', 'ai-eshop-optimizer'), $name); } elseif ('' !== $name && 1 === preg_match('/\.(min|max)$/', $path)) { $message = sprintf( __('How many of %1$s: give a number from 1 to %2$d.', 'ai-eshop-optimizer'), $name, AIEO_DMM_Complementary_Sets::MAX_UNITS ); } elseif ('effect.price' === $path) { $message = __('Give the set\'s price: an amount above 0.', 'ai-eshop-optimizer'); } elseif ('effect.value' === $path) { $message = 'percent' === $together ? __('Give a percentage above 0 and under 100.', 'ai-eshop-optimizer') : __('Give an amount above 0.', 'ai-eshop-optimizer'); } elseif ('per' === $field) { $message = __('Choose how often: for each complete set, or once per order.', 'ai-eshop-optimizer'); } elseif ('gift' === $field) { $message = __('Pick the gift the set comes with.', 'ai-eshop-optimizer'); } } return new WP_Error($refusal->get_error_code(), $message, array('field' => $field) + $data); } private static function together_of(array $row): array { $out = array( 'together' => '', 'value' => '', 'per' => '', 'gift' => array('products' => array(), 'choose' => 1), 'starts' => '', 'ends' => '', 'offer_id' => 0, 'settings' => '', ); $offer = (int) ($row['id'] ?? 0) > 0 ? AIEO_DMM_Bundles::offer_of_set((int) $row['id']) : null; if (!is_array($offer)) { return $out; } $definition = (isset($offer['_definition']) && is_array($offer['_definition'])) ? $offer['_definition'] : array(); $result = AIEO_DMM_Bundles::result_of($definition); $effect = (isset($definition['effect']) && is_array($definition['effect'])) ? $definition['effect'] : array(); $out['offer_id'] = (int) ($offer['id'] ?? 0); $out['together'] = ((int) ($row['offer_id'] ?? 0) > 0) ? $result : ''; $out['last'] = $result; if ('gift' === $result) { $out['gift'] = array( 'products' => array_values(array_filter(array_map('intval', (array) ($effect['products'] ?? array())))), 'choose' => max(1, (int) ($effect['choose'] ?? 1)), ); } elseif ('' !== $result) { $number = 'set_price' === $result ? ($effect['price'] ?? '') : ($effect['value'] ?? ''); $out['value'] = is_numeric($number) ? wc_format_localized_decimal((string) (0 + $number)) : ''; } $allocation = (string) ($definition['allocation'] ?? ''); $out['per'] = 'once' === $allocation ? 'once' : ('per_set' === $allocation ? 'set' : ''); $out['starts'] = self::day_of($offer['start_date'] ?? ''); $out['ends'] = self::day_of($offer['end_date'] ?? ''); if (class_exists('AIEO_DMM_Offer_Wizard') && AIEO_DMM_Offer_Wizard::is_on()) { $out['settings'] = AIEO_DMM_Offer_Wizard::url($out['offer_id']); } return $out; } private function view_of(array $in): array { $answer = $this->save_set($in, array('dry_run' => true)); $refusal = is_wp_error($answer) ? self::refusal_answer($answer, $in) : null; $source = (int) ($in['source_product_id'] ?? 0); $members = is_wp_error($answer) ? AIEO_DMM_Complementary_Sets::members_of(array('members' => self::source_first($source, (array) ($in['members'] ?? array())))) : $answer['members']; $usual = $members ? AIEO_DMM_Bundles::usual($members) : array('from' => 0.0, 'to' => 0.0, 'members' => array()); $about = (isset($usual['members']) && is_array($usual['members'])) ? $usual['members'] : array(); $rows = array(); $names = array(); $place = (isset($in['_rows']) && is_array($in['_rows'])) ? $in['_rows'] : array(); foreach ($members as $i => $member) { $p = (int) $member['p']; $info = (isset($about[$p]) && is_array($about[$p])) ? $about[$p] : array(); $name = (isset($info['name']) && '' !== (string) $info['name']) ? (string) $info['name'] : $this->resolve_product_name($p); $from = (float) ($info['from'] ?? 0); $to = (float) ($info['to'] ?? 0); if ($to <= 0) { $price = ''; } elseif (abs($to - $from) < 0.005) { $price = sprintf(__('%s each', 'ai-eshop-optimizer'), self::money_text($to)); } else { $price = sprintf(__('%1$s to %2$s each', 'ai-eshop-optimizer'), self::money_text($from), self::money_text($to)); } if (!empty($info['variable'])) { $mix = __('any mix of its variations', 'ai-eshop-optimizer'); $price = '' === $price ? $mix : $price . ', ' . $mix; } $names[$p] = $name; $rows[] = array( 'row' => isset($place[$i]) ? (int) $place[$i] : (int) $i, 'p' => $p, 'name' => $name, 'price' => $price, ); } $definition = (!is_wp_error($answer) && is_array($answer['definition'])) ? $answer['definition'] : null; $review = ''; if ($definition) { $with = array('names' => $names); if ((float) $usual['to'] > 0 && abs((float) $usual['to'] - (float) $usual['from']) < 0.005) { $with['usual'] = (float) $usual['to']; } $review = AIEO_DMM_Bundle_Words::review($definition, $with); } return array( 'rows' => $rows, 'sums' => self::sums_words($usual, (string) ($in['together'] ?? ''), $in['value'] ?? ''), 'review' => $review, 'refusal' => $refusal, ); } private static function sums_words(array $usual, string $together, $value): string { $from = (float) ($usual['from'] ?? 0); $to = (float) ($usual['to'] ?? 0); if ($to <= 0) { return ''; } $span = static function (float $a, float $b): string { if (abs($b - $a) < 0.005) { return self::money_text($b); } return sprintf(__('%1$s to %2$s', 'ai-eshop-optimizer'), self::money_text(min($a, $b)), self::money_text(max($a, $b))); }; $number = (is_int($value) || is_float($value)) ? (float) $value : (float) wc_format_decimal((string) $value); $usually = sprintf(__('Usually %s.', 'ai-eshop-optimizer'), $span($from, $to)); if ($number <= 0 || !in_array($together, array('set_price', 'percent', 'amount'), true)) { if ('gift' === $together) { return $usually . ' ' . __('The gift comes on top.', 'ai-eshop-optimizer'); } return $usually; } if ('set_price' === $together) { if ($number >= $to) { return $usually . ' ' . __('The set would cost more than its products: it will not apply.', 'ai-eshop-optimizer'); } $low = $number; $high = $number; } elseif ('percent' === $together) { $keep = max(0.0, 1 - $number / 100); $low = $from * $keep; $high = $to * $keep; } else { $low = max(0.0, $from - $number); $high = max(0.0, $to - $number); } return $usually . ' ' . sprintf( __('Together %1$s: the customer saves %2$s.', 'ai-eshop-optimizer'), $span($low, $high), $span(max(0.0, $from - $low), max(0.0, $to - $high)) ); } private static function source_first(int $source_id, array $given): array { $source = array('p' => $source_id); $others = array(); foreach ($given as $member) { if (!is_array($member)) { continue; } if ((int) ($member['p'] ?? 0) === $source_id) { $source = $member; } else { $others[] = $member; } } return array_merge(array($source), $others); } private function members_for_save(int $source_id, array $in) { $refuse = static function ($message, $field) { return new WP_Error('aieo_complementary_refused', $message, array('field' => $field)); }; $source = array('p' => $source_id, 'min' => 1, 'max' => 1); $others = array(); $source_seen = false; foreach ((isset($in['members']) && is_array($in['members'])) ? $in['members'] : array() as $member) { if (!is_array($member) || empty($member['p']) || (int) $member['p'] <= 0) { continue; } $min = isset($member['min']) ? (int) $member['min'] : 1; $member = array( 'p' => (int) $member['p'], 'min' => $min, 'max' => (isset($member['max']) && '' !== $member['max']) ? (int) $member['max'] : $min, ); if ($member['p'] !== $source_id) { $others[] = $member; } elseif ($source_seen) { return $refuse(__('A product can\'t complement itself — remove it from the complementary list.', 'ai-eshop-optimizer'), 'members'); } else { $source = $member; $source_seen = true; } } if (!$others) { return $refuse(__('Pick at least one complementary product.', 'ai-eshop-optimizer'), 'members'); } $members = array_merge(array($source), $others); if (count($members) > AIEO_DMM_Complementary_Sets::MAX_MEMBERS) { return $refuse(sprintf( __('A set holds up to %d products, the source product included: remove some.', 'ai-eshop-optimizer'), AIEO_DMM_Complementary_Sets::MAX_MEMBERS ), 'members'); } $seen = array(); foreach ($members as $i => $member) { if (isset($seen[$member['p']])) { return $refuse(sprintf(__('%s is in the set twice: keep one of its rows.', 'ai-eshop-optimizer'), $this->resolve_product_name($member['p'])), 'members.' . $i); } $seen[$member['p']] = true; foreach (array('min', 'max') as $end) { if ($member[$end] < 1 || $member[$end] > AIEO_DMM_Complementary_Sets::MAX_UNITS) { return $refuse(sprintf( __('How many of %1$s: give a number from 1 to %2$d.', 'ai-eshop-optimizer'), $this->resolve_product_name($member['p']), AIEO_DMM_Complementary_Sets::MAX_UNITS ), 'members.' . $i . '.' . $end); } } if ($member['max'] < $member['min']) { return $refuse(sprintf(__('How many of %s: the second number cannot be lower than the first.', 'ai-eshop-optimizer'), $this->resolve_product_name($member['p'])), 'members.' . $i . '.max'); } } return $members; } public function ajax_delete() { AIEO_DMM::verify_ajax_request(); $id = isset($_POST['id']) ? absint(wp_unslash($_POST['id'])) : 0; if ($id <= 0) { wp_send_json_error(array('message' => __('Invalid id.', 'ai-eshop-optimizer'))); } $archived = AIEO_DMM_Bundles::archive_offer($id, __('Its set was deleted in Complementary Products.', 'ai-eshop-optimizer')); if (is_wp_error($archived)) { wp_send_json_error(array('message' => $archived->get_error_message())); } global $wpdb; $wpdb->delete($wpdb->prefix . 'aieo_dmm_complementary', array('id' => $id), array('%d')); AIEO_DMM_Cache::bump_version('complementary'); wp_send_json_success(); } public static function on_offer_saved($offer_id, $before, $after) { if (!is_array($after) || AIEO_DMM_Bundles::saving()) { return; } $set_id = AIEO_DMM_Bundles::set_of($after); if ($set_id <= 0) { return; } $runs = static function ($row): bool { return is_array($row) && !empty($row['enabled']) && 'archived' !== (string) ($row['state'] ?? ''); }; global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_complementary'; if (($runs($before) && !$runs($after)) || 'archived' === (string) ($after['state'] ?? '')) { $wpdb->query($wpdb->prepare("UPDATE {$table} SET offer_id = 0 WHERE id = %d AND offer_id = %d", $set_id, (int) $offer_id)); } elseif (!$runs($before) && $runs($after)) { $wpdb->query($wpdb->prepare("UPDATE {$table} SET offer_id = %d, enabled = 1 WHERE id = %d AND (offer_id = 0 OR offer_id = %d)", (int) $offer_id, $set_id, (int) $offer_id)); } else { return; } AIEO_DMM_Cache::bump_version('complementary'); } public function ajax_search_products() { AIEO_DMM::verify_ajax_request(); $q = isset($_GET['q']) ? sanitize_text_field(wp_unslash($_GET['q'])) : ''; if (!function_exists('wc_get_products')) { wp_send_json(array('results' => array())); } $products = wc_get_products(array( 'status' => array('publish', 'private'), 'limit' => 25, 's' => $q, 'orderby' => 'title', 'order' => 'ASC', )); $results = array(); foreach ($products as $p) { $results[] = array('id' => (int) $p->get_id(), 'text' => $p->get_name() . ' (#' . (int) $p->get_id() . ')'); } wp_send_json(array('results' => $results)); } const CSV_HEAD = array('source_sku', 'source_count'); const CSV_TAIL = array('label', 'enabled', 'offer_title', 'button_text', 'together', 'together_value', 'together_per', 'gift_skus', 'starts', 'ends'); public static function csv_columns(int $members = 1): array { $columns = self::CSV_HEAD; for ($n = 1; $n <= max(1, $members); $n++) { $columns[] = 'member_' . $n . '_sku'; $columns[] = 'member_' . $n . '_count'; } return array_merge($columns, self::CSV_TAIL); } public function ajax_import_csv() { AIEO_DMM::verify_ajax_request(); if (empty($_FILES['csv']['tmp_name']) || !is_uploaded_file($_FILES['csv']['tmp_name'])) { wp_send_json_error(array('message' => __('No CSV uploaded.', 'ai-eshop-optimizer'))); } $answer = $this->import_csv($_FILES['csv']['tmp_name']); if (is_wp_error($answer)) { wp_send_json_error(array('message' => $answer->get_error_message())); } wp_send_json_success($answer); } public function import_csv(string $path) { $fh = fopen($path, 'r'); if (!$fh) { return new WP_Error('aieo_complementary_csv', __('Could not open uploaded file.', 'ai-eshop-optimizer')); } $header = fgetcsv($fh, 0, ',', '"', ''); if (!$header) { fclose($fh); return new WP_Error('aieo_complementary_csv', __('Empty CSV.', 'ai-eshop-optimizer')); } $idx = array_flip(array_map(static function ($name) { return strtolower(trim((string) preg_replace('/^\xEF\xBB\xBF/', '', (string) $name))); }, $header)); foreach (array('source_sku', 'member_1_sku') as $col) { if (!isset($idx[$col])) { fclose($fh); return new WP_Error('aieo_complementary_csv', sprintf( __('Missing required column: %s', 'ai-eshop-optimizer'), $col )); } } global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_complementary'; $stats = array('inserted' => 0, 'updated' => 0, 'skipped' => 0, 'errors' => array()); $line = 1; $sku = static function (string $sku): int { return '' === $sku ? 0 : (int) wc_get_product_id_by_sku($sku); }; $refuse = static function (int $line, string $message) use (&$stats) { $stats['skipped']++; $stats['errors'][] = sprintf(__('Line %1$d: %2$s', 'ai-eshop-optimizer'), $line, $message); }; while (($row = fgetcsv($fh, 0, ',', '"', '')) !== false) { $line++; $get = static function ($key) use ($row, $idx) { return isset($idx[$key]) && isset($row[$idx[$key]]) ? trim((string) $row[$idx[$key]]) : ''; }; if (array() === array_filter(array_map('trim', array_map('strval', $row)), 'strlen')) { continue; } $source_sku = $get('source_sku'); $source_id = $sku($source_sku); if ($source_id <= 0) { $refuse($line, sprintf(__('Unknown source SKU: %s', 'ai-eshop-optimizer'), $source_sku)); continue; } list($min, $max) = self::csv_count($get('source_count')); $members = array(array('p' => $source_id, 'min' => $min, 'max' => $max)); $unknown = ''; for ($n = 1; isset($idx['member_' . $n . '_sku']); $n++) { $member_sku = $get('member_' . $n . '_sku'); if ('' === $member_sku) { continue; } $pid = $sku($member_sku); if ($pid <= 0) { $unknown = $member_sku; break; } list($min, $max) = self::csv_count($get('member_' . $n . '_count')); $members[] = array('p' => $pid, 'min' => $min, 'max' => $max); } if ('' !== $unknown) { $refuse($line, sprintf(__('Unknown SKU: %1$s (in row for %2$s)', 'ai-eshop-optimizer'), $unknown, $source_sku)); continue; } $gifts = array(); foreach (array_filter(array_map('trim', explode('|', $get('gift_skus'))), 'strlen') as $gift_sku) { $pid = $sku($gift_sku); if ($pid <= 0) { $unknown = $gift_sku; break; } $gifts[] = $pid; } if ('' !== $unknown) { $refuse($line, sprintf(__('Unknown SKU: %1$s (in row for %2$s)', 'ai-eshop-optimizer'), $unknown, $source_sku)); continue; } $existing = $wpdb->get_row($wpdb->prepare("SELECT id, placement, checkboxes_state FROM {$table} WHERE source_product_id = %d", $source_id), ARRAY_A); $in = array( 'id' => is_array($existing) ? (int) $existing['id'] : 0, 'source_product_id' => $source_id, 'enabled' => '0' === $get('enabled') ? 0 : 1, 'label' => sanitize_text_field($get('label')), 'offer_title' => sanitize_text_field($get('offer_title')), 'button_text' => sanitize_text_field($get('button_text')), 'placement' => is_array($existing) ? (string) $existing['placement'] : 'before_add_to_cart', 'checkboxes_state' => is_array($existing) ? (string) $existing['checkboxes_state'] : 'unchecked', 'members' => $members, 'together' => sanitize_key($get('together')), 'value' => $get('together_value'), 'gift' => array('products' => $gifts, 'choose' => 1), ); if ('' !== $get('together_per')) { $in['per'] = sanitize_key($get('together_per')); } if (isset($idx['starts']) || isset($idx['ends'])) { $in['starts'] = $get('starts'); $in['ends'] = $get('ends'); } if ('' !== $in['together'] && !in_array($in['together'], AIEO_DMM_Bundles::RESULTS, true)) { $refuse($line, __('Choose what buying the set together gives: set_price, percent, amount, gift, or nothing.', 'ai-eshop-optimizer')); continue; } $saved = $this->save_set($in); if (is_wp_error($saved)) { $refuse($line, $saved->get_error_message()); continue; } $stats[$saved['is_update'] ? 'updated' : 'inserted']++; } fclose($fh); return array( 'message' => sprintf( __('Import complete: %1$d inserted, %2$d updated, %3$d skipped.', 'ai-eshop-optimizer'), $stats['inserted'], $stats['updated'], $stats['skipped'] ), 'stats' => $stats, ); } private static function csv_count(string $count): array { $count = trim($count); if ('' === $count) { return array(1, null); } if (1 === preg_match('/^(\d{1,3})(?:\s*-\s*(\d{1,3}))?$/', $count, $m)) { return array((int) $m[1], isset($m[2]) ? (int) $m[2] : null); } return array(0, null); } private static function csv_count_text(array $member): string { return (int) $member['max'] > (int) $member['min'] ? (int) $member['min'] . '-' . (int) $member['max'] : (string) (int) $member['min']; } public function ajax_export_csv() { AIEO_DMM::verify_ajax_request(); wp_send_json_success(array( 'filename' => 'aieo-complementary-' . gmdate('Ymd-His') . '.csv', 'mime' => 'text/csv', 'b64' => base64_encode($this->export_csv()), )); } public function export_csv(): string { global $wpdb; $rows = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "aieo_dmm_complementary ORDER BY id ASC", ARRAY_A); $lines = array(); $widest = 1; foreach ((array) $rows as $row) { $row = AIEO_DMM_Complementary_Sets::row($row); $source = wc_get_product((int) $row['source_product_id']); if (!$source) { continue; } $members = $row['members']; $first = array_shift($members); $cells = array((string) $source->get_sku(), self::csv_count_text($first)); $others = array(); foreach ($members as $member) { $product = wc_get_product((int) $member['p']); $others[] = array($product ? (string) $product->get_sku() : '', self::csv_count_text($member)); } $widest = max($widest, count($others)); $together = self::together_of($row); $gifts = array(); foreach ('gift' === $together['together'] ? $together['gift']['products'] : array() as $gift) { $product = wc_get_product((int) $gift); if ($product) { $gifts[] = (string) $product->get_sku(); } } $value = ''; if ('' !== $together['together'] && 'gift' !== $together['together'] && '' !== (string) $together['value']) { $value = (string) wc_format_decimal($together['value']); } $lines[] = array($cells, $others, array( (string) $row['label'], !empty($row['enabled']) ? '1' : '0', (string) $row['offer_title'], (string) $row['button_text'], (string) $together['together'], $value, '' !== $together['together'] ? (string) $together['per'] : '', implode('|', $gifts), '' !== $together['together'] ? (string) $together['starts'] : '', '' !== $together['together'] ? (string) $together['ends'] : '', )); } $tmp = fopen('php://temp', 'w+'); fputcsv($tmp, self::csv_columns($widest), ',', '"', ''); foreach ($lines as list($cells, $others, $tail)) { foreach (array_pad($others, $widest, array('', '')) as $other) { $cells[] = $other[0]; $cells[] = $other[1]; } fputcsv($tmp, array_merge($cells, $tail), ',', '"', ''); } rewind($tmp); $csv = stream_get_contents($tmp); fclose($tmp); return (string) $csv; } public function render_for_current_product() { AIEO_DMM_Bundle_Card::print_for_current(); } public function get_row_for_source($source_product_id) { return AIEO_DMM_Complementary_Sets::for_source((int) $source_product_id); } public static function add_eligibility_row($rows, $product_id, $audience_key) { if (!is_array($rows)) { $rows = array(); } $product_id = (int) $product_id; if ($product_id === 0) { return $rows; } if (!class_exists('AIEO_Effective_Eligibility')) { return $rows; } $r = self::is_eligible_for($product_id, (string) $audience_key); if (!empty($r['eligible'])) { $rows[AIEO_Effective_Eligibility::SURFACE_COMPLEMENTARY] = $r; } return $rows; } public static function is_eligible_for($product_id, $audience_key = 'guest') { $product_id = (int) $product_id; if ($product_id <= 0) { return array('eligible' => false); } if (class_exists('AIEO_DMM_Settings') && !AIEO_DMM_Settings::is_module_enabled('complementary')) { return array('eligible' => false); } $instance = self::eligibility_instance(); $row = $instance->get_row_for_source($product_id); if (!$row || empty($row['product_ids'])) { return array('eligible' => false); } return array( 'eligible' => true, 'offer_id' => isset($row['id']) ? (int) $row['id'] : null, 'payload' => array( 'count' => count((array) $row['product_ids']), ), ); } private static function eligibility_instance() { static $inst = null; if ($inst === null) { if (class_exists('AIEO_DMM') && method_exists('AIEO_DMM', 'instance')) { $mod = AIEO_DMM::instance()->get_module('complementary'); $inst = ($mod instanceof self) ? $mod : new self(); } else { $inst = new self(); } } return $inst; } const APPEARANCE_OPTION = AIEO_DMM_Bundle_Card::APPEARANCE_OPTION; public static function picked($key, $hex) { return AIEO_DMM_Bundle_Card::picked($key, $hex); } public static function get_appearance_settings(): array { return AIEO_DMM_Bundle_Card::appearance(); } public static function appearance_defaults(): array { return AIEO_DMM_Bundle_Card::appearance_defaults(); } public function ajax_save_appearance(): void { AIEO_DMM::verify_ajax_request(); $cur = self::get_appearance_settings(); $num_clamps = array( 'title_size' => array(8, 48), 'text_size' => array(8, 32), 'border_width' => array(0, 10), 'border_radius' => array(0, 40), 'btn_border_width' => array(0, 10), 'btn_border_radius' => array(0, 40), ); foreach ($num_clamps as $k => list($min, $max)) { if (isset($_POST[$k])) { $cur[$k] = max($min, min($max, (int) wp_unslash($_POST[$k]))); } } foreach (array_keys(AIEO_DMM_Bundle_Card::RETIRED_COLOURS) as $k) { if (isset($_POST[$k])) { $posted = trim(wp_unslash((string) $_POST[$k])); if ('' === $posted || sanitize_hex_color($posted)) { $cur[$k] = self::picked($k, $posted); } } } update_option(self::APPEARANCE_OPTION, $cur, false); wp_send_json_success(array('message' => __('Complementary Products appearance saved.', 'ai-eshop-optimizer'))); } }