Changeset 3116743
- Timestamp:
- 07/12/2024 02:01:50 AM (21 months ago)
- Location:
- dashcommerce/trunk
- Files:
-
- 3 added
- 1 deleted
- 17 edited
-
dashcommerce.php (modified) (2 diffs)
-
features/admin-script/class-admin-script.php (modified) (7 diffs)
-
features/agency-footer/class-agency-footer.php (modified) (5 diffs)
-
features/analytics/analytics-overview.js (modified) (1 diff)
-
features/analytics/class-analytics-charts.php (modified) (1 diff)
-
features/analytics/class-analytics-values.php (modified) (6 diffs)
-
features/analytics/class-analytics.php (modified) (5 diffs)
-
features/api (added)
-
features/api/class-api.php (added)
-
features/product-metabox/class-product-metabox.php (modified) (4 diffs)
-
features/product-metabox/product-metabox.js (modified) (1 diff)
-
features/reports/class-reports-generator.php (modified) (20 diffs)
-
features/reports/class-reports.php (modified) (9 diffs)
-
features/settings-page/class-settings-page.php (modified) (19 diffs)
-
features/settings-page/settings-page.js (modified) (9 diffs)
-
jsconfig.json (modified) (1 diff)
-
options/class-current-user.php (deleted)
-
options/class-settings.php (added)
-
readme.txt (modified) (1 diff)
-
tables/class-access-logs.php (modified) (7 diffs)
-
utils/class-utils.php (modified) (6 diffs)
Legend:
- Unmodified
- Added
- Removed
-
dashcommerce/trunk/dashcommerce.php
r3098201 r3116743 12 12 * Plugin Name: DashCommerce 13 13 * Description: DashCommerce plugin for WordPress. 14 * Version: 1. 1.614 * Version: 1.2.0 15 15 * Author: DashCommerce 16 16 * License: GPL v2 … … 48 48 require_once plugin_dir_path( __FILE__ ) . 'features/reports/class-reports.php'; 49 49 require_once plugin_dir_path( __FILE__ ) . 'features/agency-footer/class-agency-footer.php'; 50 require_once plugin_dir_path( __FILE__ ) . 'features/api/class-api.php'; 50 51 51 52 /** -
dashcommerce/trunk/features/admin-script/class-admin-script.php
r3098201 r3116743 13 13 */ 14 14 15 require_once plugin_dir_path( __FILE__ ) . '../../options/class- current-user.php';15 require_once plugin_dir_path( __FILE__ ) . '../../options/class-settings.php'; 16 16 require_once plugin_dir_path( __FILE__ ) . '../../utils/class-utils.php'; 17 17 … … 32 32 public function __construct() { 33 33 global $dashcommerce_utils; 34 global $dashcommerce_ current_user;34 global $dashcommerce_settings; 35 35 36 $current_user _info = $dashcommerce_current_user->get_info();36 $current_user = $dashcommerce_settings->get_user(); 37 37 38 if ( ! $current_user _info || ! isset( $current_user_info['loggedIn'] ) || ! $current_user_info['loggedIn'] || ! isset( $current_user_info['token'] ) || ! $current_user_info['token'] ) {38 if ( ! $current_user || ! isset( $current_user['logged_in'] ) || ! $current_user['logged_in'] || ! isset( $current_user['token'] ) || ! $current_user['token'] ) { 39 39 $this->token_status = 'NO_TOKEN'; 40 } elseif ( $current_user_info['loggedIn'] && $current_user_info['token'] ) { 41 if ( ! $dashcommerce_utils->is_older_than_x_seconds( $current_user_info['lastUpdated'], 600 ) ) { 42 $this->token_status = 'VALID_NOT_EXPIRED'; 43 } else { 44 $token_check_result = $this->check_token( $current_user_info ); 45 46 if ( $token_check_result['valid'] ) { 47 $dashcommerce_current_user->update_timestamp(); 48 49 $this->token_status = 'VALID_CHECKED'; 50 } else { 51 $dashcommerce_current_user->log_out(); 52 53 $this->token_status = 'INVALID'; 54 } 55 } 40 } elseif ( $current_user['logged_in'] && $current_user['token'] ) { 41 $this->token_status = 'VALID_NOT_EXPIRED'; 56 42 } 57 43 … … 63 49 */ 64 50 public function enqueue_script() { 65 global $dashcommerce_ current_user;51 global $dashcommerce_settings; 66 52 global $dashcommerce_utils; 67 53 … … 70 56 wp_enqueue_script( 'dashcommerce-admin-script', plugin_dir_url( __FILE__ ) . 'admin-script.js', array( 'jquery' ), $ver, true ); 71 57 72 $current_user _info = $dashcommerce_current_user->get_info();58 $current_user = $dashcommerce_settings->get_user(); 73 59 74 $token_status_timestamp = isset( $current_user _info['lastUpdated'] ) ? $current_user_info['lastUpdated'] : null;60 $token_status_timestamp = isset( $current_user['last_updated'] ) ? $current_user['last_updated'] : null; 75 61 76 62 wp_localize_script( … … 90 76 * Check the validity of the token. 91 77 * 92 * @param array $current_user _infoThe current user information.78 * @param array $current_user The current user information. 93 79 * @return array The token validity and premium status. 94 80 */ 95 public function check_token( $current_user _info) {81 public function check_token( $current_user ) { 96 82 global $dashcommerce_utils; 97 83 global $dashcommerce_env; 98 global $dashcommerce_ current_user;84 global $dashcommerce_settings; 99 85 100 86 try { … … 102 88 $dashcommerce_env['EP_CHECK_TOKEN'], 103 89 array( 104 'token' => $current_user _info['token'],90 'token' => $current_user['token'], 105 91 'agency' => $dashcommerce_env['AGENCY'], 106 92 ), … … 123 109 } 124 110 125 $dashcommerce_current_user->update_openai_key_preview( $body['openaiKeyPreview'] ); 111 if ( isset( $body['openaiKeyPreview'] ) ) { 112 $dashcommerce_settings->update_openai_key_preview( $body['openaiKeyPreview'] ); 113 } 126 114 127 115 return array( -
dashcommerce/trunk/features/agency-footer/class-agency-footer.php
r3098201 r3116743 21 21 */ 22 22 public function __construct() { 23 global $dashcommerce_ current_user;24 $this-> current_user = $dashcommerce_current_user;23 global $dashcommerce_settings; 24 $this->settings = $dashcommerce_settings; 25 25 26 26 global $dashcommerce_env; … … 31 31 32 32 /** 33 * The key of the setting in the Current_Useroption.33 * The key of the setting in the plugin's settings option. 34 34 * 35 35 * @var string … … 38 38 39 39 /** 40 * Reference to global $dashcommerce_current_user.40 * Reference to global instance of Dashcommerce_Settings. 41 41 * 42 * @var Dashcommerce_ Current_User42 * @var Dashcommerce_Settings 43 43 */ 44 private $ current_user;44 private $settings; 45 45 46 46 /** … … 57 57 */ 58 58 public function set_flag( $enable ) { 59 $this-> current_user->update_single_entry( $this->setting_key, $enable );59 $this->settings->update_single_entry( $this->setting_key, $enable ); 60 60 } 61 61 … … 64 64 */ 65 65 public function get_flag() { 66 $settings = $this-> current_user->get_info();66 $settings = $this->settings->get_settings(); 67 67 68 68 if ( ! isset( $settings[ $this->setting_key ] ) ) { 69 69 $this->set_flag( false ); 70 70 71 $settings = $this-> current_user->get_info();71 $settings = $this->settings->get_settings(); 72 72 } 73 73 -
dashcommerce/trunk/features/analytics/analytics-overview.js
r3098201 r3116743 16 16 jQuery('#dashcommerce-analytics-for-empty-access-logs').hide(); 17 17 18 if (!script_vars ['current_user']?.['loggedIn']) {18 if (!script_vars.settings?.user?.['logged_in']) { 19 19 jQuery('#dashcommerce-analytics-for-logged-out-users').show(); 20 20 return; -
dashcommerce/trunk/features/analytics/class-analytics-charts.php
r3098201 r3116743 152 152 public function display_day_counts_table() { 153 153 $requests_today = $this->values->requests_in_period( 'today' ); 154 $requests_in_period = $this->values-> total_requests_in_period( '3 months ago' );154 $requests_in_period = $this->values->requests_in_period( '3 months ago' ); 155 155 $average_daily_requests = $this->values->average_daily_requests( '3 months ago' ); 156 156 $average_time_between_requests = $this->values->average_time_between_requests( '3 months ago' ); -
dashcommerce/trunk/features/analytics/class-analytics-values.php
r3098201 r3116743 81 81 $day_counts = $this->access_logs->get_day_counts( $start, $end ); 82 82 83 return number_format( $dashcommerce_utils->calculate_array_average( $day_counts ), 2 ); 84 } 85 86 /** 87 * Calculate total requests in specified period. 88 * 89 * @param string $start The start of the period. 90 * @param string $end The end of the period. Default: `today`. 91 */ 92 public function total_requests_in_period( $start, $end = 'today' ) { 93 return array_sum( $this->access_logs->get_day_counts( $start, $end ) ); 94 } 95 96 /** 97 * Calculate average time between requests. 83 return round( $dashcommerce_utils->calculate_array_average( $day_counts ), 2 ); 84 } 85 86 /** 87 * Calculate average time between requests in seconds. 98 88 * 99 89 * @param string $start The start of the period. … … 101 91 */ 102 92 public function average_time_between_requests( $start, $end = 'today' ) { 103 $total_requests_sum = $this-> total_requests_in_period( $start, $end );93 $total_requests_sum = $this->requests_in_period( $start, $end ); 104 94 105 95 $seconds_day = 24 * 60 * 60; … … 107 97 if ( $total_requests_sum > 0 ) { 108 98 $average_time_between_requests = $seconds_day / $total_requests_sum; 109 return number_format( $average_time_between_requests, 2 ) . ' s';99 return round( $average_time_between_requests, 2 ); 110 100 } else { 111 101 return 0; … … 128 118 } 129 119 130 $ dt_str_start = $this->utils->create_date( $start, 'UTC' )->modify( 'midnight' )->setTimezone( new DateTimeZone( 'UTC' ) )->format( 'Y-m-d H:i:s');131 $ dt_str_end = $this->utils->create_date( $end, 'UTC' )->modify( 'midnight' )->setTimezone( new DateTimeZone( 'UTC' ) )->format( 'Y-m-d H:i:s');120 $str_start_ltz = $this->utils->prepare_period_delimiter( $start, true ); 121 $str_end_ltz = $this->utils->prepare_period_delimiter( $end, true ); 132 122 133 123 $args = array( 134 124 'date_query' => array( 135 'after' => $ dt_str_start,136 'before' => $ dt_str_end,125 'after' => $str_start_ltz, 126 'before' => $str_end_ltz, 137 127 'inclusive' => true, 138 128 ), … … 171 161 } 172 162 173 $ dt_str_start = $this->utils->create_date( $start, 'UTC' )->modify( 'midnight' )->setTimezone( new DateTimeZone( 'UTC' ) )->format( 'Y-m-d H:i:s');174 $ dt_str_end = $this->utils->create_date( $end, 'UTC' )->modify( 'midnight' )->setTimezone( new DateTimeZone( 'UTC' ) )->format( 'Y-m-d H:i:s');163 $str_start_ltz = $this->utils->prepare_period_delimiter( $start, true ); 164 $str_end_ltz = $this->utils->prepare_period_delimiter( $end, true ); 175 165 176 166 $args = array( 177 'date_created' => $ dt_str_start . '...' . $dt_str_end,167 'date_created' => $str_start_ltz . '...' . $str_end_ltz, 178 168 'limit' => -1, // Fetch all orders. 179 169 ); … … 249 239 return $product_view_counts; 250 240 } 241 242 /** 243 * Get the current total number of users. 244 */ 245 public function users_count() { 246 $args = array( 247 'role__in' => array( 'customer' ), 248 ); 249 250 $user_query = new WP_User_Query( $args ); 251 252 $users = $user_query->get_results(); 253 254 return count( $users ); 255 } 256 257 /** 258 * Get new users in period. 259 * 260 * @param string $start The start of the period. 261 * @param string $end The end of the period. 262 */ 263 public function new_users_count( $start, $end ) { 264 $start = $this->utils->prepare_period_delimiter( $start, true ); 265 $end = $this->utils->prepare_period_delimiter( $end, true ); 266 267 $args = array( 268 'role__in' => array( 'customer' ), 269 'date_query' => array( 270 'after' => $start, 271 'before' => $end, 272 'inclusive' => true, 273 ), 274 ); 275 276 $user_query = new WP_User_Query( $args ); 277 278 $users = $user_query->get_results(); 279 280 return count( $users ); 281 } 282 283 /** 284 * Calculate conversion rate. 285 * 286 * @param string $start The start of the period. 287 * @param string $end The end of the period. 288 */ 289 public function conversion_rate( $start, $end ) { 290 $sales = $this->sales_in_period( $start, $end ); 291 $access_count = $this->requests_in_period( $start, $end ); 292 293 $sales_count = $sales['count']; 294 295 if ( $access_count > 0 ) { 296 return round( $sales_count / $access_count, 2 ); 297 } else { 298 return 0; 299 } 300 } 301 302 /** 303 * Get a summary of analytics values for a specified period. 304 * 305 * @param string $start The start of the period. 306 * @param string $end The end of the period. 307 */ 308 public function get_summary( $start, $end ) { 309 $most_sold_products = $this->products_by_sales_in_period( $start, $end ); 310 $most_view_products = $this->products_by_views_in_period( $start, $end ); 311 312 return array( 313 'requests' => array( 314 'period_avg_daily_count' => $this->average_daily_requests( $start, $end ), 315 'period_avg_time_between' => $this->average_time_between_requests( $start, $end ), 316 'period_total_count' => $this->requests_in_period( $start, $end ), 317 ), 318 'products' => array( 319 'period_most_sold_array' => $most_sold_products, 320 'period_most_viewed_array' => $most_view_products, 321 ), 322 'users' => array( 323 'total_count' => $this->users_count(), 324 'period_new_count' => $this->new_users_count( $start, $end ), 325 'period_unique_visitors' => $this->get_unique_visitors_count( $start, $end ), 326 ), 327 'pages' => array( 328 'period_most_requested' => $this->access_logs->get_requested_page_counts( $start, $end, false ), 329 ), 330 'stats' => array( 331 'period_conversion_rate' => $this->conversion_rate( $start, $end ), 332 'period_total_sales' => $this->sales_in_period( $start, $end ), 333 ), 334 'info' => array( 335 'products' => $this->get_mentioned_products( $most_sold_products + $most_view_products ), 336 ), 337 ); 338 } 339 340 /** 341 * Gets the count of unique visitors in the period provided. 342 * 343 * @param string $start The start of the period. 344 * @param string $end The end of the period. 345 */ 346 public function get_unique_visitors_count( $start, $end ) { 347 return $this->access_logs->get_unique_visitors_count( $start, $end ); 348 } 349 350 /** 351 * Returns a list of products present in the associative array provided, with product info as the value. 352 * Each product info will include the product name and a link to the product. 353 * 354 * @param array $products Associative array with product codes as keys and amount of sales as values. 355 * @return array Associative array with product details including name and link. 356 */ 357 public function get_mentioned_products( $products ) { 358 $result = array(); 359 360 foreach ( $products as $product_id => $sales ) { 361 $product = wc_get_product( $product_id ); 362 363 if ( $product ) { 364 $result[ $product_id ] = array( 365 'name' => $product->get_name(), 366 'link' => $product->get_permalink(), 367 ); 368 } 369 } 370 371 return $result; 372 } 251 373 } 252 374 -
dashcommerce/trunk/features/analytics/class-analytics.php
r3098201 r3116743 28 28 29 29 add_action( 'template_redirect', array( $this, 'log_page_access' ) ); 30 add_action( ' init', array( $dashcommerce_table_access_logs, 'create_table' ) );30 add_action( 'admin_init', array( $dashcommerce_table_access_logs, 'create_table' ) ); 31 31 add_action( 'admin_menu', array( $this, 'add_analytics_submenu' ) ); 32 32 add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); … … 76 76 77 77 global $dashcommerce_table_access_logs; 78 global $dashcommerce_ current_user;78 global $dashcommerce_settings; 79 79 80 80 wp_localize_script( … … 82 82 'script_vars', 83 83 array( 84 'ajax_url' => admin_url( 'admin-ajax.php' ),85 'nonce' => wp_create_nonce( 'dashcommerce_nonce' ),86 ' current_user' => $dashcommerce_current_user->get_info(),87 'data' => array(84 'ajax_url' => admin_url( 'admin-ajax.php' ), 85 'nonce' => wp_create_nonce( 'dashcommerce_nonce' ), 86 'settings' => $dashcommerce_settings->get_settings(), 87 'data' => array( 88 88 'is_empty' => $dashcommerce_table_access_logs->is_empty(), 89 89 'access_logs' => $dashcommerce_table_access_logs->get_access_logs(), … … 138 138 139 139 $parsed_url = wp_parse_url( $requested_page ); 140 141 if ( is_user_logged_in() ) { 142 $user_id = wp_get_current_user()->ID; 143 } else { 144 $user_id = null; 145 } 140 146 141 147 $utm = array( … … 158 164 'utm_term' => $utm['term'] ?? 'No term', 159 165 'utm_content' => $utm['content'] ?? 'No content', 166 'user_id' => strval( $user_id ), 160 167 ); 161 168 -
dashcommerce/trunk/features/product-metabox/class-product-metabox.php
r3098201 r3116743 13 13 */ 14 14 15 require_once plugin_dir_path( __FILE__ ) . '../../options/class- current-user.php';15 require_once plugin_dir_path( __FILE__ ) . '../../options/class-settings.php'; 16 16 require_once plugin_dir_path( __FILE__ ) . '../../utils/class-utils.php'; 17 17 … … 48 48 } 49 49 50 global $dashcommerce_ current_user;50 global $dashcommerce_settings; 51 51 52 52 global $dashcommerce_utils; … … 60 60 'script_vars', 61 61 array( 62 'ajax_url' => admin_url( 'admin-ajax.php' ),63 'nonce' => wp_create_nonce( 'dashcommerce_nonce' ),64 ' currentUser' => $dashcommerce_current_user->get_info(),62 'ajax_url' => admin_url( 'admin-ajax.php' ), 63 'nonce' => wp_create_nonce( 'dashcommerce_nonce' ), 64 'settings' => $dashcommerce_settings->get_settings(), 65 65 ) 66 66 ); … … 199 199 public function generate_ai_description() { 200 200 global $dashcommerce_utils; 201 global $dashcommerce_ current_user;201 global $dashcommerce_settings; 202 202 global $dashcommerce_env; 203 203 -
dashcommerce/trunk/features/product-metabox/product-metabox.js
r3098201 r3116743 20 20 this.setLoading(false); 21 21 22 if (script_vars. currentUser['loggedIn']) {22 if (script_vars.settings?.user?.['logged_in']) { 23 23 jQuery('#dashcommerce-product-metabox-for-non-logged-in').hide(); 24 24 25 if (script_vars. currentUser['premium']) {25 if (script_vars.settings?.user?.['premium']) { 26 26 jQuery('#dashcommerce-product-metabox-for-premium').show(); 27 27 jQuery('#dashcommerce-product-metabox-for-non-premium').hide(); -
dashcommerce/trunk/features/reports/class-reports-generator.php
r3098201 r3116743 7 7 /** 8 8 * This file is part of the DashCommerce Plugin for WordPress 9 * It includes the Dashcommerce_Reports _Pageclass which provides functions related9 * It includes the Dashcommerce_Reports class which provides functions related 10 10 * to reports message generations. 11 11 * … … 57 57 * @param string $frequency The frequency of the report. 58 58 * @param string $store The name of the store. 59 */ 60 public function generate( $frequency, $store ) { 61 $body = $this->get_statistics( $frequency ); 59 * @param array $topics The sections to be present in the plugin. 60 */ 61 public function generate( $frequency, $store, $topics ) { 62 $header = $this->get_header( $frequency, $store ); 63 $footer = $this->get_footer(); 64 65 $body = $this->get_statistics( $frequency, $topics ); 62 66 63 67 if ( null === $body ) { … … 65 69 } 66 70 67 $header = $this->get_time_indicator() . $this->get_frequency_indicator( $frequency, $store ); 68 69 global $dashcommerce_env; 70 71 $goodbye = $this->utils->apply_values( 72 "\nPara obter informações mais detalhadas, visite a tela de Analytics da <agency> no painel do WordPress da sua loja.", 73 array( 74 '<agency>' => $dashcommerce_env['AGENCY_F'], 75 ) 76 ); 77 78 $message = $header . $body . $goodbye; 71 $message = $header . "\n\n" . $body . "\n\n" . $footer; 79 72 80 73 return $message; … … 83 76 /** 84 77 * Selects a greeting based on the current time. 85 */ 86 private function get_time_indicator() { 78 * 79 * @param string $frequency The frequency. 80 * @param string $store The store name. 81 */ 82 private function get_header( $frequency, $store ) { 87 83 $hour = (int) $this->utils->create_date()->format( 'H' ); 88 84 … … 99 95 } 100 96 101 return $greet . " 👋\n"; 102 } 103 104 /** 105 * Returns a string indicating the frequency of the report. 106 * 107 * @param string $frequency The frequency. 108 * @param string $store The store name. 109 */ 110 private function get_frequency_indicator( $frequency, $store ) { 97 $time_indicator = $greet . " 👋\n"; 98 111 99 $date = $this->utils->create_date(); 112 100 $indicator = str_replace( '<store>', $store, 'Este é o relatório <freq> da loja *<store>*' ); … … 140 128 } 141 129 142 return $indicator . " 📝\n" . $segue . "\n\n"; 130 $frequency_indicator = $indicator . " 📝\n" . $segue; 131 132 return $time_indicator . $frequency_indicator; 133 } 134 135 /** 136 * Get the footer for the report message. 137 */ 138 private function get_footer() { 139 global $dashcommerce_env; 140 141 return $this->utils->apply_values( 142 'Para obter informações mais detalhadas, visite a tela de Analytics da <agency> no painel do WordPress da sua loja.', 143 array( 144 '<agency>' => $dashcommerce_env['AGENCY_F'], 145 ) 146 ); 143 147 } 144 148 … … 147 151 * 148 152 * @param string $frequency The report frequency. 149 */ 150 private function get_statistics( $frequency ) { 153 * @param array $topics The sections allowed in the report. 154 */ 155 private function get_statistics( $frequency, $topics ) { 151 156 if ( 'hourly' === $frequency ) { 152 157 $timeframe_start = '1 hour ago'; … … 184 189 'sales_completed' => $completed_sales_stats['count'], 185 190 'utm' => $this->access_logs->get_utm_overview( $current_period_start ), 186 'most_accessed' => $this->access_logs->get_requested_page_counts( $current_period_start ),191 'most_accessed' => $this->access_logs->get_requested_page_counts( $current_period_start, $current_period_end, false ), 187 192 'most_viewed' => $this->analytics->products_by_views_in_period( $current_period_start ), 188 193 'most_sold' => $this->analytics->products_by_sales_in_period( $current_period_start ), … … 195 200 'sales_completed' => $completed_sales_stats_previous['count'], 196 201 'utm' => $this->access_logs->get_utm_overview( $previous_period_start, $previous_period_end ), 197 'most_accessed' => $this->access_logs->get_requested_page_counts( $previous_period_start, $previous_period_end ),202 'most_accessed' => $this->access_logs->get_requested_page_counts( $previous_period_start, $previous_period_end, false ), 198 203 'most_viewed' => $this->analytics->products_by_views_in_period( $previous_period_start, $previous_period_end ), 199 204 'most_sold' => $this->analytics->products_by_sales_in_period( $previous_period_start, $previous_period_end ), … … 201 206 202 207 $lines = array( 203 'requests' => $this->generate_str_requests( $frequency, $stats_current['requests'], $stats_previous['requests'] ), 204 'new_sales' => $this->generate_str_sales( $frequency, $stats_current['new_sales'], $stats_previous['new_sales'] ), 205 'income' => $this->generate_str_income( $frequency, $stats_current['new_sales_value'], $stats_previous['new_sales_value'] ), 206 'utm' => $this->generate_str_utm( $stats_current['utm'] ), 207 'most_viewed' => $this->generate_str_most_viewed( $stats_current['most_viewed'], $stats_previous['most_viewed'], $frequency ), 208 'most_sold' => $this->generate_str_most_sold( $stats_current['most_sold'], $stats_previous['most_sold'], $frequency ), 208 'access_count' => $this->generate_str_requests( $frequency, $stats_current['requests'], $stats_previous['requests'] ), 209 'sales_count' => $this->generate_str_sales( $frequency, $stats_current['new_sales'], $stats_previous['new_sales'] ), 210 'income' => $this->generate_str_income( $frequency, $stats_current['new_sales_value'], $stats_previous['new_sales_value'] ), 211 'utm' => $this->generate_str_utm( $stats_current['utm'] ), 212 'most_acessed_pages' => $this->generate_str_most_accessed( $stats_current['most_accessed'] ), 213 'most_viewed_prods' => $this->generate_str_most_viewed( $stats_current['most_viewed'], $stats_previous['most_viewed'], $frequency ), 214 'most_sold_prods' => $this->generate_str_most_sold( $stats_current['most_sold'], $stats_previous['most_sold'], $frequency ), 209 215 ); 210 216 211 217 $lines = array_filter( 212 218 $lines, 213 function ( $value ) { 214 return null !== $value; 215 } 219 function ( $value, $key ) use ( $topics ) { 220 $has_data = null !== $value; 221 $should_display = ( ! is_null( $topics ) ) && in_array( $key, $topics, true ); 222 223 return $has_data && $should_display; 224 }, 225 ARRAY_FILTER_USE_BOTH 216 226 ); 217 227 218 $message = implode( "\n ", $lines );228 $message = implode( "\n\n", $lines ); 219 229 220 230 if ( '' === $message ) { … … 222 232 } 223 233 224 return rtrim( $message, "\n " );234 return rtrim( $message, "\n\n" ); 225 235 } 226 236 … … 271 281 */ 272 282 private function generate_str_requests( $frequency, $current, $previous ) { 283 if ( 0 === $current ) { 284 return '🌐 Não houve acessos :('; 285 } 286 273 287 $previous_desc = $this->get_previous_desc( $frequency ); 274 288 $previous_desc_alt = $this->get_previous_desc_alt( $frequency ); … … 284 298 } elseif ( $previous > 0 ) { 285 299 $str = $this->utils->apply_values( 286 '🌐 A sua loja teve <current> acessos, uma alteração de <comparison>% em relação <previous_desc_alt> (<previous> acessos <previous_desc>)',300 '🌐 A sua loja teve <current> acessos, <change>% em relação <previous_desc_alt> (<previous> acessos <previous_desc>)', 287 301 array( 288 302 '<current>' => $current, 289 303 '<previous>' => $previous, 290 '<c omparison>'=> sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ),304 '<change>' => sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ), 291 305 '<previous_desc>' => $previous_desc, 292 306 '<previous_desc_alt>' => $previous_desc_alt, … … 334 348 } elseif ( $previous > 0 ) { 335 349 $str = $this->utils->apply_values( 336 '🛒 Foram feitas <current> novas vendas, uma alteração de <comparison>% em relação <previous_desc_alt> (<previous> novas vendas <previous_desc>)',350 '🛒 Foram feitas <current> novas vendas, <change>% em relação <previous_desc_alt> (<previous> novas vendas <previous_desc>)', 337 351 array( 338 352 '<current>' => $current, 339 353 '<previous>' => $previous, 340 '<c omparison>'=> sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ),354 '<change>' => sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ), 341 355 '<previous_desc>' => $previous_desc, 342 356 '<previous_desc_alt>' => $previous_desc_alt, … … 380 394 } elseif ( $previous > 0 ) { 381 395 $str = $this->utils->apply_values( 382 '📦 <current> vendas foram marcadas como completas, uma alteração de <comparison>% em relação <previous_desc_alt> (<previous> <previous_desc>)',396 '📦 <current> vendas foram marcadas como completas, <change>% em relação <previous_desc_alt> (<previous> <previous_desc>)', 383 397 array( 384 398 '<current>' => $current, 385 399 '<previous>' => $previous, 386 '<c omparison>'=> sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ),400 '<change>' => sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ), 387 401 '<previous_desc>' => $previous_desc, 388 402 '<previous_desc_alt>' => $previous_desc_alt, … … 436 450 } elseif ( $previous > 0 ) { 437 451 $str = $this->utils->apply_values( 438 '💵 A loja faturou <current>, uma alteração de <comparison>% em relação <previous_desc_alt> (<previous> faturado <previous_desc>)',452 '💵 A loja faturou <current>, <change>% em relação <previous_desc_alt> (<previous> faturado <previous_desc>)', 439 453 array( 440 454 '<current>' => $currency_symbol . ' ' . $current, 441 455 '<previous>' => $currency_symbol . ' ' . $previous, 442 '<c omparison>'=> sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ),456 '<change>' => sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ), 443 457 '<previous_desc>' => $previous_desc, 444 458 '<previous_desc_alt>' => $previous_desc_alt, … … 470 484 471 485 if ( ! $this->is_utm_category_empty( $current, 'source' ) ) { 472 $message .= "\n🔗 Suas maiores fontes de tráfego foram:";486 $message .= '🔗 Suas maiores fontes de tráfego foram:'; 473 487 $message .= $this->generate_str_list( $current['source'], 'source' ); 488 489 $message .= "\n\n"; 474 490 } 475 491 476 492 if ( ! $this->is_utm_category_empty( $current, 'campaign' ) ) { 477 $message .= "\n\n📢 As campanhas que mais trouxeram tráfego foram:";493 $message .= '📢 As campanhas que mais trouxeram tráfego foram:'; 478 494 $message .= $this->generate_str_list( $current['campaign'], 'campaign' ); 479 495 } … … 566 582 $max_visible = 5; 567 583 568 $message = "\n📄 As páginas mais visitadas da loja foram:";584 $message = '📄 As páginas mais visitadas da loja foram:'; 569 585 $counter = 0; 570 586 … … 606 622 $max_visible = 5; 607 623 608 $message = "\n📦 Os produtos mais vendidos foram:";624 $message = '📦 Os produtos mais vendidos foram:'; 609 625 $counter = 0; 610 626 … … 686 702 $max_visible = 5; 687 703 688 $message = "\n👀 Os produtos mais visualizados foram:";704 $message = '👀 Os produtos mais visualizados foram:'; 689 705 $counter = 0; 690 706 -
dashcommerce/trunk/features/reports/class-reports.php
r3098201 r3116743 7 7 /** 8 8 * This file is part of the DashCommerce Plugin for WordPress 9 * It includes the Dashcommerce_Reports _Pageclass which provides functions related9 * It includes the Dashcommerce_Reports class which provides functions related 10 10 * to reports. 11 11 * … … 18 18 * This class represents the reports feature of the plugin. 19 19 */ 20 class Dashcommerce_Reports _Page{20 class Dashcommerce_Reports { 21 21 /** 22 22 * Class constructor. 23 23 */ 24 24 public function __construct() { 25 global $dashcommerce_ current_user;26 $this-> current_user = $dashcommerce_current_user;25 global $dashcommerce_settings; 26 $this->settings = $dashcommerce_settings; 27 27 28 28 global $dashcommerce_utils; … … 46 46 47 47 /** 48 * The key in the current_useroption for the report settings.48 * The key in the plugin's settings option for the report settings. 49 49 * 50 50 * @var string; … … 53 53 54 54 /** 55 * Reference to global instance of Dashcommerce_ Current_User.56 * 57 * @var Dashcommerce_ Current_User58 */ 59 private $ current_user;55 * Reference to global instance of Dashcommerce_Settings. 56 * 57 * @var Dashcommerce_Settings 58 */ 59 private $settings; 60 60 61 61 /** … … 90 90 $this->update_report_schedule( 'monthly', $schedules['monthly']['enable'], $time ); 91 91 92 $this-> current_user->update_single_entry( $this->settings_key, $settings );92 $this->settings->update_single_entry( $this->settings_key, $settings ); 93 93 94 94 return true; … … 156 156 157 157 $mobiles = $report_settings['mobiles']; 158 $webhook = $report_settings['webhook']; 159 $topics = $report_settings['topics']; 158 160 159 161 if ( isset( $mobiles['mobile1'] ) && ! empty( $mobiles['mobile1'] ) ) { 160 $message = $this->generator->generate( 'daily', $store_name );161 162 $this-> send_whatsapp_message( $mobiles['mobile1'], $message );162 $message = $this->generator->generate( 'daily', $store_name, $topics ); 163 164 $this->utils->send_whatsapp_message( $mobiles['mobile1'], $message ); 163 165 } 164 166 165 167 if ( isset( $mobiles['mobile2'] ) && ! empty( $mobiles['mobile2'] ) ) { 166 $message = $this->generator->generate( 'daily', $store_name );167 168 $this-> send_whatsapp_message( $mobiles['mobile2'], $message );168 $message = $this->generator->generate( 'daily', $store_name, $topics ); 169 170 $this->utils->send_whatsapp_message( $mobiles['mobile2'], $message ); 169 171 } 170 172 171 173 if ( isset( $mobiles['mobile3'] ) && ! empty( $mobiles['mobile3'] ) ) { 172 $message = $this->generator->generate( 'daily', $store_name ); 173 174 $this->send_whatsapp_message( $mobiles['mobile3'], $message ); 174 $message = $this->generator->generate( 'daily', $store_name, $topics ); 175 176 $this->utils->send_whatsapp_message( $mobiles['mobile3'], $message ); 177 } 178 179 if ( isset( $webhook ) && ! empty( $webhook ) ) { 180 $message = $this->generator->generate( 'daily', $store_name, $topics ); 181 182 $this->send_webhook_call( $webhook, $message ); 175 183 } 176 184 … … 179 187 180 188 /** 181 * Sends a WhatsApp message to the specified phone number.182 * 183 * @param string $ phone The recipient's phone number.189 * Sends a call to a webhook. 190 * 191 * @param string $url The webhook url. 184 192 * @param string $message The message to be sent. 185 193 */ 186 public function send_w hatsapp_message( $phone, $message ) {194 public function send_webhook_call( $url, $message ) { 187 195 if ( null === $message ) { 188 196 return null; 189 197 } 190 198 191 global $dashcommerce_env; 199 if ( false === filter_var( $url, FILTER_VALIDATE_URL ) ) { 200 return null; 201 } 192 202 193 203 $response = $this->utils->http_post( 194 $ dashcommerce_env['EP_SEND_WHATSAPP_MESSAGE'],204 $url, 195 205 array( 196 'recipients' => array( $phone ), 197 'message' => $message, 206 'message' => $message, 198 207 ), 199 208 array(), 200 209 array(), 201 true210 false 202 211 ); 203 212 … … 232 241 ), 233 242 'time' => null, 234 ); 235 } 236 237 /** 238 * Clears the settings for the reports in the current_user option. 243 'webhook' => null, 244 'topics' => array(), 245 ); 246 } 247 248 /** 249 * Clears the settings for the reports in the plugin's settings option. 239 250 */ 240 251 private function clear_reports_settings() { 241 $template = $this->generate_settings_template(); 242 243 $this->current_user->update_single_entry( $this->settings_key, $template ); 252 $default = $this->generate_settings_template(); 253 254 $default['topics'] = array( 255 'access_count', 256 'sales_count', 257 'income', 258 'most_viewed_prods', 259 'most_sold_prods', 260 ); 261 262 $this->settings->update_single_entry( $this->settings_key, $default ); 244 263 } 245 264 … … 248 267 */ 249 268 public function get_current_settings() { 250 $user_info = $this->current_user->get_info(); 251 252 if ( isset( $user_info[ $this->settings_key ] ) && ! empty( $user_info[ $this->settings_key ] ) ) { 253 $return_value = array_merge( 254 $this->generate_settings_template(), 255 $user_info[ $this->settings_key ], 256 ); 257 258 return $return_value; 269 $plugin_settings = $this->settings->get_settings(); 270 271 if ( isset( $plugin_settings[ $this->settings_key ] ) && ! empty( $plugin_settings[ $this->settings_key ] ) ) { 272 return $plugin_settings[ $this->settings_key ]; 259 273 } else { 260 274 return null; 261 275 } 262 276 } 277 278 /** 279 * Returns the report schedules in the WP cron system. 280 */ 281 public function get_schedules() { 282 return array( 283 'daily' => $this->utils->get_all_scheduled_instances( $this->schedule_hook_prefix . '_daily' ), 284 'weekly' => $this->utils->get_all_scheduled_instances( $this->schedule_hook_prefix . '_weekly' ), 285 'monthly' => $this->utils->get_all_scheduled_instances( $this->schedule_hook_prefix . '_monthly' ), 286 ); 287 } 263 288 } 264 289 265 290 global $dashcommerce_reports; 266 291 267 $dashcommerce_reports = new Dashcommerce_Reports _Page();292 $dashcommerce_reports = new Dashcommerce_Reports(); -
dashcommerce/trunk/features/settings-page/class-settings-page.php
r3098201 r3116743 14 14 */ 15 15 16 require_once plugin_dir_path( __FILE__ ) . '../../options/class- current-user.php';16 require_once plugin_dir_path( __FILE__ ) . '../../options/class-settings.php'; 17 17 require_once plugin_dir_path( __FILE__ ) . '../../utils/class-utils.php'; 18 18 … … 48 48 } 49 49 50 global $dashcommerce_current_user; 51 global $dashcommerce_reports; 50 global $dashcommerce_settings; 52 51 global $dashcommerce_utils; 53 52 … … 60 59 'script_vars', 61 60 array( 62 'ajax_url' => admin_url( 'admin-ajax.php' ), 63 'nonce' => wp_create_nonce( 'dashcommerce_nonce' ), 64 'currentUser' => $dashcommerce_current_user->get_info(), 65 'reportSettings' => $dashcommerce_reports->get_current_settings(), 61 'ajax_url' => admin_url( 'admin-ajax.php' ), 62 'nonce' => wp_create_nonce( 'dashcommerce_nonce' ), 63 'settings' => $dashcommerce_settings->get_settings(), 66 64 ) 67 65 ); … … 122 120 */ 123 121 public function settings_callback() { 124 global $dashcommerce_ current_user;122 global $dashcommerce_settings; 125 123 global $dashcommerce_env; 126 124 global $dashcommerce_utils; … … 130 128 $agency_tooltip = $dashcommerce_env['AGENCY'] . ' ' . $version . ' (' . $dashcommerce_env['ENV'] . ')'; 131 129 132 $user = $dashcommerce_ current_user->get_info();130 $user = $dashcommerce_settings->get_user(); 133 131 134 132 ?> … … 232 230 </div> 233 231 234 <p> 235 <label>Números de WhatsApp:</label> 236 <input type="tel" id="dashcommerce-reports-input-mobile-1" placeholder="Adicione um número"> 237 <input type="tel" id="dashcommerce-reports-input-mobile-2" placeholder="Adicione um número"> 238 <input type="tel" id="dashcommerce-reports-input-mobile-3" placeholder="Adicione um número"> 239 <div> 232 <div> 233 <p> 234 Você pode adicionar até três números para receber os relatórios programados ou informar uma url a ser chamada no horário programado. 235 </p> 236 237 <div> 238 <label>Números de WhatsApp:</label> 239 <input type="tel" id="dashcommerce-reports-input-mobile-1" placeholder="Adicione um número"> 240 <input type="tel" id="dashcommerce-reports-input-mobile-2" placeholder="Adicione um número"> 241 <input type="tel" id="dashcommerce-reports-input-mobile-3" placeholder="Adicione um número"> 240 242 (somente números, com código do país, DDD e dígito 9 - ex: 5561912345678) 241 <br> 242 Você pode adicionar até três números para receber os relatórios programados. 243 </div> 244 </p> 243 </div> 244 245 <div style="margin-top: 13px;"> 246 <label>Endpoint:</label> 247 <input style="width: 500px" type="text" id="dashcommerce-reports-input-webhook" placeholder="Insira a URL do seu endpoint aqui"> 248 </div> 249 </div> 250 251 <div style="display: flex; flex-direction: column; margin: 13px 0;"> 252 <div> 253 <input type="checkbox" id="dashcommerce-reports-input-optional-accesses" name="dashcommerce-reports-input-optional-accesses"> 254 <label for="dashcommerce-reports-input-optional-accesses">Incluir quantidade de acessos</label> 255 </div> 256 257 <div> 258 <input type="checkbox" id="dashcommerce-reports-input-optional-sales" name="dashcommerce-reports-input-optional-sales"> 259 <label for="dashcommerce-reports-input-optional-sales">Incluir quantidade de vendas</label> 260 </div> 261 262 <div> 263 <input type="checkbox" id="dashcommerce-reports-input-optional-income" name="dashcommerce-reports-input-optional-income"> 264 <label for="dashcommerce-reports-input-optional-income">Incluir receita somada</label> 265 </div> 266 267 <div> 268 <input type="checkbox" id="dashcommerce-reports-input-optional-utm" name="dashcommerce-reports-input-optional-utm"> 269 <label for="dashcommerce-reports-input-optional-utm">Incluir resumo de dados UTM</label> 270 </div> 271 272 <div> 273 <input type="checkbox" id="dashcommerce-reports-input-optional-most-accessed-pages" name="dashcommerce-reports-input-optional-most-accessed-pages"> 274 <label for="dashcommerce-reports-input-optional-most-accessed-pages">Incluir lista de páginas mais acessadas</label> 275 </div> 276 277 <div> 278 <input type="checkbox" id="dashcommerce-reports-input-optional-most-viewed-prods" name="dashcommerce-reports-input-optional-most-viewed-prods"> 279 <label for="dashcommerce-reports-input-optional-most-viewed-prods">Incluir lista de produtos mais acessados</label> 280 </div> 281 282 <div> 283 <input type="checkbox" id="dashcommerce-reports-input-optional-most-sold-prods" name="dashcommerce-reports-input-optional-most-sold-prods"> 284 <label for="dashcommerce-reports-input-optional-most-sold-prods">Incluir lista de produtos mais vendidos</label> 285 </div> 286 </div> 245 287 246 288 <div style="display: flex;"> … … 335 377 * 5. Checks the response from the server. If the response indicates an error, it sends a JSON response with the error message. 336 378 * 6. Checks if the response contains the expected fields (pluginToken and premium). If not, it sends a JSON response indicating failure. 337 * 7. Sets the user information (username, pluginToken, and premium) in the dashcommerce_ current_userobject.379 * 7. Sets the user information (username, pluginToken, and premium) in the dashcommerce_settings object. 338 380 * 8. Sends a JSON response indicating success and includes the pluginToken. 339 381 * … … 342 384 public function handle_login() { 343 385 global $dashcommerce_utils; 344 global $dashcommerce_ current_user;386 global $dashcommerce_settings; 345 387 global $dashcommerce_env; 346 388 … … 361 403 wp_die(); 362 404 } 405 406 $home = home_url(); 363 407 364 408 try { … … 366 410 $dashcommerce_env['EP_LOG_IN'], 367 411 array( 412 'storeUrl' => home_url(), 368 413 'email' => $username, 369 414 'password' => $password, … … 415 460 $openai_key_preview = $body['openaiKeyPreview']; 416 461 417 $dashcommerce_ current_user->log_in( $username, $plugin_token, $is_premium, $openai_key_preview );462 $dashcommerce_settings->log_in( $username, $plugin_token, $is_premium, $openai_key_preview ); 418 463 419 464 wp_send_json( … … 421 466 'success' => true, 422 467 'token' => $plugin_token, 423 'openAiKeyPreview' => $dashcommerce_ current_user,468 'openAiKeyPreview' => $dashcommerce_settings, 424 469 ) 425 470 ); … … 441 486 } 442 487 443 global $dashcommerce_ current_user;444 445 $dashcommerce_ current_user->log_out();488 global $dashcommerce_settings; 489 490 $dashcommerce_settings->log_out( 'manual' ); 446 491 447 492 wp_send_json( array( 'success' => true ) ); … … 461 506 public function handle_save_openai_key() { 462 507 global $dashcommerce_utils; 463 global $dashcommerce_ current_user;508 global $dashcommerce_settings; 464 509 global $dashcommerce_env; 465 510 … … 477 522 } 478 523 479 $token = $dashcommerce_ current_user->get_info()['token'];524 $token = $dashcommerce_settings->get_user()['token']; 480 525 481 526 try { … … 515 560 } 516 561 517 $dashcommerce_ current_user->update_openai_key_preview( $body['masked'] );562 $dashcommerce_settings->update_openai_key_preview( $body['masked'] ); 518 563 519 564 wp_send_json( array( 'success' => true ) ); … … 528 573 public function handle_remove_openai_key() { 529 574 global $dashcommerce_utils; 530 global $dashcommerce_ current_user;575 global $dashcommerce_settings; 531 576 global $dashcommerce_env; 532 577 … … 535 580 } 536 581 537 $token = $dashcommerce_ current_user->get_info()['token'];582 $token = $dashcommerce_settings->get_user()['token']; 538 583 539 584 try { … … 572 617 } 573 618 574 $dashcommerce_ current_user->update_openai_key_preview( null );619 $dashcommerce_settings->update_openai_key_preview( null ); 575 620 576 621 wp_send_json( array( 'success' => true ) ); -
dashcommerce/trunk/features/settings-page/settings-page.js
r3098201 r3116743 23 23 * }; 24 24 * time: string; 25 * webhook?: string; 26 * topics?: string[]; 25 27 * }} ReportSettings 26 28 */ … … 62 64 }); 63 65 64 if (script_vars. currentUser['openai_key_preview']) {66 if (script_vars.settings['openai_key_preview']) { 65 67 jQuery('#dashcommerce-custom-openai-token-for-saved').show(); 66 68 jQuery('#dashcommerce-custom-openai-token-for-not-saved').hide(); … … 80 82 prepareForm() { 81 83 this.preparers.ai(); 82 this.sections.reports.fill(script_vars ['reportSettings'])83 this.sections.misc.fill(script_vars[' currentUser'])84 this.sections.reports.fill(script_vars.settings?.report_settings) 85 this.sections.misc.fill(script_vars['settings']) 84 86 85 87 this.setLogInLoading(false); … … 89 91 this.sections.misc.setLoading(false); 90 92 91 if (script_vars. currentUser && script_vars.currentUser['loggedIn']) {92 if (script_vars. currentUser['premium']) {93 if (script_vars.settings && script_vars.settings.user?.['logged_in']) { 94 if (script_vars.settings.user?.['premium']) { 93 95 jQuery('#dashcommerce-message-for-premium').show(); 94 96 jQuery('#dashcommerce-message-for-non-premium').hide(); … … 227 229 mobile1: jQuery('#dashcommerce-reports-input-mobile-1'), 228 230 mobile2: jQuery('#dashcommerce-reports-input-mobile-2'), 229 mobile3: jQuery('#dashcommerce-reports-input-mobile-3') 231 mobile3: jQuery('#dashcommerce-reports-input-mobile-3'), 232 webhook: jQuery('#dashcommerce-reports-input-webhook'), 233 includeAccessCount: jQuery('#dashcommerce-reports-input-optional-accesses'), 234 includeSalesCount: jQuery('#dashcommerce-reports-input-optional-sales'), 235 includeIncome: jQuery('#dashcommerce-reports-input-optional-income'), 236 includeUtm: jQuery('#dashcommerce-reports-input-optional-utm'), 237 includeMostAccessedPages: jQuery('#dashcommerce-reports-input-optional-most-accessed-pages'), 238 includeMostViewedProds: jQuery('#dashcommerce-reports-input-optional-most-viewed-prods'), 239 includeMostSoldProducts: jQuery('#dashcommerce-reports-input-optional-most-sold-prods'), 230 240 }, 231 241 actions: { … … 247 257 */ 248 258 getDisplayedSettings() { 259 /** @type {ReportSettings} */ 249 260 return { 250 261 schedules: { … … 265 276 mobile3: this.elements.inputs.mobile3.val().toString() || null, 266 277 }, 267 time: utils.hoursMinutesToGMT(this.elements.inputs.preferredTime.val()) 278 time: utils.hoursMinutesToGMT(this.elements.inputs.preferredTime.val()), 279 webhook: this.elements.inputs.webhook.val().toString() || null, 280 topics: this.getTopicsArray(), 268 281 }; 282 } 283 284 /** 285 * Gets the topics options as selected in the DOM. 286 * 287 * @returns {string[]} 288 */ 289 getTopicsArray() { 290 const topics = { 291 'access_count': this.elements.inputs.includeAccessCount.prop('checked'), 292 'sales_count': this.elements.inputs.includeSalesCount.prop('checked'), 293 'income': this.elements.inputs.includeIncome.prop('checked'), 294 'utm': this.elements.inputs.includeUtm.prop('checked'), 295 'most_acessed_pages': this.elements.inputs.includeMostAccessedPages.prop('checked'), 296 'most_viewed_prods': this.elements.inputs.includeMostViewedProds.prop('checked'), 297 'most_sold_prods': this.elements.inputs.includeMostSoldProducts.prop('checked'), 298 }; 299 300 return Object.entries(topics) 301 .filter(([key, value]) => value === true) 302 .map(([key, value]) => key); 269 303 } 270 304 … … 294 328 this.elements.inputs.mobile2.val(settings.mobiles.mobile2); 295 329 this.elements.inputs.mobile3.val(settings.mobiles.mobile3); 330 331 this.elements.inputs.webhook.val(settings.webhook); 332 333 if (settings.topics) { 334 this.elements.inputs.includeAccessCount.prop('checked', settings.topics.includes('access_count')); 335 this.elements.inputs.includeSalesCount.prop('checked', settings.topics.includes('sales_count')); 336 this.elements.inputs.includeIncome.prop('checked', settings.topics.includes('income')); 337 this.elements.inputs.includeUtm.prop('checked', settings.topics.includes('utm')); 338 this.elements.inputs.includeMostAccessedPages.prop('checked', settings.topics.includes('most_acessed_pages')); 339 this.elements.inputs.includeMostViewedProds.prop('checked', settings.topics.includes('most_viewed_prods')); 340 this.elements.inputs.includeMostSoldProducts.prop('checked', settings.topics.includes('most_sold_prods')); 341 } 296 342 297 343 this.elements.actions.save.attr('disabled', 'disabled'); … … 420 466 }; 421 467 422 fill( currentUser) {423 this.elements.inputs.showFooter.prop('checked', currentUser?.['show_agency_footer']);468 fill(settings) { 469 this.elements.inputs.showFooter.prop('checked', settings?.['show_agency_footer']); 424 470 } 425 471 -
dashcommerce/trunk/jsconfig.json
r3098201 r3116743 1 1 { 2 2 "compilerOptions": { 3 "target": "ES201 6"3 "target": "ES2017" 4 4 }, 5 5 "typeAcquisition": { -
dashcommerce/trunk/readme.txt
r3098575 r3116743 4 4 Requires at least: WordPress 5.0 5 5 Tested up to: 6.4.3 6 Stable tag: 1. 1.66 Stable tag: 1.2.0 7 7 Requires PHP: 8.1 8 8 License: GPL v2 -
dashcommerce/trunk/tables/class-access-logs.php
r3098201 r3116743 43 43 $full_table_name = $wpdb->prefix . $this->table_name; 44 44 45 $sql = "CREATE TABLE IF NOT EXISTS$full_table_name (45 $sql = "CREATE TABLE $full_table_name ( 46 46 id mediumint(9) NOT NULL AUTO_INCREMENT, 47 47 access_time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, … … 55 55 utm_term varchar(255) NOT NULL, 56 56 utm_content varchar(255) NOT NULL, 57 PRIMARY KEY (id) 57 user_id varchar(255), 58 PRIMARY KEY (id) 58 59 )"; 59 60 … … 73 74 74 75 // phpcs:ignore 75 $wpdb->insert(76 return $wpdb->insert( 76 77 $full_table_name, 77 78 $access_data, 78 array( '%s', '%s', '%s', '%s' )79 array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) // Fixes an issue with user_id. This is each column's type - update when making changes to the table's columns. 79 80 ); 80 81 } … … 91 92 public function get_access_logs( $start = null, $end = null ) { 92 93 global $wpdb; 93 $date_format = 'Y-m-d H:i:s'; 94 $ table_name = $wpdb->prefix . $this->table_name;95 96 $str_start_utc = $start ? ( $this->utils->create_date( $start ) )->modify( 'midnight' )->setTimezone( new DateTimeZone( 'UTC' ) )->format( $date_format ) : null; 97 $ str_end_utc = $end ? ( $this->utils->create_date( $end ) )->modify( 'midnight' )->setTimezone( new DateTimeZone( 'UTC' ) )->format( $date_format ) : null;94 95 $str_start_utc = $start ? $this->utils->prepare_period_delimiter( $start ) : null; 96 $str_end_utc = $end ? $this->utils->prepare_period_delimiter( $end ) : null; 97 98 $table_name = $wpdb->prefix . $this->table_name; 98 99 99 100 if ( $str_start_utc && $str_end_utc ) { … … 115 116 * Retrieves the count of requested pages. 116 117 * 117 * @param string $start The start of the period. 118 * @param string $end Optional. The end of the period. `today` if not provided. 118 * @param string $start The start of the period. 119 * @param string $end Optional. The end of the period. `today` if not provided. 120 * @param boolean $group Optional. Group requests into /* instead of the full URL. `true` if not provided. 119 121 * @return array The count of requested pages. 120 122 */ 121 public function get_requested_page_counts( $start = '3 months ago', $end = 'today' ) {123 public function get_requested_page_counts( $start = '3 months ago', $end = 'today', $group = true ) { 122 124 global $dashcommerce_utils; 123 125 … … 126 128 $plucked = wp_list_pluck( $access_logs, 'requested_page' ); 127 129 128 $truncated_urls = array_map( 129 function ( $url ) use ( $dashcommerce_utils ) { 130 return $dashcommerce_utils->truncate_url( $url, 1 ); 131 }, 132 $plucked 133 ); 134 135 $page_counts = array_count_values( $truncated_urls ); 130 if ( $group ) { 131 $plucked = array_map( 132 function ( $url ) use ( $dashcommerce_utils ) { 133 return $dashcommerce_utils->truncate_url( $url, 1 ); 134 }, 135 $plucked 136 ); 137 } 138 139 $page_counts = array_count_values( $plucked ); 136 140 137 141 arsort( $page_counts ); … … 228 232 return empty( $results ); 229 233 } 234 235 /** 236 * Gets the count of unique visitors in the period provided. 237 * 238 * @param string $start The start of the period. 239 * @param string $end The end of the period. Default: `today`. 240 * @return int The count of unique visitors. 241 */ 242 public function get_unique_visitors_count( $start, $end = 'today' ) { 243 global $wpdb; 244 245 $str_start_utc = $start ? $this->utils->prepare_period_delimiter( $start ) : null; 246 $str_end_utc = $end ? $this->utils->prepare_period_delimiter( $end ) : null; 247 248 if ( ! $str_start_utc || ! $str_end_utc ) { 249 return 0; 250 } 251 252 $table_name = $wpdb->prefix . $this->table_name; 253 254 /* phpcs:ignore */ 255 $query = $wpdb->prepare("SELECT COUNT(DISTINCT CONCAT(user_id, '_', user_ip)) AS user_count FROM %i WHERE access_time BETWEEN %s AND %s", 256 $table_name, 257 $str_start_utc, 258 $str_end_utc 259 ); 260 261 /* phpcs:ignore */ 262 $result = (int) $wpdb->get_var( $query ); 263 264 return $result ? $result : 0; 265 } 230 266 } 231 267 -
dashcommerce/trunk/utils/class-utils.php
r3098201 r3116743 22 22 add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); 23 23 } 24 25 /** 26 * Reference to global variable dashcommerce_env. It should be defined in load_environment(). 27 * 28 * @var array 29 */ 30 public $env; 24 31 25 32 /** … … 47 54 */ 48 55 public function get_auth_params() { 49 global $dashcommerce_current_user; 50 global $dashcommerce_env; 51 52 $user_info = $dashcommerce_current_user->get_info(); 56 global $dashcommerce_settings; 57 58 $user_info = $dashcommerce_settings->get_user(); 53 59 54 60 return array( 55 61 'token' => $user_info['token'], 56 'agency' => $ dashcommerce_env['AGENCY'],62 'agency' => $this->env['AGENCY'], 57 63 ); 58 64 } … … 220 226 } 221 227 } 228 229 $this->env = $dashcommerce_env; 222 230 } 223 231 … … 345 353 $schedules[] = array( 346 354 'timestamp' => $timestamp, 355 'readable' => gmdate( 'l, Y-m-d H:i:s', $timestamp ) . ' GMT', 347 356 'schedule' => $jobs_assigned[ $hook ][ array_key_first( $jobs_assigned[ $hook ] ) ]['schedule'], 348 357 'args' => $jobs_assigned[ $hook ][ array_key_first( $jobs_assigned[ $hook ] ) ]['args'], … … 430 439 */ 431 440 public function calculate_percentage_difference( $a, $b ) { 432 if ( 0 === $a ) {441 if ( 0 === $a || 0.0 === $a ) { 433 442 return null; 434 443 } 435 444 436 return round( ( ( $b - $a ) / $a ) * 100 );445 return round( ( ( $b - $a ) / $a ) * 100, 2 ); 437 446 } 438 447 … … 470 479 return is_plugin_active( 'woocommerce/woocommerce.php' ); 471 480 } 481 482 /** 483 * Returns the plugin's agency from the environment variables. 484 * 485 * @param boolean $formatted `true` to get the formatted version of the agency variable. `false` if not provided. 486 */ 487 public function get_agency( $formatted = false ) { 488 if ( $formatted ) { 489 return $this->env['AGENCY_F']; 490 } else { 491 return $this->env['AGENCY']; 492 } 493 } 494 495 /** 496 * Returns the plugin's environment name from the environment variables. 497 */ 498 public function get_env() { 499 return $this->env['ENV']; 500 } 501 502 /** 503 * Validate a PHP date string representation. 504 * 505 * @param string $date_string The date string to validate. 506 * @return bool True if the string is a valid date representation, false otherwise. 507 */ 508 public function is_valid_date_string( $date_string ) { 509 try { 510 $date = new DateTime( $date_string ); 511 return true; 512 } catch ( Exception $e ) { 513 return false; 514 } 515 } 516 517 /** 518 * Sends a WhatsApp message to the specified phone number. 519 * TODO: move to a more appropriate class. 520 * 521 * @param string $phone The recipient's phone number. 522 * @param string $message The message to be sent. 523 */ 524 public function send_whatsapp_message( $phone, $message ) { 525 if ( null === $message ) { 526 return null; 527 } 528 529 $response = $this->http_post( 530 $this->env['EP_SEND_WHATSAPP_MESSAGE'], 531 array( 532 'recipients' => array( $phone ), 533 'message' => $message, 534 ), 535 array(), 536 array(), 537 true 538 ); 539 540 if ( 200 === $this->extract_response_code( $response ) ) { 541 return true; 542 } else { 543 return false; 544 } 545 } 546 547 /** 548 * Sets a datestring as a date object at midnight (of the user's tz) in UTC, in the format expected by the rest of the plugin. 549 * 550 * @param string $delimiter The timestring. 551 * @param string $no_utc `false` to convert the date into UTC, `true` to keep it as is. 552 */ 553 public function prepare_period_delimiter( $delimiter, $no_utc = false ) { 554 $utc = new DateTimeZone( 'UTC' ); 555 556 if ( false === $no_utc ) { 557 return $this->create_date( $delimiter )->modify( 'midnight' )->setTimezone( $utc )->format( 'Y-m-d H:i:s' ); 558 } else { 559 return $this->create_date( $delimiter, 'UTC', true )->modify( 'midnight' )->format( 'Y-m-d H:i:s' ); 560 } 561 } 562 563 /** 564 * Calculates the difference between all nested values in two structurally identical associative arrays. 565 * 566 * @param array $previous Associative array of the old data. 567 * @param array $current Associative array of the new data. 568 * @return array An array in the same structure of the ones received as parameters - but with percentages in place of their values. 569 */ 570 public function array_diff_assoc_recursive( $previous, $current ) { 571 $result = array(); 572 573 foreach ( $previous as $key => $prev_value ) { 574 $curr_value = $current[ $key ]; 575 576 if ( is_array( $prev_value ) && isset( $curr_value ) && is_array( $curr_value ) ) { // is array. 577 $value = $this->array_diff_assoc_recursive( $prev_value, $curr_value ); 578 } elseif ( isset( $curr_value ) && 0 !== $prev_value && is_numeric( $prev_value ) && is_numeric( $curr_value ) ) { // is number. 579 $difference = $this->calculate_percentage_difference( $prev_value, $curr_value ); 580 $sign = $difference >= 0 ? '+' : '-'; 581 $value = sprintf( '%s%.2f%%', $sign, abs( $difference ) ); 582 } else { 583 $value = 0 !== $prev_value ? '+100.00%' : '+0.00%'; 584 } 585 586 if ( '+0.00%' === $value ) { 587 $value = null; 588 } 589 590 $result[ $key ] = $value; 591 } 592 593 return $result; 594 } 472 595 } 473 596
Note: See TracChangeset
for help on using the changeset viewer.