> */ public function data() { return array_merge( parent::data(), array( Cleanup::user_meta( 'welcome-markers', Converter::QUIET_META, __( 'Welcome email markers', 'admin-powerups-for-woocommerce' ), __( 'Short-lived notes on new accounts that stop a second welcome email.', 'admin-powerups-for-woocommerce' ) ), Cleanup::job_history( 'jobs', array( self::HOOK ) ), Cleanup::record( 'accounts', __( 'Customer accounts it created or linked', 'admin-powerups-for-woocommerce' ), __( 'These are real customer accounts and their orders now belong to them, so they stay.', 'admin-powerups-for-woocommerce' ) ), ) ); } /** * {@inheritDoc} */ public function views() { return array( 'convert' => __( 'Convert past orders', 'admin-powerups-for-woocommerce' ) ); } /** * Order statuses offered in settings / tool. * * @since 1.0.0 * @return array Status slug (no `wc-`) => label. */ private function status_options() { $options = array(); foreach ( wc_get_order_statuses() as $key => $label ) { $options[ substr( $key, 3 ) ] = $label; } unset( $options['checkout-draft'] ); return $options; } /** * {@inheritDoc} * * @return array> */ public function fields() { return array( array( 'id' => 'auto', 'type' => 'toggle', 'label' => __( 'Create accounts automatically', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Turn off to use only “Convert past orders”.', 'admin-powerups-for-woocommerce' ), 'default' => true, ), array( 'id' => 'statuses', 'type' => 'checkboxes', 'label' => __( 'When an order is', 'admin-powerups-for-woocommerce' ), 'default' => array( 'processing', 'completed' ), 'options' => $this->status_options(), 'badges' => array_fill_keys( array_intersect( self::UNPAID_STATUSES, array_keys( $this->status_options() ) ), __( 'Unpaid', 'admin-powerups-for-woocommerce' ) ), 'warning' => array( $this, 'unpaid_warning' ), 'warning_icon' => 'circle-alert', ), array( 'id' => 'delay', 'type' => 'number', 'label' => __( 'Wait (minutes)', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Gives the shopper time to see their order confirmation.', 'admin-powerups-for-woocommerce' ), 'warning' => array( \SmartWP\AdminPowerups\Support\Health::class, 'wait_warning' ), 'warning_icon' => 'circle-alert', 'default' => 15, 'min' => 0, 'max' => 1440, 'step' => 1, ), array( 'id' => 'link_existing', 'type' => 'toggle', 'label' => __( 'Use an existing account with the same email', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Only in “Convert past orders”, never for automatic accounts. Staff and accounts from other sites are skipped.', 'admin-powerups-for-woocommerce' ), 'warning' => __( "WooCommerce doesn't check that people own their email, so someone could register with a customer's email and see their orders. Turn on only if you trust how accounts get created.", 'admin-powerups-for-woocommerce' ), 'warning_icon' => 'circle-alert', 'default' => false, ), array( 'id' => 'send_email', 'type' => 'toggle', 'label' => __( 'Email login details to new customers', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Uses the WooCommerce “New account” email.', 'admin-powerups-for-woocommerce' ), 'default' => true, ), array( 'id' => 'copy_address', 'type' => 'toggle', 'label' => __( 'Save the order address to the account', 'admin-powerups-for-woocommerce' ), 'default' => true, ), array( 'id' => 'link_past_orders', 'type' => 'toggle', 'label' => __( "Add the customer's earlier guest orders too", 'admin-powerups-for-woocommerce' ), 'description' => __( 'For accounts created here. For existing accounts, only in “Convert past orders”.', 'admin-powerups-for-woocommerce' ), 'default' => true, ), ); } /** * Settings warning while unpaid statuses are picked (evaluated when the field is drawn). * * @since 1.0.0 * @return string '' when only paid statuses are picked. */ public function unpaid_warning() { if ( ! array_intersect( self::UNPAID_STATUSES, (array) $this->setting( 'statuses' ) ) ) { return ''; } return __( 'Anyone can place an unpaid order with any email address, so accounts and welcome emails could go to people who never ordered.', 'admin-powerups-for-woocommerce' ); } /** * {@inheritDoc} */ public function boot() { add_action( self::HOOK, array( $this, 'run_scheduled' ) ); add_action( 'woocommerce_created_customer', array( Converter::class, 'mark_quiet' ), 1 ); add_filter( 'woocommerce_email_enabled_customer_new_account', array( Converter::class, 'filter_new_account_email' ), 99, 2 ); add_action( 'rest_api_init', array( $this, 'register_routes' ) ); if ( $this->setting( 'auto' ) ) { add_action( 'woocommerce_order_status_changed', array( $this, 'maybe_schedule' ), 10, 4 ); } } /** * {@inheritDoc} * * Cancels queued conversions, so they never run later with no callback (and show as Failed). */ public function deactivate() { if ( function_exists( 'as_unschedule_all_actions' ) ) { // Hook only (it is ours): one bulk cancel of every order's job, whatever its args. as_unschedule_all_actions( self::HOOK ); } } /** * Converter configured from settings. * * @since 1.0.0 * @param string $mode Converter::MODE_AUTO (scheduled) or Converter::MODE_MANUAL (staff tool). * @return Converter */ private function converter( $mode = Converter::MODE_AUTO ) { return new Converter( array( 'mode' => $mode, 'link_existing' => (bool) $this->setting( 'link_existing' ), 'send_email' => (bool) $this->setting( 'send_email' ), 'copy_address' => (bool) $this->setting( 'copy_address' ), 'link_past_orders' => (bool) $this->setting( 'link_past_orders' ), ) ); } /** * Schedule a conversion when a guest order reaches a configured status. * * @since 1.0.0 * @param int $order_id Order ID. * @param string $from Old status. * @param string $to New status. * @param WC_Order $order Order. * @return void */ public function maybe_schedule( $order_id, $from, $to, $order ) { if ( ! $order instanceof WC_Order || $order->get_customer_id() || ! in_array( $to, (array) $this->setting( 'statuses' ), true ) ) { return; } $args = array( 'order_id' => (int) $order_id ); if ( as_has_scheduled_action( self::HOOK, $args, Jobs::GROUP ) ) { return; } $delay = max( 0, (int) $this->setting( 'delay' ) ) * MINUTE_IN_SECONDS; if ( 0 === $delay ) { as_enqueue_async_action( self::HOOK, $args, Jobs::GROUP ); } else { as_schedule_single_action( time() + $delay, self::HOOK, $args, Jobs::GROUP ); } } /** * Action Scheduler callback. * * @since 1.0.0 * @param int $order_id Order ID. * @return void */ public function run_scheduled( $order_id ) { $order = wc_get_order( $order_id ); // The order may have changed while the job waited: cancelled, refunded, failed, or linked // to an account. Only guest orders still in a picked status, or paid (e.g. completed by // Autocomplete orders during the wait), are converted. if ( ! $order instanceof WC_Order || $order->get_customer_id() ) { return; } if ( ! in_array( $order->get_status(), (array) $this->setting( 'statuses' ), true ) && ! $order->is_paid() ) { return; } $this->converter( Converter::MODE_AUTO )->convert( $order ); } /** * REST routes for the bulk tool. * * @since 1.0.0 * @return void */ public function register_routes() { $permission = static function () { return current_user_can( 'manage_woocommerce' ) && current_user_can( 'create_users' ); }; // An empty list must never reach wc_get_orders(): WooCommerce treats it as "any status". $statuses = array( 'type' => 'array', 'items' => array( 'type' => 'string', 'enum' => array_keys( $this->status_options() ), ), 'minItems' => 1, 'required' => true, ); register_rest_route( 'apwc/v1', '/guest-accounts/scan', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'rest_scan' ), 'permission_callback' => $permission, 'args' => array( 'statuses' => $statuses ), ) ); register_rest_route( 'apwc/v1', '/guest-accounts/convert', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'rest_convert' ), 'permission_callback' => $permission, 'args' => array( 'statuses' => $statuses, 'offset' => array( 'type' => 'integer', 'minimum' => 0, 'default' => 0, ), ), ) ); } /** * Valid statuses picked in the tool request. * * Second line of defence behind the route schema (`minItems`): wc_get_orders() reads an * empty status list as "any status", so an empty result here must stop the request. * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return string[]|WP_Error Status slugs without `wc-`, or an error when none are valid. */ private function requested_statuses( WP_REST_Request $request ) { $picked = array_filter( (array) $request['statuses'], 'is_string' ); $valid = array_values( array_intersect( array_unique( $picked ), array_keys( $this->status_options() ) ) ); if ( ! $valid ) { return new WP_Error( 'apwc_no_statuses', __( 'Pick at least one status.', 'admin-powerups-for-woocommerce' ), array( 'status' => 400 ) ); } return $valid; } /** * Guest order query args. * * @since 1.0.0 * @param string[] $statuses Statuses (at least one; see requested_statuses()). * @return array */ private function guest_query( array $statuses ) { return array( 'customer_id' => 0, 'status' => array_map( static fn( $s ) => 'wc-' . $s, $statuses ), 'type' => 'shop_order', 'orderby' => 'ID', 'order' => 'ASC', ); } /** * GET scan: how many guest orders would be processed. * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return \WP_REST_Response|WP_Error */ public function rest_scan( WP_REST_Request $request ) { $statuses = $this->requested_statuses( $request ); if ( is_wp_error( $statuses ) ) { return $statuses; } $result = wc_get_orders( $this->guest_query( $statuses ) + array( 'limit' => 1, 'paginate' => true, 'return' => 'ids', ) ); return rest_ensure_response( array( 'total' => (int) $result->total ) ); } /** * POST convert: process one batch. * * Converted orders leave the guest set, so `offset` only needs to skip orders that were * skipped in earlier batches. The client passes the running skipped count. * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return \WP_REST_Response|WP_Error */ public function rest_convert( WP_REST_Request $request ) { $statuses = $this->requested_statuses( $request ); if ( is_wp_error( $statuses ) ) { return $statuses; } $ids = wc_get_orders( $this->guest_query( $statuses ) + array( 'limit' => self::BATCH_SIZE, 'offset' => (int) $request['offset'], 'return' => 'ids', ) ); $converter = $this->converter( Converter::MODE_MANUAL ); $counts = array( Converter::RESULT_CREATED => 0, Converter::RESULT_LINKED => 0, Converter::RESULT_SKIPPED => 0, ); $skipped = array(); foreach ( $ids as $id ) { $order = wc_get_order( $id ); // Earlier orders in this batch may have linked this one already via "link past orders". if ( ! $order instanceof WC_Order || $order->get_customer_id() ) { continue; } $outcome = $converter->convert( $order ); ++$counts[ $outcome['result'] ]; if ( Converter::RESULT_SKIPPED === $outcome['result'] ) { $skipped[] = array( 'order' => $order->get_order_number(), 'url' => $order->get_edit_order_url(), 'reason' => $outcome['reason'], ); } } return rest_ensure_response( array( 'processed' => count( $ids ), 'counts' => $counts, 'skipped' => $skipped, 'done' => count( $ids ) < self::BATCH_SIZE, ) ); } /** * {@inheritDoc} * * @param string $view View slug from views(). */ public function enqueue_view_assets( $view ) { wp_enqueue_script( 'apwc-guest-accounts', Assets::url( 'assets/js/guest-accounts.js' ), array( 'wp-api-fetch', 'wp-i18n' ), Assets::ver( 'assets/js/guest-accounts.js' ), true ); wp_set_script_translations( 'apwc-guest-accounts', 'admin-powerups-for-woocommerce' ); } /** * {@inheritDoc} * * @param string $view View slug from views(). */ public function render_view( $view ) { $statuses = $this->status_options(); $default = array( 'processing', 'completed' ); include __DIR__ . '/views/tool.php'; } }