/var/www/html_us/wp-content/plugins/woocommerce/src/Admin/API/Reports/Customers/DataStore.php


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
<?php
/**
 * Admin\API\Reports\Customers\DataStore class file.
 */

namespace Automattic\WooCommerce\Admin\API\Reports\Customers;

defined'ABSPATH' ) || exit;

use 
Automattic\WooCommerce\Admin\API\Reports\DataStore as ReportsDataStore;
use 
Automattic\WooCommerce\Admin\API\Reports\DataStoreInterface;
use 
Automattic\WooCommerce\Admin\API\Reports\TimeInterval;
use 
Automattic\WooCommerce\Admin\API\Reports\SqlQuery;
use 
Automattic\WooCommerce\Admin\API\Reports\Cache as ReportsCache;
use 
Automattic\WooCommerce\Utilities\OrderUtil;

/**
 * Admin\API\Reports\Customers\DataStore.
 */
class DataStore extends ReportsDataStore implements DataStoreInterface {

    
/**
     * Table used to get the data.
     *
     * @override ReportsDataStore::$table_name
     *
     * @var string
     */
    
protected static $table_name 'wc_customer_lookup';

    
/**
     * Cache identifier.
     *
     * @override ReportsDataStore::$cache_key
     *
     * @var string
     */
    
protected $cache_key 'customers';

    
/**
     * Mapping columns to data type to return correct response types.
     *
     * @override ReportsDataStore::$column_types
     *
     * @var array
     */
    
protected $column_types = array(
        
'id'              => 'intval',
        
'user_id'         => 'intval',
        
'orders_count'    => 'intval',
        
'total_spend'     => 'floatval',
        
'avg_order_value' => 'floatval',
    );

    
/**
     * Data store context used to pass to filters.
     *
     * @override ReportsDataStore::$context
     *
     * @var string
     */
    
protected $context 'customers';

    
/**
     * Assign report columns once full table name has been assigned.
     *
     * @override ReportsDataStore::assign_report_columns()
     */
    
protected function assign_report_columns() {
        global 
$wpdb;
        
$table_name           self::get_db_table_name();
        
$orders_count         'SUM( CASE WHEN parent_id = 0 THEN 1 ELSE 0 END )';
        
$total_spend          'SUM( total_sales )';
        
$this->report_columns = array(
            
'id'               => "{$table_name}.customer_id as id",
            
'user_id'          => 'user_id',
            
'username'         => 'username',
            
'name'             => "CONCAT_WS( ' ', first_name, last_name ) as name"// @xxx: What does this mean for RTL?
            
'email'            => 'email',
            
'country'          => 'country',
            
'city'             => 'city',
            
'state'            => 'state',
            
'postcode'         => 'postcode',
            
'date_registered'  => 'date_registered',
            
'date_last_active' => 'IF( date_last_active <= "0000-00-00 00:00:00", NULL, date_last_active ) AS date_last_active',
            
'date_last_order'  => "MAX( {$wpdb->prefix}wc_order_stats.date_created ) as date_last_order",
            
'orders_count'     => "{$orders_count} as orders_count",
            
'total_spend'      => "{$total_spend} as total_spend",
            
'avg_order_value'  => "CASE WHEN {$orders_count} = 0 THEN NULL ELSE {$total_spend} / {$orders_count} END AS avg_order_value",
        );
    }

    
/**
     * Set up all the hooks for maintaining and populating table data.
     */
    
public static function init() {
        
add_action'woocommerce_new_customer', array( __CLASS__'update_registered_customer' ) );

        
add_action'woocommerce_update_customer', array( __CLASS__'update_registered_customer' ) );
        
add_action'profile_update', array( __CLASS__'update_registered_customer' ) );

        
add_action'added_user_meta', array( __CLASS__'update_registered_customer_via_last_active' ), 10);
        
add_action'updated_user_meta', array( __CLASS__'update_registered_customer_via_last_active' ), 10);

        
add_action'delete_user', array( __CLASS__'delete_customer_by_user_id' ) );
        
