get_id(); } foreach ( array_chunk( $ids, self::MAX_LINES ) as $chunk ) { Queue::now( self::HOOK_SEND, array( $chunk, 1 ) ); } } /** * Job: maps the orders and uploads one batch. * * @param int[] $order_ids Order IDs. * @param int $attempt Attempt number. * @return void */ public static function send( $order_ids, $attempt = 1 ) { $api_key = Credentials::get(); $settings = Settings::all(); $lines = array(); $orders = array(); foreach ( (array) $order_ids as $order_id ) { $order = wc_get_order( $order_id ); if ( ! $order instanceof \WC_Order || ! in_array( OrderMeta::state( $order ), array( OrderMeta::QUEUED, OrderMeta::SENDING ), true ) ) { continue; } if ( '' === $api_key ) { ShipmentCreator::mark_failed( $order, __( 'The store is not connected to ABS Courier.', 'abs-courier' ) ); continue; } try { $district = ShipmentCreator::district( $order, $settings ); if ( null === $district ) { ShipmentCreator::hold( $order ); continue; } $shipment = OrderMapper::shipment( $order, $settings, $district['id'] ); } catch ( MappingError $e ) { ShipmentCreator::mark_failed( $order, $e->getMessage() ); continue; } catch ( AbsError $e ) { // District list unavailable: let the single-order flow retry this one. ShipmentCreator::enqueue( $order ); continue; } ShipmentCreator::remember_district( $order, $district ); if ( ! $order->get_meta( OrderMeta::FIRST_ATTEMPT_AT ) ) { $order->update_meta_data( OrderMeta::FIRST_ATTEMPT_AT, time() ); } OrderMeta::set_state( $order, OrderMeta::SENDING ); $lines[] = $shipment; $orders[] = $order; } if ( empty( $lines ) ) { return; } $ndjson = implode( "\n", array_map( 'wp_json_encode', $lines ) ); try { $data = ( new AbsClient( $api_key ) )->post_file( 'create-shipment/bulk', array( 'cmpService' => 'DELIVERY' ), 'shipments', 'shipments.ndjson', $ndjson, 'application/x-ndjson' ); } catch ( AbsError $e ) { self::upload_failed( $orders, $e, $attempt ); return; } $job_id = is_array( $data ) && isset( $data['jobId'] ) ? (string) $data['jobId'] : ''; if ( '' === $job_id ) { self::fall_back( $orders ); return; } foreach ( $orders as $order ) { $order->update_meta_data( OrderMeta::BATCH_JOB, $job_id ); $order->save(); } Queue::later( self::HOOK_POLL, array( $job_id, array_map( array( __CLASS__, 'order_id' ), $orders ), 1 ), self::POLL_INTERVAL ); } /** * Job: checks the batch and links AWBs to orders when it is done. * * @param string $job_id ABS job ID. * @param int[] $order_ids Orders in the batch. * @param int $attempt Poll number. * @return void */ public static function poll( $job_id, $order_ids, $attempt = 1 ) { $orders = array(); foreach ( (array) $order_ids as $order_id ) { $order = wc_get_order( $order_id ); if ( $order instanceof \WC_Order && OrderMeta::SENDING === OrderMeta::state( $order ) ) { $orders[] = $order; } } if ( empty( $orders ) ) { return; } $client = new AbsClient( Credentials::get() ); try { $job = $client->get( 'create-shipment/bulk/status/' . rawurlencode( $job_id ) ); } catch ( AbsError $e ) { self::poll_again_or_fall_back( $job_id, $orders, $attempt ); return; } if ( ! is_array( $job ) || ( isset( $job['success'] ) && false === $job['success'] ) ) { self::fall_back( $orders ); return; } $status = isset( $job['status'] ) ? (string) $job['status'] : ''; if ( 'failed' === $status ) { $reason = isset( $job['error'] ) && is_string( $job['error'] ) && '' !== $job['error'] ? sanitize_text_field( $job['error'] ) : __( 'ABS Courier could not process the batch.', 'abs-courier' ); foreach ( $orders as $order ) { ShipmentCreator::mark_failed( $order, $reason ); } return; } if ( 'completed' !== $status ) { self::poll_again_or_fall_back( $job_id, $orders, $attempt ); return; } $header = isset( $job['result']['shipmentHdrId'] ) ? (int) $job['result']['shipmentHdrId'] : 0; if ( $header <= 0 ) { foreach ( $orders as $order ) { ShipmentCreator::mark_failed( $order, __( 'ABS Courier did not create any shipments in this batch.', 'abs-courier' ) ); } return; } try { $awbs = self::awbs_by_ref( $client, $header ); } catch ( AbsError $e ) { self::poll_again_or_fall_back( $job_id, $orders, $attempt ); return; } $missing = array(); foreach ( $orders as $order ) { $ref = OrderMeta::ref( $order ); if ( isset( $awbs[ $ref ] ) ) { ShipmentCreator::mark_created( $order, $awbs[ $ref ] ); } else { $missing[] = $order; } } self::fall_back( $missing ); } /** * AWBs of a batch, keyed by reference. * * @param AbsClient $client Client. * @param int $header Batch (shipment header) ID. * @return array * @throws AbsError On failure. */ private static function awbs_by_ref( AbsClient $client, $header ) { $awbs = array(); $page = 1; do { $data = $client->post( 'shipments/list', array( 'shipmentHeaderIds' => array( $header ), 'columns' => array( 'awb', 'reference' ), 'page' => $page, 'limit' => self::MAX_LINES, ) ); foreach ( isset( $data['data'] ) && is_array( $data['data'] ) ? $data['data'] : array() as $row ) { if ( isset( $row['reference'], $row['awb'] ) && ShipmentCreator::is_valid_awb( $row['awb'] ) ) { $awbs[ (string) $row['reference'] ] = (string) $row['awb']; } } ++$page; } while ( ! empty( $data['hasMore'] ) && $page <= 20 ); return $awbs; } /** * Handles a failed upload. * * @param \WC_Order[] $orders Orders in the upload. * @param AbsError $e Error. * @param int $attempt Attempt number. * @return void */ private static function upload_failed( array $orders, AbsError $e, $attempt ) { Logger::error( 'Bulk upload failed', array( 'orders' => count( $orders ), 'type' => $e->type(), 'status' => $e->status(), 'message' => $e->getMessage(), ) ); if ( AbsError::VALIDATION === $e->type() ) { // ABS names rejected rows as "Row N: reason" (1-based line numbers); fail those and re-send the rest. $rejected = self::rejected_rows( $e->getMessage() ); if ( empty( $rejected ) ) { foreach ( $orders as $order ) { ShipmentCreator::mark_failed( $order, $e->getMessage() ); } return; } $retry = array(); foreach ( $orders as $index => $order ) { if ( isset( $rejected[ $index + 1 ] ) ) { ShipmentCreator::mark_failed( $order, $rejected[ $index + 1 ] ); } else { OrderMeta::set_state( $order, OrderMeta::QUEUED ); $retry[] = $order->get_id(); } } if ( ! empty( $retry ) ) { Queue::now( self::HOOK_SEND, array( $retry, 1 ) ); } return; } if ( in_array( $e->type(), array( AbsError::RETRYABLE, AbsError::UNKNOWN_OUTCOME ), true ) ) { $delay = Queue::retry_delay( $attempt ); if ( null !== $delay ) { Queue::later( self::HOOK_SEND, array( array_map( array( __CLASS__, 'order_id' ), $orders ), $attempt + 1 ), $delay ); return; } self::fall_back( $orders ); return; } foreach ( $orders as $order ) { ShipmentCreator::mark_failed( $order, $e->getMessage() ); } } /** * Parses "Row 3: reason; Row 7: reason" into [3 => reason, 7 => reason]. * * @param string $message Error message. * @return array */ public static function rejected_rows( $message ) { $rows = array(); if ( preg_match_all( '/Row (\d+):\s*(.+?)(?=;\s*Row \d+:|$)/s', (string) $message, $matches, PREG_SET_ORDER ) ) { foreach ( $matches as $match ) { $rows[ (int) $match[1] ] = trim( $match[2] ); } } return $rows; } /** * Polls again later, or gives up and falls back to single-order lookups. * * @param string $job_id Job ID. * @param \WC_Order[] $orders Orders. * @param int $attempt Poll number. * @return void */ private static function poll_again_or_fall_back( $job_id, array $orders, $attempt ) { if ( $attempt < self::MAX_POLLS ) { Queue::later( self::HOOK_POLL, array( $job_id, array_map( array( __CLASS__, 'order_id' ), $orders ), $attempt + 1 ), self::POLL_INTERVAL ); return; } self::fall_back( $orders ); } /** * Hands orders whose outcome is unknown to the single-order flow, which searches * ABS for their reference before sending anything. * * @param \WC_Order[] $orders Orders. * @return void */ private static function fall_back( array $orders ) { foreach ( $orders as $order ) { $order->delete_meta_data( OrderMeta::BATCH_JOB ); OrderMeta::set_state( $order, OrderMeta::UNKNOWN ); Queue::now( ShipmentCreator::HOOK, array( $order->get_id(), 1 ) ); } } /** * Callback: order ID. * * @param \WC_Order $order Order. * @return int */ private static function order_id( \WC_Order $order ) { return $order->get_id(); } }