is_configured() ) { echo json_encode( [ 'result' => 'Google Ads API nie jest skonfigurowane. Uzupelnij dane w Ustawieniach.' ] ); exit; } $date = \S::get( 'date' ) ? date( 'Y-m-d', strtotime( \S::get( 'date' ) ) ) : date( 'Y-m-d', strtotime( '-1 days' ) ); $client_id = (int) \S::get( 'client_id' ); if ( $client_id > 0 ) { $client = $mdb -> get( 'clients', '*', [ 'AND' => [ 'id' => $client_id, 'google_ads_customer_id[!]' => null, 'deleted' => 0 ] ] ); if ( !$client || trim( (string) $client['google_ads_customer_id'] ) === '' ) { echo json_encode( [ 'result' => 'Nie znaleziono klienta z poprawnym Google Ads Customer ID.', 'client_id' => $client_id ] ); exit; } $sync = self::sync_products_fetch_for_client( $client, $api, $date ); $history_30 = self::aggregate_products_history_30_for_client( (int) $client['id'], $date ); $temp_rows = self::rebuild_products_temp_for_client( (int) $client['id'] ); echo json_encode( [ 'result' => empty( $sync['errors'] ) ? 'Synchronizacja produktow zakonczona.' : 'Synchronizacja produktow zakonczona z bledami.', 'client_id' => (int) $client['id'], 'date' => $date, 'phase' => 'single_full', 'processed_products' => (int) $sync['processed_products'], 'skipped' => (int) $sync['skipped'], 'history_30_products' => (int) $history_30, 'products_temp_rows' => (int) $temp_rows, 'errors' => $sync['errors'] ] ); exit; } $client_ids = $mdb -> query( "SELECT id FROM clients WHERE deleted = 0 AND google_ads_customer_id IS NOT NULL AND google_ads_customer_id <> '' ORDER BY id ASC" ) -> fetchAll( \PDO::FETCH_COLUMN ); $client_ids = array_values( array_unique( array_map( 'intval', $client_ids ) ) ); if ( empty( $client_ids ) ) { echo json_encode( [ 'result' => 'Brak klientow z ustawionym Google Ads Customer ID do przetworzenia.', 'processed_clients' => 0, 'errors' => [] ] ); exit; } $state_key = 'cron_products_pipeline_state'; $state = self::get_products_pipeline_state( $state_key, $date, $client_ids ); if ( $state['phase'] === 'done' ) { echo json_encode( [ 'result' => 'Pipeline cron_products jest zakonczony dla tej daty.', 'date' => $state['import_date'], 'phase' => 'done', 'total_clients' => count( $client_ids ) ] ); exit; } $phase_map = [ 'fetch' => 'fetch_done_ids', 'aggregate_30' => 'aggregate_30_done_ids', 'aggregate_temp' => 'aggregate_temp_done_ids' ]; $done_key = $phase_map[ $state['phase'] ] ?? null; if ( !$done_key ) { $state = self::init_products_pipeline_state( $date, $client_ids ); $done_key = 'fetch_done_ids'; } $next_client_id = self::pick_next_client_id( $client_ids, $state[ $done_key ] ); if ( !$next_client_id ) { $state = self::advance_products_pipeline_phase( $state ); self::save_products_pipeline_state( $state_key, $state ); echo json_encode( [ 'result' => 'Faza zakonczona. Przejdz do nastepnej fazy kolejnym wywolaniem.', 'date' => $state['import_date'], 'phase' => $state['phase'], 'total_clients' => count( $client_ids ) ] ); exit; } $selected_client = $mdb -> get( 'clients', '*', [ 'id' => $next_client_id ] ); if ( !$selected_client ) { echo json_encode( [ 'result' => 'Nie udalo sie wybrac klienta do synchronizacji produktow.', 'client_id' => $next_client_id ] ); exit; } $response = [ 'result' => '', 'date' => $state['import_date'], 'phase' => $state['phase'], 'client_id' => (int) $selected_client['id'], 'errors' => [] ]; if ( $state['phase'] === 'fetch' ) { $sync = self::sync_products_fetch_for_client( $selected_client, $api, $state['import_date'] ); $response['result'] = empty( $sync['errors'] ) ? 'Pobieranie produktow zakonczone.' : 'Pobieranie produktow zakonczone z bledami.'; $response['processed_products'] = (int) $sync['processed_products']; $response['skipped'] = (int) $sync['skipped']; $response['errors'] = $sync['errors']; } else if ( $state['phase'] === 'aggregate_30' ) { $history_30 = self::aggregate_products_history_30_for_client( (int) $selected_client['id'], $state['import_date'] ); $response['result'] = 'Pierwsza agregacja (history_30) zakonczona.'; $response['history_30_products'] = (int) $history_30; } else if ( $state['phase'] === 'aggregate_temp' ) { $temp_rows = self::rebuild_products_temp_for_client( (int) $selected_client['id'] ); $response['result'] = 'Druga agregacja (products_temp) zakonczona.'; $response['products_temp_rows'] = (int) $temp_rows; } // Oznaczamy klienta jako przetworzonego rowniez po bledzie, aby nie zapetlac wywolan. $state[ $done_key ][] = (int) $next_client_id; $state[ $done_key ] = array_values( array_unique( array_map( 'intval', $state[ $done_key ] ) ) ); self::save_products_pipeline_state( $state_key, $state ); $processed_in_phase = count( array_intersect( $client_ids, $state[ $done_key ] ) ); $response['processed_clients_in_phase'] = $processed_in_phase; $response['remaining_clients_in_phase'] = max( 0, count( $client_ids ) - $processed_in_phase ); $response['total_clients'] = count( $client_ids ); echo json_encode( $response ); exit; } static private function init_products_pipeline_state( $date, $client_ids ) { return [ 'import_date' => date( 'Y-m-d', strtotime( $date ) ), 'clients_hash' => md5( implode( ',', $client_ids ) ), 'phase' => 'fetch', 'fetch_done_ids' => [], 'aggregate_30_done_ids' => [], 'aggregate_temp_done_ids' => [] ]; } static private function get_products_pipeline_state( $state_key, $date, $client_ids ) { $state_raw = self::get_setting_value( $state_key, '' ); $state = json_decode( (string) $state_raw, true ); $expected_date = date( 'Y-m-d', strtotime( $date ) ); $expected_hash = md5( implode( ',', $client_ids ) ); if ( !is_array( $state ) ) { return self::init_products_pipeline_state( $expected_date, $client_ids ); } if ( ( $state['import_date'] ?? '' ) !== $expected_date || ( $state['clients_hash'] ?? '' ) !== $expected_hash ) { return self::init_products_pipeline_state( $expected_date, $client_ids ); } foreach ( [ 'fetch_done_ids', 'aggregate_30_done_ids', 'aggregate_temp_done_ids' ] as $key ) { if ( !isset( $state[ $key ] ) || !is_array( $state[ $key ] ) ) { $state[ $key ] = []; } $state[ $key ] = array_values( array_unique( array_map( 'intval', $state[ $key ] ) ) ); } if ( !isset( $state['phase'] ) ) { $state['phase'] = 'fetch'; } return $state; } static private function save_products_pipeline_state( $state_key, $state ) { self::set_setting_value( $state_key, json_encode( $state, JSON_UNESCAPED_UNICODE ) ); } static private function advance_products_pipeline_phase( $state ) { if ( $state['phase'] === 'fetch' ) { $state['phase'] = 'aggregate_30'; return $state; } if ( $state['phase'] === 'aggregate_30' ) { $state['phase'] = 'aggregate_temp'; return $state; } $state['phase'] = 'done'; return $state; } static private function sync_products_fetch_for_client( $client, $api, $date ) { global $mdb; $client_id = (int) $client['id']; $customer_id = trim( (string) ( $client['google_ads_customer_id'] ?? '' ) ); $date = date( 'Y-m-d', strtotime( $date ) ); $products = $api -> get_products_for_date( $customer_id, $date ); if ( $products === false ) { $last_err = \services\GoogleAdsApi::get_setting( 'google_ads_last_error' ); return [ 'date' => $date, 'processed_products' => 0, 'skipped' => 0, 'history_30_products' => 0, 'products_temp_rows' => 0, 'errors' => [ 'Blad API dla klienta ' . $client['name'] . ' (ID: ' . $customer_id . '): ' . $last_err ] ]; } if ( !is_array( $products ) ) { $products = []; } $processed = 0; $skipped = 0; $touched_product_ids = []; foreach ( $products as $offer ) { $offer_external_id = trim( (string) ( $offer['OfferId'] ?? '' ) ); if ( $offer_external_id === '' ) { $skipped++; continue; } $product_title = trim( (string) ( $offer['ProductTitle'] ?? '' ) ); if ( $product_title === '' ) { $product_title = $offer_external_id; } if ( !$mdb -> count( 'products', [ 'AND' => [ 'client_id' => $client_id, 'offer_id' => $offer_external_id ] ] ) ) { $mdb -> insert( 'products', [ 'client_id' => $client_id, 'offer_id' => $offer_external_id, 'name' => $product_title ] ); $product_id = $mdb -> id(); } else { $product_id = $mdb -> get( 'products', 'id', [ 'AND' => [ 'client_id' => $client_id, 'offer_id' => $offer_external_id ] ] ); $offer_current_name = $mdb -> get( 'products', 'name', [ 'AND' => [ 'client_id' => $client_id, 'offer_id' => $offer_external_id ] ] ); if ( $offer_current_name != $product_title and $date == date( 'Y-m-d', strtotime( '-1 days' ) ) ) { $mdb -> update( 'products', [ 'name' => $product_title ], [ 'AND' => [ 'client_id' => $client_id, 'offer_id' => $offer_external_id ] ] ); } } if ( !$product_id ) { $skipped++; continue; } $campaign_external_id = (int) ( $offer['CampaignId'] ?? 0 ); $campaign_name = trim( (string) ( $offer['CampaignName'] ?? '' ) ); $ad_group_external_id = (int) ( $offer['AdGroupId'] ?? 0 ); $ad_group_name = trim( (string) ( $offer['AdGroupName'] ?? '' ) ); $scope = self::resolve_products_scope_ids( $client_id, $campaign_external_id, $campaign_name, $ad_group_external_id, $ad_group_name, $date ); $db_campaign_id = (int) ( $scope['campaign_id'] ?? 0 ); $db_ad_group_id = (int) ( $scope['ad_group_id'] ?? 0 ); $impressions = (int) round( (float) ( $offer['Impressions'] ?? 0 ) ); $clicks = (int) round( (float) ( $offer['Clicks'] ?? 0 ) ); $cost = (float) ( $offer['Cost'] ?? 0 ); $conversions = (float) ( $offer['Conversions'] ?? 0 ); $conversion_value = (float) ( $offer['ConversionValue'] ?? 0 ); $ctr = ( $impressions > 0 ) ? round( $clicks / $impressions, 4 ) * 100 : 0; $offer_data = [ 'impressions' => $impressions, 'clicks' => $clicks, 'ctr' => $ctr, 'cost' => $cost, 'conversions' => $conversions, 'conversions_value' => $conversion_value, 'updated' => 1, 'campaign_id' => $db_campaign_id, 'ad_group_id' => $db_ad_group_id ]; if ( $mdb -> count( 'products_history', [ 'AND' => [ 'product_id' => $product_id, 'campaign_id' => $db_campaign_id, 'ad_group_id' => $db_ad_group_id, 'date_add' => $date ] ] ) ) { $offer_data_old = $mdb -> get( 'products_history', '*', [ 'AND' => [ 'product_id' => $product_id, 'campaign_id' => $db_campaign_id, 'ad_group_id' => $db_ad_group_id, 'date_add' => $date ] ] ); if ( $offer_data_old['impressions'] == $offer_data['impressions'] and $offer_data_old['clicks'] == $offer_data['clicks'] and number_format( (float) str_replace( ',', '.', $offer_data_old['cost'] ), 5 ) == number_format( (float) $offer_data['cost'], 5 ) and (float) $offer_data_old['conversions'] == (float) $offer_data['conversions'] and number_format( (float) str_replace( ',', '.', $offer_data_old['conversions_value'] ), 5 ) == number_format( (float) $offer_data['conversions_value'], 5 ) ) { $touched_product_ids[ $product_id ] = true; $processed++; continue; } $mdb -> update( 'products_history', $offer_data, [ 'AND' => [ 'product_id' => $product_id, 'campaign_id' => $db_campaign_id, 'ad_group_id' => $db_ad_group_id, 'date_add' => $date ] ] ); } else { $offer_data['product_id'] = $product_id; $offer_data['date_add'] = $date; $mdb -> insert( 'products_history', $offer_data ); } $touched_product_ids[ $product_id ] = true; $processed++; } return [ 'date' => $date, 'processed_products' => $processed, 'skipped' => $skipped, 'touched_products' => count( $touched_product_ids ), 'errors' => [] ]; } static public function resolve_products_scope_ids( $client_id, $campaign_external_id, $campaign_name, $ad_group_external_id, $ad_group_name, $date_sync ) { $client_id = (int) $client_id; $campaign_external_id = (int) $campaign_external_id; $ad_group_external_id = (int) $ad_group_external_id; $db_campaign_id = self::ensure_products_campaign( $client_id, $campaign_external_id, $campaign_name, $date_sync ); if ( $db_campaign_id <= 0 ) { $db_campaign_id = self::ensure_products_campaign( $client_id, 0, '--- konto ---', $date_sync ); } $db_ad_group_id = self::ensure_products_ad_group( $db_campaign_id, $ad_group_external_id, $ad_group_name, $date_sync ); return [ 'campaign_id' => (int) $db_campaign_id, 'ad_group_id' => (int) $db_ad_group_id ]; } static private function ensure_products_campaign( $client_id, $campaign_external_id, $campaign_name, $date_sync ) { global $mdb; $client_id = (int) $client_id; $campaign_external_id = (int) $campaign_external_id; $campaign_name = trim( (string) $campaign_name ); if ( $client_id <= 0 ) { return 0; } $db_campaign_id = (int) $mdb -> get( 'campaigns', 'id', [ 'AND' => [ 'client_id' => $client_id, 'campaign_id' => $campaign_external_id ] ] ); if ( $db_campaign_id > 0 ) { if ( $campaign_name !== '' ) { $mdb -> update( 'campaigns', [ 'campaign_name' => $campaign_name ], [ 'id' => $db_campaign_id ] ); } return $db_campaign_id; } if ( $campaign_name === '' ) { $campaign_name = $campaign_external_id > 0 ? 'Kampania #' . $campaign_external_id : '--- konto ---'; } $mdb -> insert( 'campaigns', [ 'client_id' => $client_id, 'campaign_id' => $campaign_external_id, 'campaign_name' => $campaign_name ] ); $db_campaign_id = (int) $mdb -> id(); if ( $db_campaign_id > 0 && $date_sync ) { if ( !$mdb -> count( 'campaigns_history', [ 'AND' => [ 'campaign_id' => $db_campaign_id, 'date_add' => $date_sync ] ] ) ) { $mdb -> insert( 'campaigns_history', [ 'campaign_id' => $db_campaign_id, 'roas_30_days' => 0, 'roas_all_time' => 0, 'budget' => 0, 'money_spent' => 0, 'conversion_value' => 0, 'bidding_strategy' => '', 'date_add' => $date_sync ] ); } } return $db_campaign_id; } static private function ensure_products_ad_group( $db_campaign_id, $ad_group_external_id, $ad_group_name, $date_sync ) { global $mdb; $db_campaign_id = (int) $db_campaign_id; $ad_group_external_id = (int) $ad_group_external_id; $ad_group_name = trim( (string) $ad_group_name ); if ( $db_campaign_id <= 0 ) { return 0; } if ( $ad_group_external_id <= 0 ) { return (int) self::ensure_campaign_level_ad_group( $db_campaign_id, $date_sync ); } $db_ad_group_id = (int) $mdb -> get( 'campaign_ad_groups', 'id', [ 'AND' => [ 'campaign_id' => $db_campaign_id, 'ad_group_id' => $ad_group_external_id ] ] ); if ( $db_ad_group_id > 0 ) { if ( $ad_group_name !== '' ) { $mdb -> update( 'campaign_ad_groups', [ 'ad_group_name' => $ad_group_name ], [ 'id' => $db_ad_group_id ] ); } return $db_ad_group_id; } if ( $ad_group_name === '' ) { $ad_group_name = 'Ad group #' . $ad_group_external_id; } $mdb -> insert( 'campaign_ad_groups', [ 'campaign_id' => $db_campaign_id, 'ad_group_id' => $ad_group_external_id, 'ad_group_name' => $ad_group_name, 'impressions_30' => 0, 'clicks_30' => 0, 'cost_30' => 0, 'conversions_30' => 0, 'conversion_value_30' => 0, 'roas_30' => 0, 'impressions_all_time' => 0, 'clicks_all_time' => 0, 'cost_all_time' => 0, 'conversions_all_time' => 0, 'conversion_value_all_time' => 0, 'roas_all_time' => 0, 'date_sync' => $date_sync ] ); return (int) $mdb -> id(); } static private function aggregate_products_history_30_for_client( $client_id, $date ) { global $mdb; $client_id = (int) $client_id; $date = date( 'Y-m-d', strtotime( $date ) ); $rows = $mdb -> query( 'SELECT DISTINCT ph.product_id, ph.campaign_id, ph.ad_group_id, ph.date_add FROM products_history AS ph INNER JOIN products AS p ON p.id = ph.product_id WHERE p.client_id = ' . $client_id . ' AND ph.updated = 1 AND ph.date_add = \'' . $date . '\' ORDER BY ph.product_id ASC, ph.campaign_id ASC, ph.ad_group_id ASC' ) -> fetchAll( \PDO::FETCH_ASSOC ); $processed = 0; foreach ( $rows as $row ) { $product_id = (int) $row['product_id']; $campaign_id = (int) ( $row['campaign_id'] ?? 0 ); $ad_group_id = (int) ( $row['ad_group_id'] ?? 0 ); self::cron_product_history_30_save( $product_id, $row['date_add'], $campaign_id, $ad_group_id ); $mdb -> query( 'UPDATE products_history AS ph INNER JOIN products AS p ON p.id = ph.product_id SET ph.updated = 0 WHERE ph.product_id = :product_id AND ph.campaign_id = :campaign_id AND ph.ad_group_id = :ad_group_id AND ph.date_add = :date_add AND p.client_id = :client_id', [ ':product_id' => $product_id, ':campaign_id' => $campaign_id, ':ad_group_id' => $ad_group_id, ':date_add' => $row['date_add'], ':client_id' => $client_id ] ); $processed++; } return $processed; } static public function rebuild_products_temp_for_client( $client_id ) { global $mdb; $client_id = (int) $client_id; if ( $client_id <= 0 ) { return 0; } $client_bestseller_min_roas = (int) \factory\Products::get_client_bestseller_min_roas( $client_id ); $rows = $mdb -> query( 'SELECT p.id AS product_id, p.name, ph.campaign_id, ph.ad_group_id, COALESCE( SUM( ph.impressions ), 0 ) AS impressions, COALESCE( SUM( ph.clicks ), 0 ) AS clicks, COALESCE( SUM( ph.cost ), 0 ) AS cost, COALESCE( SUM( ph.conversions ), 0 ) AS conversions, COALESCE( SUM( ph.conversions_value ), 0 ) AS conversions_value FROM products AS p LEFT JOIN products_history AS ph ON p.id = ph.product_id WHERE p.client_id = :client_id GROUP BY p.id, p.name, ph.campaign_id, ph.ad_group_id', [ ':client_id' => $client_id ] ) -> fetchAll( \PDO::FETCH_ASSOC ); $product_ids = $mdb -> select( 'products', 'id', [ 'client_id' => $client_id ] ); $product_ids = array_values( array_unique( array_map( 'intval', (array) $product_ids ) ) ); if ( !empty( $product_ids ) ) { $mdb -> delete( 'products_temp', [ 'product_id' => $product_ids ] ); } // products_data jest globalne per product_id, wiec klasyfikacje liczymy globalnie. $global_totals = $mdb -> query( 'SELECT p.id AS product_id, COALESCE( SUM( ph.impressions ), 0 ) AS impressions, COALESCE( SUM( ph.clicks ), 0 ) AS clicks, COALESCE( SUM( ph.cost ), 0 ) AS cost, COALESCE( SUM( ph.conversions ), 0 ) AS conversions, COALESCE( SUM( ph.conversions_value ), 0 ) AS conversions_value FROM products AS p LEFT JOIN products_history AS ph ON p.id = ph.product_id WHERE p.client_id = :client_id GROUP BY p.id', [ ':client_id' => $client_id ] ) -> fetchAll( \PDO::FETCH_ASSOC ); foreach ( $global_totals as $total ) { $product_id = (int) ( $total['product_id'] ?? 0 ); if ( $product_id <= 0 ) { continue; } $total_cost = (float) ( $total['cost'] ?? 0 ); $total_conversions = (float) ( $total['conversions'] ?? 0 ); $total_conversion_value = (float) ( $total['conversions_value'] ?? 0 ); $total_roas = ( $total_conversions > 0 && $total_cost > 0 ) ? round( $total_conversion_value / $total_cost, 2 ) * 100 : 0; $custom_label_4 = \factory\Products::get_product_data( $product_id, 'custom_label_4' ); if ( $custom_label_4 == null || ( $custom_label_4 == 'bestseller' && $client_bestseller_min_roas > 0 ) ) { $new_custom_label_4 = ( $total_roas > $client_bestseller_min_roas && $total_conversions > 10 ) ? 'bestseller' : null; $offers_data_tmp = $mdb -> get( 'products_data', '*', [ 'product_id' => $product_id ] ); if ( isset( $offers_data_tmp['id'] ) ) { if ( $new_custom_label_4 != $offers_data_tmp['custom_label_4'] ) { $mdb -> insert( 'products_comments', [ 'product_id' => $product_id, 'comment' => 'Zmiana pola "custom_label_4" na: ' . $new_custom_label_4, 'type' => 1, 'date_add' => date( 'Y-m-d' ) ] ); } $mdb -> update( 'products_data', [ 'custom_label_4' => $new_custom_label_4 ], [ 'id' => $offers_data_tmp['id'] ] ); } else { $mdb -> insert( 'products_data', [ 'product_id' => $product_id, 'custom_label_4' => $new_custom_label_4 ] ); if ( $new_custom_label_4 == 'bestseller' ) { $mdb -> insert( 'products_comments', [ 'product_id' => $product_id, 'comment' => 'Zmiana pola "custom_label_4" na: bestseller', 'type' => 1, 'date_add' => date( 'Y-m-d' ) ] ); } } } } $processed_rows = 0; foreach ( $rows as $row ) { $product_id = (int) ( $row['product_id'] ?? 0 ); if ( $product_id <= 0 ) { continue; } $campaign_id = (int) ( $row['campaign_id'] ?? 0 ); $ad_group_id = (int) ( $row['ad_group_id'] ?? 0 ); $impressions = (int) ( $row['impressions'] ?? 0 ); $clicks = (int) ( $row['clicks'] ?? 0 ); $cost = (float) ( $row['cost'] ?? 0 ); $conversions = (float) ( $row['conversions'] ?? 0 ); $conversions_value = (float) ( $row['conversions_value'] ?? 0 ); // Pomijamy puste scope bez danych. if ( $impressions <= 0 && $clicks <= 0 && $cost <= 0 && $conversions <= 0 && $conversions_value <= 0 ) { continue; } $cpc = $clicks > 0 ? round( $cost / $clicks, 6 ) : 0; $roas = ( $conversions > 0 && $cost > 0 ) ? round( $conversions_value / $cost, 2 ) * 100 : 0; $impressions_30 = (int) \factory\Products::get_impressions_30( $product_id, $campaign_id, $ad_group_id ); $clicks_30 = (int) \factory\Products::get_clicks_30( $product_id, $campaign_id, $ad_group_id ); $mdb -> insert( 'products_temp', [ 'product_id' => $product_id, 'campaign_id' => $campaign_id, 'ad_group_id' => $ad_group_id, 'name' => $row['name'], 'impressions' => $impressions, 'impressions_30' => $impressions_30, 'clicks' => $clicks, 'clicks_30' => $clicks_30, 'ctr' => ( $impressions > 0 ) ? round( $clicks / $impressions, 4 ) * 100 : 0, 'cost' => $cost, 'conversions' => $conversions, 'conversions_value' => $conversions_value, 'cpc' => $cpc, 'roas' => $roas, ] ); $processed_rows++; } return $processed_rows; } static public function cron_products_history_30() { global $mdb; $start_time = microtime(true); $client_id = \S::get( 'client_id' ); if ( !$client_id ) { echo json_encode( [ 'result' => "Nie podano ID klienta." ] ); exit; } if ( !$mdb -> count( 'clients', [ 'id' => $client_id ] ) ) { echo json_encode( [ 'result' => "Nie znaleziono klienta o podanym ID.", "client" => "Nie istnieje" ] ); exit; } $products = $mdb -> select( 'products', 'id', [ 'client_id' => $client_id ] ); foreach ( $products as $product ) { $scopes = $mdb -> query( 'SELECT DISTINCT campaign_id, ad_group_id, date_add FROM products_history WHERE product_id = ' . $product . ' AND updated = 1 ORDER BY date_add DESC' ) -> fetchAll( \PDO::FETCH_ASSOC ); foreach ( $scopes as $scope ) { $campaign_id = (int) ( $scope['campaign_id'] ?? 0 ); $ad_group_id = (int) ( $scope['ad_group_id'] ?? 0 ); $date_add = $scope['date_add'] ?? ''; self::cron_product_history_30_save( $product, $date_add, $campaign_id, $ad_group_id ); $mdb -> update( 'products_history', [ 'updated' => 0 ], [ 'AND' => [ 'product_id' => $product, 'campaign_id' => $campaign_id, 'ad_group_id' => $ad_group_id, 'date_add' => $date_add ] ] ); } } $end_time = microtime(true); $execution_time = $end_time - $start_time; echo json_encode( [ 'result' => "Agregacja zakonczona, dane zapisane do offers_history_30. Czas wykonania skryptu: " . round($execution_time, 4) . " sekund." ] ); exit; } static public function get_roas_all_time( $product_id, $date_to, $campaign_id = 0, $ad_group_id = 0 ) { global $mdb; $product_id = (int) $product_id; $campaign_id = (int) $campaign_id; $ad_group_id = (int) $ad_group_id; $sql = 'SELECT SUM(conversions_value) / SUM(cost) * 100 AS roas_all_time FROM products_history WHERE product_id = :product_id AND date_add <= :date_to AND campaign_id = :campaign_id AND ad_group_id = :ad_group_id'; $roas_all_time = $mdb -> query( $sql, [ ':product_id' => $product_id, ':date_to' => $date_to, ':campaign_id' => $campaign_id, ':ad_group_id' => $ad_group_id ] ) -> fetchColumn(); return round( $roas_all_time, 2 ); } static public function cron_product_history_30_save( $product_id, $date_to, $campaign_id = 0, $ad_group_id = 0 ) { global $mdb; $product_id = (int) $product_id; $campaign_id = (int) $campaign_id; $ad_group_id = (int) $ad_group_id; $data = $mdb -> query( 'SELECT date_add, SUM( impressions ) AS impressions, SUM( clicks ) AS clicks, SUM( cost ) AS cost, SUM( conversions ) AS conversions, SUM( conversions_value ) AS conversions_value FROM products_history WHERE product_id = :product_id AND campaign_id = :campaign_id AND ad_group_id = :ad_group_id AND date_add <= :date_to GROUP BY date_add ORDER BY date_add DESC LIMIT 30', [ ':product_id' => $product_id, ':campaign_id' => $campaign_id, ':ad_group_id' => $ad_group_id, ':date_to' => $date_to ] ) -> fetchAll( \PDO::FETCH_ASSOC ); // Inicjalizacja tablic do przechowywania danych $offers_data = []; // Grupowanie danych wedug produktow foreach ( $data as $entry ) { if ( !isset( $offers_data[$product_id] ) ) { $offers_data[$product_id] = [ 'impressions' => 0, 'clicks' => 0, 'cost' => 0.0, 'conversions' => 0, 'conversions_value' => 0.0, 'roas' => 0, 'days_counted' => [] ]; } // Sumowanie danych wedug produktu $offers_data[$product_id]['impressions'] += $entry['impressions']; $offers_data[$product_id]['clicks'] += $entry['clicks']; $offers_data[$product_id]['cost'] += $entry['cost']; $offers_data[$product_id]['conversions'] += $entry['conversions']; $offers_data[$product_id]['conversions_value'] += $entry['conversions_value']; $offers_data[$product_id]['days_counted'][] = $entry['date_add']; } foreach ( $offers_data as $offer ) { $day_count = count( $offer['days_counted'] ); $impressions = $offer['impressions']; $clicks = $offer['clicks']; $ctr = ( $clicks > 0 and $impressions ) ? round( $clicks / $impressions, 4 ) * 100 : 0; $cost = $offer['cost']; $conversions = $offer['conversions']; $conversions_value = $offer['conversions_value']; $roas = ( $conversions_value > 0 and $cost ) ? round( $conversions_value / $cost, 2 ) * 100 : 0; $days_count_for_product = (int) $mdb -> query( 'SELECT COUNT( DISTINCT date_add ) FROM products_history WHERE product_id = :product_id AND campaign_id = :campaign_id AND ad_group_id = :ad_group_id AND date_add <= :date_to', [ ':product_id' => $product_id, ':campaign_id' => $campaign_id, ':ad_group_id' => $ad_group_id, ':date_to' => $date_to ] ) -> fetchColumn(); if ( $days_count_for_product >= 14 ) { if ( $mdb -> count( 'products_history_30', [ 'AND' => [ 'product_id' => $product_id, 'campaign_id' => $campaign_id, 'ad_group_id' => $ad_group_id, 'date_add' => $date_to ] ] ) > 0 ) { $mdb -> update( 'products_history_30', [ 'impressions' => $impressions, 'clicks' => $clicks, 'ctr' => $ctr, 'cost' => $cost, 'conversions' => $conversions, 'conversions_value' => $conversions_value, 'roas' => $roas, 'roas_all_time' => self::get_roas_all_time( $product_id, $date_to, $campaign_id, $ad_group_id ) ], [ 'AND' => [ 'product_id' => $product_id, 'campaign_id' => $campaign_id, 'ad_group_id' => $ad_group_id, 'date_add' => $date_to ] ] ); } else { $mdb -> insert( 'products_history_30', [ 'product_id' => $product_id, 'campaign_id' => $campaign_id, 'ad_group_id' => $ad_group_id, 'impressions' => $impressions, 'clicks' => $clicks, 'ctr' => $ctr, 'cost' => $cost, 'conversions' => $conversions, 'conversions_value' => $conversions_value, 'roas' => $roas, 'roas_all_time' => self::get_roas_all_time( $product_id, $date_to, $campaign_id, $ad_group_id ), 'date_add' => $date_to ] ); } } } } static public function cron_xml() { global $mdb; if ( !$client_id = \S::get( 'client_id' ) ) { echo json_encode( [ 'result' => "Nie podano ID klienta." ] ); exit; } if ( !$mdb -> count( 'clients', [ 'id' => $client_id ] ) ) { echo json_encode( [ 'result' => "Nie znaleziono klienta o podanym ID.", "client" => "Nie istnieje" ] ); exit; } $results = $mdb -> query( 'SELECT * FROM products AS p INNER JOIN products_data AS pd ON p.id = pd.product_id WHERE p.client_id = ' . $client_id ) -> fetchAll( \PDO::FETCH_ASSOC ); // if empty results if ( empty( $results ) ) { echo json_encode( [ 'result' => "Brak produktow do wygenerowania pliku XML." ] ); exit; } $doc = new \DOMDocument('1.0', 'UTF-8'); $xmlRoot = $doc->createElement('rss'); $xmlRoot = $doc->appendChild($xmlRoot); $xmlRoot->setAttribute('version', '2.0'); $xmlRoot->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:g', 'http://base.google.com/ns/1.0'); $channelNode = $xmlRoot->appendChild($doc->createElement('channel')); $channelNode->appendChild($doc->createElement('title', 'Custom Feed')); $channelNode->appendChild($doc->createElement('link', 'https://ads.pagedev.pl')); $fieldMappings = [ 'title' => 'g:title', 'description' => 'g:description', 'custom_label_4' => 'g:custom_label_4', 'custom_label_3' => 'g:custom_label_3', 'google_product_category' => 'g:google_product_category' ]; foreach ($results as $row) { $hasValidField = false; foreach ($fieldMappings as $dbField => $xmlTag) { if (!empty($row[$dbField])) { $hasValidField = true; break; } } if ( $hasValidField ) { $itemNode = $channelNode->appendChild($doc->createElement('item')); $offer_id = $mdb -> get( 'products', 'offer_id', [ 'id' => $row['product_id'] ] ); $offer_id = str_replace( 'shopify_pl', 'shopify_PL', $offer_id ); $p_gid = $itemNode->appendChild($doc->createElement('id', $offer_id)); foreach ($fieldMappings as $dbField => $xmlTag) { if (!empty($row[$dbField])) { $itemNode->appendChild($doc->createElement($xmlTag, $row[$dbField])); } } } } file_put_contents('xml/custom-feed-' . $_GET['client_id'] . '.xml', $doc->saveXML()); echo json_encode( [ 'result' => "Plik XML zostal wygenerowany https://adspro.projectpro.pl/xml/custom-feed-" . $_GET['client_id'] . ".xml." ] ); exit; } static public function cron_phrases() { global $mdb; if ( !$client_id = \S::get( 'client_id' ) ) { echo json_encode( [ 'result' => "Nie podano ID klienta." ] ); exit; } if ( !$mdb -> count( 'clients', [ 'id' => $client_id ] ) ) { echo json_encode( [ 'result' => "Nie znaleziono klienta o podanym ID.", "client" => "Nie istnieje" ] ); exit; } $data = $mdb -> query( 'SELECT * FROM phrases AS p INNER JOIN phrases_history AS ph ON p.id = ph.phrase_id WHERE p.client_id = ' . $client_id ) -> fetchAll( \PDO::FETCH_ASSOC ); $aggregated_data = []; foreach ( $data as $row ) { $phrase_id = $row['phrase_id']; if ( !isset( $aggregated_data[$client_id] ) ) { $aggregated_data[$client_id] = []; } if ( !isset( $aggregated_data[$client_id][$phrase_id] ) ) { $aggregated_data[$client_id][$phrase_id] = [ 'phrase_id' => $phrase_id, 'phrase' => $row['phrase'], 'impressions' => 0, 'clicks' => 0, 'cost' => 0.0, 'conversions' => 0, 'conversions_value' => 0.0 ]; } $aggregated_data[$client_id][$phrase_id]['impressions'] += $row['impressions']; $aggregated_data[$client_id][$phrase_id]['clicks'] += $row['clicks']; $aggregated_data[$client_id][$phrase_id]['cost'] += $row['cost']; $aggregated_data[$client_id][$phrase_id]['conversions'] += $row['conversions']; $aggregated_data[$client_id][$phrase_id]['conversions_value'] += $row['conversions_value']; } $phrases_ids = $mdb -> select( 'phrases', 'id', [ 'client_id' => $client_id ] ); foreach ( $phrases_ids as $phrase_id ) { $phrases_ids_array[] = $phrase_id -> id; } $mdb -> delete( 'phrases_temp', [ 'phrase_id' => $phrases_ids_array ] ); foreach ( $aggregated_data as $client_phrases ) { foreach ( $client_phrases as $phrase_data ) { $cpc = $phrase_data['clicks'] > 0 ? round( $phrase_data['cost'] / $phrase_data['clicks'], 6 ) : 0; $roas = ( $phrase_data['conversions'] > 0 and $phrase_data['cost'] ) ? round( $phrase_data['conversions_value'] / $phrase_data['cost'], 2 ) * 100 : 0; $mdb -> insert( 'phrases_temp', [ 'phrase_id' => $phrase_data['phrase_id'], 'phrase' => $phrase_data['phrase'], 'impressions' => $phrase_data['impressions'], 'clicks' => $phrase_data['clicks'], 'cost' => $phrase_data['cost'], 'conversions' => $phrase_data['conversions'], 'conversions_value' => $phrase_data['conversions_value'], 'cpc' => $cpc, 'roas' => $roas, ] ); } } echo json_encode( [ 'result' => "Agregacja zakonczona, dane zapisane do phrases_temp." ] ); exit; } static public function cron_phrases_history_30() { global $mdb; $start_time = microtime( true ); // Rozpoczcie mierzenia czasu $client_id = \S::get( 'client_id' ); // Pobranie ID klienta if ( !$client_id ) // Jeli nie podano ID klienta { echo json_encode( [ 'result' => "Nie podano ID klienta." ] ); // Wyswietlenie komunikatu exit; // Zakonczenie dziaania skryptu } if ( !$mdb -> count( 'clients', [ 'id' => $client_id ] ) ) // Sprawdzenie, czy klient istnieje { echo json_encode( [ 'result' => "Nie znaleziono klienta o podanym ID.", "client" => "Nie istnieje" ] ); // Wyswietlenie komunikatu exit; // Zakonczenie dziaania skryptu } // Pobranie biecej daty i daty sprzed 30 dni $phrases = $mdb -> query( 'SELECT * FROM phrases WHERE client_id = ' . $client_id ) -> fetchAll( \PDO::FETCH_ASSOC ); // Pobranie fraz dla danego klienta foreach ( $phrases as $phrase ) { for ( $i = 0; $i < 30; $i++ ) { $date_to = date( 'Y-m-d', strtotime( '-' . ( 1 + $i ) . ' days' ) ); $date_from = date( 'Y-m-d', strtotime( '-' . ( 31 + $i ) . ' days' ) ); $data_updated = false; if ( $mdb -> count( 'phrases_history', [ 'AND' => [ 'phrase_id' => $phrase['id'], 'date_add[>=]' => $date_from, 'date_add[<=]' => $date_to, 'updated' => 1 ] ] ) > 0 ) { $data_updated = true; } if ( $data_updated ) { self::cron_phrase_history_30_save( $phrase['id'], $date_from, $date_to ); } } $mdb -> update( 'phrases_history', [ 'updated' => 0 ], [ 'AND' => [ 'phrase_id' => $phrase['id'], 'updated' => 1 ] ] ); } $end_time = microtime( true ); // Zakonczenie mierzenia czasu $execution_time = $end_time - $start_time; // Obliczenie czasu wykonania echo json_encode( [ 'result' => "Agregacja zakonczona, dane zapisane do phrases_history_30. Czas wykonania skryptu: " . round( $execution_time, 4 ) . " sekund.", 'client' => \factory\Campaigns::get_client_name( $client_id ) ] ); // Wyswietlenie komunikatu exit; } // =========================== // KAMPANIE - Google Ads API // =========================== static public function cron_campaigns() { global $mdb; $api = new \services\GoogleAdsApi(); if ( !$api -> is_configured() ) { echo json_encode( [ 'result' => 'Google Ads API nie jest skonfigurowane. Uzupelnij dane w Ustawieniach.' ] ); exit; } $client_id = (int) \S::get( 'client_id' ); if ( $client_id > 0 ) { $client = $mdb -> get( 'clients', '*', [ 'AND' => [ 'id' => $client_id, 'google_ads_customer_id[!]' => null, 'deleted' => 0 ] ] ); if ( !$client ) { echo json_encode( [ 'result' => 'Nie znaleziono klienta z poprawnym Google Ads Customer ID.', 'client_id' => $client_id ] ); exit; } $sync = self::sync_campaigns_for_client( $client, $api ); echo json_encode( [ 'result' => empty( $sync['errors'] ) ? 'Synchronizacja kampanii zakonczona.' : 'Synchronizacja kampanii zakonczona z bledami.', 'client_id' => (int) $client['id'], 'processed_records' => (int) $sync['processed_records'], 'ad_groups_synced' => (int) ( $sync['ad_groups_synced'] ?? 0 ), 'search_terms_synced' => (int) ( $sync['search_terms_synced'] ?? 0 ), 'negative_keywords_synced' => (int) ( $sync['negative_keywords_synced'] ?? 0 ), 'errors' => $sync['errors'] ] ); exit; } $clients = $mdb -> select( 'clients', '*', [ 'AND' => [ 'google_ads_customer_id[!]' => null, 'deleted' => 0 ], 'ORDER' => [ 'id' => 'ASC' ] ] ); if ( empty( $clients ) ) { echo json_encode( [ 'result' => 'Brak klientow z ustawionym Google Ads Customer ID.' ] ); exit; } $client_ids = []; $clients_map = []; foreach ( $clients as $client ) { $cid = (int) $client['id']; if ( $cid <= 0 ) { continue; } $client_ids[] = $cid; $clients_map[$cid] = $client; } $client_ids = array_values( array_unique( $client_ids ) ); $state_key = 'cron_campaigns_state'; $state = self::get_daily_cron_state( $state_key ); $next_client_id = self::pick_next_client_id( $client_ids, $state['processed_ids'] ); if ( !$next_client_id ) { echo json_encode( [ 'result' => 'Wszyscy klienci kampanii zostali juz dzis przetworzeni.', 'date' => $state['date'], 'processed_clients' => count( array_intersect( $client_ids, $state['processed_ids'] ) ), 'total_clients' => count( $client_ids ) ] ); exit; } $selected_client = $clients_map[$next_client_id] ?? null; if ( !$selected_client ) { echo json_encode( [ 'result' => 'Nie udalo sie wybrac klienta do synchronizacji kampanii.', 'client_id' => $next_client_id ] ); exit; } $sync = self::sync_campaigns_for_client( $selected_client, $api ); // Oznaczamy klienta jako przetworzonego rowniez po bledzie, aby nie zapetlac wywolan. $state['processed_ids'][] = (int) $next_client_id; $state['processed_ids'] = array_values( array_unique( array_map( 'intval', $state['processed_ids'] ) ) ); self::save_daily_cron_state( $state_key, $state ); $processed_today = count( array_intersect( $client_ids, $state['processed_ids'] ) ); echo json_encode( [ 'result' => empty( $sync['errors'] ) ? 'Synchronizacja kampanii zakonczona.' : 'Synchronizacja kampanii zakonczona z bledami.', 'client_id' => $next_client_id, 'processed_records' => (int) $sync['processed_records'], 'ad_groups_synced' => (int) ( $sync['ad_groups_synced'] ?? 0 ), 'search_terms_synced' => (int) ( $sync['search_terms_synced'] ?? 0 ), 'negative_keywords_synced' => (int) ( $sync['negative_keywords_synced'] ?? 0 ), 'processed_clients_today' => $processed_today, 'remaining_clients_today' => max( 0, count( $client_ids ) - $processed_today ), 'errors' => $sync['errors'] ] ); exit; } static private function sync_campaigns_for_client( $client, $api ) { global $mdb; $today = date( 'Y-m-d' ); $processed = 0; $errors = []; $customer_id = $client['google_ads_customer_id']; $campaigns_db_map = []; $campaigns_30 = $api -> get_campaigns_30_days( $customer_id ); if ( $campaigns_30 === false ) { $last_err = \services\GoogleAdsApi::get_setting( 'google_ads_last_error' ); $errors[] = 'Blad API dla klienta ' . $client['name'] . ' (ID: ' . $customer_id . '): ' . $last_err; return [ 'processed_records' => 0, 'ad_groups_synced' => 0, 'search_terms_synced' => 0, 'negative_keywords_synced' => 0, 'errors' => $errors ]; } if ( !is_array( $campaigns_30 ) ) { $campaigns_30 = []; } $campaigns_all_time = $api -> get_campaigns_all_time( $customer_id ); $all_time_map = []; $all_time_totals = [ 'cost' => 0.0, 'conversion_value' => 0.0, ]; if ( is_array( $campaigns_all_time ) ) { foreach ( $campaigns_all_time as $cat ) { $all_time_map[ $cat['campaign_id'] ] = $cat['roas_all_time']; $all_time_totals['cost'] += (float) ( $cat['cost_all_time'] ?? 0 ); $all_time_totals['conversion_value'] += (float) ( $cat['conversion_value_all_time'] ?? 0 ); } } $account_30_totals = [ 'budget' => 0.0, 'money_spent' => 0.0, 'conversion_value' => 0.0, ]; foreach ( $campaigns_30 as $campaign ) { $external_campaign_id = isset( $campaign['campaign_id'] ) ? (string) $campaign['campaign_id'] : ''; if ( $external_campaign_id === '' ) { continue; } $advertising_channel_type = strtoupper( trim( (string) ( $campaign['advertising_channel_type'] ?? '' ) ) ); $account_30_totals['budget'] += (float) ( $campaign['budget'] ?? 0 ); $account_30_totals['money_spent'] += (float) ( $campaign['money_spent'] ?? 0 ); $account_30_totals['conversion_value'] += (float) ( $campaign['conversion_value'] ?? 0 ); if ( !$mdb -> count( 'campaigns', [ 'AND' => [ 'client_id' => $client['id'], 'campaign_id' => $external_campaign_id ] ] ) ) { $mdb -> insert( 'campaigns', [ 'client_id' => $client['id'], 'campaign_id' => $external_campaign_id, 'campaign_name' => $campaign['campaign_name'], 'advertising_channel_type' => $advertising_channel_type !== '' ? $advertising_channel_type : null ] ); $db_campaign_id = $mdb -> id(); } else { $db_campaign_id = $mdb -> get( 'campaigns', 'id', [ 'AND' => [ 'client_id' => $client['id'], 'campaign_id' => $external_campaign_id ] ] ); $mdb -> update( 'campaigns', [ 'campaign_name' => $campaign['campaign_name'], 'advertising_channel_type' => $advertising_channel_type !== '' ? $advertising_channel_type : null ], [ 'id' => $db_campaign_id ] ); } $bidding_strategy = self::format_bidding_strategy( $campaign['bidding_strategy'], $campaign['target_roas'] ?? 0 ); $history_data = [ 'roas_30_days' => $campaign['roas_30_days'], 'roas_all_time' => $all_time_map[ $external_campaign_id ] ?? 0, 'budget' => $campaign['budget'], 'money_spent' => $campaign['money_spent'], 'conversion_value' => $campaign['conversion_value'], 'bidding_strategy' => $bidding_strategy, ]; if ( $mdb -> count( 'campaigns_history', [ 'AND' => [ 'campaign_id' => $db_campaign_id, 'date_add' => $today ] ] ) ) { $mdb -> update( 'campaigns_history', $history_data, [ 'AND' => [ 'campaign_id' => $db_campaign_id, 'date_add' => $today ] ] ); } else { $history_data['campaign_id'] = $db_campaign_id; $history_data['date_add'] = $today; $mdb -> insert( 'campaigns_history', $history_data ); } $campaigns_db_map[ $external_campaign_id ] = (int) $db_campaign_id; $processed++; } $account_roas_30 = ( $account_30_totals['money_spent'] > 0 ) ? round( ( $account_30_totals['conversion_value'] / $account_30_totals['money_spent'] ) * 100, 2 ) : 0; $account_roas_all_time = ( $all_time_totals['cost'] > 0 ) ? round( ( $all_time_totals['conversion_value'] / $all_time_totals['cost'] ) * 100, 2 ) : 0; if ( !$mdb -> count( 'campaigns', [ 'AND' => [ 'client_id' => $client['id'], 'campaign_id' => 0 ] ] ) ) { $mdb -> insert( 'campaigns', [ 'client_id' => $client['id'], 'campaign_id' => 0, 'campaign_name' => '--- konto ---', 'advertising_channel_type' => null ] ); $db_account_campaign_id = $mdb -> id(); } else { $db_account_campaign_id = $mdb -> get( 'campaigns', 'id', [ 'AND' => [ 'client_id' => $client['id'], 'campaign_id' => 0 ] ] ); $mdb -> update( 'campaigns', [ 'campaign_name' => '--- konto ---', 'advertising_channel_type' => null ], [ 'id' => $db_account_campaign_id ] ); } $account_history_data = [ 'roas_30_days' => $account_roas_30, 'roas_all_time' => $account_roas_all_time, 'budget' => $account_30_totals['budget'], 'money_spent' => $account_30_totals['money_spent'], 'conversion_value' => $account_30_totals['conversion_value'], 'bidding_strategy' => 'Konto (agregacja wszystkich kampanii)', ]; if ( $mdb -> count( 'campaigns_history', [ 'AND' => [ 'campaign_id' => $db_account_campaign_id, 'date_add' => $today ] ] ) ) { $mdb -> update( 'campaigns_history', $account_history_data, [ 'AND' => [ 'campaign_id' => $db_account_campaign_id, 'date_add' => $today ] ] ); } else { $account_history_data['campaign_id'] = $db_account_campaign_id; $account_history_data['date_add'] = $today; $mdb -> insert( 'campaigns_history', $account_history_data ); } $processed++; $ad_groups_sync = self::sync_campaign_ad_groups_for_client( $campaigns_db_map, $customer_id, $api, $today ); $search_terms_sync = self::sync_campaign_search_terms_for_client( $campaigns_db_map, $ad_groups_sync['ad_group_map'], $customer_id, $api, $today ); $negative_keywords_sync = self::sync_campaign_negative_keywords_for_client( $campaigns_db_map, $ad_groups_sync['ad_group_map'], $customer_id, $api, $today ); $errors = array_merge( $errors, $ad_groups_sync['errors'], $search_terms_sync['errors'], $negative_keywords_sync['errors'] ); return [ 'processed_records' => $processed, 'ad_groups_synced' => (int) $ad_groups_sync['count'], 'search_terms_synced' => (int) $search_terms_sync['count'], 'negative_keywords_synced' => (int) $negative_keywords_sync['count'], 'errors' => $errors ]; } static private function sync_campaign_ad_groups_for_client( $campaigns_db_map, $customer_id, $api, $date_sync ) { global $mdb; $campaign_db_ids = array_values( array_unique( array_map( 'intval', array_values( $campaigns_db_map ) ) ) ); if ( empty( $campaign_db_ids ) ) { return [ 'count' => 0, 'ad_group_map' => [], 'errors' => [] ]; } $ad_groups_30 = $api -> get_ad_groups_30_days( $customer_id ); if ( $ad_groups_30 === false ) { $last_err = \services\GoogleAdsApi::get_setting( 'google_ads_last_error' ); return [ 'count' => 0, 'ad_group_map' => [], 'errors' => [ 'Blad pobierania grup reklam (30 dni): ' . $last_err ] ]; } $ad_groups_all_time = $api -> get_ad_groups_all_time( $customer_id ); if ( $ad_groups_all_time === false ) { $last_err = \services\GoogleAdsApi::get_setting( 'google_ads_last_error' ); return [ 'count' => 0, 'ad_group_map' => [], 'errors' => [ 'Blad pobierania grup reklam (all time): ' . $last_err ] ]; } if ( !is_array( $ad_groups_30 ) ) { $ad_groups_30 = []; } if ( !is_array( $ad_groups_all_time ) ) { $ad_groups_all_time = []; } $map_30 = []; foreach ( $ad_groups_30 as $row ) { $campaign_external_id = isset( $row['campaign_id'] ) ? (string) $row['campaign_id'] : ''; $ad_group_external_id = isset( $row['ad_group_id'] ) ? (string) $row['ad_group_id'] : ''; if ( $campaign_external_id === '' || $ad_group_external_id === '' ) { continue; } $map_30[ $campaign_external_id . '|' . $ad_group_external_id ] = $row; } $map_all_time = []; foreach ( $ad_groups_all_time as $row ) { $campaign_external_id = isset( $row['campaign_id'] ) ? (string) $row['campaign_id'] : ''; $ad_group_external_id = isset( $row['ad_group_id'] ) ? (string) $row['ad_group_id'] : ''; if ( $campaign_external_id === '' || $ad_group_external_id === '' ) { continue; } $map_all_time[ $campaign_external_id . '|' . $ad_group_external_id ] = $row; } $mdb -> delete( 'campaign_ad_groups', [ 'campaign_id' => $campaign_db_ids ] ); $keys = array_values( array_unique( array_merge( array_keys( $map_30 ), array_keys( $map_all_time ) ) ) ); $ad_group_db_map = []; $count = 0; foreach ( $keys as $key ) { $parts = explode( '|', $key, 2 ); $campaign_external_id = $parts[0] ?? ''; $ad_group_external_id = $parts[1] ?? ''; $db_campaign_id = (int) ( $campaigns_db_map[ $campaign_external_id ] ?? 0 ); if ( $db_campaign_id <= 0 || $ad_group_external_id === '' ) { continue; } $row_30 = $map_30[ $key ] ?? []; $row_all_time = $map_all_time[ $key ] ?? []; $ad_group_name = trim( (string) ( $row_30['ad_group_name'] ?? ( $row_all_time['ad_group_name'] ?? '' ) ) ); if ( $ad_group_name === '' ) { $ad_group_name = 'Ad group #' . $ad_group_external_id; } $mdb -> insert( 'campaign_ad_groups', [ 'campaign_id' => $db_campaign_id, 'ad_group_id' => (int) $ad_group_external_id, 'ad_group_name' => $ad_group_name, 'impressions_30' => (int) ( $row_30['impressions'] ?? 0 ), 'clicks_30' => (int) ( $row_30['clicks'] ?? 0 ), 'cost_30' => (float) ( $row_30['cost'] ?? 0 ), 'conversions_30' => (float) ( $row_30['conversions'] ?? 0 ), 'conversion_value_30' => (float) ( $row_30['conversion_value'] ?? 0 ), 'roas_30' => (float) ( $row_30['roas'] ?? 0 ), 'impressions_all_time' => (int) ( $row_all_time['impressions'] ?? 0 ), 'clicks_all_time' => (int) ( $row_all_time['clicks'] ?? 0 ), 'cost_all_time' => (float) ( $row_all_time['cost'] ?? 0 ), 'conversions_all_time' => (float) ( $row_all_time['conversions'] ?? 0 ), 'conversion_value_all_time' => (float) ( $row_all_time['conversion_value'] ?? 0 ), 'roas_all_time' => (float) ( $row_all_time['roas'] ?? 0 ), 'date_sync' => $date_sync ] ); $db_ad_group_id = (int) $mdb -> id(); if ( $db_ad_group_id > 0 ) { $ad_group_db_map[ $key ] = $db_ad_group_id; $count++; } } return [ 'count' => $count, 'ad_group_map' => $ad_group_db_map, 'errors' => [] ]; } static private function sync_campaign_search_terms_for_client( $campaigns_db_map, $ad_group_db_map, $customer_id, $api, $date_sync ) { global $mdb; $campaign_db_ids = array_values( array_unique( array_map( 'intval', array_values( $campaigns_db_map ) ) ) ); if ( empty( $campaign_db_ids ) ) { return [ 'count' => 0, 'errors' => [] ]; } $search_terms_30 = $api -> get_search_terms_30_days( $customer_id ); if ( $search_terms_30 === false ) { $last_err = \services\GoogleAdsApi::get_setting( 'google_ads_last_error' ); return [ 'count' => 0, 'errors' => [ 'Blad pobierania fraz wyszukiwanych (30 dni): ' . $last_err ] ]; } $search_terms_all_time = $api -> get_search_terms_all_time( $customer_id ); if ( $search_terms_all_time === false ) { $last_err = \services\GoogleAdsApi::get_setting( 'google_ads_last_error' ); return [ 'count' => 0, 'errors' => [ 'Blad pobierania fraz wyszukiwanych (all time): ' . $last_err ] ]; } if ( !is_array( $search_terms_30 ) ) { $search_terms_30 = []; } if ( !is_array( $search_terms_all_time ) ) { $search_terms_all_time = []; } $map_30 = []; foreach ( $search_terms_30 as $row ) { $campaign_external_id = isset( $row['campaign_id'] ) ? (string) $row['campaign_id'] : ''; $ad_group_external_id = isset( $row['ad_group_id'] ) ? (string) $row['ad_group_id'] : ''; $search_term = trim( (string) ( $row['search_term'] ?? '' ) ); if ( $campaign_external_id === '' || $ad_group_external_id === '' || $search_term === '' ) { continue; } $map_30[ $campaign_external_id . '|' . $ad_group_external_id . '|' . strtolower( $search_term ) ] = $row; } $map_all_time = []; foreach ( $search_terms_all_time as $row ) { $campaign_external_id = isset( $row['campaign_id'] ) ? (string) $row['campaign_id'] : ''; $ad_group_external_id = isset( $row['ad_group_id'] ) ? (string) $row['ad_group_id'] : ''; $search_term = trim( (string) ( $row['search_term'] ?? '' ) ); if ( $campaign_external_id === '' || $ad_group_external_id === '' || $search_term === '' ) { continue; } $map_all_time[ $campaign_external_id . '|' . $ad_group_external_id . '|' . strtolower( $search_term ) ] = $row; } $mdb -> delete( 'campaign_search_terms', [ 'campaign_id' => $campaign_db_ids ] ); $keys = array_values( array_unique( array_merge( array_keys( $map_30 ), array_keys( $map_all_time ) ) ) ); $count = 0; foreach ( $keys as $key ) { $parts = explode( '|', $key, 3 ); $campaign_external_id = $parts[0] ?? ''; $ad_group_external_id = $parts[1] ?? ''; $db_campaign_id = (int) ( $campaigns_db_map[ $campaign_external_id ] ?? 0 ); $db_ad_group_id = (int) ( $ad_group_db_map[ $campaign_external_id . '|' . $ad_group_external_id ] ?? 0 ); if ( $db_campaign_id > 0 && $db_ad_group_id <= 0 && $ad_group_external_id === '0' ) { $db_ad_group_id = self::ensure_campaign_level_ad_group( $db_campaign_id, $date_sync ); if ( $db_ad_group_id > 0 ) { $ad_group_db_map[ $campaign_external_id . '|0' ] = $db_ad_group_id; } } if ( $db_campaign_id <= 0 || $db_ad_group_id <= 0 ) { continue; } $row_30 = $map_30[ $key ] ?? []; $row_all_time = $map_all_time[ $key ] ?? []; $search_term = trim( (string) ( $row_30['search_term'] ?? ( $row_all_time['search_term'] ?? '' ) ) ); if ( $search_term === '' ) { continue; } $clicks_30 = (int) ( $row_30['clicks'] ?? 0 ); $clicks_all_time = (int) ( $row_all_time['clicks'] ?? 0 ); if ( $clicks_30 <= 0 && $clicks_all_time <= 0 ) { continue; } $mdb -> insert( 'campaign_search_terms', [ 'campaign_id' => $db_campaign_id, 'ad_group_id' => $db_ad_group_id, 'search_term' => $search_term, 'impressions_30' => (int) ( $row_30['impressions'] ?? 0 ), 'clicks_30' => $clicks_30, 'cost_30' => (float) ( $row_30['cost'] ?? 0 ), 'conversions_30' => (float) ( $row_30['conversions'] ?? 0 ), 'conversion_value_30' => (float) ( $row_30['conversion_value'] ?? 0 ), 'roas_30' => (float) ( $row_30['roas'] ?? 0 ), 'impressions_all_time' => (int) ( $row_all_time['impressions'] ?? 0 ), 'clicks_all_time' => $clicks_all_time, 'cost_all_time' => (float) ( $row_all_time['cost'] ?? 0 ), 'conversions_all_time' => (float) ( $row_all_time['conversions'] ?? 0 ), 'conversion_value_all_time' => (float) ( $row_all_time['conversion_value'] ?? 0 ), 'roas_all_time' => (float) ( $row_all_time['roas'] ?? 0 ), 'date_sync' => $date_sync ] ); $count++; } return [ 'count' => $count, 'errors' => [] ]; } static private function ensure_campaign_level_ad_group( $db_campaign_id, $date_sync ) { global $mdb; $db_campaign_id = (int) $db_campaign_id; if ( $db_campaign_id <= 0 ) { return 0; } $existing_id = (int) $mdb -> get( 'campaign_ad_groups', 'id', [ 'AND' => [ 'campaign_id' => $db_campaign_id, 'ad_group_id' => 0 ] ] ); if ( $existing_id > 0 ) { return $existing_id; } $mdb -> insert( 'campaign_ad_groups', [ 'campaign_id' => $db_campaign_id, 'ad_group_id' => 0, 'ad_group_name' => 'PMax (bez grup reklam)', 'impressions_30' => 0, 'clicks_30' => 0, 'cost_30' => 0, 'conversions_30' => 0, 'conversion_value_30' => 0, 'roas_30' => 0, 'impressions_all_time' => 0, 'clicks_all_time' => 0, 'cost_all_time' => 0, 'conversions_all_time' => 0, 'conversion_value_all_time' => 0, 'roas_all_time' => 0, 'date_sync' => $date_sync ] ); return (int) $mdb -> id(); } static private function sync_campaign_negative_keywords_for_client( $campaigns_db_map, $ad_group_db_map, $customer_id, $api, $date_sync ) { global $mdb; $campaign_db_ids = array_values( array_unique( array_map( 'intval', array_values( $campaigns_db_map ) ) ) ); if ( empty( $campaign_db_ids ) ) { return [ 'count' => 0, 'errors' => [] ]; } $negatives = $api -> get_negative_keywords( $customer_id ); if ( $negatives === false ) { $last_err = \services\GoogleAdsApi::get_setting( 'google_ads_last_error' ); return [ 'count' => 0, 'errors' => [ 'Blad pobierania fraz wykluczajacych: ' . $last_err ] ]; } if ( !is_array( $negatives ) ) { $negatives = []; } $mdb -> delete( 'campaign_negative_keywords', [ 'campaign_id' => $campaign_db_ids ] ); $count = 0; $seen = []; foreach ( $negatives as $row ) { $campaign_external_id = isset( $row['campaign_id'] ) ? (string) $row['campaign_id'] : ''; $db_campaign_id = (int) ( $campaigns_db_map[ $campaign_external_id ] ?? 0 ); if ( $db_campaign_id <= 0 ) { continue; } $scope = ( $row['scope'] ?? '' ) === 'ad_group' ? 'ad_group' : 'campaign'; $db_ad_group_id = null; if ( $scope === 'ad_group' ) { $ad_group_external_id = isset( $row['ad_group_id'] ) ? (string) $row['ad_group_id'] : ''; $mapped_ad_group_id = (int) ( $ad_group_db_map[ $campaign_external_id . '|' . $ad_group_external_id ] ?? 0 ); if ( $mapped_ad_group_id <= 0 ) { continue; } $db_ad_group_id = $mapped_ad_group_id; } $keyword_text = trim( (string) ( $row['keyword_text'] ?? '' ) ); if ( $keyword_text === '' ) { continue; } $match_type = trim( (string) ( $row['match_type'] ?? '' ) ); $uniq_key = $db_campaign_id . '|' . (int) $db_ad_group_id . '|' . $scope . '|' . strtolower( $keyword_text ) . '|' . strtolower( $match_type ); if ( isset( $seen[ $uniq_key ] ) ) { continue; } $seen[ $uniq_key ] = true; $mdb -> insert( 'campaign_negative_keywords', [ 'campaign_id' => $db_campaign_id, 'ad_group_id' => $db_ad_group_id, 'scope' => $scope, 'keyword_text' => $keyword_text, 'match_type' => $match_type, 'date_sync' => $date_sync ] ); $count++; } return [ 'count' => $count, 'errors' => [] ]; } static private function get_daily_cron_state( $state_key ) { $today = date( 'Y-m-d' ); $state_raw = self::get_setting_value( $state_key, '' ); $state = json_decode( (string) $state_raw, true ); if ( !is_array( $state ) || ( $state['date'] ?? '' ) !== $today ) { return [ 'date' => $today, 'processed_ids' => [] ]; } $processed_ids = []; if ( isset( $state['processed_ids'] ) && is_array( $state['processed_ids'] ) ) { foreach ( $state['processed_ids'] as $id ) { $id = (int) $id; if ( $id > 0 ) { $processed_ids[] = $id; } } } return [ 'date' => $today, 'processed_ids' => array_values( array_unique( $processed_ids ) ) ]; } static private function save_daily_cron_state( $state_key, $state ) { $payload = [ 'date' => date( 'Y-m-d' ), 'processed_ids' => array_values( array_unique( array_map( 'intval', $state['processed_ids'] ?? [] ) ) ) ]; self::set_setting_value( $state_key, json_encode( $payload, JSON_UNESCAPED_UNICODE ) ); } static private function pick_next_client_id( $client_ids, $processed_ids ) { $processed_lookup = []; foreach ( $processed_ids as $pid ) { $pid = (int) $pid; if ( $pid > 0 ) { $processed_lookup[$pid] = true; } } foreach ( $client_ids as $cid ) { $cid = (int) $cid; if ( $cid > 0 && !isset( $processed_lookup[$cid] ) ) { return $cid; } } return 0; } static private function get_setting_value( $setting_key, $default = null ) { global $mdb; $value = $mdb -> get( 'settings', 'setting_value', [ 'setting_key' => $setting_key ] ); if ( $value === null || $value === false ) { return $default; } return $value; } static private function set_setting_value( $setting_key, $setting_value ) { global $mdb; if ( $mdb -> count( 'settings', [ 'setting_key' => $setting_key ] ) ) { $mdb -> update( 'settings', [ 'setting_value' => $setting_value ], [ 'setting_key' => $setting_key ] ); return; } $mdb -> insert( 'settings', [ 'setting_key' => $setting_key, 'setting_value' => $setting_value ] ); } static private function format_bidding_strategy( $strategy_type, $target_roas = 0 ) { $map = [ 'MAXIMIZE_CONVERSIONS' => 'Maksymalizacja liczby konwersji', 'MAXIMIZE_CONVERSION_VALUE' => 'Maksymalizacja wartosci konwersji', 'TARGET_ROAS' => 'Docelowy ROAS', 'TARGET_CPA' => 'Docelowy CPA', 'MANUAL_CPC' => 'Reczny CPC', 'MANUAL_CPM' => 'Reczny CPM', 'TARGET_IMPRESSION_SHARE' => 'Docelowy udzial w wyswietleniach', ]; $label = $map[ $strategy_type ] ?? $strategy_type ?? 'brak'; if ( $target_roas > 0 ) { $label .= ' | docelowy ROAS: ' . round( $target_roas * 100 ) . '%'; } return $label; } // =========================== // FRAZY - history 30 // =========================== static public function cron_phrase_history_30_save( $phrase_id, $date_from, $date_to ) { global $mdb; $data = $mdb -> query( 'SELECT * FROM phrases_history WHERE phrase_id = ' . $phrase_id . ' AND date_add >= \'' . $date_from . '\' AND date_add <= \'' . $date_to . '\' ORDER BY date_add ASC' ) -> fetchAll( \PDO::FETCH_ASSOC ); // Inicjalizacja tablic do przechowywania danych $phrases_data = []; // Grupowanie danych wedug fraz foreach ( $data as $entry ) { $phrase_id = $entry['phrase_id']; if ( !isset( $phrases_data[$phrase_id] ) ) { $phrases_data[$phrase_id] = [ 'impressions' => 0, 'clicks' => 0, 'cost' => 0.0, 'conversions' => 0, 'conversions_value' => 0.0, 'roas' => 0, 'days_counted' => [] ]; } // Sumowanie danych wedug fraz $phrases_data[$phrase_id]['impressions'] += $entry['impressions']; $phrases_data[$phrase_id]['clicks'] += $entry['clicks']; $phrases_data[$phrase_id]['cost'] += $entry['cost']; $phrases_data[$phrase_id]['conversions'] += $entry['conversions']; $phrases_data[$phrase_id]['conversions_value'] += $entry['conversions_value']; $phrases_data[$phrase_id]['days_counted'][] = $entry['date_add']; } foreach ( $phrases_data as $phrase ) { $day_count = count( $phrase['days_counted'] ); $impressions = $phrase['impressions'] / $day_count; $clicks = $phrase['clicks'] / $day_count; $cost = $phrase['cost'] / $day_count; $conversions = $phrase['conversions'] / $day_count; $conversions_value = $phrase['conversions_value'] / $day_count; $roas = ( $conversions_value > 0 and $cost ) ? round( $conversions_value / $cost, 2 ) * 100 : 0; if ( $day_count > 14 ) { if ( $mdb -> count( 'phrases_history_30', [ 'AND' => [ 'phrase_id' => $phrase_id, 'date_add' => $date_to ] ] ) > 0 ) { $mdb -> update( 'phrases_history_30', [ 'impressions' => $impressions, 'clicks' => $clicks, 'cost' => $cost, 'conversions' => $conversions, 'conversions_value' => $conversions_value, 'roas' => $roas ], [ 'AND' => [ 'phrase_id' => $phrase_id, 'date_add' => $date_to ] ] ); } else { $mdb -> insert( 'phrases_history_30', [ 'phrase_id' => $phrase_id, 'impressions' => $impressions, 'clicks' => $clicks, 'cost' => $cost, 'conversions' => $conversions, 'conversions_value' => $conversions_value, 'roas' => $roas, 'date_add' => $date_to ] ); } } } } }