add_action'remove_user_from_blog', array( __CLASS__'delete_customer_by_user_id' ) );

        
add_action'woocommerce_privacy_remove_order_personal_data', array( __CLASS__'anonymize_customer' ) );

        
add_action'woocommerce_analytics_delete_order_stats', array( __CLASS__'sync_on_order_delete' ), 15);
    }

    
/**
     * Sync customers data after an order was deleted.
     *
     * When an order is deleted, the customer record is deleted from the
     * table if the customer has no other orders.
     *
     * @param int $order_id Order ID.
     * @param int $customer_id Customer ID.
     */
    
public static function sync_on_order_delete$order_id$customer_id ) {
        
$customer_id absint$customer_id );

        if ( 
=== $customer_id ) {
            return;
        }

        
// Calculate the amount of orders remaining for this customer.
        
$order_count self::get_order_count$customer_id );

        if ( 
=== $order_count ) {
            
self::delete_customer$customer_id );
        }
    }

    
/**
     * Sync customers data after an order was updated.
     *
     * Only updates customer if it is the customers last order.
     *
     * @param int $post_id of order.
     * @return true|-1
     */
    
public static function sync_order_customer$post_id ) {
        global 
$wpdb;

        if ( ! 
OrderUtil::is_order$post_id, array( 'shop_order''shop_order_refund' ) ) ) {
            return -
1;
        }

        
$order       wc_get_order$post_id );
        
$customer_id self::get_existing_customer_id_from_order$order );
        if ( 
false === $customer_id ) {
            return -
1;
        }
        
$last_order self::get_last_order$customer_id );

        if ( ! 
$last_order || $order->get_id() !== $last_order->get_id() ) {
            return -
1;
        }

        list(
$data$format) = self::get_customer_order_data_and_format$order );

        
$result $wpdb->updateself::get_db_table_name(), $data, array( 'customer_id' => $customer_id ), $format );

        
/**
         * Fires when a customer is updated.
         *
         * @param int $customer_id Customer ID.
         * @since 4.0.0
         */
        
do_action'woocommerce_analytics_update_customer'$customer_id );

        return 
=== $result;
    }

    
/**
     * Maps ordering specified by the user to columns in the database/fields in the data.
     *
     * @override ReportsDataStore::normalize_order_by()
     *
     * @param string $order_by Sorting criterion.
     * @return string
     */
    
protected function normalize_order_by$order_by ) {
        if ( 
'name' === $order_by ) {
            return 
"CONCAT_WS( ' ', first_name, last_name )";
        }

        return 
$order_by;
    }

    
/**
     * Fills WHERE clause of SQL request with date-related constraints.
     *
     * @override ReportsDataStore::add_time_period_sql_params()
     *
     * @param array  $query_args Parameters supplied by the user.
     * @param string $table_name Name of the db table relevant for the date constraint.
     */
    
protected function add_time_period_sql_params$query_args$table_name ) {
        global 
$wpdb;

        
$this->clear_sql_clause( array( 'where''where_time''having' ) );
        
$date_param_mapping  = array(
            
'registered'  => array(
                
'clause' => 'where',
                
'column' => $table_name '.date_registered',
            ),
            
'order'       => array(
                
'clause' => 'where',
                
'column' => $wpdb->prefix 'wc_order_stats.date_created',
            ),
            
'last_active' => array(
                
'clause' => 'where',
                
'column' => $table_name '.date_last_active',
            ),
            
'last_order'  => array(
                
'clause' => 'having',
                
'column' => "MAX( {$wpdb->prefix}wc_order_stats.date_created )",
            ),
        );
        
$match_operator      $this->get_match_operator$query_args );
        
$where_time_clauses  = array();
        
$having_time_clauses = array();

        foreach ( 
$date_param_mapping as $query_param => $param_info ) {
            
$subclauses  = array();
            
$before_arg  $query_param '_before';
            
$after_arg   $query_param '_after';
            
$column_name $param_info['column'];

            if ( ! empty( 
$query_args$before_arg ] ) ) {
                
$datetime     = new \DateTime$query_args$before_arg ] );
                
$datetime_str $datetime->formatTimeInterval::$sql_datetime_format );
                
