*/ private $completing = array(); /** * Orders inside a real WC_Order::payment_complete() call in this request. * * @var array */ private $paying = array(); /** * Decision made for each paying order: null = leave WooCommerce's status. * * @var array */ private $decisions = array(); /** * {@inheritDoc} */ public function id() { return 'autocomplete-orders'; } /** * {@inheritDoc} */ public function title() { return __( 'Autocomplete orders', 'admin-powerups-for-woocommerce' ); } /** * {@inheritDoc} */ public function description() { return __( 'Mark orders completed automatically when your rules match, like paid orders for virtual products.', 'admin-powerups-for-woocommerce' ); } /** * {@inheritDoc} */ public function category() { return 'orders'; } /** * {@inheritDoc} */ public function location() { return __( 'Order status after payment', 'admin-powerups-for-woocommerce' ); } /** * {@inheritDoc} */ public function icon() { return 'check-check'; } /** * {@inheritDoc} * * @return array> */ public function data() { return array_merge( parent::data(), array( Cleanup::order_meta( 'email-markers', self::QUIET_META, __( 'Email markers', 'admin-powerups-for-woocommerce' ), __( 'Short-lived notes on orders that stop the “Completed order” email when you turned it off.', 'admin-powerups-for-woocommerce' ) ), Cleanup::job_history( 'jobs', array( self::HOOK ) ), Cleanup::record( 'orders', __( 'Completed orders and their notes', 'admin-powerups-for-woocommerce' ), __( 'Order statuses and notes are part of your order history, so they stay.', 'admin-powerups-for-woocommerce' ) ), ) ); } /** * {@inheritDoc} */ public function views() { return array( 'check' => __( 'Check and apply', 'admin-powerups-for-woocommerce' ) ); } /** * Gateways whose orders are placed before any money arrives. * * @since 1.0.0 * @return string[] */ public static function unpaid_gateways() { /** * Filter payment methods whose orders are not paid when placed (flagged in settings). * * @since 1.0.0 * @param string[] $ids Gateway IDs. */ return (array) apply_filters( 'apwc_autocomplete_unpaid_gateways', array( 'bacs', 'cheque', 'cod' ) ); } /** * {@inheritDoc} * * @return array> */ public function fields() { $classes = array(); foreach ( WC()->shipping() ? WC()->shipping()->get_shipping_classes() : array() as $class ) { $classes[ (string) $class->term_id ] = $class->name; } $gateways = array(); foreach ( WC()->payment_gateways() ? WC()->payment_gateways()->payment_gateways() : array() as $gateway ) { $gateways[ $gateway->id ] = wp_strip_all_tags( $gateway->get_method_title() ? $gateway->get_method_title() : $gateway->id ); } $unpaid = array_fill_keys( array_intersect( self::unpaid_gateways(), array_keys( $gateways ) ), __( 'Not paid yet', 'admin-powerups-for-woocommerce' ) ); return array( array( 'id' => 'rules', 'type' => 'checkboxes', 'label' => __( 'Complete an order when', 'admin-powerups-for-woocommerce' ), 'default' => array(), 'options' => Rules::labels(), 'warning' => __( '“The order is paid” completes every paid order, including ones you still need to ship. Other rules only complete paid orders too, except the payment method rule.', 'admin-powerups-for-woocommerce' ), 'warning_icon' => 'circle-alert', ), array( 'id' => 'match', 'type' => 'select', 'label' => __( 'Rules needed', 'admin-powerups-for-woocommerce' ), 'default' => 'any', 'options' => array( 'any' => __( 'Any checked rule', 'admin-powerups-for-woocommerce' ), 'all' => __( 'All checked rules', 'admin-powerups-for-woocommerce' ), ), ), array( 'id' => 'products', 'type' => 'search', 'source' => 'products', 'label' => __( 'Products', 'admin-powerups-for-woocommerce' ), 'placeholder' => __( 'Search by name, SKU or ID', 'admin-powerups-for-woocommerce' ), 'default' => array(), 'show_if' => array( 'rules', 'products' ), ), array( 'id' => 'categories', 'type' => 'search', 'source' => 'product_cat', 'label' => __( 'Categories', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Subcategories count too.', 'admin-powerups-for-woocommerce' ), 'placeholder' => __( 'Search categories', 'admin-powerups-for-woocommerce' ), 'default' => array(), 'show_if' => array( 'rules', 'categories' ), ), array( 'id' => 'tags', 'type' => 'search', 'source' => 'product_tag', 'label' => __( 'Tags', 'admin-powerups-for-woocommerce' ), 'placeholder' => __( 'Search tags', 'admin-powerups-for-woocommerce' ), 'default' => array(), 'show_if' => array( 'rules', 'tags' ), ), array( 'id' => 'shipping_classes', 'type' => 'checkboxes', 'label' => __( 'Shipping classes', 'admin-powerups-for-woocommerce' ), 'description' => $classes ? '' : __( 'No shipping classes yet. Add them in WooCommerce → Settings → Shipping → Classes.', 'admin-powerups-for-woocommerce' ), 'default' => array(), 'options' => $classes, 'show_if' => array( 'rules', 'shipping_classes' ), ), array( 'id' => 'gateways', 'type' => 'checkboxes', 'label' => __( 'Payment methods', 'admin-powerups-for-woocommerce' ), 'default' => array(), 'options' => $gateways, 'badges' => $unpaid, 'warning' => $unpaid ? __( 'Methods marked “Not paid yet” complete orders before the money arrives, and completed orders unlock downloads. Only pick them if you trust those customers.', 'admin-powerups-for-woocommerce' ) : '', 'warning_icon' => 'circle-alert', 'show_if' => array( 'rules', 'gateways' ), ), array( 'id' => 'exceptions', 'type' => 'heading', 'label' => __( 'Never complete when', 'admin-powerups-for-woocommerce' ), 'description' => __( 'These always win over the rules above.', 'admin-powerups-for-woocommerce' ), ), array( 'id' => 'exclude_products', 'type' => 'search', 'source' => 'products', 'label' => __( 'The order has these products', 'admin-powerups-for-woocommerce' ), 'placeholder' => __( 'Search by name, SKU or ID', 'admin-powerups-for-woocommerce' ), 'default' => array(), ), array( 'id' => 'exclude_categories', 'type' => 'search', 'source' => 'product_cat', 'label' => __( 'The order has products in these categories', 'admin-powerups-for-woocommerce' ), 'placeholder' => __( 'Search categories', 'admin-powerups-for-woocommerce' ), 'default' => array(), ), array( 'id' => 'max_total', 'type' => 'number', 'label' => __( 'The total is above', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Leave big orders for a manual check. Use 0 for no limit.', 'admin-powerups-for-woocommerce' ), 'default' => 0, 'min' => 0, 'max' => 100000000, 'step' => 0.01, ), array( 'id' => 'skip_customer_note', 'type' => 'toggle', 'label' => __( 'The customer left a note', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Someone should read it first.', 'admin-powerups-for-woocommerce' ), 'default' => true, ), array( 'id' => 'include_manual', 'type' => 'toggle', 'label' => __( 'Also complete orders staff set to Processing', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Off: changing a status by hand is left alone.', 'admin-powerups-for-woocommerce' ), 'default' => false, ), array( 'id' => 'timing', 'type' => 'heading', 'label' => __( 'Timing and email', 'admin-powerups-for-woocommerce' ), ), array( 'id' => 'delay', 'type' => 'number', 'label' => __( 'Wait before completing (minutes)', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Use 0 to complete right away. A wait gives fraud checks and other plugins time to act.', 'admin-powerups-for-woocommerce' ), 'warning' => array( \SmartWP\AdminPowerups\Support\Health::class, 'wait_warning' ), 'warning_icon' => 'circle-alert', 'default' => 0, 'min' => 0, 'max' => 10080, 'step' => 1, ), array( 'id' => 'send_email', 'type' => 'toggle', 'label' => __( 'Send the “Order completed” email', 'admin-powerups-for-woocommerce' ), 'default' => true, ), ); } /** * {@inheritDoc} */ public function boot() { add_action( 'woocommerce_pre_payment_complete', array( $this, 'start_payment' ) ); add_filter( 'woocommerce_valid_order_statuses_for_payment_complete', array( $this, 'watch_payment_statuses' ), PHP_INT_MAX, 2 ); add_filter( 'woocommerce_payment_complete_order_status', array( $this, 'on_payment_complete' ), 20, 3 ); add_action( 'woocommerce_payment_complete', array( $this, 'finish_payment' ), 5 ); // A payment_complete() that threw never reaches finish_payment(): forget it once the request // (or one Action Scheduler job in a batch) is over. add_action( 'shutdown', array( $this, 'forget_payments' ) ); add_action( 'action_scheduler_after_execute', array( $this, 'forget_payments' ) ); add_action( 'action_scheduler_failed_execute', array( $this, 'forget_payments' ) ); add_action( 'woocommerce_order_status_changed', array( $this, 'on_status_changed' ), 20, 4 ); add_action( self::HOOK, array( $this, 'run_scheduled' ) ); add_filter( 'woocommerce_email_enabled_customer_completed_order', array( $this, 'filter_completed_email' ), 99, 2 ); add_action( 'woocommerce_order_status_completed_notification', array( $this, 'clear_quiet_marker' ), 999, 2 ); add_action( 'rest_api_init', array( $this, 'register_routes' ) ); } /** * {@inheritDoc} * * Cancels delayed completions, so they never run later with no callback (and show as Failed). */ public function deactivate() { if ( function_exists( 'as_unschedule_all_actions' ) ) { // Hook only (no args, no group): one bulk cancel of every job, whatever order ID it carries. as_unschedule_all_actions( self::HOOK ); } } /** * Rule engine with current settings. * * @since 1.0.0 * @return Rules */ public function rules() { return new Rules( $this->settings() ); } /** * A gateway started WC_Order::payment_complete() for this order. * * @since 1.0.0 * @param int $order_id Order ID. * @return void */ public function start_payment( $order_id ) { $this->paying[ (int) $order_id ] = true; unset( $this->decisions[ (int) $order_id ] ); } /** * Forget payments still marked as running (their payment_complete() threw). * * @since 1.0.0 * @return void */ public function forget_payments() { $this->paying = array(); $this->decisions = array(); } /** * A payment_complete() call on an order that can't take a payment (e.g. already paid) stops here and * never fires `woocommerce_payment_complete`: forget it, so a later status filter call in this * request isn't treated as a payment. Observes only; the statuses pass through unchanged. * * @since 1.0.0 * @param mixed $statuses Statuses that may take a payment. * @param mixed $order Order. * @return mixed */ public function watch_payment_statuses( $statuses, $order = null ) { if ( $order instanceof WC_Order && isset( $this->paying[ (int) $order->get_id() ] ) && ! $order->has_status( (array) $statuses ) ) { unset( $this->paying[ (int) $order->get_id() ], $this->decisions[ (int) $order->get_id() ] ); } return $statuses; } /** * Status after payment: skip Processing when rules match (and no delay is set). * * WooCommerce also runs this filter from WC_Order::maybe_set_date_paid() on ordinary status * changes of unpaid orders (and again when HPOS sync copies an order): there it changes * nothing (WooCommerce's own answer decides the paid date). For a real payment, side effects * happen once: the email marker here, set on the order being paid so it is saved together with * the new status (before emails go out, never alone), the notes and action in finish_payment(). * * @since 1.0.0 * @param string $status Next status. * @param int $order_id Order ID. * @param WC_Order|null $order Order. * @return string */ public function on_payment_complete( $status, $order_id, $order = null ) { $given = $order instanceof WC_Order; // The object payment_complete() is about to save. $order = $given ? $order : wc_get_order( $order_id ); if ( ! $order instanceof WC_Order ) { return $status; } $id = (int) $order->get_id(); // payment_complete() sets the paid date before this filter; maybe_set_date_paid() runs it only without one. $paying = isset( $this->paying[ $id ] ) && $order->get_date_paid( 'edit' ); if ( ! $paying ) { return $status; // No payment running: the rules assume "paid", so they have no say here. } if ( array_key_exists( $id, $this->decisions ) ) { $decision = $this->decisions[ $id ]; return $decision ? $decision['status'] : $status; } $decision = $this->decide( (string) $status, $order ); $this->decisions[ $id ] = $decision; if ( $decision && 'completed' === $decision['status'] ) { $this->before_complete( $order ); } elseif ( $order->get_meta( self::QUIET_META ) ) { // Left over from a payment or completion that failed half way: saved with this payment. $order->delete_meta_data( self::QUIET_META ); } if ( ! $given ) { $order->save_meta_data(); // Other code ran the filter without the order: our copy won't be saved. } return $decision ? $decision['status'] : $status; } /** * What the rules make of an order being paid: its next status. No side effects. * * @since 1.0.0 * @param string $status Status WooCommerce picked. * @param WC_Order $order Order. * @return array{status: string, reason: string, blocked: string}|null Null leaves WooCommerce's status. */ private function decide( $status, WC_Order $order ) { if ( ! array_intersect( array_keys( Rules::labels() ), (array) $this->setting( 'rules' ) ) ) { return null; // No rules on: leave WooCommerce's own decision alone, exceptions included. } if ( 'completed' === $status ) { // WooCommerce completes virtual + downloadable orders on its own. Our exceptions still win. $blocked = $this->rules()->exception( $order ); return '' === $blocked ? null : array( 'status' => 'processing', 'reason' => '', 'blocked' => $blocked, ); } if ( (int) $this->setting( 'delay' ) > 0 ) { return null; // Delayed completion is scheduled once the order reaches Processing. } $verdict = $this->rules()->evaluate( $order, true ); if ( ! $verdict['complete'] ) { return null; } return array( 'status' => 'completed', 'reason' => (string) $verdict['reason'], 'blocked' => '', ); } /** * Payment finished (order saved with its new status): add our note and announce it, once. * * @since 1.0.0 * @param int $order_id Order ID. * @return void */ public function finish_payment( $order_id ) { $id = (int) $order_id; $decision = $this->decisions[ $id ] ?? null; unset( $this->paying[ $id ], $this->decisions[ $id ] ); if ( ! $decision ) { return; } $order = wc_get_order( $id ); if ( ! $order instanceof WC_Order ) { return; } if ( '' !== $decision['blocked'] ) { /* translators: %s: reason. */ $order->add_order_note( sprintf( __( 'Admin Powerups kept this order in Processing: %s', 'admin-powerups-for-woocommerce' ), $decision['blocked'] ) ); return; } if ( ! $order->has_status( 'completed' ) ) { // Other code changed the status after us: don't leave the email marker behind. if ( $order->get_meta( self::QUIET_META ) ) { $order->delete_meta_data( self::QUIET_META ); $order->save_meta_data(); } return; } $order->add_order_note( $this->note( $decision['reason'] ) ); $this->after_complete( $order, $decision['reason'] ); } /** * Order reached Processing or On hold (cash on delivery, bank transfer, other code). * * @since 1.0.0 * @param int $order_id Order ID. * @param string $from Old status. * @param string $to New status. * @param WC_Order|null $order Order (other code may fire the hook without one). * @return void */ public function on_status_changed( $order_id, $from, $to, $order ) { if ( 'completed' !== $to && $order instanceof WC_Order && $order->get_meta( self::QUIET_META ) ) { // A marker left by a completion whose email step failed: never let it silence the next one. $order->delete_meta_data( self::QUIET_META ); $order->save_meta_data(); } if ( ! in_array( $to, array( 'processing', 'on-hold' ), true ) || isset( $this->completing[ (int) $order_id ] ) ) { return; } if ( $this->is_manual_change() && ! $this->setting( 'include_manual' ) ) { return; } $order = $order instanceof WC_Order ? $order : wc_get_order( $order_id ); if ( ! $order instanceof WC_Order || ! $this->rules()->evaluate( $order )['complete'] ) { return; } $delay = max( 0, (int) $this->setting( 'delay' ) ) * MINUTE_IN_SECONDS; if ( $delay > 0 ) { $args = array( 'order_id' => (int) $order_id ); if ( ! as_has_scheduled_action( self::HOOK, $args, Jobs::GROUP ) ) { as_schedule_single_action( time() + $delay, self::HOOK, $args, Jobs::GROUP ); } return; } $this->complete( $order ); } /** * Delayed completion: re-check, then complete. * * @since 1.0.0 * @param int $order_id Order ID. * @return void */ public function run_scheduled( $order_id ) { $order = wc_get_order( $order_id ); if ( $order instanceof WC_Order && $order->has_status( array( 'processing', 'on-hold' ) ) ) { $this->complete( $order ); } } /** * Complete an order now if the rules still match. * * @since 1.0.0 * @param WC_Order $order Order. * @return bool Whether it was completed. */ public function complete( WC_Order $order ) { $verdict = $this->rules()->evaluate( $order ); if ( ! $verdict['complete'] || $order->has_status( 'completed' ) ) { return false; } $this->completing[ $order->get_id() ] = true; $this->before_complete( $order ); $order->update_status( 'completed', $this->note( $verdict['reason'] ) ); unset( $this->completing[ $order->get_id() ] ); $this->after_complete( $order, $verdict['reason'] ); return true; } /** * Mark the order before its status changes (email preference survives deferred emails). * * Only set on the object: the status save that follows (payment_complete(), update_status()) * stores it with the new status, before status emails go out. If that save fails, no marker is * left behind to silence a later Completed email. * * @since 1.0.0 * @param WC_Order $order Order about to be saved as Completed. * @return void */ private function before_complete( WC_Order $order ) { if ( ! $this->setting( 'send_email' ) ) { $order->update_meta_data( self::QUIET_META, '1' ); } } /** * Log and announce a completion. * * @since 1.0.0 * @param WC_Order $order Order. * @param string $reason Matched rule. * @return void */ private function after_complete( WC_Order $order, $reason ) { if ( function_exists( 'wc_get_logger' ) ) { wc_get_logger()->info( sprintf( 'Order #%s completed automatically (%s).', $order->get_order_number(), $reason ), array( 'source' => 'apwc-autocomplete' ) ); } /** * Fires after Admin Powerups completed an order. * * @since 1.0.0 * @param WC_Order $order Order. * @param string $reason Matched rule. */ do_action( 'apwc_order_autocompleted', $order, $reason ); } /** * Order note text. * * @since 1.0.0 * @param string $reason Matched rule. * @return string */ private function note( $reason ) { /* translators: %s: rule that matched. */ return sprintf( __( 'Completed automatically by Admin Powerups: %s.', 'admin-powerups-for-woocommerce' ), lcfirst( $reason ) ); } /** * Honour "Send the Order completed email" for orders we completed. * * @since 1.0.0 * @param bool $enabled Enabled. * @param mixed $order Email object. * @return bool */ public function filter_completed_email( $enabled, $order = null ) { // Only the automatic "status became Completed" send is silenced; a later manual resend // (order actions, Email log) runs outside that notification and always sends. if ( $order instanceof WC_Order && doing_action( 'woocommerce_order_status_completed_notification' ) && $order->get_meta( self::QUIET_META ) ) { return false; } return $enabled; } /** * Remove the "no Completed email" marker once the completion notification has run (after * WooCommerce's email at priority 10, also when emails are deferred to a later request). * * @since 1.0.0 * @param int $order_id Order ID. * @param WC_Order|null $order Order. * @return void */ public function clear_quiet_marker( $order_id, $order = null ) { $order = $order instanceof WC_Order ? $order : wc_get_order( $order_id ); if ( $order instanceof WC_Order && $order->get_meta( self::QUIET_META ) ) { $order->delete_meta_data( self::QUIET_META ); $order->save_meta_data(); } } /** * Whether the current status change was made by staff by hand. * * @since 1.0.0 * @return bool */ private function is_manual_change() { if ( doing_action( 'wp_ajax_woocommerce_mark_order_status' ) ) { return true; } $rest = defined( 'REST_REQUEST' ) && REST_REQUEST; return is_admin() && ! wp_doing_ajax() && ! wp_doing_cron() && ! $rest; } /* ------------------------------------------------------------------ tool: check and apply */ /** * REST routes for the tool tab. * * @since 1.0.0 * @return void */ public function register_routes() { $permission = static fn() => current_user_can( 'manage_woocommerce' ); register_rest_route( 'apwc/v1', '/autocomplete/check', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'rest_check' ), 'permission_callback' => $permission, 'args' => array( 'order' => array( 'type' => 'string', 'required' => true, ), ), ) ); register_rest_route( 'apwc/v1', '/autocomplete/apply', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'rest_apply' ), 'permission_callback' => $permission, 'args' => array( 'offset' => array( 'type' => 'integer', 'minimum' => 0, 'default' => 0, ), 'dry_run' => array( 'type' => 'boolean', 'default' => false, ), ), ) ); } /** * GET check: explain what would happen to one order. * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function rest_check( WP_REST_Request $request ) { $order = $this->find_order( (string) $request['order'] ); if ( ! $order ) { return new \WP_Error( 'apwc_no_order', __( 'No order with that number.', 'admin-powerups-for-woocommerce' ), array( 'status' => 404 ) ); } $verdict = $this->rules()->evaluate( $order ); return rest_ensure_response( array( 'number' => $order->get_order_number(), 'url' => $order->get_edit_order_url(), 'status' => wc_get_order_status_name( $order->get_status() ), 'paid' => $verdict['paid'], 'complete' => $verdict['complete'], 'reason' => $verdict['reason'], 'blocked' => $verdict['blocked'], 'checks' => array_values( array_map( static fn( $key, $check ) => array( 'rule' => $key ) + $check, array_keys( $verdict['checks'] ), $verdict['checks'] ) ), ) ); } /** * POST apply: complete matching orders waiting in Processing, one batch at a time. * * Completed orders leave the set, so `offset` only skips orders left alone in earlier batches. * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return \WP_REST_Response */ public function rest_apply( WP_REST_Request $request ) { $dry = (bool) $request['dry_run']; $ids = wc_get_orders( array( 'status' => 'wc-processing', 'type' => 'shop_order', 'limit' => self::BATCH_SIZE, 'offset' => (int) $request['offset'], 'orderby' => 'ID', 'order' => 'ASC', 'return' => 'ids', ) ); $completed = 0; $left = 0; $rules = $this->rules(); foreach ( $ids as $id ) { $order = wc_get_order( $id ); if ( ! $order instanceof WC_Order ) { continue; } if ( $dry ) { $rules->evaluate( $order )['complete'] ? ++$completed : ++$left; continue; } $this->complete( $order ) ? ++$completed : ++$left; } return rest_ensure_response( array( 'checked' => count( $ids ), 'completed' => $completed, 'left' => $left, 'done' => count( $ids ) < self::BATCH_SIZE, ) ); } /** * Find an order by displayed number or ID (a custom order number wins over an ID). * * @since 1.0.0 * @param string $number Order ID or number (with or without #). * @return WC_Order|null */ private function find_order( $number ) { return Orders::find_by_number( (string) $number ); } /** * {@inheritDoc} * * @param string $view View ID. */ public function enqueue_view_assets( $view ) { wp_enqueue_script( 'apwc-autocomplete', Assets::url( 'assets/js/autocomplete-orders.js' ), array( 'wp-api-fetch', 'wp-i18n' ), Assets::ver( 'assets/js/autocomplete-orders.js' ), true ); wp_set_script_translations( 'apwc-autocomplete', 'admin-powerups-for-woocommerce' ); } /** * {@inheritDoc} * * @param string $view View ID. */ public function render_view( $view ) { include __DIR__ . '/views/check.php'; } }