'completed']) creates * the order already AT that status rather than transitioning into it, * so the order-status-change hooks WooCommerce core hangs stock * reduction off never fire the normal way (nor does payment_complete(), * since "completed" isn't one of its valid from-statuses) — and that * same creation-time status can itself trip WooCommerce's own * stock-reduction hooks on the still-empty order (no line items added * yet), marking it "reduced" with nothing in it. $reduceStock calls * wc_reduce_stock_levels() (the unconditional reducer, NOT the * guarded wc_maybe_reduce_stock_levels() — that guard is exactly what a * premature empty-order reduction would have already tripped) explicitly * after save(), once line items exist. * * findExisting()+create is check-then-act: two requests for the same * pos_order_id arriving close together could both find nothing and both * create an order (observed in production as duplicate WooCommerce orders * for one POS sale). $lock/$unlock wrap that whole sequence in a MySQL * advisory lock keyed on pos_order_id so only one build() per POS order can * be in the critical section at a time — mirrors the same GET_LOCK pattern * akantio_pos itself uses (withTenantSyncLock) for the equivalent race on * its own side. * * $orderFactory/$lineItemFactory/$taxLineFactory/$lock/$unlock/$reduceStock * default to real WooCommerce/$wpdb calls; tests inject fakes so this class * is unit-testable without a WooCommerce or database runtime. */ class OrderBuilder { public const POS_ORDER_ID_META = '_akantio_pos_order_id'; /** @var callable */ private $orderFactory; /** @var callable */ private $lineItemFactory; /** @var callable */ private $taxLineFactory; /** @var callable */ private $lock; /** @var callable */ private $unlock; /** @var callable */ private $reduceStock; public function __construct( ?callable $orderFactory = null, ?callable $lineItemFactory = null, ?callable $lock = null, ?callable $unlock = null, ?callable $taxLineFactory = null, ?callable $reduceStock = null ) { $this->orderFactory = $orderFactory ?? static function ( array $args ) { return wc_create_order( $args ); }; $this->lineItemFactory = $lineItemFactory ?? static function () { return new \WC_Order_Item_Product(); }; $this->taxLineFactory = $taxLineFactory ?? static function () { return new \WC_Order_Item_Tax(); }; // GET_LOCK()/RELEASE_LOCK() are MySQL advisory locks with no // WordPress-native equivalent (no wp_cache_*/options API provides // cross-request mutual exclusion) — a direct, properly $wpdb->prepare()'d // query is the only way to use them. $this->lock = $lock ?? static function ( string $key ): bool { global $wpdb; return 1 === (int) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 5)', $key ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching }; $this->unlock = $unlock ?? static function ( string $key ): void { global $wpdb; $wpdb->query( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $key ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching }; // wc_maybe_reduce_stock_levels() is a *guarded* wrapper: it skips // reduction entirely if the order's "_order_stock_reduced" flag is // already set. wc_create_order(['status' => $payload->status()]) // sets that status at creation time, before any line items exist — // if WooCommerce's own status-transition hooks fire on that (still // empty) order, they can mark it "reduced" with nothing in it, // permanently no-op-ing this later call. wc_reduce_stock_levels() is // the actual unconditional reducer with no such guard — safe here // since this only ever runs once per order (see the advisory lock // in build()). $this->reduceStock = $reduceStock ?? static function ( int $orderId ): void { wc_reduce_stock_levels( $orderId ); }; } /** * @throws ProductNotFoundException * @throws \RuntimeException if WooCommerce fails to create the order, or * if another request for the same POS order * is already in progress */ public function build( OrderPayload $payload ) { $lockKey = 'akantio_pos_order:' . $payload->posOrderId(); if ( ! ( $this->lock )( $lockKey ) ) { throw new \RuntimeException( 'Another push for this order is already in progress.' ); } try { return $this->buildLocked( $payload ); } finally { ( $this->unlock )( $lockKey ); } } private function buildLocked( OrderPayload $payload ) { $existing = $this->findExisting( $payload->posOrderId() ); if ( null !== $existing ) { return $existing; } $order = ( $this->orderFactory )( [ 'status' => $payload->status() ] ); if ( is_wp_error( $order ) ) { // Caught in Rest\OrderController and returned inside a WP_Error's // JSON body (never rendered as HTML), so HTML-escaping this would // be the wrong control, not a missing one. throw new \RuntimeException( 'Failed to create order: ' . $order->get_error_message() ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } $order->set_currency( $payload->currency() ); $order->set_payment_method( $payload->paymentMethod() ); $order->update_meta_data( self::POS_ORDER_ID_META, $payload->posOrderId() ); foreach ( $payload->metaData() as $meta ) { if ( isset( $meta['key'] ) ) { $order->update_meta_data( $meta['key'], $meta['value'] ?? '' ); } } foreach ( $payload->lineItems() as $lineItemData ) { $order->add_item( $this->buildLineItem( $lineItemData ) ); } foreach ( $payload->taxLines() as $taxLineData ) { $order->add_item( $this->buildTaxLine( $taxLineData ) ); } $order->set_total( $payload->total() ); $order->set_cart_tax( $payload->totalTax() ); if ( $payload->setPaid() ) { $order->payment_complete(); } $order->save(); if ( $payload->setPaid() ) { ( $this->reduceStock )( $order->get_id() ); } return $order; } /** * Public lookup used by OrderController's GET /orders route, so * akantio_pos can check for an already-created order before attempting * a push — the same check build() itself does internally, exposed so * the caller can decide not to push at all rather than rely solely on * this class's own idempotency. */ public function findExistingByPosOrderId( string $posOrderId ) { return $this->findExisting( $posOrderId ); } private function findExisting( string $posOrderId ) { // wc_get_orders() is WooCommerce's own documented query API (not raw // SQL) — meta_key/meta_value lookup by pos_order_id is the only way // it supports finding an order by a custom meta field. $orders = wc_get_orders( [ 'meta_key' => self::POS_ORDER_ID_META, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key 'meta_value' => $posOrderId, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value 'limit' => 1, 'return' => 'objects', ] ); return $orders[0] ?? null; } private function buildLineItem( array $data ) { $item = ( $this->lineItemFactory )(); $item->set_product( $this->resolveProduct( $data ) ); $item->set_quantity( (int) $data['quantity'] ); $item->set_subtotal( (string) ( $data['subtotal'] ?? $data['total'] ) ); $item->set_total( (string) ( $data['total'] ?? $data['subtotal'] ) ); $item->set_subtotal_tax( (string) ( $data['subtotal_tax'] ?? '0' ) ); $item->set_total_tax( (string) ( $data['total_tax'] ?? '0' ) ); // Ties this line's tax amount to a real rate_id, matching the // corresponding WC_Order_Item_Tax added in buildLocked() — without // this, set_subtotal_tax()/set_total_tax() above are just scalar // display fields with nothing to key them to, and WooCommerce's // admin UI shows no tax for the order at all. if ( ! empty( $data['tax_rate_id'] ) ) { $rateId = (string) $data['tax_rate_id']; $item->set_taxes( [ 'total' => [ $rateId => (string) ( $data['total_tax'] ?? '0' ) ], 'subtotal' => [ $rateId => (string) ( $data['subtotal_tax'] ?? '0' ) ], ] ); } return $item; } private function buildTaxLine( array $data ) { $taxItem = ( $this->taxLineFactory )(); $taxItem->set_rate_id( (int) ( $data['rate_id'] ?? 0 ) ); $taxItem->set_label( (string) ( $data['label'] ?? 'Tax' ) ); $taxItem->set_tax_total( (string) ( $data['tax_total'] ?? '0' ) ); return $taxItem; } /** * @throws ProductNotFoundException */ private function resolveProduct( array $data ) { if ( ! empty( $data['product_id'] ) ) { $product = wc_get_product( (int) $data['product_id'] ); if ( ! $product ) { // Caught in Rest\OrderController and returned inside a // WP_Error's JSON body (422), never rendered as HTML. throw new ProductNotFoundException( "No product found for product_id {$data['product_id']}." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } return $product; } $productId = wc_get_product_id_by_sku( (string) $data['sku'] ); if ( ! $productId ) { throw new ProductNotFoundException( "No product found for SKU {$data['sku']}." ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped } return wc_get_product( $productId ); } }