$subclauses[] = "{$column_name} <= '$datetime_str'";
            }

            if ( ! empty( 
$query_args$after_arg ] ) ) {
                
$datetime     = new \DateTime$query_args$after_arg ] );
                
$datetime_str $datetime->formatTimeInterval::$sql_datetime_format );
                
$subclauses[] = "{$column_name} >= '$datetime_str'";
            }

            if ( 
$subclauses && ( 'where' === $param_info['clause'] ) ) {
                
$where_time_clauses[] = '(' implode' AND '$subclauses ) . ')';
            }

            if ( 
$subclauses && ( 'having' === $param_info['clause'] ) ) {
                
$having_time_clauses[] = '(' implode' AND '$subclauses ) . ')';
            }
        }

        if ( 
$where_time_clauses ) {
            
$this->subquery->add_sql_clause'where_time''AND ' implode{$match_operator} "$where_time_clauses ) );
        }

        if ( 
$having_time_clauses ) {
            
$this->subquery->add_sql_clause'having''AND ' implode{$match_operator} "$having_time_clauses ) );
        }
    }

    
/**
     * Updates the database query with parameters used for Customers report: categories and order status.
     *
     * @param array $query_args Query arguments supplied by the user.
     */
    
protected function add_sql_query_params$query_args ) {
        global 
$wpdb;
        
$customer_lookup_table  self::get_db_table_name();
        
$order_stats_table_name $wpdb->prefix 'wc_order_stats';

        
$this->add_time_period_sql_params$query_args$customer_lookup_table );
        
$this->get_limit_sql_params$query_args );
        
$this->add_order_by_sql_params$query_args );
        
$this->subquery->add_sql_clause'left_join'"LEFT JOIN {$order_stats_table_name} ON {$customer_lookup_table}.customer_id = {$order_stats_table_name}.customer_id" );

        
$match_operator $this->get_match_operator$query_args );
        
$where_clauses  = array();
        
$having_clauses = array();

        
$exact_match_params = array(
            
'name',
            
'username',
            
'email',
            
'country',
        );

        foreach ( 
$exact_match_params as $exact_match_param ) {
            if ( ! empty( 
$query_args$exact_match_param '_includes' ] ) ) {
                
$exact_match_arguments         $query_args$exact_match_param '_includes' ];
                
$exact_match_arguments_escaped array_map'esc_sql'explode','$exact_match_arguments ) );
                
$included                      implode"','"$exact_match_arguments_escaped );
                
// 'country_includes' is a list of country codes, the others will be a list of customer ids.
                
$table_column    'country' === $exact_match_param $exact_match_param 'customer_id';
                
$where_clauses[] = "{$customer_lookup_table}.{$table_column} IN ('{$included}')";
            }

            if ( ! empty( 
$query_args$exact_match_param '_excludes' ] ) ) {
                
$exact_match_arguments         $query_args$exact_match_param '_excludes' ];
                
$exact_match_arguments_escaped array_map'esc_sql'explode','$exact_match_arguments ) );
                
$excluded                      implode"','"$exact_match_arguments_escaped );
                
// 'country_includes' is a list of country codes, the others will be a list of customer ids.
                
$table_column    'country' === $exact_match_param $exact_match_param 'customer_id';
                
$where_clauses[] = "{$customer_lookup_table}.{$table_column} NOT IN ('{$excluded}')";
            }
        }

        
$search_params = array(
            
'name',
            
'username',
            
'email',
            
'all',
        );

        if ( ! empty( 
$query_args['search'] ) ) {
            
$name_like '%' $wpdb->esc_like$query_args['search'] ) . '%';

            if ( empty( 
$query_args['searchby'] ) || 'name' === $query_args['searchby'] || ! in_array$query_args['searchby'], $search_paramstrue ) ) {
                
$searchby "CONCAT_WS( ' ', first_name, last_name )";
            } elseif ( 
'all' === $query_args['searchby'] ) {
                
$searchby "CONCAT_WS( ' ', first_name, last_name, username, email )";
            } else {
                
$searchby $query_args['searchby'];
            }

            
