autoship_get_product_sync_summary

(src/products.php) Function used to get and use QPilot's API response from syncing a product. Takes a product id as a parameter. 

Example
 
/**
* Retrieves the product summary from QPilot for the supplied id..
*
* @param mixed $id. Product id.
* @return array|WP_Error The Summary Data or WP_Error on failure
*/
function autoship_get_product_sync_summary ( $id ){

  // Get the product ( if invalid or wrong type or not correct status returns false )
  if ( ( $product = autoship_productize_and_validate( $id ) ) === false )
  return new WP_Error( 'Product Summary Retrieval Failed', __( 'Autoship Sync information is not available for this product.  Please confirm the product is a valid product type and status.', "autoship" ) );

  // Create the QPilot client
  // Grab the client and only continue if connection exists.
  if ( empty( $client = autoship_get_default_client() ) || empty( $client->get_token_auth() ) )
  return new WP_Error( 'Product Summary Retrieval Failed', __( 'A problem was encountered while trying to retrieve this Product\'s Sync Information.  Please confirm your Autoship Connection is healthy and setup correctly.', "autoship" ) );

  // Get the product via external id.
  $all_ids = array( $id );
  $ids = array();
  if ( 'variable' == $product->get_type() ){

    // If Variation get all children as well
    $ids = autoship_get_available_variations( $product, true );
    // $ids['valids'][] = $id;
    $all_ids = array_merge( $ids['valids'] , $ids['invalids'], array( $id ) );

  }

  try {

    $summaries = $client->get_product_summary_by_external_ids( $all_ids );

  } catch ( Exception $e ) {

    if ( '404' == $e->getCode() ){
      error_log( sprintf( 'The supplied product can not be found in Autoship Cloud. Additional Details: %s', $e->getMessage() ) );
      return new WP_Error( 'Product Not Found', __( "The supplied product could not be found in Autoship Cloud", "autoship" ) );
    } else {
      $notice = autoship_expand_http_code( $e->getCode() );
      error_log( sprintf( 'Product Summary Retrieval Failed. Additional Details: %s', $e->getMessage() ) );
      return new WP_Error( 'Product Summary Retrieval Failed', sprintf( __( 'A problem was encountered while trying to retrieve this Product\'s Sync Information.  Please confirm your Autoship Connection is healthy and setup correctly. Additional Details: <i>%s</i>', "autoship" ), $notice['desc'] ) );
    }

  }

  if ( empty( $summaries ) )
  return new WP_Error( 'Product Not Found', __( "The supplied product could not be found in QPilot", "autoship" ) );

  $totals = array();
  if ( 'variation' == $product->get_type() || 'simple' == $product->get_type() ){

    $totals = apply_filters( 'autoship_product_summary_data', array(
      'Id'                            => $summaries[0]->Id,
      'ExternalId'                    => $summaries[0]->ExternalId,
      'ProductName'                   => $summaries[0]->ProductName,
      'AddToScheduledOrder'           => strpos($summaries[0]->Availability, 'AddToScheduledOrder') !== false,
      'ProcessScheduledOrder'         => strpos($summaries[0]->Availability, 'ProcessScheduledOrder') !== false,
      'Availability'                  => $summaries[0]->Availability,
      'ProductType'                   => $summaries[0]->ProductType,
      'StockLevel'                    => $summaries[0]->StockLevel,
      'TotalStock'                    => $summaries[0]->Stock,
      'QuantityScheduled'             => $summaries[0]->TotalQuantityScheduledActive +
                                         $summaries[0]->TotalQuantityScheduledPaused +
                                         $summaries[0]->TotalQuantityFailed +
                                         $summaries[0]->TotalQuantityProcessing +
                                         $summaries[0]->TotalQuantityQueued,
      'TotalQuantityScheduledActive'  => $summaries[0]->TotalQuantityScheduledActive,
      'TotalQuantityScheduledPaused'  => $summaries[0]->TotalQuantityScheduledPaused,
      'TotalQuantityFailed'           => $summaries[0]->TotalQuantityFailed,
      'TotalQuantityProcessing'       => $summaries[0]->TotalQuantityProcessing,
      'TotalQuantityQueued'           => $summaries[0]->TotalQuantityQueued,
      'LifetimeValue'                 => $summaries[0]->LifetimeValue,
      'ShippingClass'                 => $summaries[0]->ShippingClass,
      'Active'                        => $summaries[0]->Active,
      'Valid'                         => $summaries[0]->Valid,
      'ValidationErrorCode'           => $summaries[0]->ValidationErrorCode,
      'UpdatedUtc'                    => $summaries[0]->UpdatedUtc,
      'SyncError'                     => ''
    ), $summaries[0], $product );

    // Since we've already pulled the Active flag from QPilot get the flag from WooCommerce / Autoship
    $totals['AutoshipActive'] = ( 'yes' === autoship_sync_active_enabled( $product ) );

    // Run Sync Checks
    $totals['SyncError'] = apply_filters( 'autoship_product_summary_data_sync_error', $totals['SyncError'], $totals, $summaries[0], $product, $ids );

    return apply_filters( 'autoship_total_product_summary_data', $totals, $product );

  // If this is a variable product then sum variations totals.
  } else {


    $totals = array(
      'TotalActive'                   => 0,
      'TotalAutoshipActive'           => 0,
      'TotalInactive'                 => 0,
      'TotalAddToScheduledOrder'      => 0,
      'TotalProcessScheduledOrder'    => 0,
      'TotalUnAvailable'              => 0,
      'TotalInStock'                  => 0,
      'TotalOutOfStock'               => 0,
      'QuantityScheduled'             => 0,
      'TotalQuantityScheduledActive'  => 0,
      'TotalQuantityScheduledPaused'  => 0,
      'TotalQuantityFailed'           => 0,
      'TotalQuantityProcessing'       => 0,
      'TotalVariations'               => 0,
      'TotalAutoshipVariations'       => 0,
      'TotalErrors'                   => 0,
      'TotalInvalids'                 => 0,
      'TotalValids'                   => 0,
      'TotalActiveInvalids'           => 0,
    );

    $variations = $autoship_variations = $errors = array();
    foreach ( $summaries as $key => $summary) {

      // Try to get the product in WC
      $row_product = wc_get_product( $summary->ExternalId );

      // If product variation doesn't exist in WC but exists in QPilot we can't gather any info.
      // TODO: We need to better deal with this situation.
      if ( !$row_product )
      continue;

      $variations[$summary->ExternalId] = apply_filters( 'autoship_variable_product_summary_data', array(
        'Id'                            => $summary->Id,
        'ExternalId'                    => $summary->ExternalId,
        'ProductName'                   => $summary->ProductName,
        'AddToScheduledOrder'           => strpos($summary->Availability, 'AddToScheduledOrder') !== false,
        'ProcessScheduledOrder'         => strpos($summary->Availability, 'ProcessScheduledOrder') !== false,
        'Availability'                  => $summary->Availability,
        'ProductType'                   => $summary->ProductType,
        'StockLevel'                    => $summary->StockLevel,
        'TotalStock'                    => $summary->Stock,
        'QuantityScheduled'             => $summary->TotalQuantityScheduledActive +
                                           $summary->TotalQuantityScheduledPaused +
                                           $summary->TotalQuantityFailed +
                                           $summary->TotalQuantityProcessing +
                                           $summary->TotalQuantityQueued,
        'TotalQuantityScheduledActive'  => $summary->TotalQuantityScheduledActive,
        'TotalQuantityScheduledPaused'  => $summary->TotalQuantityScheduledPaused,
        'TotalQuantityFailed'           => $summary->TotalQuantityFailed,
        'TotalQuantityProcessing'       => $summary->TotalQuantityProcessing,
        'TotalQuantityQueued'           => $summary->TotalQuantityQueued,
        'LifetimeValue'                 => $summary->LifetimeValue,
        'ShippingClass'                 => $summary->ShippingClass,
        'Active'                        => $summary->Active,
        'Valid'                         => $summary->Valid,
        'ValidationErrorCode'           => $summary->ValidationErrorCode,
        'UpdatedUtc'                    => $summary->UpdatedUtc,
        'SyncError'                     => ''
      ), $summary, $product );

      // Since we've already pulled the Active flag from QPilot get the flag from WooCommerce / Autoship
      $variations[$summary->ExternalId]['AutoshipActive'] = ( 'yes' === autoship_sync_active_enabled( $row_product ) );

      // Run Sync Checks
      $variations[$summary->ExternalId]['SyncError'] = apply_filters( 'autoship_product_summary_data_sync_error', $variations[$summary->ExternalId]['SyncError'], $variations[$summary->ExternalId], $summary, $row_product, $ids );

      if ( is_wp_error( $variations[$summary->ExternalId]['SyncError'] ) )
      $errors[] = $variations[$summary->ExternalId]['SyncError'];

      // Only include variations in totals NOT variable
      if ( 'variation' == $summary->ProductType ){
        $totals['TotalAddToScheduledOrder']      += (int) $variations[$summary->ExternalId]['AddToScheduledOrder'];
        $totals['TotalProcessScheduledOrder']    += (int) $variations[$summary->ExternalId]['ProcessScheduledOrder'];
        $totals['TotalUnAvailable']              += (int) 'None' == $variations[$summary->ExternalId]['Availability'];
        $totals['TotalActive']                   += (int) $variations[$summary->ExternalId]['Active'];
        $totals['TotalAutoshipActive']           += (int) $variations[$summary->ExternalId]['AutoshipActive'];
        $totals['TotalInactive']                 += (int)!$variations[$summary->ExternalId]['Active'];
        $totals['TotalInStock']                  += (int) 'InStock' == $variations[$summary->ExternalId]['StockLevel'];
        $totals['TotalOutOfStock']               += (int) 'InStock' != $variations[$summary->ExternalId]['StockLevel'];
        $totals['QuantityScheduled']             += $variations[$summary->ExternalId]['QuantityScheduled'];
        $totals['TotalQuantityScheduledActive']  += $variations[$summary->ExternalId]['TotalQuantityScheduledActive'];
        $totals['TotalQuantityScheduledPaused']  += $variations[$summary->ExternalId]['TotalQuantityScheduledPaused'];
        $totals['TotalQuantityFailed']           += $variations[$summary->ExternalId]['TotalQuantityFailed'];
        $totals['TotalQuantityProcessing']       += $variations[$summary->ExternalId]['TotalQuantityProcessing'];
        $totals['TotalVariations']               += (int) ( 'variation' == $summary->ProductType );
        $totals['TotalInvalids']                 += (int) ( !$variations[$summary->ExternalId]['Valid'] );
        $totals['TotalValids']                   += (int) ( $variations[$summary->ExternalId]['Valid'] );

        // Not valid and active are a problem and should be addressed.
        $totals['TotalActiveInvalids']           += (int) ( !$variations[$summary->ExternalId]['Valid'] && $variations[$summary->ExternalId]['Active'] );

        // Gather variations that are active in WooCommerce / Autoship
        if ( $variations[$summary->ExternalId]['AutoshipActive'] )
        $autoship_variations[$summary->ExternalId] = $summary->ExternalId;

      }

    }

    $totals['StockLevel']                    = $totals['TotalInStock'] ? 'InStock' : 'OutOfStock';
    $totals['Variations']                    = $variations;
    $totals['AutoshipVariations']            = $autoship_variations;
    $totals['SyncError']                     = reset( $errors );
    $totals['AllSyncError']                  = $errors;
    $totals['TotalErrors']                   = count( $errors );

    return apply_filters( 'autoship_total_variation_product_summary_data', $totals, $product, $ids );

  }

}