Status > * Scheduled Actions, group "abcreate-warranty-desk"). */ final class WooHooks { public const GROUP = 'abcreate-warranty-desk'; public const ACTION_SYNC = 'abcreate_wd_sync_order'; public const ACTION_CHANGED = 'abcreate_wd_order_changed'; public const ACTION_REFUND = 'abcreate_wd_order_refunded'; public const ACTION_REFUND_DELETED = 'abcreate_wd_refund_deleted'; private const MAX_ATTEMPTS = 3; private const OK = 'ok'; public function __construct( private readonly WarrantyService $service, private readonly WooOrders $orders, private readonly WpdbUnitRepository $units, private readonly WpdbClaimRepository $claims, ) { } public function register(): void { // Step 1: WooCommerce events -> queue. add_action('woocommerce_order_status_completed', [$this, 'onCompleted'], 10, 1); add_action('woocommerce_order_refunded', [$this, 'onRefunded'], 10, 2); add_action('woocommerce_order_status_cancelled', [$this, 'onCancelled'], 10, 1); add_action('woocommerce_order_status_failed', [$this, 'onCancelled'], 10, 1); add_action('woocommerce_trash_order', [$this, 'onCancelled'], 10, 1); add_action('wp_trash_post', [$this, 'onTrashPost'], 10, 1); add_action('woocommerce_saved_order_items', [$this, 'onItemsSaved'], 10, 1); // Lines changed outside the order screen (REST API, code). add_action('woocommerce_update_order_item', [$this, 'onItemChanged'], 10, 3); add_action('woocommerce_before_delete_order_item', [$this, 'onItemDeleted'], 10, 1); // Orders deleted for good, with HPOS and with posts. add_action('woocommerce_before_delete_order', [$this, 'onCancelled'], 10, 1); add_action('before_delete_post', [$this, 'onTrashPost'], 10, 1); add_action('woocommerce_refund_deleted', [$this, 'onRefundDeleted'], 10, 2); // The guarantee length agreed at the sale goes on the order line // (Woo's own item meta, saved by Woo with the order). add_action('woocommerce_checkout_create_order_line_item', [$this, 'rememberGuarantee'], 10, 1); add_action('woocommerce_new_order_item', [$this, 'onNewOrderItem'], 10, 2); // Step 2: queue -> units and claims, in real transactions. add_action(self::ACTION_SYNC, [$this, 'processSync'], 10, 1); add_action(self::ACTION_CHANGED, [$this, 'processChanged'], 10, 3); add_action(self::ACTION_REFUND, [$this, 'processRefund'], 10, 2); add_action(self::ACTION_REFUND_DELETED, [$this, 'processRefundDeleted'], 10, 2); } // ------------------------------------------------------------------ // Step 1: inside WooCommerce, enqueue only // ------------------------------------------------------------------ public function onCompleted($orderId): void { $this->guard(fn () => $this->enqueue(self::ACTION_SYNC, [(int) $orderId])); } public function onRefunded($orderId, $refundId): void { $this->guard(fn () => $this->enqueue(self::ACTION_REFUND, [(int) $orderId, (int) $refundId])); } public function onCancelled($orderId): void { $this->guard(fn () => $this->enqueue(self::ACTION_CHANGED, [(int) $orderId, ReviewReason::ORDER_CANCELLED, self::token()])); } public function onTrashPost($postId): void { $this->guard(function () use ($postId): void { if (in_array(get_post_type((int) $postId), ['shop_order', 'shop_order_placehold'], true)) { $this->enqueue(self::ACTION_CHANGED, [(int) $postId, ReviewReason::ORDER_CANCELLED, self::token()]); } }); } public function onItemsSaved($orderId): void { // No token: one pending check per order is enough, and the key of the // review comes from the line as it is then (see processChanged). $this->guard(fn () => $this->enqueue(self::ACTION_CHANGED, [(int) $orderId, ReviewReason::ORDER_ITEMS_EDITED, ''])); } public function onItemChanged($itemId, $item = null, $orderId = 0): void { $this->guard(function () use ($item, $orderId): void { $orderId = (int) $orderId ?: ($item instanceof \WC_Order_Item ? (int) $item->get_order_id() : 0); if ($orderId > 0) { $this->onItemsSaved($orderId); } }); } public function onItemDeleted($itemId): void { $this->guard(function () use ($itemId): void { $orderId = (int) wc_get_order_id_by_order_item_id((int) $itemId); if ($orderId > 0) { $this->onItemsSaved($orderId); } }); } public function onRefundDeleted($refundId, $orderId): void { $this->guard(fn () => $this->enqueue(self::ACTION_REFUND_DELETED, [(int) $orderId, (int) $refundId])); } /** * Checkout (classic and blocks): the line is not saved yet, Woo saves the * meta with it. Nothing of the plugin's own tables is written. */ public function rememberGuarantee($item): void { $this->guard(function () use ($item): void { if ($item instanceof \WC_Order_Item_Product && '' === (string) $item->get_meta(Options::ITEM_MONTHS_META, true)) { $item->add_meta_data(Options::ITEM_MONTHS_META, $this->orders->productGuaranteeMonths($item), true); } }); } /** Lines added from the order screen or the REST API, already saved by Woo. */ public function onNewOrderItem($itemId, $item = null): void { $this->guard(function () use ($itemId, $item): void { if ($item instanceof \WC_Order_Item_Product && '' === (string) $item->get_meta(Options::ITEM_MONTHS_META, true)) { wc_add_order_item_meta((int) $itemId, Options::ITEM_MONTHS_META, $this->orders->productGuaranteeMonths($item), true); } }); } // ------------------------------------------------------------------ // Step 2: queued actions // ------------------------------------------------------------------ /** * The order was completed: lines already tracked take the estimated * delivery. Lines nobody looked at stay untracked (units are created * when first needed). */ public function processSync($orderId): void { $order = $this->orders->order((int) $orderId); if (null === $order) { return; } foreach ($order->get_items() as $item) { if (!$item instanceof \WC_Order_Item_Product || [] === $this->units->findByOrderItem((int) $item->get_id())) { continue; } $line = $this->orders->lineFacts($order, $item); if (null !== $line) { $this->withRetry(fn () => $this->service->syncUnits($line)); } } } /** * Rule 10 for refunds: only lines whose quantity was refunded go to * review (a money-only refund is a price reduction the operator links * to the claim). */ public function processRefund($orderId, $refundId): void { $refund = wc_get_order((int) $refundId); if (!$refund instanceof \WC_Order_Refund) { return; } foreach (self::refundedLines($refund) as $itemId) { $this->review($itemId, ReviewReason::ORDER_REFUNDED, self::refundKey((int) $refundId, $itemId)); } } /** * Reads WooCommerce again for one claim: the queue may not have run yet, * or may run late. Order state and order line are compared with the facts * a person accepted when reconciling: only a difference sends the claim * to review. The key names the claim, the fact, its value and the * revision of the accepted facts, so the queue and the REST layer share * it, the same change is raised once, and a change accepted is not raised * again unless the facts move away from it. Refunds of the line use the * same keys as the refund action. Returns whether the claim went to review. */ public function reviewIfOrderChanged(int $claimId): bool { $claim = $this->claims->get($claimId); if (null === $claim || 'closed' === $claim->state()->value) { return false; } $accepted = $claim->acceptedFacts(); $reviewed = false; foreach ($this->orderFacts($claim) as $name => $value) { if (self::OK === $value || ($accepted[$name] ?? self::OK) === $value) { continue; } $reason = match (true) { 'order' === $name => ReviewReason::ORDER_CANCELLED, 'removed' === $value => ReviewReason::ORDER_LINE_REMOVED, default => ReviewReason::ORDER_ITEMS_EDITED, }; $key = 'facts:' . $claimId . ':' . $name . '=' . $value . ':r' . $claim->factsRevision(); $this->withRetry(function () use ($claimId, $reason, $key, $name, $value, &$reviewed): void { $reviewed = $this->service->markClaimForReview($claimId, $reason, new Operation(null, $key, $reason), [$name => $value]) || $reviewed; }); } $itemId = $claim->orderItemId(); $order = $this->orders->order($claim->orderId()); foreach (null !== $order ? $order->get_refunds() : [] as $refund) { if (!in_array((int) $refund->get_id(), $claim->refundIds(), true) && in_array($itemId, self::refundedLines($refund), true)) { $reviewed = $this->reviewNow($itemId, ReviewReason::ORDER_REFUNDED, self::refundKey((int) $refund->get_id(), $itemId), $claimId) || $reviewed; } } return $reviewed; } /** * The order as it concerns a claim: "ok", or what is wrong with it. * Stored with the claim when a person reconciles it. * * @return array{order:string, line:string} */ public function orderFacts(Claim $claim): array { $order = $this->orders->order($claim->orderId()); if (null === $order) { return ['order' => 'deleted', 'line' => self::OK]; } $item = $this->orders->item($order, $claim->orderItemId()); if (null === $item) { $line = 'removed'; } elseif ($this->lineStillHolds($claim->unitIds(), $item)) { $line = self::OK; } else { $line = 'q' . (int) $item->get_quantity() . '-p' . (int) ($item->get_variation_id() ?: $item->get_product_id()); } return [ 'order' => $this->orders->isEligible($order) ? self::OK : (string) $order->get_status(), 'line' => $line, ]; } /** * A short fingerprint of the order facts: the admin screen sends back the * one it showed, and a reconcile is refused if the order moved since. * * @param array $facts */ public static function factsToken(array $facts): string { ksort($facts); return substr(hash('sha256', (string) wp_json_encode($facts)), 0, 16); } /** * Cancelled, failed, trashed or deleted orders and edited order lines: * every claim of the order still being worked on is checked against the * facts accepted for it (see reviewIfOrderChanged). The reason and the * token of the queued action only say why the check runs. */ public function processChanged($orderId, $reasonCode = '', $token = ''): void { unset($reasonCode, $token); foreach ($this->claims->findByOrder((int) $orderId) as $claim) { if ('closed' !== $claim->state()->value) { $this->reviewIfOrderChanged((int) $claim->id()); } } } /** * A refund linked to a claim was deleted in WooCommerce: the money no * longer moved, so the outcome must be checked. */ public function processRefundDeleted($orderId, $refundId): void { foreach ($this->claims->findByOrder((int) $orderId) as $claim) { if (!in_array((int) $refundId, $claim->refundIds(), true)) { continue; } $key = 'refund_deleted:' . (int) $refundId . ':' . (int) $claim->id(); $this->withRetry(function () use ($claim, $key): void { $current = $this->claims->get((int) $claim->id()); if (null !== $current) { $this->service->flagForReview((int) $current->id(), $current->version(), ReviewReason::REFUND_DELETED, new Operation(null, $key, ReviewReason::REFUND_DELETED)); } }); } } // ------------------------------------------------------------------ private function reviewNow(int $orderItemId, string $reasonCode, string $key, int $claimId): bool { $changed = $this->service->markLineForReview($orderItemId, $reasonCode, new Operation(null, $key, $reasonCode)); foreach ($changed as $claim) { if ((int) $claim->id() === $claimId) { return true; } } return false; } /** * The order lines whose quantity a refund gave back. * * @return list */ public static function refundedLines(\WC_Order_Refund $refund): array { $lines = []; foreach ($refund->get_items() as $refundItem) { if (!$refundItem instanceof \WC_Order_Item_Product || 0.0 === abs((float) $refundItem->get_quantity())) { continue; } $itemId = (int) $refundItem->get_meta('_refunded_item_id', true); if ($itemId > 0) { $lines[] = $itemId; } } return array_values(array_unique($lines)); } private static function refundKey(int $refundId, int $itemId): string { return 'refund:' . $refundId . ':' . $itemId; } /** @param list $unitIds */ private function lineStillHolds(array $unitIds, \WC_Order_Item_Product $item): bool { $productId = (int) ($item->get_variation_id() ?: $item->get_product_id()); foreach ($this->units->findByOrderItem((int) $item->get_id()) as $unit) { if (!in_array((int) $unit->id(), $unitIds, true)) { continue; } if ($unit->unitIndex() > (int) $item->get_quantity() || $unit->toRow()['product_id'] !== $productId) { return false; } } return true; } private function review(int $orderItemId, string $reasonCode, string $key): void { $this->withRetry(fn () => $this->service->markLineForReview($orderItemId, $reasonCode, new Operation(null, $key, $reasonCode))); } /** * Never runs the action on the spot: that would write the plugin's * tables inside WooCommerce's flow, the very thing the queue avoids. * * @param list $args */ private function enqueue(string $hook, array $args): void { if (!function_exists('as_enqueue_async_action')) { throw new \RuntimeException(sprintf('Action Scheduler is not available: %s for order %d was not queued. Check the claims of this order by hand.', esc_html($hook), (int) ($args[0] ?? 0))); } as_enqueue_async_action($hook, $args, self::GROUP, true); } /** Each change gets its own key, so a later change is never taken for a repeat. */ private static function token(): string { return str_replace('.', '', uniqid('', true)); } /** An operator may save the same claim at the same moment: reload and try again. */ private function withRetry(callable $callback): void { for ($attempt = 1; ; $attempt++) { try { $callback(); return; } catch (DomainError $e) { if ('abcreate_wd_version_conflict' !== $e->errorCode || $attempt >= self::MAX_ATTEMPTS) { throw $e; } } } } private function guard(callable $callback): void { try { $callback(); } catch (\Throwable $e) { if (function_exists('wc_get_logger')) { wc_get_logger()->error($e->getMessage(), ['source' => 'abcreate-warranty-desk', 'exception' => get_class($e)]); } } } }