$where_clauses[] = $wpdb->prepare"{$searchby} LIKE %s"$name_like ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        
}

        
$filter_empty_params = array(
            
'email',
            
'name',
            
'country',
            
'city',
            
'state',
            
'postcode',
        );

        if ( ! empty( 
$query_args['filter_empty'] ) ) {
            
$fields_to_filter_by array_intersect$query_args['filter_empty'], $filter_empty_params );
            if ( 
in_array'name'$fields_to_filter_bytrue ) ) {
                
$fields_to_filter_by   array_diff$fields_to_filter_by, array( 'name' ) );
                
$fields_to_filter_by[] = "CONCAT_WS( ' ', first_name, last_name )";
            }
            
$fields_with_not_condition array_map(
                function ( 
$field ) {
                    return 
$field ' <> \'\'';
                },
                
$fields_to_filter_by
            
);
            
$where_clauses[]           = '(' implode' AND '$fields_with_not_condition ) . ')';
        }

        
// Allow a list of customer IDs to be specified.
        
if ( ! empty( $query_args['customers'] ) ) {
            
$included_customers $this->get_filtered_ids$query_args'customers' );
            
$where_clauses[]    = "{$customer_lookup_table}.customer_id IN ({$included_customers})";
        }

        
// Allow a list of user IDs to be specified.
        
if ( ! empty( $query_args['users'] ) ) {
            
$included_users  $this->get_filtered_ids$query_args'users' );
            
$where_clauses[] = "{$customer_lookup_table}.user_id IN ({$included_users})";
        }

        
$numeric_params = array(
            
'orders_count'    => array(
                
'column' => 'COUNT( order_id )',
                
'format' => '%d',
            ),
            
'total_spend'     => array(
                
'column' => 'SUM( total_sales )',
                
'format' => '%f',
            ),
            
'avg_order_value' => array(
                
'column' => '( SUM( total_sales ) / COUNT( order_id ) )',
                
'format' => '%f',
            ),
        );

        foreach ( 
$numeric_params as $numeric_param => $param_info ) {
            
$subclauses = array();
            
$min_param  $numeric_param '_min';
            
$max_param  $numeric_param '_max';
            
$or_equal   = isset( $query_args$min_param ] ) && isset( $query_args$max_param ] ) ? '=' '';

            if ( isset( 
$query_args$min_param ] ) ) {
                
$subclauses[] = $wpdb->prepare(
                    
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
                    
"{$param_info['column']} >{$or_equal} {$param_info['format']}",
                    
$query_args$min_param ]
                );
            }

            if ( isset( 
$query_args$max_param ] ) ) {
                
$subclauses[] = $wpdb->prepare(
                    
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
                    
"{$param_info['column']} <{$or_equal} {$param_info['format']}",
                    
$query_args$max_param ]
                );
            }

            if ( 
$subclauses ) {
                
$having_clauses[] = '(' implode' AND '$subclauses ) . ')';
            }
        }

        if ( 
$where_clauses ) {
            
$preceding_match = empty( $this->get_sql_clause'where_time' ) ) ? ' AND ' {$match_operator} ";
            
$this->subquery->add_sql_clause'where'$preceding_match implode{$match_operator} "$where_clauses ) );
        }

        
$order_status_filter $this->get_status_subquery$query_args );
        if ( 
$order_status_filter ) {
            
$this->subquery->add_sql_clause'left_join'"AND ( {$order_status_filter} )" );
        }

        if ( 
$having_clauses ) {
            
$preceding_match = empty( $this->get_sql_clause'having' ) ) ? ' AND ' {$match_operator} ";
            
$this->subquery->add_sql_clause'having'$preceding_match implode{$match_operator} "$having_clauses ) );
        }
    }

    
/**
     * Get the default query arguments to be used by get_data().
     * These defaults are only partially applied when used via REST API, as that has its own defaults.
     *
     * @override ReportsDataStore::get_default_query_vars()
     *
     * @return array Query parameters.
     */
    
public function get_default_query_vars() {
        
$defaults                 parent::get_default_query_vars();
        
$defaults['orderby']      = 'date_registered';
        
$defaults['order_before'] = TimeInterval::default_before();
        
$defaults['order_after']  = TimeInterval::default_after();

        return 
$defaults;
    }

    
