capture_saved((int) $order_id); } public function capture_via_new_order($order_id, $order = null) { $this->capture_saved((int) $order_id); } private function capture_saved($order_id) { if ($order_id <= 0 || isset(self::$captured[$order_id]) || !function_exists('wc_get_order')) { return; } $order = wc_get_order($order_id); if (!$order || !is_a($order, 'WC_Order') || !$order->get_items()) { return; } self::$captured[$order_id] = true; try { $this->stamp_lines($order); } catch (\Throwable $e) { if (defined('WP_DEBUG') && WP_DEBUG) { error_log('[AIEO offers] The lines of order #' . (int) $order_id . ' were not stamped: ' . $e->getMessage()); } } $this->record_attributions_for_order($order); } private function stamp_lines($order) { if (class_exists('AIEO_DMM_Offer_Store') && AIEO_DMM_Offer_Store::reads_unified()) { return; } if (!class_exists('AIEO_DMM_Offer_Record') || !AIEO_DMM_Offer_Record::is_on()) { return; } if (!class_exists('AIEO_DMM_Pricing_Engine') || !class_exists('AIEO_DMM_Offer_Sets') || !class_exists('AIEO_DMM_Offer_Matcher') || !is_callable(array('AIEO_DMM_Offer_Matcher', 'rank')) || !function_exists('wc_get_product')) { return; } $engine = AIEO_DMM_Pricing_Engine::instance(); $customer = (int) $order->get_customer_id(); $sets = array(); foreach ($order->get_items() as $line) { if (!is_a($line, 'WC_Order_Item_Product')) { continue; } if ((int) $line->get_meta('_aieo_dmm_gift_offer_id', true) > 0) { continue; } if ('' !== (string) $line->get_meta('_aieo_offers', true)) { continue; } $priced_id = (int) $line->get_variation_id(); if ($priced_id <= 0) { $priced_id = (int) $line->get_product_id(); } if ($priced_id <= 0) { continue; } $rules = $engine->matching_discount_rules($priced_id); if (!$rules) { continue; } $product = wc_get_product($priced_id); if (!$product) { continue; } $regular = $product->get_regular_price('edit'); $regular = is_numeric($regular) ? (float) $regular : 0.0; $offers = array(); $members = array(); foreach ($rules as $rule) { $store = isset($rule['s']) && '' !== (string) $rule['s'] ? (string) $rule['s'] : 'bd'; $offers[] = array( 's' => $store, 'id' => (int) $rule['id'], 'pct' => (float) $rule['percent'], 'w' => (int) AIEO_DMM_Offer_Matcher::width_of_row($rule), 'start' => (string) AIEO_DMM_Offer_Matcher::start_of_row($rule), ); $members[] = $store . ':' . (int) $rule['id']; } $ranked = AIEO_DMM_Offer_Matcher::rank($offers, $regular); $charge = AIEO_DMM_Offer_Record::charge($product, $customer); $stamp = array('v' => 1, 'by' => 'capture', 'chg' => $charge['charged'] ? 1 : 0); if (!$charge['charged'] && !$charge['blocked'] && '' !== $charge['won']) { $stamp['won'] = $charge['won']; } $stamp['set'] = AIEO_DMM_Offer_Sets::hash($members); $stamp['tb'] = (string) $ranked['tb']; if (isset($ranked['tbk'])) { $stamp['tbk'] = (string) $ranked['tbk']; } $stamp['offers'] = array(); $quantity = (int) $line->get_quantity(); foreach ($ranked['offers'] as $offer) { $percent = (float) $offer['pct']; if ($charge['charged']) { $role = (string) $offer['role']; } else { $role = $charge['blocked'] ? 'blocked' : 'outbid'; } $stamp['offers'][] = array( 's' => (string) $offer['s'], 'id' => (int) $offer['id'], 'k' => 'discount', 'p' => ((float) (int) $percent === $percent) ? (int) $percent : round($percent, 2), 'role' => $role, 'alone' => round((float) $offer['alone'], 4), 'marg' => $charge['charged'] ? round((float) $offer['marg'], 4) : 0.0, 'w' => (int) $offer['w'], 'u' => $quantity, ); } $line->add_meta_data('_aieo_offers', wp_json_encode($stamp, JSON_PRESERVE_ZERO_FRACTION), true); $line->save_meta_data(); if ('' !== $stamp['set']) { $sets[$stamp['set']] = $members; } } if ($sets) { $now = current_time('mysql', true); foreach ($sets as $members) { AIEO_DMM_Offer_Sets::touch($members, $now); } } } private function record_attributions_for_order($order) { $order_id = (int) $order->get_id(); $rows = array(); $entry_channel = $this->resolve_entry_channel($order); $entry_branch_id = $this->resolve_entry_branch_id($order); $entry_campaign_id = $this->resolve_entry_campaign_id($order); $user_id = (int) $order->get_user_id(); $order_total = (float) $order->get_total(); $gift_measured = array(); foreach ($order->get_items() as $line) { list($offer_id, $offer_type) = $this->gift_line_log_id($line); if ($offer_id <= 0) { continue; } $product_id = (int) ($line->get_variation_id() ?: $line->get_product_id()); $product = wc_get_product($product_id); if (!$product) { continue; } $retail = (float) $product->get_regular_price(); list($cogs, $basis) = AIEO_DMM_Offer_Matcher::product_cost($product_id); $qty = max(1, (int) $line->get_quantity()); $own = array(0, 0.0); if (!isset($gift_measured[$offer_type . ':' . $offer_id])) { $gift_measured[$offer_type . ':' . $offer_id] = true; $gift_offer = 'gift' === $offer_type ? $this->gift_offer_row($offer_id) : $this->one_table_row($offer_id); if ($gift_offer) { $own = $this->target_measures($order, $gift_offer); } } $rows[] = array( 'order_id' => $order_id, 'offer_id' => $offer_id, 'offer_type' => $offer_type, 'offer_label' => $this->offer_label($offer_id, $offer_type, $product->get_name()), 'applied_value' => round($retail * $qty, 2), 'actual_cost' => round($cogs * $qty, 2), 'cost_basis' => $basis, 'order_total' => $order_total, 'entry_channel' => $entry_channel, 'entry_campaign_id'=> $entry_campaign_id, 'entry_branch_id' => $entry_branch_id, 'user_id' => $user_id, 'target_product_id'=> $product_id, 'target_units' => $own[0], 'target_revenue' => $own[1], ); } $unified = class_exists('AIEO_DMM_Offer_Store') && AIEO_DMM_Offer_Store::reads_unified() && class_exists('AIEO_DMM_Pricing_Engine'); $active_discounts = $unified ? array() : $this->load_active_discount_offers(); if ($unified || !empty($active_discounts)) { foreach ($order->get_items() as $line) { if ((int) $line->get_meta('_aieo_dmm_gift_offer_id', true) > 0) { continue; } $product_id = (int) $line->get_product_id(); if ($product_id <= 0) { continue; } $matched = $unified ? $this->discount_rules_of_the_price($product_id) : $this->not_excluding_the_line(AIEO_DMM_Offer_Matcher::for_product($product_id, $active_discounts), $line); if (empty($matched)) { continue; } $product = wc_get_product($product_id); if (!$product) { continue; } $regular = (float) $product->get_regular_price(); $line_total = (float) $line->get_total(); $line_qty = max(1, (int) $line->get_quantity()); $forgone = max(0, ($regular * $line_qty) - $line_total); if ($forgone <= 0) { continue; } $offer = $this->applied_discount_row($line, $matched); list($offer_id, $offer_type) = $this->discount_log_id($offer); $rows[] = array( 'order_id' => $order_id, 'offer_id' => $offer_id, 'offer_type' => $offer_type, 'offer_label' => $this->offer_label($offer_id, $offer_type, (string) ($offer['label'] ?? '')), 'applied_value' => round($forgone, 2), 'actual_cost' => round($forgone, 2), 'cost_basis' => 'forgone_revenue', 'order_total' => $order_total, 'entry_channel' => $entry_channel, 'entry_campaign_id'=> $entry_campaign_id, 'entry_branch_id' => $entry_branch_id, 'user_id' => $user_id, 'target_product_id'=> $product_id, 'target_units' => max(0, (int) $line->get_quantity()), 'target_revenue' => round((float) $line->get_total() + (float) $line->get_total_tax(), 2), ); } } $fs_rule_ids = array(); foreach ($order->get_shipping_methods() as $ship) { $rule_id = (int) $ship->get_meta('_aieo_fs_rule', true); if ($rule_id > 0) { $fs_rule_ids[$rule_id] = true; } } foreach (array_keys($fs_rule_ids) as $rule_id) { $rule = $this->free_shipping_rule_row($rule_id); $own = $rule ? $this->target_measures($order, $rule) : array(0, 0.0); $rows[] = array( 'order_id' => $order_id, 'offer_id' => $rule_id, 'offer_type' => 'free_shipping', 'offer_label' => $this->offer_label($rule_id, 'free_shipping', $rule ? (string) ($rule['label'] ?? '') : ''), 'applied_value' => 0.00, 'actual_cost' => null, 'cost_basis' => 'forgone_revenue', 'order_total' => $order_total, 'entry_channel' => $entry_channel, 'entry_campaign_id'=> $entry_campaign_id, 'entry_branch_id' => $entry_branch_id, 'user_id' => $user_id, 'target_product_id'=> 0, 'target_units' => $own[0], 'target_revenue' => $own[1], ); } if (!class_exists('AIEO_Popup_Display') && defined('AIEO_DIR') && file_exists(AIEO_DIR . 'includes/class-aieo-popup-display.php')) { require_once AIEO_DIR . 'includes/class-aieo-popup-display.php'; } if (class_exists('AIEO_Popup_Display')) { $ei_codes = AIEO_Popup_Display::configured_coupon_codes(); if (!empty($ei_codes)) { $applied = array_map('strtolower', (array) $order->get_coupon_codes()); $matched = array_values(array_intersect($ei_codes, $applied)); if (!empty($matched)) { $own = $this->coupon_line_measures($order); foreach ($matched as $code) { $discount = $this->coupon_discount_on_order($order, $code); $rows[] = array( 'order_id' => $order_id, 'offer_id' => $this->popup_offer_id($code), 'offer_type' => 'exit_intent', 'offer_label' => $code, 'applied_value' => round($discount, 2), 'actual_cost' => round($discount, 2), 'cost_basis' => 'forgone_revenue', 'order_total' => $order_total, 'entry_channel' => $entry_channel, 'entry_campaign_id' => $entry_campaign_id, 'entry_branch_id' => $entry_branch_id, 'user_id' => $user_id, 'target_product_id' => 0, 'target_units' => $own[0], 'target_revenue' => $own[1], ); } } } } if (empty($rows)) { return; } global $wpdb; $tbl = $wpdb->prefix . 'aieo_dmm_offer_attributions'; if (!aieo_dmm_table_exists($tbl)) { return; } if ($wpdb->get_var($wpdb->prepare("SELECT 1 FROM {$tbl} WHERE order_id = %d LIMIT 1", $order_id))) { return; } foreach ($rows as $row) { $this->insert_row($tbl, $row); } } private function insert_row($tbl, array $row) { global $wpdb; if (empty($row['fired_at'])) { $row['fired_at'] = current_time('mysql', true); } $suppress = $wpdb->suppress_errors(true); $ok = $wpdb->insert($tbl, $row); $wpdb->suppress_errors($suppress); if (false === $ok) { unset($row['target_units'], $row['target_revenue']); $wpdb->insert($tbl, $row); } } private function target_measures($order, array $offer) { $units = 0; $revenue = 0.0; foreach ($order->get_items() as $line) { if ((int) $line->get_meta('_aieo_dmm_gift_offer_id', true) > 0) { continue; } $resolve_id = (int) $line->get_product_id(); if ($resolve_id <= 0) { continue; } $pid = (int) ($line->get_variation_id() ?: $resolve_id); $ctx = AIEO_DMM_Offer_Matcher::line_context($resolve_id, $pid); if (AIEO_DMM_Offer_Matcher::offer_excludes($offer, $ctx)) { continue; } if (!AIEO_DMM_Offer_Matcher::offer_targets($offer, $ctx)) { continue; } $units += max(0, (int) $line->get_quantity()); $revenue += (float) $line->get_total() + (float) $line->get_total_tax(); } return array($units, round($revenue, 2)); } private function coupon_line_measures($order) { $units = 0; $revenue = 0.0; foreach ($order->get_items() as $line) { if ((int) $line->get_meta('_aieo_dmm_gift_offer_id', true) > 0) { continue; } if ((float) $line->get_subtotal() - (float) $line->get_total() < 0.005) { continue; } $units += max(0, (int) $line->get_quantity()); $revenue += (float) $line->get_total() + (float) $line->get_total_tax(); } return array($units, round($revenue, 2)); } private function gift_line_log_id($line) { $id = (int) $line->get_meta('_aieo_dmm_gift_offer_id', true); if ($id <= 0 || 'of' !== (string) $line->get_meta('_aieo_offer_store', true)) { return array($id, 'gift'); } global $wpdb; if (!self::first_columns_ready()) { return array($id, 'of_gift'); } $row = $wpdb->get_row($wpdb->prepare("SELECT id, legacy_table, legacy_id FROM {$wpdb->prefix}aieo_dmm_offers WHERE id = %d", $id), ARRAY_A); if (!AIEO_DMM_Schema_Gate::failed('attributor') && is_array($row) && self::need_offer_ids()) { $named = AIEO_DMM_Offer_Ids::record_id($row); if ('go' === $named['s']) { return array((int) $named['id'], 'gift'); } } return array($id, 'of_gift'); } private function discount_log_id(array $offer) { $store = 'bd'; $id = (int) (!empty($offer['legacy_id']) ? $offer['legacy_id'] : ($offer['id'] ?? 0)); if (isset($offer['s']) && '' !== (string) $offer['s']) { $store = (string) $offer['s']; } elseif (array_key_exists('legacy_table', $offer)) { list($store, $id) = AIEO_DMM_Offer_Matcher::store_id($offer); } return array((int) $id, 'of' === $store ? 'of_discount' : 'discount'); } private function one_table_row($id) { global $wpdb; $tbl = $wpdb->prefix . 'aieo_dmm_offers'; if (!self::first_columns_ready()) { return array(); } $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$tbl} WHERE id = %d", (int) $id), ARRAY_A); return !AIEO_DMM_Schema_Gate::failed('attributor') && is_array($row) ? $row : array(); } private static function first_columns_ready() { global $wpdb; if (!class_exists('AIEO_DMM_Schema_Gate', false)) { require_once __DIR__ . '/class-aieo-dmm-schema-gate.php'; } return function_exists('aieo_dmm_table_exists') && aieo_dmm_table_exists($wpdb->prefix . 'aieo_dmm_offers'); } private static function need_offer_ids() { if (!class_exists('AIEO_DMM_Offer_Ids') && is_readable(__DIR__ . '/class-aieo-dmm-offer-ids.php')) { require_once __DIR__ . '/class-aieo-dmm-offer-ids.php'; } return class_exists('AIEO_DMM_Offer_Ids', false); } private function discount_rules_of_the_price($product_id) { $out = array(); foreach ((array) AIEO_DMM_Pricing_Engine::instance()->matching_discount_rules((int) $product_id) as $rule) { $out[] = array('legacy_id' => (int) $rule['id']) + $rule; } return $out; } private function gift_offer_row($offer_id) { global $wpdb; $tbl = $wpdb->prefix . 'aieo_dmm_brand_gift_offers'; if (!aieo_dmm_table_exists($tbl)) { return array(); } $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$tbl} WHERE id = %d", (int) $offer_id), ARRAY_A); return is_array($row) ? $row : array(); } private function free_shipping_rule_row($rule_id) { global $wpdb; $tbl = $wpdb->prefix . 'aieo_dmm_offers'; if (!self::first_columns_ready()) { return array(); } $row = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$tbl} WHERE id = %d AND type = 'free_shipping'", (int) $rule_id), ARRAY_A); return !AIEO_DMM_Schema_Gate::failed('attributor') && is_array($row) ? $row : array(); } private function resolve_entry_channel($order) { if ( class_exists( 'AIEO_Order_Facts' ) ) { $ch = AIEO_Order_Facts::channel( (int) $order->get_id() ); if ( null !== $ch && '' !== $ch ) { return $ch; } } $val = (string) $order->get_meta('_aieo_entry_channel', true); return $val !== '' ? $val : 'unattributed'; } private function resolve_entry_branch_id($order) { if (!class_exists('AIEO_DMM_Branches')) { require_once __DIR__ . '/class-aieo-dmm-branches.php'; } return AIEO_DMM_Branches::id_for_order($order); } private function resolve_entry_campaign_id($order) { $slug = (string) $order->get_meta('_aieo_entry_campaign', true); if ($slug === '') { return null; } if (!class_exists('AIEO_DMM_Campaigns')) { return null; } $id = AIEO_DMM_Campaigns::id_for_slug($slug); return $id ? (int) $id : null; } private function load_active_discount_offers() { global $wpdb; if (aieo_dmm_table_exists($wpdb->prefix . 'aieo_dmm_brand_discounts')) { return $this->load_active_legacy_discount_offers(); } return $this->load_active_one_table_discount_offers(); } private function load_active_one_table_discount_offers() { global $wpdb; $tbl = $wpdb->prefix . 'aieo_dmm_offers'; if (!self::first_columns_ready()) { return array(); } if (!class_exists('AIEO_DMM_Schedule', false)) { require_once __DIR__ . '/class-aieo-dmm-schedule.php'; } $today = AIEO_DMM_Schedule::today(); $rows = $wpdb->get_results($wpdb->prepare( "SELECT *, UNIX_TIMESTAMP(created_at) AS created_ts FROM {$tbl} WHERE type = 'discount' AND enabled = 1 AND (start_date IS NULL OR start_date <= %s) AND (end_date IS NULL OR end_date >= %s)", $today, $today ), ARRAY_A); return !AIEO_DMM_Schema_Gate::failed('attributor') && is_array($rows) ? $rows : array(); } private function load_active_legacy_discount_offers() { global $wpdb; $tbl = $wpdb->prefix . 'aieo_dmm_brand_discounts'; if (!aieo_dmm_table_exists($tbl)) { return array(); } $today = current_time('Y-m-d'); $rows = $wpdb->get_results($wpdb->prepare( "SELECT *, UNIX_TIMESTAMP(created_at) AS created_ts FROM {$tbl} WHERE enabled = 1 AND (date_from IS NULL OR date_from <= %s) AND (date_to IS NULL OR date_to >= %s)", $today, $today ), ARRAY_A); if (!is_array($rows)) { return array(); } static $asked = false; if (!$asked && class_exists('AIEO_DMM_Offers_Held') && class_exists('AIEO_DMM_Pricing_Engine') && (!AIEO_DMM_Offers_Held::seeded('bd_pattern_or') || !AIEO_DMM_Offers_Held::seeded('bd_cart_conditions'))) { $asked = true; AIEO_DMM_Pricing_Engine::instance()->load_brand_discount_rules(); } $held = class_exists('AIEO_DMM_Offers_Held') ? AIEO_DMM_Offers_Held::ids('bd') : array(); if ($held) { $rows = array_values(array_filter($rows, static function ($row) use ($held) { return !in_array((int) ($row['id'] ?? 0), $held, true); })); } foreach ($rows as &$r) { $bid = isset($r['brand_term_id']) ? (int) $r['brand_term_id'] : 0; if (empty($r['brand_term_ids'])) { $r['brand_term_ids'] = $bid > 0 ? wp_json_encode(array($bid)) : '[]'; } $r['legacy_id'] = isset($r['id']) ? (int) $r['id'] : 0; } unset($r); return $rows; } private function not_excluding_the_line(array $matched, $line) { if (!$matched) { return $matched; } $parent = (int) $line->get_product_id(); $priced = (int) ($line->get_variation_id() ?: $parent); $self = array_values(array_unique(array($priced, $parent))); $context = AIEO_DMM_Offer_Matcher::product_context($parent); $context['product_ids'] = $self; $context['code_ids'] = $self; return array_values(array_filter($matched, static function ($offer) use ($context) { return !AIEO_DMM_Offer_Matcher::offer_excludes((array) $offer, $context); })); } private function applied_discount_row($line, array $matched) { $matched = array_values($matched); $id_of = static function (array $row) { return (int) (!empty($row['legacy_id']) ? $row['legacy_id'] : ($row['id'] ?? 0)); }; $stamp = json_decode((string) $line->get_meta('_aieo_offers', true), true); if (is_array($stamp) && !empty($stamp['offers']) && is_array($stamp['offers'])) { foreach ($stamp['offers'] as $named) { if (!is_array($named) || 'applied' !== ($named['role'] ?? '')) { continue; } if ('of' === (string) ($named['s'] ?? '')) { foreach ($matched as $row) { if ($this->one_table_id_of_row($row, $id_of($row)) === (int) ($named['id'] ?? 0)) { return $row; } } continue; } foreach ($matched as $row) { if ($id_of($row) === (int) ($named['id'] ?? 0)) { return $row; } } } } if (count($matched) === 1 || !class_exists('AIEO_DMM_Offer_Matcher') || !is_callable(array('AIEO_DMM_Offer_Matcher', 'rank'))) { return $matched[0]; } $offers = array(); foreach ($matched as $i => $row) { $payload = isset($row['payload']) ? json_decode((string) $row['payload'], true) : null; $percent = is_array($payload) ? (float) ($payload['discount_value'] ?? 0) : (float) ($row['percent'] ?? 0); $offers[] = array( 's' => 'bd', 'id' => $id_of($row), 'pct' => $percent, 'w' => (int) AIEO_DMM_Offer_Matcher::width_of_row($row), 'start' => (string) AIEO_DMM_Offer_Matcher::start_of_row($row), 'row' => $i, ); } $ranked = AIEO_DMM_Offer_Matcher::rank($offers, 100.0); return $matched[(int) $ranked['offers'][0]['row']]; } private function one_table_id_of_row(array $row, $record_id) { if (!empty($row['offer_id'])) { return (int) $row['offer_id']; } if (array_key_exists('legacy_table', $row)) { return (int) ($row['id'] ?? 0); } return class_exists('AIEO_DMM_Offer_Ids') ? AIEO_DMM_Offer_Ids::resolve('bd', (int) $record_id) : 0; } private function offer_label($offer_id, $offer_type, $fallback = '') { if ($fallback !== '') { return $fallback; } if (self::need_offer_ids() && in_array(AIEO_DMM_Offer_Ids::log_kind((string) $offer_type), array('discount', 'gift'), true)) { $row_id = isset(AIEO_DMM_Offer_Ids::LOG_OWN_IDS[(string) $offer_type]) ? (int) $offer_id : AIEO_DMM_Offer_Ids::for_log_row((string) $offer_type, (int) $offer_id); if ($row_id > 0 && self::first_columns_ready()) { global $wpdb; $label = trim((string) $wpdb->get_var($wpdb->prepare("SELECT label FROM {$wpdb->prefix}aieo_dmm_offers WHERE id = %d", $row_id))); if (!AIEO_DMM_Schema_Gate::failed('attributor') && '' !== $label) { return $label; } } } return $offer_type . '#' . (int) $offer_id; } private function popup_offer_id($code) { if (!class_exists('AIEO_DMM_Offer_Access') || !AIEO_DMM_Offer_Access::is_on() || !function_exists('wc_get_coupon_id_by_code')) { return 0; } $coupon_id = (int) wc_get_coupon_id_by_code((string) $code); return $coupon_id > 0 ? max(0, (int) get_post_meta($coupon_id, AIEO_DMM_Offer_Access::COUPON_OFFER, true)) : 0; } private function coupon_discount_on_order($order, $code) { $code = strtolower((string) $code); $sum = 0.0; foreach ($order->get_items('coupon') as $coupon_item) { if (strtolower((string) $coupon_item->get_code()) !== $code) { continue; } $sum += (float) $coupon_item->get_discount(); $sum += (float) $coupon_item->get_discount_tax(); } return $sum; } }