*/ public static function thresholds() { return array( 'strict' => 90, 'balanced' => 80, 'loose' => 70, ); } /** * {@inheritDoc} */ public function fields() { return array( array( 'id' => 'rules', 'type' => 'checkboxes', 'label' => __( 'Match customers with', 'admin-powerups-for-woocommerce' ), 'default' => array( 'email', 'phone', 'address', 'name_address' ), 'options' => array( 'email' => __( 'The same email', 'admin-powerups-for-woocommerce' ), 'phone' => __( 'The same phone', 'admin-powerups-for-woocommerce' ), 'address' => __( 'The same address', 'admin-powerups-for-woocommerce' ), 'name_address' => __( 'A similar name at a similar address', 'admin-powerups-for-woocommerce' ), ), ), array( 'id' => 'sensitivity', 'type' => 'select', 'label' => __( 'How close names must be', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Similar names include typos, word order and names that sound alike. Looser finds more, with more false matches.', 'admin-powerups-for-woocommerce' ), 'default' => 'balanced', 'options' => array( 'strict' => __( 'Strict', 'admin-powerups-for-woocommerce' ), 'balanced' => __( 'Balanced', 'admin-powerups-for-woocommerce' ), 'loose' => __( 'Loose', 'admin-powerups-for-woocommerce' ), ), 'warning' => __( 'A scan reads every customer account in batches. On stores with many customers it can take a few minutes; it runs only when you press Scan.', 'admin-powerups-for-woocommerce' ), ), ); } /** * {@inheritDoc} */ public function shortcut() { return 'duplicates'; } /** * {@inheritDoc} */ public function views() { return array( 'duplicates' => __( 'Find duplicates', 'admin-powerups-for-woocommerce' ) ); } /** * {@inheritDoc} * * @return array> */ public function data() { return array_merge( parent::data(), array( Cleanup::option( 'results', Scanner::RESULTS, __( 'Last scan results', 'admin-powerups-for-woocommerce' ), __( 'The groups found by the last scan. Scan again to rebuild them.', 'admin-powerups-for-woocommerce' ) ), array( 'id' => 'scan-token', 'kind' => 'cache', 'label' => __( 'Scan in progress', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Where a running scan is up to, so two scans at once don’t mix. Removed when a scan finishes.', 'admin-powerups-for-woocommerce' ), 'count' => static fn() => false === get_option( Scanner::TOKEN ) ? 0 : 1, 'summary' => static fn( $count ) => $count ? __( 'Stored', 'admin-powerups-for-woocommerce' ) : __( 'Nothing stored', 'admin-powerups-for-woocommerce' ), 'delete' => static function () { delete_option( Scanner::TOKEN ); Lock::clear( Scanner::LOCK ); return 0; }, ), array( 'id' => 'dismissed', 'kind' => 'content', 'label' => __( 'Marked “Not a duplicate”', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Pairs you dismissed. Deleting them lets those matches show again on the next scan.', 'admin-powerups-for-woocommerce' ), 'count' => static fn() => count( (array) get_option( Scanner::DISMISSED, array() ) ), 'summary' => static fn( $count ) => $count /* translators: %s: number of dismissed pairs. */ ? sprintf( _n( '%s pair', '%s pairs', $count, 'admin-powerups-for-woocommerce' ), number_format_i18n( $count ) ) : __( 'Nothing stored', 'admin-powerups-for-woocommerce' ), 'delete' => static function () { delete_option( Scanner::DISMISSED ); return 0; }, ), array( 'id' => 'scan-table', 'kind' => 'cache', 'label' => __( 'Scan work tables', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Small database tables used while scanning. Emptied after each scan; created again when you scan.', 'admin-powerups-for-woocommerce' ), 'count' => static function () { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- schema check for the Data section. return Scanner::ready() || Scanner::table() === $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( Scanner::table() ) ) ) ? 1 : 0; }, 'summary' => static fn( $count ) => $count ? __( 'Present', 'admin-powerups-for-woocommerce' ) : __( 'Nothing stored', 'admin-powerups-for-woocommerce' ), 'delete' => static function () { Scanner::drop(); return 0; }, ), ) ); } /** * {@inheritDoc} */ public function activate() { Scanner::install(); } /** * {@inheritDoc} */ public function boot() { add_action( 'rest_api_init', array( $this, 'register_routes' ) ); } /** * Scanner with the current settings. * * @since 1.0.0 * @return Scanner */ public function scanner() { $sensitivity = (string) $this->setting( 'sensitivity' ); return new Scanner( (array) $this->setting( 'rules' ), self::thresholds()[ $sensitivity ] ?? 80 ); } /** * {@inheritDoc} * * @param string $view View slug. */ public function enqueue_view_assets( $view ) { wp_enqueue_script( 'apwc-duplicate-customers', Assets::url( 'assets/js/duplicate-customers.js' ), array( 'wp-api-fetch', 'wp-i18n' ), Assets::ver( 'assets/js/duplicate-customers.js' ), true ); wp_set_script_translations( 'apwc-duplicate-customers', 'admin-powerups-for-woocommerce' ); } /** * {@inheritDoc} * * @param string $view View slug. */ public function render_view( $view ) { $this->render_results(); } /** * Tab markup (redrawn after scans and dismissals). * * @since 1.0.0 * @return string Markup, for REST responses. */ public function results_html() { ob_start(); $this->render_results(); return (string) ob_get_clean(); } /** * Print tab markup (redrawn after scans and dismissals). * * @since 1.0.0 * @return void */ public function render_results() { $results = get_option( Scanner::RESULTS ); $results = is_array( $results ) ? $results : null; // Customers the last scan read; counted live (a slow user query on big stores) only before a first scan. $total = $results && (int) ( $results['scanned'] ?? 0 ) > 0 ? (int) $results['scanned'] : Scanner::total(); $rules = (array) $this->setting( 'rules' ); $shown = 100; $groups = $results ? array_slice( (array) $results['groups'], 0, $shown ) : array(); // Only accounts that still exist (one lookup, then users and their meta primed); a group needs two. $ids = $groups ? array_merge( ...array_map( static fn( $g ) => array_map( 'intval', (array) $g['ids'] ), $groups ) ) : array(); $existing = $ids ? array_flip( Scanner::existing_ids( $ids ) ) : array(); if ( $existing ) { cache_users( array_keys( $existing ) ); } $groups = array_values( array_filter( array_map( static function ( $group ) use ( $existing ) { $group['ids'] = array_values( array_filter( array_map( 'intval', (array) $group['ids'] ), static fn( $id ) => isset( $existing[ $id ] ) ) ); return $group; }, $groups ), static fn( $group ) => count( $group['ids'] ) > 1 ) ); $counts = self::order_counts( array_keys( $existing ) ); include __DIR__ . '/views/duplicates.php'; } /** * Order counts per customer, in one grouped query (orders table with HPOS, posts + postmeta otherwise). * * @since 1.0.0 * @param int[] $ids Customer IDs. * @return array */ public static function order_counts( array $ids ) { global $wpdb; $ids = array_values( array_unique( array_filter( array_map( 'intval', $ids ) ) ) ); if ( ! $ids ) { return array(); } if ( Orders::hpos() ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- one %d placeholder built per ID; counts for one page of groups. $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT customer_id, COUNT(*) AS n FROM %i WHERE type = 'shop_order' AND status NOT IN ('wc-checkout-draft', 'auto-draft', 'trash') AND customer_id IN (" . implode( ',', array_fill( 0, count( $ids ), '%d' ) ) . ') GROUP BY customer_id', OrderUtil::get_table_for_orders(), ...$ids ) ); } else { // Legacy storage: meta_value is a string column, so compare as strings (%s) to keep the meta_key index usable. // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- one %s placeholder built per ID; counts for one page of groups. $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT pm.meta_value AS customer_id, COUNT(*) AS n FROM %i p INNER JOIN %i pm ON pm.post_id = p.ID AND pm.meta_key = '_customer_user' WHERE p.post_type = 'shop_order' AND p.post_status NOT IN ('wc-checkout-draft', 'auto-draft', 'trash') AND pm.meta_value IN (" . implode( ',', array_fill( 0, count( $ids ), '%s' ) ) . ') GROUP BY pm.meta_value', $wpdb->posts, $wpdb->postmeta, ...array_map( 'strval', $ids ) ) ); } $counts = array(); foreach ( $rows as $row ) { $counts[ (int) $row->customer_id ] = (int) $row->n; } return $counts; } /** * REST routes. * * @since 1.0.0 * @return void */ public function register_routes() { $can = static fn() => current_user_can( 'manage_woocommerce' ) && current_user_can( 'list_users' ); register_rest_route( 'apwc/v1', '/duplicates/scan', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'rest_scan' ), 'permission_callback' => $can, 'args' => array( 'offset' => array( 'type' => 'integer', 'default' => 0, 'minimum' => 0, ), 'token' => array( 'type' => 'string', 'default' => '', 'maxLength' => 64, 'pattern' => '^[A-Za-z0-9_-]*$', ), ), ) ); register_rest_route( 'apwc/v1', '/duplicates/dismiss', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'rest_dismiss' ), 'permission_callback' => $can, 'args' => array( 'ids' => array( 'type' => 'array', 'items' => array( 'type' => 'integer' ), 'maxItems' => Scanner::MAX_DISMISS, 'required' => true, ), ), ) ); } /** * POST /duplicates/scan: one step of a scan. Offset 0 without a token starts a new scan * (and indexes its first batch); later steps send the token back, and the server's saved * cursor decides what runs next. The group step saves the results; cleanup steps then empty * the work tables, and the last one answers with the tab. * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function rest_scan( WP_REST_Request $request ) { $token = (string) $request['token']; $start = 0 === (int) $request['offset'] && '' === $token; $rules = (array) $this->setting( 'rules' ); if ( $start && ! array_intersect( $rules, array( 'email', 'phone', 'address', 'name_address' ) ) ) { return new \WP_Error( 'apwc_no_rules', __( 'Pick at least one way to match customers in Settings.', 'admin-powerups-for-woocommerce' ), array( 'status' => 400 ) ); } if ( ! $start && ! Scanner::is_current( $token ) ) { return self::replaced(); } $lock = Scanner::lock(); if ( '' === $lock ) { return new \WP_Error( 'apwc_scan_busy', __( 'The previous scan step is still running.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } try { if ( $start ) { $sensitivity = (string) $this->setting( 'sensitivity' ); $state = Scanner::begin( $rules, self::thresholds()[ $sensitivity ] ?? 80 ); } else { // Checked again under the lock: a newer scan may have started meanwhile. $state = Scanner::is_current( $token ) ? Scanner::state() : null; if ( ! $state ) { return self::replaced(); } } $step = Scanner::for_state( $state )->run( $state ); } finally { Scanner::unlock( $lock ); } if ( null !== $step['results'] ) { $results = $step['results']; /** * Fires after a duplicate customer scan finished. * * @since 1.0.0 * @param array $results Saved results (`scanned_at`, `scanned`, `groups`, `truncated`). */ do_action( 'apwc_duplicate_scan_finished', $results ); return rest_ensure_response( array( 'done' => true, 'groups' => count( $results['groups'] ), 'html' => $this->results_html(), ) ); } $state = (array) $step['state']; return rest_ensure_response( array( 'done' => false, 'phase' => (string) $state['phase'], 'next' => (int) $state['read'], 'total' => (int) $state['total'], 'blocks_done' => (int) $state['blocks_done'], 'blocks' => max( 0, (int) $state['blocks'] ), 'token' => (string) $state['token'], ) ); } /** * The error for a step of a scan that was replaced or already finished. * * @since 1.0.0 * @return \WP_Error */ private static function replaced() { return new \WP_Error( 'apwc_scan_replaced', __( 'Another scan started. Scan again.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } /** * POST /duplicates/dismiss: "Not a duplicate". The IDs must be the members of one saved group * that still exist (2–200 of them). * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function rest_dismiss( WP_REST_Request $request ) { // Under the scan lock: two dismissals (or a dismissal and a group step) each read and // rewrite the dismissed list and the results, and one would drop the other's change. $lock = Scanner::lock(); if ( '' === $lock ) { return new \WP_Error( 'apwc_scan_busy', __( 'A scan step or another change is running. Try again in a moment.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } try { $dismissed = Scanner::dismiss( (array) $request['ids'] ); } finally { Scanner::unlock( $lock ); } if ( ! $dismissed ) { return new \WP_Error( 'apwc_bad_group', __( 'That group is no longer in the results.', 'admin-powerups-for-woocommerce' ), array( 'status' => 400 ) ); } return rest_ensure_response( array( 'html' => $this->results_html() ) ); } }