/**
     * Returns an existing customer ID for an order if one exists.
     *
     * @param object $order WC Order.
     * @return int|bool
     */
    
public static function get_existing_customer_id_from_order$order ) {
        global 
$wpdb;

        if ( ! 
is_a$order'WC_Order' ) ) {
            return 
false;
        }

        
$user_id $order->get_customer_id();

        if ( 
=== $user_id ) {
            
$customer_id $wpdb->get_var(
                
$wpdb->prepare(
                    
"SELECT customer_id FROM {$wpdb->prefix}wc_order_stats WHERE order_id = %d",
                    
$order->get_id()
                )
            );

            if ( 
$customer_id ) {
                return 
$customer_id;
            }

            
$email $order->get_billing_email'edit' );

            if ( 
$email ) {
                return 
self::get_guest_id_by_email$email );
            } else {
                return 
false;
            }
        } else {
            return 
self::get_customer_id_by_user_id$user_id );
        }
    }

    
/**
     * Returns the report data based on normalized parameters.
     * Will be called by `get_data` if there is no data in cache.
     *
     * @override ReportsDataStore::get_noncached_data()
     *
     * @see get_data
     * @param array $query_args Query parameters.
     * @return stdClass|WP_Error Data object `{ totals: *, intervals: array, total: int, pages: int, page_no: int }`, or error.
     */
    
public function get_noncached_data$query_args ) {
        global 
$wpdb;

        
$this->initialize_queries();

        
$data = (object) array(
            
'data'    => array(),
            
'total'   => 0,
            
'pages'   => 0,
            
'page_no' => 0,
        );

        
$selections       $this->selected_columns$query_args );
        
$sql_query_params $this->add_sql_query_params$query_args );
        
$count_query      "SELECT COUNT(*) FROM (
                
{$this->subquery->get_query_statement()}
            ) as tt
            "
;
        
$db_records_count = (int) $wpdb->get_var(
            
$count_query // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        
);

        
$params      $this->get_limit_params$query_args );
        
$total_pages = (int) ceil$db_records_count $params['per_page'] );
        if ( 
$query_args['page'] < || $query_args['page'] > $total_pages ) {
            return 
$data;
        }

        
$this->subquery->clear_sql_clause'select' );
        
$this->subquery->add_sql_clause'select'$selections );
        
$this->subquery->add_sql_clause'order_by'$this->get_sql_clause'order_by' ) );
        
$this->subquery->add_sql_clause'limit'$this->get_sql_clause'limit' ) );

        
$customer_data $wpdb->get_results(
            
$this->subquery->get_query_statement(), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
            
ARRAY_A
        
);

        if ( 
null === $customer_data ) {
            return 
$data;
        }

        
$customer_data array_map( array( $this'cast_numbers' ), $customer_data );
        
$data          = (object) array(
            
'data'    => $customer_data,
            
'total'   => $db_records_count,
            
'pages'   => $total_pages,
            
'page_no' => (int) $query_args['page'],
        );

        return 
$data;
    }

    
/**
     * Get or create a customer from a given order.
     *
     * @param object $order WC Order.
     * @return int|bool
     */
    
public static function get_or_create_customer_from_order$order ) {
        if ( ! 
$order ) {
            return 
false;
        }

        global 
$wpdb;

        if ( ! 
is_a$order'WC_Order' ) ) {
            return 
false;
        }

        
$returning_customer_id self::get_existing_customer_id_from_order$order );

        if ( 
$returning_customer_id ) {
            return 
$returning_customer_id;
        }

        list(
$data$format) = self::get_customer_order_data_and_format$order );

        
$result      $wpdb->insertself::get_db_table_name(), $data$format );
        
$customer_id $wpdb->insert_id;

        
/**
         * Fires when a new report customer is created.
         *
         * @param int $customer_id Customer ID.
         * @since 4.0.0
         */
        
do_action'woocommerce_analytics_new_customer'$customer_id );

        return 
$result $customer_id false;
    }

    
