'; } } add_action( 'manage_product_posts_custom_column', 'ninetytwo_notify_add_custom_button_to_alerts_column', 10, 2 ); /** * Loads admin JS/CSS only on the Products list screen, where the Notify * button and its confirmation dialog actually appear. * * @param string $hook_suffix The current admin screen's hook suffix. */ function ninetytwo_notify_enqueue_products_screen_assets( $hook_suffix ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only screen check, not a form submission. $post_type = isset( $_GET['post_type'] ) ? sanitize_key( wp_unslash( $_GET['post_type'] ) ) : ''; if ( 'edit.php' !== $hook_suffix || 'product' !== $post_type ) { return; } $css_path = NINETYTWO_NOTIFY_PLUGIN_DIR . 'assets/css/admin.css'; $js_path = NINETYTWO_NOTIFY_PLUGIN_DIR . 'assets/js/admin.js'; wp_enqueue_style( 'ninetytwo-notify-admin-css', NINETYTWO_NOTIFY_PLUGIN_URL . 'assets/css/admin.css', array(), file_exists( $css_path ) ? filemtime( $css_path ) : false ); wp_enqueue_script( 'ninetytwo-notify-admin-submit-js', NINETYTWO_NOTIFY_PLUGIN_URL . 'assets/js/admin.js', array( 'jquery' ), file_exists( $js_path ) ? filemtime( $js_path ) : false, true ); wp_localize_script( 'ninetytwo-notify-admin-submit-js', 'ninetyTwoNotifyAdmin', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'ninetytwo-notify-admin-nonce' ), 'i18n' => array( 'confirm' => __( 'Send restock alerts to matching subscribers now?', '92-notify-for-woocommerce' ), 'sending' => __( 'Sending…', '92-notify-for-woocommerce' ), 'notify' => __( 'Notify', '92-notify-for-woocommerce' ), 'error' => __( 'Something went wrong.', '92-notify-for-woocommerce' ), ), ) ); } add_action( 'admin_enqueue_scripts', 'ninetytwo_notify_enqueue_products_screen_assets' ); define( 'NINETYTWO_NOTIFY_ALERT_BATCH_SIZE', 25 ); define( 'NINETYTWO_NOTIFY_ALERT_BATCH_GROUP', 'ninetytwo-notify' ); /** * Works out who needs a restock alert for a product (and its variations), * without sending anything yet. Returns a flat list of small "jobs" so the * caller can chunk them into background batches instead of sending * hundreds or thousands of emails inline during one request. * * @param int $product_id The product that just came back in stock. * @return array */ function ninetytwo_notify_get_stock_alert_jobs( $product_id ) { global $wpdb; $table_name = $wpdb->prefix . 'ninetytwo_notify_subscribers'; $jobs = array(); $product = wc_get_product( $product_id ); if ( ! $product ) { return $jobs; } // Variation-specific subscribers: only alert them once their exact // selected variation is back in stock. $variation_subscribers = $wpdb->get_results( $wpdb->prepare( 'SELECT id, email, product_name, variation_id FROM %i WHERE product_id = %d AND variation_id != 0 AND status = 1', $table_name, $product_id ), ARRAY_A ); foreach ( $variation_subscribers as $row ) { $variation = wc_get_product( $row['variation_id'] ); if ( ! $variation || ! $variation->is_in_stock() || empty( $row['email'] ) ) { continue; } $jobs[] = array( 'type' => 'variation', 'id' => $row['id'], 'email' => $row['email'], 'product_id' => $row['variation_id'], 'match_type' => 'exact', ); } if ( ! $product->is_in_stock() ) { return $jobs; } // Exact subscribers of the product itself (general, non-variation subscriptions). $exact_subscribers = $wpdb->get_results( $wpdb->prepare( 'SELECT id, email FROM %i WHERE product_id = %d AND variation_id = 0 AND status = 1', $table_name, $product_id ), ARRAY_A ); $notified_emails = array(); foreach ( $exact_subscribers as $row ) { $jobs[] = array( 'type' => 'general', 'id' => $row['id'], 'email' => $row['email'], 'product_id' => $product_id, 'match_type' => 'exact', ); $notified_emails[ strtolower( $row['email'] ) ] = true; } // Similar products: also alert subscribers of products WooCommerce // considers related to this one, deduplicated so a subscriber who // already gets the exact-match email above isn't emailed twice. if ( get_option( 'ninetytwo_notify_similar_products_label' ) ) { $related_ids = apply_filters( 'ninetytwo_notify_similar_product_ids', array_map( 'absint', wc_get_related_products( $product_id, 10 ) ), $product_id ); if ( $related_ids ) { $placeholders = implode( ',', array_fill( 0, count( $related_ids ), '%d' ) ); // $placeholders is a self-built "%d,%d,..." string sized to count( $related_ids ), // not user input, so this interpolation is safe. $similar_subscribers = $wpdb->get_results( $wpdb->prepare( "SELECT id, email FROM %i WHERE product_id IN ($placeholders) AND variation_id = 0 AND status = 1", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared array_merge( array( $table_name ), $related_ids ) ), ARRAY_A ); foreach ( $similar_subscribers as $row ) { $email_key = strtolower( $row['email'] ); if ( isset( $notified_emails[ $email_key ] ) ) { continue; } $jobs[] = array( 'type' => 'general', 'id' => $row['id'], 'email' => $row['email'], 'product_id' => $product_id, 'match_type' => 'similar', ); $notified_emails[ $email_key ] = true; } } } return $jobs; } /** * Sends alerts for one small batch of jobs (a handful of subscribers). This * is what actually runs in the background via Action Scheduler, so a store * with thousands of subscribers never blocks a single request. * * @param array $jobs Job rows built by ninetytwo_notify_get_stock_alert_jobs(). * @param int $product_id Unused here; kept so Action Scheduler's Scheduled * Actions screen shows which product each queued * batch belongs to. */ function ninetytwo_notify_send_alert_batch( $jobs, $product_id ) { global $wpdb; $table_name = $wpdb->prefix . 'ninetytwo_notify_subscribers'; $now = current_time( 'mysql' ); foreach ( $jobs as $job ) { $product = wc_get_product( $job['product_id'] ); if ( ! $product ) { continue; } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT unsubscribe_token FROM %i WHERE id = %d', $table_name, $job['id'] ), ARRAY_A ); if ( ! $row ) { continue; } $token = $row['unsubscribe_token']; if ( empty( $token ) ) { $token = ninetytwo_notify_generate_unsubscribe_token(); $wpdb->update( $table_name, array( 'unsubscribe_token' => $token ), array( 'id' => $job['id'] ), array( '%s' ), array( '%d' ) ); } $sent = ninetytwo_notify_send_notification_email( $job['email'], $product, $job['match_type'], $token ); $update_data = array( 'notified_at' => $now ); $update_format = array( '%s' ); if ( 'variation' === $job['type'] && $sent ) { $update_data['status'] = 0; $update_format[] = '%d'; } $wpdb->update( $table_name, $update_data, array( 'id' => $job['id'] ), $update_format, array( '%d' ) ); } } add_action( 'ninetytwo_notify_send_alert_batch', 'ninetytwo_notify_send_alert_batch', 10, 2 ); /** * Queues restock alerts for a product in small background batches instead * of sending everything inline. A short-lived lock keyed by product ID * prevents duplicate queueing if WooCommerce fires its stock-status hook * more than once for the same transition, or if a manual notify overlaps * with an in-progress automatic one. * * @param int $product_id The product that just came back in stock. * @return int Number of subscribers queued for a notification. */ function ninetytwo_notify_queue_stock_alerts( $product_id ) { if ( ! $product_id ) { return 0; } $lock_key = 'ninetytwo_notify_lock_' . $product_id; if ( get_transient( $lock_key ) ) { return 0; } set_transient( $lock_key, 1, MINUTE_IN_SECONDS ); $jobs = ninetytwo_notify_get_stock_alert_jobs( $product_id ); if ( ! $jobs ) { return 0; } if ( ! function_exists( 'as_schedule_single_action' ) ) { return 0; } $batches = array_chunk( $jobs, NINETYTWO_NOTIFY_ALERT_BATCH_SIZE ); foreach ( $batches as $index => $batch ) { as_schedule_single_action( time() + ( $index * 15 ), 'ninetytwo_notify_send_alert_batch', array( 'jobs' => $batch, 'product_id' => $product_id, ), NINETYTWO_NOTIFY_ALERT_BATCH_GROUP ); } return count( $jobs ); } /** * AJAX handler for the manual "Notify" button on the Products list. */ function ninetytwo_notify_send_alert_from_admin() { if ( ! current_user_can( 'manage_woocommerce' ) || ! check_ajax_referer( 'ninetytwo-notify-admin-nonce', 'nonce', false ) ) { wp_send_json_error( __( 'Unauthorized.', '92-notify-for-woocommerce' ), 403 ); } $product_id = absint( $_POST['product_id'] ?? 0 ); $queued = ninetytwo_notify_queue_stock_alerts( $product_id ); if ( $queued > 0 ) { /* translators: %d: number of subscribers */ wp_send_json_success( sprintf( __( 'Alerts queued for %d subscriber(s).', '92-notify-for-woocommerce' ), $queued ) ); } wp_send_json_success( __( 'No matching subscribers to notify.', '92-notify-for-woocommerce' ) ); } add_action( 'wp_ajax_ninetytwo_notify_send_alert_from_admin', 'ninetytwo_notify_send_alert_from_admin' ); if ( ! function_exists( 'ninetytwo_notify_maybe_auto_notify_on_stock_change' ) ) { /** * Auto-notify: when enabled in settings, queue alerts automatically the * moment a product or variation's stock status flips to "in stock". This * hook only fires when WooCommerce's own data store recorded stock_status * as an actually-changed property, so this is already a genuine transition * and not merely a re-save with the same status. * * @param int $product_id Product or variation ID whose stock status changed. * @param string $status The new stock status. * @param WC_Product|null $product The product or variation object. */ function ninetytwo_notify_maybe_auto_notify_on_stock_change( $product_id, $status, $product ) { if ( ! get_option( 'ninetytwo_notify_auto_notify_label' ) ) { return; } if ( 'instock' !== $status ) { return; } $parent_id = ( $product && $product->is_type( 'variation' ) ) ? $product->get_parent_id() : $product_id; ninetytwo_notify_queue_stock_alerts( $parent_id ); } add_action( 'woocommerce_product_set_stock_status', 'ninetytwo_notify_maybe_auto_notify_on_stock_change', 10, 3 ); add_action( 'woocommerce_variation_set_stock_status', 'ninetytwo_notify_maybe_auto_notify_on_stock_change', 10, 3 ); }