get_id() : (int) $order; if ( $id > 0 ) { self::sync_order( $id ); } } public static function on_status( $order_id, $from = '', $to = '', $order = null ) { self::sync_order( (int) $order_id ); } public static function sync_order( $order_id ) { $order_id = (int) $order_id; if ( $order_id <= 0 ) { return false; } $s = self::backfill_orders( array( 'order_id' => $order_id ) ); return ! empty( $s['written'] ); } public static function sweep_recent( $days = 3 ) { $s = self::backfill_orders( array( 'since' => gmdate( 'Y-m-d', time() - max( 1, (int) $days ) * DAY_IN_SECONDS ), ) ); return isset( $s['written'] ) ? (int) $s['written'] : 0; } public static function credit_for_orders( array $order_ids ) { global $wpdb; $order_ids = array_values( array_unique( array_map( 'intval', $order_ids ) ) ); if ( empty( $order_ids ) ) { return array(); } $re = $wpdb->prefix . 'aieo_reco_events'; $ae = $wpdb->prefix . 'aieo_addcart_events'; if ( ! self::table_exists( $re ) || ! self::table_exists( $ae ) ) { return array(); } $in = implode( ',', array_fill( 0, count( $order_ids ), '%d' ) ); $sql = $wpdb->prepare( "SELECT order_id, surface, anchor_pid, anchor_term_id, anchor_term_tax, target_pid, position, click_at, line_value FROM ( SELECT e.order_id, r.surface, r.anchor_pid, r.anchor_term_id, r.anchor_term_tax, r.target_pid, r.position, r.ts AS click_at, ( e.unit_price * GREATEST(e.quantity, 1) ) AS line_value, ROW_NUMBER() OVER ( PARTITION BY e.order_id ORDER BY ( e.unit_price * GREATEST(e.quantity, 1) ) DESC, r.ts DESC, r.id ASC ) AS rn FROM `{$re}` r JOIN `{$ae}` e ON e.session_id = r.session_id AND e.product_id = r.target_pid AND e.ts_added > r.ts AND e.ts_added < DATE_ADD(r.ts, INTERVAL %d DAY) WHERE r.event_type = 'reco_click' AND e.order_id IN ({$in}) ) x WHERE rn = 1", array_merge( array( self::ASSIST_WINDOW_DAYS ), $order_ids ) ); $multi = array(); foreach ( (array) $wpdb->get_results( $wpdb->prepare( "SELECT e.order_id, COUNT(DISTINCT r.surface) n FROM `{$re}` r JOIN `{$ae}` e ON e.session_id = r.session_id AND e.product_id = r.target_pid AND e.ts_added > r.ts AND e.ts_added < DATE_ADD(r.ts, INTERVAL %d DAY) WHERE r.event_type = 'reco_click' AND e.order_id IN ({$in}) GROUP BY e.order_id", array_merge( array( self::ASSIST_WINDOW_DAYS ), $order_ids ) ), ARRAY_A ) as $r ) { $multi[ (int) $r['order_id'] ] = (int) $r['n']; } $out = array(); foreach ( (array) $wpdb->get_results( $sql, ARRAY_A ) as $r ) { $oid = (int) $r['order_id']; $a_type = ''; $a_id = 0; if ( (int) $r['anchor_pid'] > 0 ) { $a_type = 'product'; $a_id = (int) $r['anchor_pid']; } elseif ( (int) $r['anchor_term_id'] > 0 ) { $a_type = (string) $r['anchor_term_tax'] !== '' ? substr( (string) $r['anchor_term_tax'], 0, 20 ) : 'term'; $a_id = (int) $r['anchor_term_id']; } $out[ $oid ] = array( 'int_surface' => (string) $r['surface'], 'int_anchor_type' => $a_type, 'int_anchor_id' => $a_id, 'int_target_id' => (int) $r['target_pid'], 'int_position' => (int) $r['position'], 'int_click_at' => (string) $r['click_at'], 'int_origin' => AIEO_DMM_Conversions_Registry::INT_RECO_CLICK, '_surfaces_seen' => isset( $multi[ $oid ] ) ? $multi[ $oid ] : 1, ); } return $out; } public static function backfill_orders( array $args = array() ) { global $wpdb; $since = isset( $args['since'] ) ? (string) $args['since'] : '2019-01-01'; $until = isset( $args['until'] ) ? (string) $args['until'] : gmdate( 'Y-m-d', time() + DAY_IN_SECONDS ); $limit = isset( $args['limit'] ) ? (int) $args['limit'] : 0; $only_id = isset( $args['order_id'] ) ? (int) $args['order_id'] : 0; $dry = ! empty( $args['dry_run'] ); $batch = 500; if ( ! AIEO_DMM_Conversions_Registry::ensure_schema() ) { return array( 'error' => 'schema_unavailable' ); } $P = $wpdb->prefix; if ( ! AIEO_Order_Store::hpos_readable() ) { return array( 'scanned' => 0, 'written' => 0, 'with_external' => 0, 'with_internal' => 0, 'both_planes' => 0, 'neither' => 0, 'multi_surface' => 0, 'rejected_external' => 0, 'by_surface' => array(), 'skipped' => self::table_exists( $P . 'wc_orders' ) ? 'orders_not_in_hpos' : 'no_woocommerce_orders_table', ); } $oa = $P . 'aieo_order_attribution'; $has_oa = self::table_exists( $oa ); if ( ! class_exists( 'AIEO_DMM_Branches' ) ) { require_once __DIR__ . '/services/class-aieo-dmm-branches.php'; } $stats = array( 'scanned' => 0, 'written' => 0, 'with_external' => 0, 'with_internal' => 0, 'both_planes' => 0, 'neither' => 0, 'multi_surface' => 0, 'rejected_external' => 0, 'by_surface' => array(), 'dry_run' => $dry, ); $last = 0; while ( true ) { if ( $only_id > 0 ) { $orders = $wpdb->get_results( $wpdb->prepare( "SELECT o.id, o.status, o.date_created_gmt, o.total_amount, o.currency, o.customer_id FROM {$P}wc_orders o WHERE o.id = %d AND o.status NOT IN ('trash','auto-draft','wc-checkout-draft')", $only_id ), ARRAY_A ); } else { $orders = $wpdb->get_results( $wpdb->prepare( "SELECT o.id, o.status, o.date_created_gmt, o.total_amount, o.currency, o.customer_id FROM {$P}wc_orders o WHERE o.id > %d AND o.status NOT IN ('trash','auto-draft','wc-checkout-draft') AND o.date_created_gmt >= %s AND o.date_created_gmt < %s ORDER BY o.id ASC LIMIT %d", $last, $since . ' 00:00:00', $until . ' 00:00:00', $batch ), ARRAY_A ); } if ( empty( $orders ) ) { break; } $ids = array(); foreach ( $orders as $o ) { $ids[] = (int) $o['id']; $last = (int) $o['id']; } $ext = array(); if ( $has_oa ) { $in = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); foreach ( (array) $wpdb->get_results( $wpdb->prepare( "SELECT order_id, channel, utm_source, utm_medium, utm_campaign, utm_term, utm_content, origin FROM `{$oa}` WHERE order_id IN ({$in})", $ids ), ARRAY_A ) as $r ) { $ext[ (int) $r['order_id'] ] = $r; } } $meta = array(); $in = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); foreach ( (array) $wpdb->get_results( $wpdb->prepare( "SELECT order_id, meta_key, meta_value FROM {$P}wc_orders_meta WHERE order_id IN ({$in}) AND meta_key IN ('_wc_order_attribution_utm_source','_wc_order_attribution_utm_medium', '_wc_order_attribution_utm_campaign','_wc_order_attribution_utm_term', '_wc_order_attribution_utm_content','_wc_order_attribution_referrer', '_wc_order_attribution_session_entry','soft1_branches')", $ids ), ARRAY_A ) as $r ) { $k = str_replace( '_wc_order_attribution_', '', (string) $r['meta_key'] ); $meta[ (int) $r['order_id'] ][ $k ] = (string) $r['meta_value']; } $internal = self::credit_for_orders( $ids ); foreach ( $orders as $o ) { $oid = (int) $o['id']; $stats['scanned']++; $row = array( 'conversion_type' => AIEO_DMM_Conversions_Registry::TYPE_ORDER, 'source_key' => AIEO_DMM_Conversions_Registry::source_key_for_order( $oid ), 'occurred_at' => (string) $o['date_created_gmt'], 'order_id' => $oid, 'order_status' => (string) $o['status'], 'customer_id' => (int) $o['customer_id'], 'conversion_value' => (float) $o['total_amount'], 'value_basis' => 'order_total', 'currency' => (string) $o['currency'], 'entry_branch_id' => AIEO_DMM_Branches::id_for_erp( isset( $meta[ $oid ]['soft1_branches'] ) ? $meta[ $oid ]['soft1_branches'] : '' ), ); $src = isset( $ext[ $oid ] ) ? $ext[ $oid ] : array(); $origin = 'aieo'; if ( empty( $src['utm_source'] ) && isset( $meta[ $oid ]['utm_source'] ) ) { $src = array( 'utm_source' => $meta[ $oid ]['utm_source'], 'utm_medium' => isset( $meta[ $oid ]['utm_medium'] ) ? $meta[ $oid ]['utm_medium'] : '', 'utm_campaign' => isset( $meta[ $oid ]['utm_campaign'] ) ? $meta[ $oid ]['utm_campaign'] : '', 'utm_term' => isset( $meta[ $oid ]['utm_term'] ) ? $meta[ $oid ]['utm_term'] : '', 'utm_content' => isset( $meta[ $oid ]['utm_content'] ) ? $meta[ $oid ]['utm_content'] : '', 'channel' => '', ); $origin = 'wc_native'; } $ext_src = isset( $src['utm_source'] ) ? (string) $src['utm_source'] : ''; $reject = AIEO_DMM_Conversions_Registry::rejection_reason( $ext_src ); if ( 'internal_upsell_tagging' === $reject ) { $aio = AIEO_DMM_Conversions_Registry::aio_surface_map(); $sf = isset( $aio[ strtolower( $ext_src ) ] ) ? $aio[ strtolower( $ext_src ) ] : ''; if ( '' !== $sf && '' === ( isset( $row['int_surface'] ) ? $row['int_surface'] : '' ) ) { $pair = array( 0, 0, 0 ); if ( preg_match( '/^(\d+)_(\d+)_(\d+)$/', (string) ( isset( $src['utm_campaign'] ) ? $src['utm_campaign'] : '' ), $m ) ) { $pair = array( (int) $m[1], (int) $m[2], (int) $m[3] ); } $row['int_surface'] = $sf; $row['int_anchor_type'] = 'product'; $row['int_position'] = $pair[0]; $row['int_anchor_id'] = $pair[1]; $row['int_target_id'] = $pair[2]; $row['int_origin'] = AIEO_DMM_Conversions_Registry::INT_AIO_IMPORT; } $row['utm_medium'] = isset( $src['utm_medium'] ) ? (string) $src['utm_medium'] : ''; $row['attr_origin'] = AIEO_DMM_Conversions_Registry::EXT_OVERWRITTEN; $row['channel'] = ''; $stats['rejected_external']++; } elseif ( '' === $reject ) { $row['utm_source'] = $ext_src; $row['utm_medium'] = isset( $src['utm_medium'] ) ? (string) $src['utm_medium'] : ''; $row['utm_campaign'] = isset( $src['utm_campaign'] ) ? (string) $src['utm_campaign'] : ''; $row['utm_term'] = isset( $src['utm_term'] ) ? (string) $src['utm_term'] : ''; $row['utm_content'] = isset( $src['utm_content'] ) ? (string) $src['utm_content'] : ''; $row['channel'] = isset( $src['channel'] ) ? (string) $src['channel'] : ''; $row['attr_origin'] = $origin; $stats['with_external']++; } $entry = isset( $meta[ $oid ]['session_entry'] ) ? (string) $meta[ $oid ]['session_entry'] : ''; if ( '' !== $entry ) { $lp = self::landing_path_of( $entry ); if ( '' !== $lp ) { $row['landing_path'] = $lp; $pid = self::landing_post_id( $lp ); if ( $pid > 0 ) { $row['landing_post_id'] = $pid; } } } if ( isset( $internal[ $oid ] ) ) { $i = $internal[ $oid ]; if ( $i['_surfaces_seen'] > 1 ) { $stats['multi_surface']++; } unset( $i['_surfaces_seen'] ); $row = array_merge( $row, $i ); } if ( ! empty( $row['int_surface'] ) ) { $stats['with_internal']++; $sf = $row['int_surface']; $stats['by_surface'][ $sf ] = ( isset( $stats['by_surface'][ $sf ] ) ? $stats['by_surface'][ $sf ] : 0 ) + 1; if ( ! empty( $row['utm_source'] ) ) { $stats['both_planes']++; } } elseif ( empty( $row['utm_source'] ) ) { $stats['neither']++; } if ( ! $dry ) { if ( false !== AIEO_DMM_Conversions_Registry::record( $row ) ) { $stats['written']++; } } else { $stats['written']++; } if ( $limit > 0 && $stats['scanned'] >= $limit ) { break 2; } } if ( $only_id > 0 ) { break; } } arsort( $stats['by_surface'] ); return $stats; } public static function ipr_value( $surface, $placement_id = 0 ) { $surface = sanitize_key( (string) $surface ); $placement_id = (int) $placement_id; return $placement_id > 0 ? $surface . self::IPR_PLACEMENT . $placement_id : $surface; } public static function read_ipr( $value ) { $none = array( 'surface' => '', 'placement_id' => 0, ); if ( ! is_string( $value ) ) { return $none; } $value = strtolower( trim( $value ) ); if ( '' === $value || strlen( $value ) > self::IPR_MAX || 1 !== preg_match( '/^[a-z0-9_-]+$/', $value ) ) { return $none; } if ( 1 === preg_match( '/^(.+)' . preg_quote( self::IPR_PLACEMENT, '/' ) . '([1-9][0-9]{0,17})$/', $value, $m ) ) { return array( 'surface' => $m[1], 'placement_id' => (int) $m[2], ); } return array( 'surface' => $value, 'placement_id' => 0, ); } public static function ipr_of_url( $url ) { $query = wp_parse_url( (string) $url, PHP_URL_QUERY ); $args = array(); if ( is_string( $query ) && '' !== $query ) { parse_str( $query, $args ); } return self::read_ipr( isset( $args[ self::IPR_PARAM ] ) ? $args[ self::IPR_PARAM ] : null ); } private static function table_exists( $table ) { global $wpdb; return (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table; } private static function landing_path_of( $url ) { $url = trim( (string) $url ); if ( '' === $url ) { return ''; } $p = wp_parse_url( $url, PHP_URL_PATH ); if ( ! is_string( $p ) || '' === $p ) { return '/'; } $p = strtok( $p, '#' ); if ( strlen( $p ) > 1 ) { $p = rtrim( $p, '/' ); } return substr( '' === $p ? '/' : $p, 0, 500 ); } private static function landing_post_id( $path ) { static $cache = array(); if ( isset( $cache[ $path ] ) ) { return $cache[ $path ]; } if ( count( $cache ) > 5000 ) { $cache = array(); } $id = (int) url_to_postid( home_url( $path ) ); $cache[ $path ] = $id; return $id; } }