/**
     * Returns a data object and format object of the customers data coming from the order.
     *
     * @param object      $order         WC_Order where we get customer info from.
     * @param object|null $customer_user WC_Customer registered customer WP user.
     * @return array ($data, $format)
     */
    
public static function get_customer_order_data_and_format$order$customer_user null ) {
        
$data   = array(
            
'first_name'       => $order->get_customer_first_name(),
            
'last_name'        => $order->get_customer_last_name(),
            
'email'            => $order->get_billing_email'edit' ),
            
'city'             => $order->get_billing_city'edit' ),
            
'state'            => $order->get_billing_state'edit' ),
            
'postcode'         => $order->get_billing_postcode'edit' ),
            
'country'          => $order->get_billing_country'edit' ),
            
'date_last_active' => gmdate'Y-m-d H:i:s'$order->get_date_created'edit' )->getTimestamp() ),
        );
        
$format = array(
            
'%s',
            
'%s',
            
'%s',
            
'%s',
            
'%s',
            
'%s',
            
'%s',
            
'%s',
        );

        
// Add registered customer data.
        
if ( !== $order->get_user_id() ) {
            
$user_id $order->get_user_id();
            if ( 
is_null$customer_user ) ) {
                
$customer_user = new \WC_Customer$user_id );
            }

            
// Set email as customer email instead of Order Billing Email if we have a customer.
            
$data['email'] = $customer_user->get_email'edit' );

            
// Adding other relevant customer data.
            
$data['user_id']         = $user_id;
            
$data['username']        = $customer_user->get_username'edit' );
            
$data['date_registered'] = $customer_user->get_date_created'edit' ) ? $customer_user->get_date_created'edit' )->dateTimeInterval::$sql_datetime_format ) : null;
            
$format[]                = '%d';
            
$format[]                = '%s';
            
$format[]                = '%s';
        }
        return array( 
$data$format );
    }

    
/**
     * Retrieve a guest ID (when user_id is null) by email.
     *
     * @param string $email Email address.
     * @return false|array Customer array if found, boolean false if not.
     */
    
public static function get_guest_id_by_email$email ) {
        global 
$wpdb;

        
$table_name  self::get_db_table_name();
        
$customer_id $wpdb->get_var(
            
$wpdb->prepare(
                
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                
"SELECT customer_id FROM {$table_name} WHERE email = %s AND user_id IS NULL LIMIT 1",
                
$email
            
)
        );

        return 
$customer_id ? (int) $customer_id false;
    }

    
/**
     * Retrieve a registered customer row id by user_id.
     *
     * @param string|int $user_id User ID.
     * @return false|int Customer ID if found, boolean false if not.
     */
    
public static function get_customer_id_by_user_id$user_id ) {
        global 
$wpdb;

        
$table_name  self::get_db_table_name();
        
$customer_id $wpdb->get_var(
            
$wpdb->prepare(
                
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                
"SELECT customer_id FROM {$table_name} WHERE user_id = %d LIMIT 1",
                
$user_id
            
)
        );

        return 
$customer_id ? (int) $customer_id false;
    }

    
/**
     * Retrieve the last order made by a customer.
     *
     * @param int $customer_id Customer ID.
     * @return object WC_Order|false.
     */
    
public static function get_last_order$customer_id ) {
        global 
$wpdb;
        
$orders_table $wpdb->prefix 'wc_order_stats';

        
$last_order $wpdb->get_var(
            
$wpdb->prepare(
                
// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                
"SELECT order_id, date_created_gmt FROM {$orders_table}
                WHERE customer_id = %d
                ORDER BY date_created_gmt DESC, order_id DESC LIMIT 1"
,
                
// phpcs:enable
                
$customer_id
            
)
        );
        if ( ! 
$last_order ) {
            return 
false;
        }
        return 
wc_get_orderabsint$last_order ) );
    }

    
/**
     * Retrieve the oldest orders made by a customer.
     *
     * @param int $customer_id Customer ID.
     * @return array Orders.
     */
    
