Plugin Directory

Changeset 3116743


Ignore:
Timestamp:
07/12/2024 02:01:50 AM (21 months ago)
Author:
dashcommerce
Message:

update login method, add api

Location:
dashcommerce/trunk
Files:
3 added
1 deleted
17 edited

Legend:

Unmodified
Added
Removed
  • dashcommerce/trunk/dashcommerce.php

    r3098201 r3116743  
    1212 * Plugin Name: DashCommerce
    1313 * Description: DashCommerce plugin for WordPress.
    14  * Version: 1.1.6
     14 * Version: 1.2.0
    1515 * Author: DashCommerce
    1616 * License: GPL v2
     
    4848require_once plugin_dir_path( __FILE__ ) . 'features/reports/class-reports.php';
    4949require_once plugin_dir_path( __FILE__ ) . 'features/agency-footer/class-agency-footer.php';
     50require_once plugin_dir_path( __FILE__ ) . 'features/api/class-api.php';
    5051
    5152/**
  • dashcommerce/trunk/features/admin-script/class-admin-script.php

    r3098201 r3116743  
    1313 */
    1414
    15 require_once plugin_dir_path( __FILE__ ) . '../../options/class-current-user.php';
     15require_once plugin_dir_path( __FILE__ ) . '../../options/class-settings.php';
    1616require_once plugin_dir_path( __FILE__ ) . '../../utils/class-utils.php';
    1717
     
    3232    public function __construct() {
    3333        global $dashcommerce_utils;
    34         global $dashcommerce_current_user;
     34        global $dashcommerce_settings;
    3535
    36         $current_user_info = $dashcommerce_current_user->get_info();
     36        $current_user = $dashcommerce_settings->get_user();
    3737
    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'] ) {
    3939            $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';
    5642        }
    5743
     
    6349     */
    6450    public function enqueue_script() {
    65         global $dashcommerce_current_user;
     51        global $dashcommerce_settings;
    6652        global $dashcommerce_utils;
    6753
     
    7056        wp_enqueue_script( 'dashcommerce-admin-script', plugin_dir_url( __FILE__ ) . 'admin-script.js', array( 'jquery' ), $ver, true );
    7157
    72         $current_user_info = $dashcommerce_current_user->get_info();
     58        $current_user = $dashcommerce_settings->get_user();
    7359
    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;
    7561
    7662        wp_localize_script(
     
    9076     * Check the validity of the token.
    9177     *
    92      * @param array $current_user_info The current user information.
     78     * @param array $current_user The current user information.
    9379     * @return array The token validity and premium status.
    9480     */
    95     public function check_token( $current_user_info ) {
     81    public function check_token( $current_user ) {
    9682        global $dashcommerce_utils;
    9783        global $dashcommerce_env;
    98         global $dashcommerce_current_user;
     84        global $dashcommerce_settings;
    9985
    10086        try {
     
    10288                $dashcommerce_env['EP_CHECK_TOKEN'],
    10389                array(
    104                     'token'  => $current_user_info['token'],
     90                    'token'  => $current_user['token'],
    10591                    'agency' => $dashcommerce_env['AGENCY'],
    10692                ),
     
    123109        }
    124110
    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        }
    126114
    127115        return array(
  • dashcommerce/trunk/features/agency-footer/class-agency-footer.php

    r3098201 r3116743  
    2121     */
    2222    public function __construct() {
    23         global $dashcommerce_current_user;
    24         $this->current_user = $dashcommerce_current_user;
     23        global $dashcommerce_settings;
     24        $this->settings = $dashcommerce_settings;
    2525
    2626        global $dashcommerce_env;
     
    3131
    3232    /**
    33      * The key of the setting in the Current_User option.
     33     * The key of the setting in the plugin's settings option.
    3434     *
    3535     * @var string
     
    3838
    3939    /**
    40      * Reference to global $dashcommerce_current_user.
     40     * Reference to global instance of Dashcommerce_Settings.
    4141     *
    42      * @var Dashcommerce_Current_User
     42     * @var Dashcommerce_Settings
    4343     */
    44     private $current_user;
     44    private $settings;
    4545
    4646    /**
     
    5757     */
    5858    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 );
    6060    }
    6161
     
    6464     */
    6565    public function get_flag() {
    66         $settings = $this->current_user->get_info();
     66        $settings = $this->settings->get_settings();
    6767
    6868        if ( ! isset( $settings[ $this->setting_key ] ) ) {
    6969            $this->set_flag( false );
    7070
    71             $settings = $this->current_user->get_info();
     71            $settings = $this->settings->get_settings();
    7272        }
    7373
  • dashcommerce/trunk/features/analytics/analytics-overview.js

    r3098201 r3116743  
    1616        jQuery('#dashcommerce-analytics-for-empty-access-logs').hide();
    1717
    18         if (!script_vars['current_user']?.['loggedIn']) {
     18        if (!script_vars.settings?.user?.['logged_in']) {
    1919            jQuery('#dashcommerce-analytics-for-logged-out-users').show();
    2020            return;
  • dashcommerce/trunk/features/analytics/class-analytics-charts.php

    r3098201 r3116743  
    152152    public function display_day_counts_table() {
    153153        $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' );
    155155        $average_daily_requests        = $this->values->average_daily_requests( '3 months ago' );
    156156        $average_time_between_requests = $this->values->average_time_between_requests( '3 months ago' );
  • dashcommerce/trunk/features/analytics/class-analytics-values.php

    r3098201 r3116743  
    8181        $day_counts = $this->access_logs->get_day_counts( $start, $end );
    8282
    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.
    9888     *
    9989     * @param string $start The start of the period.
     
    10191     */
    10292    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 );
    10494
    10595        $seconds_day = 24 * 60 * 60;
     
    10797        if ( $total_requests_sum > 0 ) {
    10898            $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 );
    110100        } else {
    111101            return 0;
     
    128118        }
    129119
    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 );
    132122
    133123        $args = array(
    134124            'date_query' => array(
    135                 'after'     => $dt_str_start,
    136                 'before'    => $dt_str_end,
     125                'after'     => $str_start_ltz,
     126                'before'    => $str_end_ltz,
    137127                'inclusive' => true,
    138128            ),
     
    171161        }
    172162
    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 );
    175165
    176166        $args = array(
    177             'date_created' => $dt_str_start . '...' . $dt_str_end,
     167            'date_created' => $str_start_ltz . '...' . $str_end_ltz,
    178168            'limit'        => -1, // Fetch all orders.
    179169        );
     
    249239        return $product_view_counts;
    250240    }
     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    }
    251373}
    252374
  • dashcommerce/trunk/features/analytics/class-analytics.php

    r3098201 r3116743  
    2828
    2929        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' ) );
    3131        add_action( 'admin_menu', array( $this, 'add_analytics_submenu' ) );
    3232        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
     
    7676
    7777        global $dashcommerce_table_access_logs;
    78         global $dashcommerce_current_user;
     78        global $dashcommerce_settings;
    7979
    8080        wp_localize_script(
     
    8282            'script_vars',
    8383            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(
    8888                    'is_empty'    => $dashcommerce_table_access_logs->is_empty(),
    8989                    'access_logs' => $dashcommerce_table_access_logs->get_access_logs(),
     
    138138
    139139        $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        }
    140146
    141147        $utm = array(
     
    158164            'utm_term'       => $utm['term'] ?? 'No term',
    159165            'utm_content'    => $utm['content'] ?? 'No content',
     166            'user_id'        => strval( $user_id ),
    160167        );
    161168
  • dashcommerce/trunk/features/product-metabox/class-product-metabox.php

    r3098201 r3116743  
    1313 */
    1414
    15 require_once plugin_dir_path( __FILE__ ) . '../../options/class-current-user.php';
     15require_once plugin_dir_path( __FILE__ ) . '../../options/class-settings.php';
    1616require_once plugin_dir_path( __FILE__ ) . '../../utils/class-utils.php';
    1717
     
    4848        }
    4949
    50         global $dashcommerce_current_user;
     50        global $dashcommerce_settings;
    5151
    5252        global $dashcommerce_utils;
     
    6060            'script_vars',
    6161            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(),
    6565            )
    6666        );
     
    199199    public function generate_ai_description() {
    200200        global $dashcommerce_utils;
    201         global $dashcommerce_current_user;
     201        global $dashcommerce_settings;
    202202        global $dashcommerce_env;
    203203
  • dashcommerce/trunk/features/product-metabox/product-metabox.js

    r3098201 r3116743  
    2020        this.setLoading(false);
    2121
    22         if (script_vars.currentUser['loggedIn']) {
     22        if (script_vars.settings?.user?.['logged_in']) {
    2323            jQuery('#dashcommerce-product-metabox-for-non-logged-in').hide();
    2424
    25             if (script_vars.currentUser['premium']) {
     25            if (script_vars.settings?.user?.['premium']) {
    2626                jQuery('#dashcommerce-product-metabox-for-premium').show();
    2727                jQuery('#dashcommerce-product-metabox-for-non-premium').hide();
  • dashcommerce/trunk/features/reports/class-reports-generator.php

    r3098201 r3116743  
    77/**
    88 * This file is part of the DashCommerce Plugin for WordPress
    9  * It includes the Dashcommerce_Reports_Page class which provides functions related
     9 * It includes the Dashcommerce_Reports class which provides functions related
    1010 * to reports message generations.
    1111 *
     
    5757     * @param string $frequency The frequency of the report.
    5858     * @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 );
    6266
    6367        if ( null === $body ) {
     
    6569        }
    6670
    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;
    7972
    8073        return $message;
     
    8376    /**
    8477     * 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 ) {
    8783        $hour = (int) $this->utils->create_date()->format( 'H' );
    8884
     
    9995        }
    10096
    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
    11199        $date      = $this->utils->create_date();
    112100        $indicator = str_replace( '<store>', $store, 'Este é o relatório <freq> da loja *<store>*' );
     
    140128        }
    141129
    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        );
    143147    }
    144148
     
    147151     *
    148152     * @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 ) {
    151156        if ( 'hourly' === $frequency ) {
    152157            $timeframe_start = '1 hour ago';
     
    184189            'sales_completed' => $completed_sales_stats['count'],
    185190            '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 ),
    187192            'most_viewed'     => $this->analytics->products_by_views_in_period( $current_period_start ),
    188193            'most_sold'       => $this->analytics->products_by_sales_in_period( $current_period_start ),
     
    195200            'sales_completed' => $completed_sales_stats_previous['count'],
    196201            '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 ),
    198203            'most_viewed'     => $this->analytics->products_by_views_in_period( $previous_period_start, $previous_period_end ),
    199204            'most_sold'       => $this->analytics->products_by_sales_in_period( $previous_period_start, $previous_period_end ),
     
    201206
    202207        $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 ),
    209215        );
    210216
    211217        $lines = array_filter(
    212218            $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
    216226        );
    217227
    218         $message = implode( "\n", $lines );
     228        $message = implode( "\n\n", $lines );
    219229
    220230        if ( '' === $message ) {
     
    222232        }
    223233
    224         return rtrim( $message, "\n" );
     234        return rtrim( $message, "\n\n" );
    225235    }
    226236
     
    271281     */
    272282    private function generate_str_requests( $frequency, $current, $previous ) {
     283        if ( 0 === $current ) {
     284            return '🌐 Não houve acessos :(';
     285        }
     286
    273287        $previous_desc     = $this->get_previous_desc( $frequency );
    274288        $previous_desc_alt = $this->get_previous_desc_alt( $frequency );
     
    284298        } elseif ( $previous > 0 ) {
    285299            $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>)',
    287301                array(
    288302                    '<current>'           => $current,
    289303                    '<previous>'          => $previous,
    290                     '<comparison>'        => sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ),
     304                    '<change>'            => sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ),
    291305                    '<previous_desc>'     => $previous_desc,
    292306                    '<previous_desc_alt>' => $previous_desc_alt,
     
    334348        } elseif ( $previous > 0 ) {
    335349            $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>)',
    337351                array(
    338352                    '<current>'           => $current,
    339353                    '<previous>'          => $previous,
    340                     '<comparison>'        => sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ),
     354                    '<change>'            => sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ),
    341355                    '<previous_desc>'     => $previous_desc,
    342356                    '<previous_desc_alt>' => $previous_desc_alt,
     
    380394        } elseif ( $previous > 0 ) {
    381395            $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>)',
    383397                array(
    384398                    '<current>'           => $current,
    385399                    '<previous>'          => $previous,
    386                     '<comparison>'        => sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ),
     400                    '<change>'            => sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ),
    387401                    '<previous_desc>'     => $previous_desc,
    388402                    '<previous_desc_alt>' => $previous_desc_alt,
     
    436450        } elseif ( $previous > 0 ) {
    437451            $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>)',
    439453                array(
    440454                    '<current>'           => $currency_symbol . ' ' . $current,
    441455                    '<previous>'          => $currency_symbol . ' ' . $previous,
    442                     '<comparison>'        => sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ),
     456                    '<change>'            => sprintf( '%+d', round( $this->utils->calculate_percentage_difference( $previous, $current ) ) ),
    443457                    '<previous_desc>'     => $previous_desc,
    444458                    '<previous_desc_alt>' => $previous_desc_alt,
     
    470484
    471485        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:';
    473487            $message .= $this->generate_str_list( $current['source'], 'source' );
     488
     489            $message .= "\n\n";
    474490        }
    475491
    476492        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:';
    478494            $message .= $this->generate_str_list( $current['campaign'], 'campaign' );
    479495        }
     
    566582        $max_visible = 5;
    567583
    568         $message = "\n📄 As páginas mais visitadas da loja foram:";
     584        $message = '📄 As páginas mais visitadas da loja foram:';
    569585        $counter = 0;
    570586
     
    606622        $max_visible = 5;
    607623
    608         $message = "\n📦 Os produtos mais vendidos foram:";
     624        $message = '📦 Os produtos mais vendidos foram:';
    609625        $counter = 0;
    610626
     
    686702        $max_visible = 5;
    687703
    688         $message = "\n👀 Os produtos mais visualizados foram:";
     704        $message = '👀 Os produtos mais visualizados foram:';
    689705        $counter = 0;
    690706
  • dashcommerce/trunk/features/reports/class-reports.php

    r3098201 r3116743  
    77/**
    88 * This file is part of the DashCommerce Plugin for WordPress
    9  * It includes the Dashcommerce_Reports_Page class which provides functions related
     9 * It includes the Dashcommerce_Reports class which provides functions related
    1010 * to reports.
    1111 *
     
    1818 * This class represents the reports feature of the plugin.
    1919 */
    20 class Dashcommerce_Reports_Page {
     20class Dashcommerce_Reports {
    2121    /**
    2222     * Class constructor.
    2323     */
    2424    public function __construct() {
    25         global $dashcommerce_current_user;
    26         $this->current_user = $dashcommerce_current_user;
     25        global $dashcommerce_settings;
     26        $this->settings = $dashcommerce_settings;
    2727
    2828        global $dashcommerce_utils;
     
    4646
    4747    /**
    48      * The key in the current_user option for the report settings.
     48     * The key in the plugin's settings option for the report settings.
    4949     *
    5050     * @var string;
     
    5353
    5454    /**
    55      * Reference to global instance of Dashcommerce_Current_User.
    56      *
    57      * @var Dashcommerce_Current_User
    58      */
    59     private $current_user;
     55     * Reference to global instance of Dashcommerce_Settings.
     56     *
     57     * @var Dashcommerce_Settings
     58     */
     59    private $settings;
    6060
    6161    /**
     
    9090        $this->update_report_schedule( 'monthly', $schedules['monthly']['enable'], $time );
    9191
    92         $this->current_user->update_single_entry( $this->settings_key, $settings );
     92        $this->settings->update_single_entry( $this->settings_key, $settings );
    9393
    9494        return true;
     
    156156
    157157        $mobiles = $report_settings['mobiles'];
     158        $webhook = $report_settings['webhook'];
     159        $topics  = $report_settings['topics'];
    158160
    159161        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 );
    163165        }
    164166
    165167        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 );
    169171        }
    170172
    171173        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 );
    175183        }
    176184
     
    179187
    180188    /**
    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.
    184192     * @param string $message The message to be sent.
    185193     */
    186     public function send_whatsapp_message( $phone, $message ) {
     194    public function send_webhook_call( $url, $message ) {
    187195        if ( null === $message ) {
    188196            return null;
    189197        }
    190198
    191         global $dashcommerce_env;
     199        if ( false === filter_var( $url, FILTER_VALIDATE_URL ) ) {
     200            return null;
     201        }
    192202
    193203        $response = $this->utils->http_post(
    194             $dashcommerce_env['EP_SEND_WHATSAPP_MESSAGE'],
     204            $url,
    195205            array(
    196                 'recipients' => array( $phone ),
    197                 'message'    => $message,
     206                'message' => $message,
    198207            ),
    199208            array(),
    200209            array(),
    201             true
     210            false
    202211        );
    203212
     
    232241            ),
    233242            '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.
    239250     */
    240251    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 );
    244263    }
    245264
     
    248267     */
    249268    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 ];
    259273        } else {
    260274            return null;
    261275        }
    262276    }
     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    }
    263288}
    264289
    265290global $dashcommerce_reports;
    266291
    267 $dashcommerce_reports = new Dashcommerce_Reports_Page();
     292$dashcommerce_reports = new Dashcommerce_Reports();
  • dashcommerce/trunk/features/settings-page/class-settings-page.php

    r3098201 r3116743  
    1414 */
    1515
    16 require_once plugin_dir_path( __FILE__ ) . '../../options/class-current-user.php';
     16require_once plugin_dir_path( __FILE__ ) . '../../options/class-settings.php';
    1717require_once plugin_dir_path( __FILE__ ) . '../../utils/class-utils.php';
    1818
     
    4848        }
    4949
    50         global $dashcommerce_current_user;
    51         global $dashcommerce_reports;
     50        global $dashcommerce_settings;
    5251        global $dashcommerce_utils;
    5352
     
    6059            'script_vars',
    6160            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(),
    6664            )
    6765        );
     
    122120     */
    123121    public function settings_callback() {
    124         global $dashcommerce_current_user;
     122        global $dashcommerce_settings;
    125123        global $dashcommerce_env;
    126124        global $dashcommerce_utils;
     
    130128        $agency_tooltip = $dashcommerce_env['AGENCY'] . ' ' . $version . ' (' . $dashcommerce_env['ENV'] . ')';
    131129
    132         $user = $dashcommerce_current_user->get_info();
     130        $user = $dashcommerce_settings->get_user();
    133131
    134132        ?>
     
    232230                        </div>
    233231
    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">
    240242                                (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>
    245287
    246288                        <div style="display: flex;">
     
    335377     * 5. Checks the response from the server. If the response indicates an error, it sends a JSON response with the error message.
    336378     * 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_user object.
     379     * 7. Sets the user information (username, pluginToken, and premium) in the dashcommerce_settings object.
    338380     * 8. Sends a JSON response indicating success and includes the pluginToken.
    339381     *
     
    342384    public function handle_login() {
    343385        global $dashcommerce_utils;
    344         global $dashcommerce_current_user;
     386        global $dashcommerce_settings;
    345387        global $dashcommerce_env;
    346388
     
    361403            wp_die();
    362404        }
     405
     406        $home = home_url();
    363407
    364408        try {
     
    366410                $dashcommerce_env['EP_LOG_IN'],
    367411                array(
     412                    'storeUrl' => home_url(),
    368413                    'email'    => $username,
    369414                    'password' => $password,
     
    415460        $openai_key_preview = $body['openaiKeyPreview'];
    416461
    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 );
    418463
    419464        wp_send_json(
     
    421466                'success'          => true,
    422467                'token'            => $plugin_token,
    423                 'openAiKeyPreview' => $dashcommerce_current_user,
     468                'openAiKeyPreview' => $dashcommerce_settings,
    424469            )
    425470        );
     
    441486        }
    442487
    443         global $dashcommerce_current_user;
    444 
    445         $dashcommerce_current_user->log_out();
     488        global $dashcommerce_settings;
     489
     490        $dashcommerce_settings->log_out( 'manual' );
    446491
    447492        wp_send_json( array( 'success' => true ) );
     
    461506    public function handle_save_openai_key() {
    462507        global $dashcommerce_utils;
    463         global $dashcommerce_current_user;
     508        global $dashcommerce_settings;
    464509        global $dashcommerce_env;
    465510
     
    477522        }
    478523
    479         $token = $dashcommerce_current_user->get_info()['token'];
     524        $token = $dashcommerce_settings->get_user()['token'];
    480525
    481526        try {
     
    515560        }
    516561
    517         $dashcommerce_current_user->update_openai_key_preview( $body['masked'] );
     562        $dashcommerce_settings->update_openai_key_preview( $body['masked'] );
    518563
    519564        wp_send_json( array( 'success' => true ) );
     
    528573    public function handle_remove_openai_key() {
    529574        global $dashcommerce_utils;
    530         global $dashcommerce_current_user;
     575        global $dashcommerce_settings;
    531576        global $dashcommerce_env;
    532577
     
    535580        }
    536581
    537         $token = $dashcommerce_current_user->get_info()['token'];
     582        $token = $dashcommerce_settings->get_user()['token'];
    538583
    539584        try {
     
    572617        }
    573618
    574         $dashcommerce_current_user->update_openai_key_preview( null );
     619        $dashcommerce_settings->update_openai_key_preview( null );
    575620
    576621        wp_send_json( array( 'success' => true ) );
  • dashcommerce/trunk/features/settings-page/settings-page.js

    r3098201 r3116743  
    2323    *   };
    2424    *   time: string;
     25    *       webhook?: string;
     26    *       topics?: string[];
    2527    * }} ReportSettings
    2628 */
     
    6264            });
    6365
    64             if (script_vars.currentUser['openai_key_preview']) {
     66            if (script_vars.settings['openai_key_preview']) {
    6567                jQuery('#dashcommerce-custom-openai-token-for-saved').show();
    6668                jQuery('#dashcommerce-custom-openai-token-for-not-saved').hide();
     
    8082    prepareForm() {
    8183        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'])
    8486
    8587        this.setLogInLoading(false);
     
    8991        this.sections.misc.setLoading(false);
    9092
    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']) {
    9395                jQuery('#dashcommerce-message-for-premium').show();
    9496                jQuery('#dashcommerce-message-for-non-premium').hide();
     
    227229                    mobile1: jQuery('#dashcommerce-reports-input-mobile-1'),
    228230                    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'),
    230240                },
    231241                actions: {
     
    247257             */
    248258            getDisplayedSettings() {
     259                /** @type {ReportSettings} */
    249260                return {
    250261                    schedules: {
     
    265276                        mobile3: this.elements.inputs.mobile3.val().toString() || null,
    266277                    },
    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(),
    268281                };
     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);
    269303            }
    270304
     
    294328                this.elements.inputs.mobile2.val(settings.mobiles.mobile2);
    295329                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                }
    296342
    297343                this.elements.actions.save.attr('disabled', 'disabled');
     
    420466            };
    421467
    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']);
    424470            }
    425471
  • dashcommerce/trunk/jsconfig.json

    r3098201 r3116743  
    11{
    22  "compilerOptions": {
    3         "target": "ES2016"
     3        "target": "ES2017"
    44  },
    55  "typeAcquisition": {
  • dashcommerce/trunk/readme.txt

    r3098575 r3116743  
    44Requires at least: WordPress 5.0
    55Tested up to: 6.4.3
    6 Stable tag: 1.1.6
     6Stable tag: 1.2.0
    77Requires PHP: 8.1
    88License: GPL v2
  • dashcommerce/trunk/tables/class-access-logs.php

    r3098201 r3116743  
    4343        $full_table_name = $wpdb->prefix . $this->table_name;
    4444
    45         $sql = "CREATE TABLE IF NOT EXISTS $full_table_name (
     45        $sql = "CREATE TABLE $full_table_name (
    4646        id mediumint(9) NOT NULL AUTO_INCREMENT,
    4747        access_time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
     
    5555                utm_term varchar(255) NOT NULL,
    5656                utm_content varchar(255) NOT NULL,
    57         PRIMARY KEY  (id)
     57                user_id varchar(255),
     58        PRIMARY KEY (id)
    5859    )";
    5960
     
    7374
    7475        // phpcs:ignore
    75         $wpdb->insert(
     76        return $wpdb->insert(
    7677            $full_table_name,
    7778            $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.
    7980        );
    8081    }
     
    9192    public function get_access_logs( $start = null, $end = null ) {
    9293        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;
    9899
    99100        if ( $str_start_utc && $str_end_utc ) {
     
    115116     * Retrieves the count of requested pages.
    116117     *
    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.
    119121     * @return array The count of requested pages.
    120122     */
    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 ) {
    122124        global $dashcommerce_utils;
    123125
     
    126128        $plucked = wp_list_pluck( $access_logs, 'requested_page' );
    127129
    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 );
    136140
    137141        arsort( $page_counts );
     
    228232        return empty( $results );
    229233    }
     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    }
    230266}
    231267
  • dashcommerce/trunk/utils/class-utils.php

    r3098201 r3116743  
    2222        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
    2323    }
     24
     25    /**
     26     * Reference to global variable dashcommerce_env. It should be defined in load_environment().
     27     *
     28     * @var array
     29     */
     30    public $env;
    2431
    2532    /**
     
    4754     */
    4855    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();
    5359
    5460        return array(
    5561            'token'  => $user_info['token'],
    56             'agency' => $dashcommerce_env['AGENCY'],
     62            'agency' => $this->env['AGENCY'],
    5763        );
    5864    }
     
    220226            }
    221227        }
     228
     229        $this->env = $dashcommerce_env;
    222230    }
    223231
     
    345353                    $schedules[] = array(
    346354                        'timestamp' => $timestamp,
     355                        'readable'  => gmdate( 'l, Y-m-d H:i:s', $timestamp ) . ' GMT',
    347356                        'schedule'  => $jobs_assigned[ $hook ][ array_key_first( $jobs_assigned[ $hook ] ) ]['schedule'],
    348357                        'args'      => $jobs_assigned[ $hook ][ array_key_first( $jobs_assigned[ $hook ] ) ]['args'],
     
    430439     */
    431440    public function calculate_percentage_difference( $a, $b ) {
    432         if ( 0 === $a ) {
     441        if ( 0 === $a || 0.0 === $a ) {
    433442            return null;
    434443        }
    435444
    436         return round( ( ( $b - $a ) / $a ) * 100 );
     445        return round( ( ( $b - $a ) / $a ) * 100, 2 );
    437446    }
    438447
     
    470479        return is_plugin_active( 'woocommerce/woocommerce.php' );
    471480    }
     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    }
    472595}
    473596
Note: See TracChangeset for help on using the changeset viewer.