public static function get_oldest_orders$customer_id ) {
        global 
$wpdb;
        
$orders_table                $wpdb->prefix 'wc_order_stats';
        
$excluded_statuses           array_map( array( __CLASS__'normalize_order_status' ), self::get_excluded_report_order_statuses() );
        
$excluded_statuses_condition '';
        if ( ! empty( 
$excluded_statuses ) ) {
            
$excluded_statuses_str       implode"','"$excluded_statuses );
            
$excluded_statuses_condition "AND status NOT IN ('{$excluded_statuses_str}')";
        }

        return 
$wpdb->get_results(
            
$wpdb->prepare(
                
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                
"SELECT order_id, date_created FROM {$orders_table} WHERE customer_id = %d {$excluded_statuses_condition} ORDER BY date_created, order_id ASC LIMIT 2",
                
$customer_id
            
)
        );
    }

    
/**
     * Retrieve the amount of orders made by a customer.
     *
     * @param int $customer_id Customer ID.
     * @return int|null Amount of orders for customer or null on failure.
     */
    
public static function get_order_count$customer_id ) {
        global 
$wpdb;
        
$customer_id absint$customer_id );

        if ( 
=== $customer_id ) {
            return 
null;
        }

        
$result $wpdb->get_var(
            
$wpdb->prepare(
                
"SELECT COUNT( order_id ) FROM {$wpdb->prefix}wc_order_stats WHERE customer_id = %d",
                
$customer_id
            
)
        );

        if ( 
is_null$result ) ) {
            return 
null;
        }

        return (int) 
$result;
    }

    
/**
     * Update the database with customer data.
     *
     * @param int $user_id WP User ID to update customer data for.
     * @return int|bool|null Number or rows modified or false on failure.
     */
    
public static function update_registered_customer$user_id ) {
        global 
$wpdb;

        
$customer = new \WC_Customer$user_id );

        if ( ! 
self::is_valid_customer$user_id ) ) {
            return 
false;
        }

        
$first_name $customer->get_first_name();
        
$last_name  $customer->get_last_name();

        if ( empty( 
$first_name ) ) {
            
$first_name $customer->get_billing_first_name();
        }
        if ( empty( 
$last_name ) ) {
            
$last_name $customer->get_billing_last_name();
        }

        
$last_active $customer->get_meta'wc_last_active'true'edit' );
        
$data        = array(
            
'user_id'          => $user_id,
            
'username'         => $customer->get_username'edit' ),
            
'first_name'       => $first_name,
            
'last_name'        => $last_name,
            
'email'            => $customer->get_email'edit' ),
            
'city'             => $customer->get_billing_city'edit' ),
            
'state'            => $customer->get_billing_state'edit' ),
            
'postcode'         => $customer->get_billing_postcode'edit' ),
            
'country'          => $customer->get_billing_country'edit' ),
            
'date_registered'  => $customer->get_date_created'edit' ) ? $customer->get_date_created'edit' )->dateTimeInterval::$sql_datetime_format ) : null,
            
'date_last_active' => $last_active gmdate'Y-m-d H:i:s'$last_active ) : null,
        );
        
$format      = array(
            
'%d',
            
'%s',
            
'%s',
            
'%s',
            
'%s',
            
'%s',
            
'%s',
            
'%s',
            
'%s',
            
'%s',
            
'%s',
        );

        
$customer_id self::get_customer_id_by_user_id$user_id );

        if ( 
$customer_id ) {
            
// Preserve customer_id for existing user_id.
            
$data['customer_id'] = $customer_id;
            
$format[]            = '%d';
        }

        
$results $wpdb->replaceself::get_db_table_name(), $data$format );

        
/**
         * Fires when customser's reports are updated.
         *
         * @param int $customer_id Customer ID.
         * @since 4.0.0
         */
        
do_action'woocommerce_analytics_update_customer'$customer_id );

        
ReportsCache::invalidate();

        return 
$results;
    }

    
/**
     * Update the database if the "last active" meta value was changed.
     * Function expects to be hooked into the `added_user_meta` and `updated_user_meta` actions.
     *
     * @param int    $meta_id ID of updated metadata entry.
     * @param int    $user_id ID of the user being updated.
     * @param string $meta_key Meta key being updated.
     */
    
public static function update_registered_customer_via_last_active$meta_id$user_id$meta_key ) {
        if ( 
'wc_last_active' === $meta_key ) {
            
self::update_registered_customer$user_id );
        }
    }

    
/**
     * Check if a user ID is a valid customer or other user role with past orders.
     *
     * @param int $user_id User ID.
     * @return bool
     */
    
protected static function is_valid_customer$user_id ) {
        
$user = new \WP_User$user_id );

        if ( (int) 
$user_id !== $user->ID ) {
            return 
false;
        }

        
/**
         * Filter the customer roles, used to check if the user is a customer.
         *
         * @param array List of customer roles.
         * @since 4.0.0
         */
        
$customer_roles = (array) apply_filters'woocommerce_analytics_customer_roles', array( 'customer' ) );

        if ( empty( 
$user->roles ) || empty( array_intersect$user->roles$customer_roles ) ) ) {
            return 
false;
        }

        return 
true;
    }

    
/**
     * Delete a customer lookup row.
     *
     * @param int $customer_id Customer ID.
     */
    
public static function delete_customer$customer_id ) {
        global 
$wpdb;

        
$customer_id = (int) $customer_id;
        
$num_deleted $wpdb->deleteself::get_db_table_name(), array( 'customer_id' => $customer_id ) );

        if ( 
$num_deleted ) {
            
/**
             * Fires when a customer is deleted.
             *
             * @param int $order_id Order ID.
             * @since 4.0.0
             */
            
do_action'woocommerce_analytics_delete_customer'$customer_id );

            
ReportsCache::invalidate();
        }
    }

    
/**
     * Delete a customer lookup row by WordPress User ID.
     *
     * @param int $user_id WordPress User ID.
     */
    
public static function delete_customer_by_user_id$user_id ) {
        global 
$wpdb;

        if ( (int) 
$user_id || doing_action'wp_uninitialize_site' ) ) {
            
// Skip the deletion.
            
return;
        }

        
$user_id     = (int) $user_id;
        
$num_deleted $wpdb->deleteself::get_db_table_name(), array( 'user_id' => $user_id ) );

        if ( 
$num_deleted ) {
            
ReportsCache::invalidate();
        }
    }

    
/**
     * Anonymize the customer data for a single order.
     *
     * @internal
     * @param int|WC_Order $order Order instance or ID.
     * @return void
     */
    
public static function anonymize_customer$order ) {
        global 
$wpdb;

        if ( ! 
is_object$order ) ) {
            
$order wc_get_orderabsint$order ) );
        }

        
$customer_id $wpdb->get_var(
            
$wpdb->prepare"SELECT customer_id FROM {$wpdb->prefix}wc_order_stats WHERE order_id = %d"$order->get_id() )
        );

        if ( ! 
$customer_id ) {
            return;
        }

        
// Long form query because $wpdb->update rejects [deleted].
        
$deleted_text __'[deleted]''woocommerce' );
        
$updated      $wpdb->query(
            
$wpdb->prepare(
                
"UPDATE {$wpdb->prefix}wc_customer_lookup
                    SET
                        user_id = NULL,
                        username = %s,
                        first_name = %s,
                        last_name = %s,
                        email = %s,
                        country = '',
                        postcode = %s,
                        city = %s,
                        state = %s
                    WHERE
                        customer_id = %d"
,
                array(
                    
$deleted_text,
                    
$deleted_text,
                    
$deleted_text,
                    
'[email protected]',
                    
$deleted_text,
                    
$deleted_text,
                    
$deleted_text,
                    
$customer_id,
                )
            )
        );
        
// If the customer row was anonymized, flush the cache.
        
if ( $updated ) {
            
ReportsCache::invalidate();
        }
    }

    
/**
     * Initialize query objects.
     */
    
protected function initialize_queries() {
        
$this->clear_all_clauses();
        
$table_name     self::get_db_table_name();
        
$this->subquery = new SqlQuery$this->context '_subquery' );
        
$this->subquery->add_sql_clause'from'$table_name );
        
$this->subquery->add_sql_clause'select'"{$table_name}.customer_id" );
        
$this->subquery->add_sql_clause'group_by'"{$table_name}.customer_id" );
    }
}