/**
  * Extracts the weight and dimensions from the package.
  *
  * @return array
  */
 protected function get_package_data()
 {
     $count = 0;
     $height = array();
     $width = array();
     $length = array();
     $weight = array();
     // Shipping per item.
     foreach ($this->package['contents'] as $item_id => $values) {
         $product = $values['data'];
         $qty = $values['quantity'];
         if ($qty > 0 && $product->needs_shipping()) {
             $_height = wc_get_dimension($this->fix_format($product->height), 'cm');
             $_width = wc_get_dimension($this->fix_format($product->width), 'cm');
             $_length = wc_get_dimension($this->fix_format($product->length), 'cm');
             $_weight = wc_get_weight($this->fix_format($product->weight), 'kg');
             $height[$count] = $_height;
             $width[$count] = $_width;
             $length[$count] = $_length;
             $weight[$count] = $_weight;
             if ($qty > 1) {
                 $n = $count;
                 for ($i = 0; $i < $qty; $i++) {
                     $height[$n] = $_height;
                     $width[$n] = $_width;
                     $length[$n] = $_length;
                     $weight[$n] = $_weight;
                     $n++;
                 }
                 $count = $n;
             }
             $count++;
         }
     }
     return array('height' => array_values($height), 'length' => array_values($length), 'width' => array_values($width), 'weight' => array_sum($weight));
 }
/**
 * @deprecated
 */
function woocommerce_get_weight($weight, $to_unit)
{
    return wc_get_weight($weight, $to_unit);
}
Ejemplo n.º 3
0
function amt_product_data_jsonld_schemaorg_woocommerce($metatags, $post)
{
    // Get the product object
    $product = get_product($post->ID);
    // WC API:
    // http://docs.woothemes.com/wc-apidocs/class-WC_Product.html
    // http://docs.woothemes.com/wc-apidocs/class-WC_Product_Variable.html
    // http://docs.woothemes.com/wc-apidocs/class-WC_Product_Variation.html
    // Schema.org:
    // http://schema.org/Product
    // http://schema.org/IndividualProduct
    // http://schema.org/ProductModel
    // http://schema.org/Offer
    // http://schema.org/Review
    // http://schema.org/AggregateRating
    // Currently, the schema.org JSON-LD WC generator supports all product types.
    // simple, external, grouped (no price), variable (multiple prices)
    // The relevant meta tags are generated only if the relevant data can be retrieved
    // from the product object.
    $product_type = $product->product_type;
    //if ( ! in_array( $product_type, array('simple', 'external') ) ) {
    //    $metatags = apply_filters( 'amt_product_data_woocommerce_opengraph', $metatags );
    //    return $metatags;
    //}
    // Variations (only in variable products)
    $variations = null;
    if ($product_type == 'variable') {
        $variations = $product->get_available_variations();
    }
    //var_dump($variations);
    // Variation attributes
    $variation_attributes = null;
    if ($product_type == 'variable') {
        $variation_attributes = $product->get_variation_attributes();
    }
    //var_dump($variation_attributes);
    // Schema.org property to WooCommerce attribute map
    $property_map = array('brand' => 'brand', 'color' => 'color', 'condition' => 'condition', 'mpn' => 'mpn', 'gtin' => 'gtin');
    $property_map = apply_filters('amt_schemaorg_woocommerce_property_map', $property_map);
    // Product category
    $product_cats = wp_get_post_terms($post->ID, 'product_cat');
    $product_category = array_shift($product_cats);
    if (!empty($product_category)) {
        $metatags['category'] = esc_attr($product_category->name);
    }
    // Brand
    $brand = $product->get_attribute($property_map['brand']);
    if (!empty($brand)) {
        $metatags['brand'] = esc_attr($brand);
    }
    // Weight
    $weight_unit = apply_filters('amt_woocommerce_default_weight_unit', 'kg');
    $weight = wc_get_weight($product->get_weight(), $weight_unit);
    if (!empty($weight)) {
        $metatags['weight'] = array();
        $metatags['weight']['@type'] = 'QuantitativeValue';
        $metatags['weight']['value'] = esc_attr($weight);
        $metatags['weight']['unitText'] = esc_attr($weight_unit);
    }
    // Dimensions
    // Schema.org has: width(length), depth(width), height(height)
    $dimension_unit = get_option('woocommerce_dimension_unit');
    if (!empty($product->length)) {
        $metatags['width'] = array();
        $metatags['width']['@type'] = 'QuantitativeValue';
        $metatags['width']['value'] = esc_attr($product->length);
        $metatags['width']['unitText'] = esc_attr($dimension_unit);
    }
    if (!empty($product->width)) {
        $metatags['depth'] = array();
        $metatags['depth']['@type'] = 'QuantitativeValue';
        $metatags['depth']['value'] = esc_attr($product->width);
        $metatags['depth']['unitText'] = esc_attr($dimension_unit);
    }
    if (!empty($product->height)) {
        $metatags['height'] = array();
        $metatags['height']['@type'] = 'QuantitativeValue';
        $metatags['height']['value'] = esc_attr($product->height);
        $metatags['height']['unitText'] = esc_attr($dimension_unit);
    }
    // Color
    $color = $product->get_attribute($property_map['color']);
    if (!empty($color)) {
        $metatags['color'] = esc_attr($color);
    }
    // Condition
    $condition = $product->get_attribute($property_map['condition']);
    if (!empty($condition)) {
        if (in_array($age_group, array('new', 'refurbished', 'used'))) {
            $schema_org_condition_map = array('new' => 'NewCondition', 'refurbished' => 'RefurbishedCondition', 'used' => 'UsedCondition');
            $metatags['itemCondition'] = esc_attr($schema_org_condition_map[$condition]);
        }
    } else {
        $metatags['itemCondition'] = 'NewCondition';
    }
    // Codes
    // SKU (product:retailer_part_no?)
    // By convention we use the SKU as the product:retailer_part_no. TODO: check this
    $sku = $product->get_sku();
    if (!empty($sku)) {
        $metatags['sku'] = esc_attr($sku);
    }
    // GTIN: A Global Trade Item Number, which encompasses UPC, EAN, JAN, and ISBN
    $gtin = $product->get_attribute($property_map['gtin']);
    if (!empty($gtin)) {
        $metatags['gtin14'] = esc_attr($gtin);
    }
    // MPN: A manufacturer's part number for the item
    $mpn = $product->get_attribute($property_map['mpn']);
    if (!empty($mpn)) {
        $metatags['mpn'] = esc_attr($mpn);
    }
    // Aggregated Rating
    $avg_rating = $product->get_average_rating();
    $rating_count = $product->get_rating_count();
    $review_count = $product->get_review_count();
    if ($rating_count > 0) {
        $metatags['aggregateRating'] = array();
        $metatags['aggregateRating']['@type'] = 'AggregateRating';
        // Rating value
        if (!empty($avg_rating)) {
            $metatags['aggregateRating']['ratingValue'] = esc_attr($avg_rating);
        }
        // Rating count
        if (!empty($rating_count)) {
            $metatags['aggregateRating']['ratingCount'] = esc_attr($rating_count);
        }
        // Review count
        if (!empty($review_count)) {
            $metatags['aggregateRating']['reviewCount'] = esc_attr($review_count);
        }
        // Reviews
        // Review counter
        //$rc = 0;
        // TODO: check how default reviews are generated by WC
        //$metatags[] = '<!-- Scope BEGIN: UserComments -->';
        //$metatags[] = '<span itemprop="review" itemscope itemtype="http://schema.org/Review">';
        //$metatags[] = '</span>';
    }
    // Offers
    $metatags['offers'] = array();
    if (empty($variations)) {
        // Availability
        $availability = '';
        if ($product->is_in_stock()) {
            $availability = 'InStock';
            //} elseif ( $product->backorders_allowed() ) {
            //    $availability = 'pending';
        } else {
            $availability = 'OutOfStock';
        }
        // Regular Price Offer
        $offer = array();
        $offer['@type'] = 'Offer';
        // Availability
        if (!empty($availability)) {
            $offer['availability'] = 'http://schema.org/' . esc_attr($availability);
        }
        // Regular Price
        $regular_price = $product->get_regular_price();
        if (!empty($regular_price)) {
            $offer['price'] = esc_attr($regular_price);
            // Currency
            $offer['priceCurrency'] = esc_attr(get_woocommerce_currency());
        }
        $metatags['offers'][] = $offer;
        // Sale Price Offer
        if ($product->is_on_sale()) {
            $offer = array();
            $offer['@type'] = 'Offer';
            // Availability
            if (!empty($availability)) {
                $offer['availability'] = 'http://schema.org/' . esc_attr($availability);
            }
            // Sale Price
            $sale_price = $product->get_sale_price();
            if (!empty($sale_price)) {
                $offer['price'] = esc_attr($sale_price);
                // Currency
                $offer['priceCurrency'] = esc_attr(get_woocommerce_currency());
                // Sale price to date
                $sale_price_date_to = get_post_meta($post->ID, '_sale_price_dates_to', true);
                if (!empty($sale_price_date_to)) {
                    $offer['priceValidUntil'] = esc_attr(date_i18n('Y-m-d', $sale_price_date_to));
                }
            }
            $metatags['offers'][] = $offer;
        }
        // Offers for variations (Variable Products)
    } else {
        // Variation offers counter
        $oc = 0;
        foreach ($variations as $variation_info) {
            foreach (array('regular', 'sale') as $offer_type) {
                // Get the variation object
                $variation = $product->get_child($variation_info['variation_id']);
                //var_dump($variation);
                if ($offer_type == 'sale' && !$variation->is_on_sale()) {
                    continue;
                }
                // Increase the Offer counter
                $oc++;
                // Availability
                $availability = '';
                if ($variation->is_in_stock()) {
                    $availability = 'InStock';
                    //} elseif ( $variation->backorders_allowed() ) {
                    //    $availability = 'pending';
                } else {
                    $availability = 'OutOfStock';
                }
                $offer = array();
                $offer['@type'] = 'Offer';
                // Availability
                if (!empty($availability)) {
                    $offer['availability'] = 'http://schema.org/' . esc_attr($availability);
                }
                // Regular Price Offer
                if ($offer_type == 'regular') {
                    // Regular Price
                    $regular_price = $variation->get_regular_price();
                    if (!empty($regular_price)) {
                        $offer['price'] = esc_attr($regular_price);
                        // Currency
                        $offer['priceCurrency'] = esc_attr(get_woocommerce_currency());
                    }
                } elseif ($offer_type == 'sale') {
                    // Sale Price Offer
                    if ($variation->is_on_sale()) {
                        // Sale Price
                        $sale_price = $variation->get_sale_price();
                        if (!empty($sale_price)) {
                            $offer['price'] = esc_attr($sale_price);
                            // Currency
                            $offer['priceCurrency'] = esc_attr(get_woocommerce_currency());
                            // Sale price to date
                            $sale_price_date_to = get_post_meta($variation->variation_id, '_sale_price_dates_to', true);
                            if (!empty($sale_price_date_to)) {
                                $offer['priceValidUntil'] = esc_attr(date_i18n('Y-m-d', $sale_price_date_to));
                            }
                        }
                    }
                }
                // Item Offered
                $offer['itemOffered'] = array();
                $offer['itemOffered']['@type'] = 'Product';
                // Check whether you should use 'IndividualProduct)
                // Attributes
                $offer['itemOffered']['additionalProperty'] = array();
                foreach ($variation_info['attributes'] as $variation_attribute_name => $variation_attribute_value) {
                    $variation_attribute_name = str_replace('attribute_pa_', '', $variation_attribute_name);
                    $variation_attribute_name = str_replace('attribute_', '', $variation_attribute_name);
                    if (!empty($variation_attribute_value)) {
                        $additional_property = array();
                        $additional_property['@type'] = 'PropertyValue';
                        $additional_property['name'] = esc_attr($variation_attribute_name);
                        $additional_property['value'] = esc_attr($variation_attribute_value);
                        $offer['itemOffered']['additionalProperty'][] = $additional_property;
                    }
                }
                // Weight
                $variation_weight = wc_get_weight($variation->get_weight(), $weight_unit);
                if (!empty($variation_weight) && $variation_weight != $weight) {
                    $offer['itemOffered']['weight'] = array();
                    $offer['itemOffered']['weight']['@type'] = 'QuantitativeValue';
                    $offer['itemOffered']['weight']['value'] = esc_attr($variation_weight);
                    $offer['itemOffered']['weight']['unitText'] = esc_attr($weight_unit);
                }
                // Dimensions
                // Schema.org has: width(length), depth(width), height(height)
                if (!empty($variation->length) && $variation->length != $product->length) {
                    $offer['itemOffered']['width'] = array();
                    $offer['itemOffered']['width']['@type'] = 'QuantitativeValue';
                    $offer['itemOffered']['width']['value'] = esc_attr($variation->length);
                    $offer['itemOffered']['width']['unitText'] = esc_attr($dimension_unit);
                }
                if (!empty($variation->width) && $variation->width != $product->width) {
                    $offer['itemOffered']['depth'] = array();
                    $offer['itemOffered']['depth']['@type'] = 'QuantitativeValue';
                    $offer['itemOffered']['depth']['value'] = esc_attr($variation->width);
                    $offer['itemOffered']['depth']['unitText'] = esc_attr($dimension_unit);
                }
                if (!empty($variation->height) && $variation->height != $product->height) {
                    $offer['itemOffered']['height'] = array();
                    $offer['itemOffered']['height']['@type'] = 'QuantitativeValue';
                    $offer['itemOffered']['height']['value'] = esc_attr($variation->height);
                    $offer['itemOffered']['height']['unitText'] = esc_attr($dimension_unit);
                }
                // Image
                $parent_image_id = $product->get_image_id();
                $variation_image_id = $variation->get_image_id();
                if (!empty($variation_image_id) && $variation_image_id != $parent_image_id) {
                    $offer['itemOffered']['image'] = esc_url_raw(wp_get_attachment_url($variation_image_id));
                }
                // Codes
                // SKU
                $variation_sku = $variation->get_sku();
                if (!empty($variation_sku) && $variation_sku != $sku) {
                    $offer['itemOffered']['sku'] = esc_attr($variation_sku);
                }
                $metatags['offers'][] = $offer;
            }
        }
    }
    $metatags = apply_filters('amt_product_data_woocommerce_jsonld_schemaorg', $metatags);
    return $metatags;
}
Ejemplo n.º 4
0
 /**
  * Test wc_get_weight().
  *
  * @since 2.2
  */
 public function test_wc_get_weight()
 {
     // save default
     $default_unit = get_option('woocommerce_weight_unit');
     // kg (default unit)
     $this->assertEquals(10, wc_get_weight(10, 'kg'));
     $this->assertEquals(10000, wc_get_weight(10, 'g'));
     $this->assertEquals(22.0462, wc_get_weight(10, 'lbs'));
     $this->assertEquals(352.74, wc_get_weight(10, 'oz'));
     // g
     update_option('woocommerce_weight_unit', 'g');
     $this->assertEquals(0.01, wc_get_weight(10, 'kg'));
     $this->assertEquals(10, wc_get_weight(10, 'g'));
     $this->assertEquals(0.0220462, wc_get_weight(10, 'lbs'));
     $this->assertEquals(0.35274, wc_get_weight(10, 'oz'));
     // lbs
     update_option('woocommerce_weight_unit', 'lbs');
     $this->assertEquals(4.53592, wc_get_weight(10, 'kg'));
     $this->assertEquals(4535.92, wc_get_weight(10, 'g'));
     $this->assertEquals(10, wc_get_weight(10, 'lbs'));
     $this->assertEquals(160.00004208, wc_get_weight(10, 'oz'));
     // oz
     update_option('woocommerce_weight_unit', 'oz');
     $this->assertEquals(0.283495, wc_get_weight(10, 'kg'));
     $this->assertEquals(283.495, wc_get_weight(10, 'g'));
     $this->assertEquals(0.6249987469, wc_get_weight(10, 'lbs'));
     $this->assertEquals(10, wc_get_weight(10, 'oz'));
     // custom from unit
     $this->assertEquals(0.283495, wc_get_weight(10, 'kg', 'oz'));
     $this->assertEquals(0.01, wc_get_weight(10, 'kg', 'g'));
     $this->assertEquals(4.53592, wc_get_weight(10, 'kg', 'lbs'));
     $this->assertEquals(10, wc_get_weight(10, 'kg', 'kg'));
     // negative
     $this->assertEquals(0, wc_get_weight(-10, 'g'));
     // restore default
     update_option('woocommerce_weight_unit', $default_unit);
 }
 /**
  * Get products data.
  *
  * @param  WC_Order $order
  *
  * @return array
  */
 protected function get_products_data($order)
 {
     $i = 1;
     $data = array();
     // Force only one item.
     if ('yes' == $this->send_only_total || 'yes' == get_option('woocommerce_prices_include_tax')) {
         $data['cart_' . $i . '_name'] = $this->sanitize_string(sprintf(__('Order %s', 'woocommerce-checkout-cielo'), $order->get_order_number()));
         // $data['cart_' . $i . '_description'] = '';
         $data['cart_' . $i . '_unitprice'] = $this->get_price($order->get_total()) - $this->get_price($order->get_total_shipping()) + $this->get_discount($order);
         $data['cart_' . $i . '_quantity'] = '1';
         $data['cart_' . $i . '_type'] = '1';
         // $data['cart_' . $i . '_code']        = '';
         $data['cart_' . $i . '_weight'] = '0';
     } else {
         if (0 < sizeof($order->get_items())) {
             foreach ($order->get_items() as $order_item) {
                 if ($order_item['qty']) {
                     $item_total = $this->get_price($order->get_item_subtotal($order_item, false));
                     if (0 > $item_total) {
                         continue;
                     }
                     // Get product data.
                     $_product = apply_filters('woocommerce_order_item_product', $order->get_product_from_item($order_item), $order_item);
                     if (defined('WC_VERSION') && version_compare(WC_VERSION, '2.4.0', '<')) {
                         $item_meta = new WC_Order_Item_Meta($order_item['item_meta'], $_product);
                     } else {
                         $item_meta = new WC_Order_Item_Meta($order_item, $_product);
                     }
                     $data['cart_' . $i . '_name'] = $this->sanitize_string($order_item['name']);
                     if ($meta = $item_meta->display(true, true)) {
                         $data['cart_' . $i . '_description'] = $this->sanitize_string($meta, 256);
                     }
                     $data['cart_' . $i . '_unitprice'] = $item_total;
                     $data['cart_' . $i . '_quantity'] = $order_item['qty'];
                     $data['cart_' . $i . '_type'] = '1';
                     if ($sku = $_product->get_sku()) {
                         $data['cart_' . $i . '_code'] = $sku;
                     }
                     $data['cart_' . $i . '_weight'] = wc_get_weight($_product->get_weight(), 'g');
                     $i++;
                 }
             }
         }
         // Fees.
         if (0 < sizeof($order->get_fees())) {
             foreach ($order->get_fees() as $fee) {
                 $fee_total = $this->get_price($fee['line_total']);
                 if (0 > $fee_total) {
                     continue;
                 }
                 $data['cart_' . $i . '_name'] = $this->sanitize_string($fee['name']);
                 $data['cart_' . $i . '_unitprice'] = $fee_total;
                 $data['cart_' . $i . '_quantity'] = '1';
                 $data['cart_' . $i . '_type'] = '4';
                 $i++;
             }
         }
         // Taxes.
         if (0 < sizeof($order->get_taxes())) {
             foreach ($order->get_taxes() as $tax) {
                 $tax_total = $this->get_price($tax['tax_amount'] + $tax['shipping_tax_amount']);
                 if (0 > $tax_total) {
                     continue;
                 }
                 $data['cart_' . $i . '_name'] = $this->sanitize_string($tax['label']);
                 $data['cart_' . $i . '_unitprice'] = $tax_total;
                 $data['cart_' . $i . '_quantity'] = '1';
                 $data['cart_' . $i . '_type'] = '4';
                 $i++;
             }
         }
     }
     return $data;
 }
 /**
  * box_shipping function.
  *
  * @access private
  * @param mixed $package
  * @return void
  */
 private function box_shipping($package)
 {
     $requests = array();
     if (!class_exists('WC_Boxpack')) {
         include_once 'box-packer/class-wc-boxpack.php';
     }
     $boxpack = new WC_Boxpack();
     // Add Standard UPS boxes
     if (!empty($this->ups_packaging)) {
         foreach ($this->ups_packaging as $key => $box_code) {
             $box = $this->packaging[$box_code];
             $newbox = $boxpack->add_box($this->get_packaging_dimension($box['length']), $this->get_packaging_dimension($box['width']), $this->get_packaging_dimension($box['height']));
             $newbox->set_inner_dimensions($this->get_packaging_dimension($box['length']), $this->get_packaging_dimension($box['width']), $this->get_packaging_dimension($box['height']));
             $newbox->set_id($box['name']);
             if ($box['weight']) {
                 $newbox->set_max_weight($this->get_packaging_weight($box['weight']));
             }
         }
     }
     // Define boxes
     if (!empty($this->boxes)) {
         foreach ($this->boxes as $box) {
             $newbox = $boxpack->add_box($box['outer_length'], $box['outer_width'], $box['outer_height'], $box['box_weight']);
             $newbox->set_inner_dimensions($box['inner_length'], $box['inner_width'], $box['inner_height']);
             if ($box['max_weight']) {
                 $newbox->set_max_weight($box['max_weight']);
             }
         }
     }
     // Add items
     $ctr = 0;
     foreach ($package['contents'] as $item_id => $values) {
         $ctr++;
         if (!$values['data']->needs_shipping()) {
             $this->debug(sprintf(__('Product #%d is virtual. Skipping.', 'woocommerce-shipping-ups'), $ctr));
             continue;
         }
         if ($values['data']->length && $values['data']->height && $values['data']->width && $values['data']->weight) {
             $dimensions = array($values['data']->length, $values['data']->height, $values['data']->width);
             for ($i = 0; $i < $values['quantity']; $i++) {
                 $boxpack->add_item(number_format(wc_get_dimension($dimensions[2], $this->dim_unit), 2, '.', ''), number_format(wc_get_dimension($dimensions[1], $this->dim_unit), 2, '.', ''), number_format(wc_get_dimension($dimensions[0], $this->dim_unit), 2, '.', ''), number_format(wc_get_weight($values['data']->get_weight(), $this->weight_unit), 2, '.', ''), $values['data']->get_price());
             }
         } else {
             $this->debug(sprintf(__('UPS Parcel Packing Method is set to Pack into Boxes. Product #%d is missing dimensions. Aborting.', 'woocommerce-shipping-ups'), $ctr), 'error');
             return;
         }
     }
     // Pack it
     $boxpack->pack();
     // Get packages
     $box_packages = $boxpack->get_packages();
     $ctr = 0;
     foreach ($box_packages as $key => $box_package) {
         $ctr++;
         $this->debug("PACKAGE " . $ctr . " (" . $key . ")\n<pre>" . print_r($box_package, true) . "</pre>");
         $weight = $box_package->weight;
         $dimensions = array($box_package->length, $box_package->width, $box_package->height);
         sort($dimensions);
         // get weight, or 1 if less than 1 lbs.
         // $_weight = ( floor( $weight ) < 1 ) ? 1 : $weight;
         $request = '<Package>' . "\n";
         $request .= '	<PackagingType>' . "\n";
         $request .= '		<Code>02</Code>' . "\n";
         $request .= '		<Description>Package/customer supplied</Description>' . "\n";
         $request .= '	</PackagingType>' . "\n";
         $request .= '	<Description>Rate</Description>' . "\n";
         $request .= '	<Dimensions>' . "\n";
         $request .= '		<UnitOfMeasurement>' . "\n";
         $request .= '	 		<Code>' . $this->dim_unit . '</Code>' . "\n";
         $request .= '		</UnitOfMeasurement>' . "\n";
         $request .= '		<Length>' . $dimensions[2] . '</Length>' . "\n";
         $request .= '		<Width>' . $dimensions[1] . '</Width>' . "\n";
         $request .= '		<Height>' . $dimensions[0] . '</Height>' . "\n";
         $request .= '	</Dimensions>' . "\n";
         $request .= '	<PackageWeight>' . "\n";
         $request .= '		<UnitOfMeasurement>' . "\n";
         $request .= '			<Code>' . $this->weight_unit . '</Code>' . "\n";
         $request .= '		</UnitOfMeasurement>' . "\n";
         $request .= '		<Weight>' . $weight . '</Weight>' . "\n";
         $request .= '	</PackageWeight>' . "\n";
         if ($this->insuredvalue) {
             $request .= '	<PackageServiceOptions>' . "\n";
             // InsuredValue
             if ($this->insuredvalue) {
                 $request .= '		<InsuredValue>' . "\n";
                 $request .= '			<CurrencyCode>' . get_woocommerce_currency() . '</CurrencyCode>' . "\n";
                 $request .= '			<MonetaryValue>' . $box_package->value . '</MonetaryValue>' . "\n";
                 $request .= '		</InsuredValue>' . "\n";
             }
             $request .= '	</PackageServiceOptions>' . "\n";
         }
         $request .= '</Package>' . "\n";
         $requests[] = $request;
     }
     return $requests;
 }
Ejemplo n.º 7
0
 /**
  * Test wc_get_weight()
  *
  * @since 2.2
  */
 public function test_wc_get_weight()
 {
     // save default
     $default_unit = get_option('woocommerce_weight_unit');
     // kg (default unit)
     $this->assertEquals(10, wc_get_weight(10, 'kg'));
     $this->assertEquals(10000, wc_get_weight(10, 'g'));
     $this->assertEquals(22.046, wc_get_weight(10, 'lbs'));
     $this->assertEquals(352.74, wc_get_weight(10, 'oz'));
     // g
     update_option('woocommerce_weight_unit', 'g');
     $this->assertEquals(0.01, wc_get_weight(10, 'kg'));
     $this->assertEquals(10, wc_get_weight(10, 'g'));
     $this->assertEquals(0.022046, wc_get_weight(10, 'lbs'));
     $this->assertEquals(0.35274, wc_get_weight(10, 'oz'));
     // lbs
     update_option('woocommerce_weight_unit', 'lbs');
     $this->assertEquals(4.536, wc_get_weight(10, 'kg'));
     $this->assertEquals(4536, wc_get_weight(10, 'g'));
     $this->assertEquals(10, wc_get_weight(10, 'lbs'));
     $this->assertEquals(160.002864, wc_get_weight(10, 'oz'));
     // oz
     update_option('woocommerce_weight_unit', 'oz');
     $this->assertEquals(0.283, wc_get_weight(10, 'kg'));
     $this->assertEquals(283, wc_get_weight(10, 'g'));
     $this->assertEquals(0.6239018, wc_get_weight(10, 'lbs'));
     $this->assertEquals(10, wc_get_weight(10, 'oz'));
     // negative
     $this->assertEquals(0, wc_get_weight(-10, 'g'));
     // restore default
     update_option('woocommerce_weight_unit', $default_unit);
 }
 protected function frenet_calculate($package)
 {
     $values = array();
     $RecipientCEP = $package['destination']['postcode'];
     $RecipientCountry = $package['destination']['country'];
     // Checks if services and zipcode is empty.
     if (empty($RecipientCEP) && $RecipientCountry == 'BR') {
         if ('yes' == $this->debug) {
             $this->log->add($this->id, "ERRO: CEP destino não informado");
         }
         return $values;
     }
     if (empty($this->zip_origin)) {
         if ('yes' == $this->debug) {
             $this->log->add($this->id, "ERRO: CEP origem não configurado");
         }
         return $values;
     }
     // product array
     $shippingItemArray = array();
     $count = 0;
     // Shipping per item.
     foreach ($package['contents'] as $item_id => $values) {
         $product = $values['data'];
         $qty = $values['quantity'];
         if ('yes' == $this->debug) {
             $this->log->add($this->id, 'Product: ' . print_r($product, true));
         }
         $shippingItem = new stdClass();
         if ($qty > 0 && $product->needs_shipping()) {
             if (version_compare(WOOCOMMERCE_VERSION, '2.1', '>=')) {
                 $_height = wc_get_dimension($this->fix_format($product->height), 'cm');
                 $_width = wc_get_dimension($this->fix_format($product->width), 'cm');
                 $_length = wc_get_dimension($this->fix_format($product->length), 'cm');
                 $_weight = wc_get_weight($this->fix_format($product->weight), 'kg');
             } else {
                 $_height = woocommerce_get_dimension($this->fix_format($product->height), 'cm');
                 $_width = woocommerce_get_dimension($this->fix_format($product->width), 'cm');
                 $_length = woocommerce_get_dimension($this->fix_format($product->length), 'cm');
                 $_weight = woocommerce_get_weight($this->fix_format($product->weight), 'kg');
             }
             if (empty($_height)) {
                 $_height = $this->minimum_height;
             }
             if (empty($_width)) {
                 $_width = $this->minimum_width;
             }
             if (empty($_length)) {
                 $_length = $this->minimum_length;
             }
             if (empty($_weight)) {
                 $_weight = 1;
             }
             $shippingItem->Weight = $_weight * $qty;
             $shippingItem->Length = $_length;
             $shippingItem->Height = $_height;
             $shippingItem->Width = $_width;
             $shippingItem->Diameter = 0;
             $shippingItem->SKU = $product->get_sku();
             // wp_get_post_terms( your_id, 'product_cat' );
             $shippingItem->Category = '';
             $shippingItem->isFragile = false;
             if ('yes' == $this->debug) {
                 $this->log->add($this->id, 'shippingItem: ' . print_r($shippingItem, true));
             }
             $shippingItemArray[$count] = $shippingItem;
             $count++;
         }
     }
     if ('yes' == $this->debug) {
         $this->log->add($this->id, 'CEP ' . $package['destination']['postcode']);
     }
     $service_param = array('quoteRequest' => array('Username' => $this->login, 'Password' => $this->password, 'SellerCEP' => $this->zip_origin, 'RecipientCEP' => $RecipientCEP, 'RecipientDocument' => '', 'ShipmentInvoiceValue' => WC()->cart->cart_contents_total, 'ShippingItemArray' => $shippingItemArray, 'RecipientCountry' => $RecipientCountry));
     if ('yes' == $this->debug) {
         $this->log->add($this->id, 'Requesting the Frenet WebServices...');
         $this->log->add($this->id, print_r($service_param, true));
     }
     // Gets the WebServices response.
     $client = new SoapClient($this->webservice, array("soap_version" => SOAP_1_1, "trace" => 1));
     $response = $client->__soapCall("GetShippingQuote", array($service_param));
     if ('yes' == $this->debug) {
         $this->log->add($this->id, $client->__getLastRequest());
         $this->log->add($this->id, $client->__getLastResponse());
     }
     if (is_wp_error($response)) {
         if ('yes' == $this->debug) {
             $this->log->add($this->id, 'WP_Error: ' . $response->get_error_message());
         }
     } else {
         if (isset($response->GetShippingQuoteResult)) {
             if (count($response->GetShippingQuoteResult->ShippingSevicesArray->ShippingSevices) == 1) {
                 $servicosArray[0] = $response->GetShippingQuoteResult->ShippingSevicesArray->ShippingSevices;
             } else {
                 $servicosArray = $response->GetShippingQuoteResult->ShippingSevicesArray->ShippingSevices;
             }
             if (!empty($servicosArray)) {
                 foreach ($servicosArray as $servicos) {
                     if ('yes' == $this->debug) {
                         $this->log->add($this->id, 'Percorrendo os serviços retornados');
                     }
                     if (!isset($servicos->ServiceCode) || $servicos->ServiceCode . '' == '' || !isset($servicos->ShippingPrice)) {
                         continue;
                     }
                     $code = (string) $servicos->ServiceCode;
                     if ('yes' == $this->debug) {
                         $this->log->add($this->id, 'WebServices response [' . $servicos->ServiceDescription . ']: ' . print_r($servicos, true));
                     }
                     $values[$code] = $servicos;
                 }
             }
         }
     }
     return $values;
 }
Ejemplo n.º 9
0
 function calculate_shipping($package = array())
 {
     if (WOOTAN_DEBUG) {
         error_log("calculating shipping for " . serialize($package));
     }
     if ($this->is_package_po_box($package)) {
         if (WOOTAN_DEBUG) {
             error_log("-> package is PO, no shipping options");
         }
         return;
     }
     $wootan_containers = $this->get_containers();
     $wootan_methods = $this->get_methods();
     //determine precisely how many f***s to give
     if (WOOTAN_DEBUG) {
         error_log("-> determining number of f***s given");
     }
     $fucks_given = array();
     foreach ($wootan_methods as $code => $method) {
         if (array_intersect(array('min_total_container', 'max_total_container'), array_keys($method))) {
             $fucks_given['summary'] = true;
         }
         if (array_intersect(array('include_roles', 'exclude_roles'), array_keys($method))) {
             $fucks_given['tiers'] = true;
         }
     }
     if (isset($fucks_given['summary'])) {
         if (WOOTAN_DEBUG) {
             error_log("--> getting summary");
         }
         $summary = $this->get_summary($package['contents']);
         if ($summary) {
             if (WOOTAN_DEBUG) {
                 error_log("---> summary is: " . serialize($summary));
             }
         } else {
             if (WOOTAN_DEBUG) {
                 error_log("---> cannot get summary");
             }
             return;
         }
     }
     if (isset($fucks_given['tiers'])) {
         if (WOOTAN_DEBUG) {
             error_log("--> getting roles");
         }
         $user = new WP_User($package['user']['ID']);
         global $Lasercommerce_Tier_Tree;
         if (!isset($Lasercommerce_Tier_Tree)) {
             $Lasercommerce_Tier_Tree = new Lasercommerce_Tier_Tree();
         }
         $visibleTiers = $Lasercommerce_Tier_Tree->getVisibleTiers($user);
         $visibleTierIDs = $Lasercommerce_Tier_Tree->getTierIDs($visibleTiers);
         if (WOOTAN_DEBUG) {
             error_log("---> visible tiers are: " . serialize($visibleTierIDs));
         }
     }
     foreach ($wootan_methods as $code => $method) {
         $name = isset($method['title']) ? $method['title'] : $code;
         if (WOOTAN_DEBUG) {
             error_log("");
         }
         if (WOOTAN_DEBUG) {
             error_log("-> testing eligibility of " . $name);
         }
         //test dangerous
         if (isset($method['dangerous']) and $method['dangerous'] == 'N') {
             if (WOOTAN_DEBUG) {
                 error_log("--> testing dangerous criteria");
             }
             $dangerous = $this->is_package_dangerous($package);
             if ($dangerous) {
                 if (WOOTAN_DEBUG) {
                     error_log("--> failed danger criteria");
                 }
                 continue;
             } else {
                 if (WOOTAN_DEBUG) {
                     error_log("--> passed danger criteria");
                 }
             }
         }
         if (isset($method['include_roles'])) {
             if (WOOTAN_DEBUG) {
                 error_log("--> testing include role criteria");
             }
             if (array_intersect($method['include_roles'], $visibleTierIDs)) {
                 if (WOOTAN_DEBUG) {
                     error_log('---> user included');
                 }
             } else {
                 if (WOOTAN_DEBUG) {
                     error_log('---> user not included');
                 }
                 continue;
             }
         }
         if (isset($method['exclude_roles'])) {
             if (WOOTAN_DEBUG) {
                 error_log("--> testing exclude role criteria");
             }
             if (array_intersect($method['exclude_roles'], $visibleTierIDs)) {
                 if (WOOTAN_DEBUG) {
                     error_log('---> user excluded');
                 }
                 continue;
             } else {
                 if (WOOTAN_DEBUG) {
                     error_log('---> user not excluded');
                 }
             }
         }
         //test total containers
         if (isset($method['min_total_container']) or isset($method['max_total_container'])) {
             if (WOOTAN_DEBUG) {
                 error_log("--> testing total_container criteria");
             }
             $cube_length = pow($summary['total_volume'], 1.0 / 3.0) * 1000;
             $total_item = array('kilo' => $summary['total_weight'], 'length' => $cube_length, 'width' => $cube_length, 'height' => $cube_length);
             if (isset($method['min_total_container'])) {
                 $container = $method['min_total_container'];
                 if (WOOTAN_DEBUG) {
                     error_log("--> testing min_total_container criteria: " . $method['min_total_container']);
                 }
                 if (in_array($container, array_keys($wootan_containers))) {
                     $result = $this->fits_in_container($total_item, $wootan_containers[$container]);
                 } else {
                     if (WOOTAN_DEBUG) {
                         error_log("---> container does not exist: " . $container);
                     }
                     continue;
                 }
                 if (!$result) {
                     if (WOOTAN_DEBUG) {
                         error_log("---> passed min_total_container criteria: " . $result);
                     }
                 } else {
                     if (WOOTAN_DEBUG) {
                         error_log("---> failed min_total_container criteria: " . $result);
                     }
                     continue;
                 }
             }
             if (isset($method['max_total_container'])) {
                 $container = $method['max_total_container'];
                 if (WOOTAN_DEBUG) {
                     error_log("--> testing max_total_container criteria: " . $container);
                 }
                 if (in_array($container, array_keys($wootan_containers))) {
                     $result = $this->fits_in_container($total_item, $wootan_containers[$container]);
                 } else {
                     if (WOOTAN_DEBUG) {
                         error_log("---> container does not exist: " . $container);
                     }
                     continue;
                 }
                 if ($result) {
                     if (WOOTAN_DEBUG) {
                         error_log("---> passed max_total_container criteria: " . $result);
                     }
                 } else {
                     if (WOOTAN_DEBUG) {
                         error_log("---> failed max_total_container criteria: " . $result);
                     }
                     continue;
                 }
             }
         }
         if (isset($method['max_item_container'])) {
             $container = $method['max_item_container'];
             if (WOOTAN_DEBUG) {
                 error_log("--> testing item_container criteria: " . $container);
             }
             $fits = true;
             foreach ($package['contents'] as $line) {
                 if (WOOTAN_DEBUG) {
                     error_log("---> analysing line: " . $line['product_id']);
                 }
                 if ($line['data']->has_weight()) {
                     $item_weight = wc_get_weight($line['data']->get_weight(), 'kg');
                 } else {
                     // throw exception because can't get weight
                 }
                 if ($line['data']->has_dimensions()) {
                     $item_dim = explode(' x ', $line['data']->get_dimensions());
                     $dimension_unit = get_option('woocommerce_dimension_unit');
                     $item_dim[2] = str_replace(' ' . $dimension_unit, '', $item_dim[2]);
                 } else {
                     // throw exception because can't get dimensions
                 }
                 $item = array('kilo' => $item_weight, 'length' => $item_dim[0], 'width' => $item_dim[1], 'height' => $item_dim[2]);
                 if (in_array($container, array_keys($wootan_containers))) {
                     $result = $this->fits_in_container($item, $wootan_containers[$container]);
                     if ($result) {
                         if (WOOTAN_DEBUG) {
                             error_log("---> passed max_item_container criteria: " . $result);
                         }
                     } else {
                         if (WOOTAN_DEBUG) {
                             error_log("---> failed max_item_container criteria: " . $result);
                         }
                         $fits = false;
                         break;
                     }
                 } else {
                     if (WOOTAN_DEBUG) {
                         error_log("---> container does not exist: " . $container);
                     }
                     $fits = false;
                     break;
                 }
             }
             if (!$fits) {
                 continue;
             }
         }
         if (isset($method['elig_fn'])) {
             if (WOOTAN_DEBUG) {
                 error_log("--> testing eligibility criteria");
             }
             $result = call_user_func($method['elig_fn'], $package);
             if ($result) {
                 if (WOOTAN_DEBUG) {
                     error_log("---> passed eligibility criteria: " . serialize($result));
                 }
             } else {
                 if (WOOTAN_DEBUG) {
                     error_log("---> failed eligibility criteria: " . serialize($result));
                 }
                 continue;
             }
         }
         if (isset($method['notify_shipping_upgrade'])) {
             if (WOOTAN_DEBUG) {
                 error_log("--> adding shipping upgrade notification");
             }
             $this->write_free_fright_notice($package);
         }
         //gauntlet passed, add rate
         if (WOOTAN_DEBUG) {
             error_log("-> method passed");
         }
         if (isset($method['cost_fn'])) {
             $cost = call_user_func($method['cost_fn'], $package);
             if (!is_numeric($cost)) {
                 if (WOOTAN_DEBUG) {
                     error_log("-> cost could not be determined!");
                 }
                 continue;
             }
         } else {
             if (WOOTAN_DEBUG) {
                 error_log("-> No Cost function set!");
             }
             continue;
         }
         $this->add_rate(array('id' => $this->get_rate_id($code), 'label' => $name, 'cost' => $cost, 'package' => $package));
     }
 }
 /**
  * Retrieves order items and packs them into boxes by dimensions
  *
  * @params mixed $order for order we are working with
  * @params array $shipment for order we are working with
  *
  * @return mixed array
  */
 public static function get_packages($order, $shipment)
 {
     global $woocommerce;
     //load box packer if not already loaded
     if (!class_exists('WC_Boxpack')) {
         include_once WP_CONTENT_DIR . '/plugins/woocommerce-shipping-usps/includes/box-packer/class-wc-boxpack.php';
     }
     //pack items if not set
     if (!isset($shipment['_packages'])) {
         $boxpack = new WC_Boxpack();
         self::$shipper = self::get_shipper($order);
         //get boxes from shipper class settings
         $boxes = self::$shipper->get_boxes();
         //Add Standard and Custom Boxes
         if (!empty($boxes)) {
             foreach ($boxes as $key => $box) {
                 $newbox = $boxpack->add_box($box['outer_length'], $box['outer_width'], $box['outer_height'], $box['box_weight']);
                 $newbox->set_inner_dimensions($box['inner_length'], $box['inner_width'], $box['inner_height']);
                 $newbox->set_max_weight($box['max_weight']);
                 $newbox->set_id = $key;
             }
         }
         //retrieve order items for packing
         $items = $order->get_items();
         //add order items
         foreach ($items as $key => $item) {
             $product = $order->get_product_from_item($item);
             $item_key = $key;
             $dim = explode(' ', str_replace(' x ', ' ', $product->get_dimensions()));
             for ($i = 0; $i < $item['qty']; ++$i) {
                 $boxpack->add_item(number_format(wc_get_dimension($dim[0], 'in'), 2), number_format(wc_get_dimension($dim[1], 'in'), 2), number_format(wc_get_dimension($dim[2], 'in'), 2), number_format(wc_get_weight($product->get_weight(), 'lbs'), 2), $product->get_price(), array('id' => $item['variation_id'] ? $item['variation_id'] : $item['product_id']));
             }
         }
         //Pack Items into boxes & return
         $boxpack->pack();
         //get packed items
         $shipment['_packages'] = $boxpack->get_packages();
     }
     //normalize array for later use
     if (!is_array($shipment['_packages'][0]->packed[0])) {
         //Parse through items and convert std objects to arrays
         foreach ($shipment['_packages'] as $package) {
             //if no tracking number set
             if (!isset($package->id) || empty($package->id)) {
                 $package->id = 'No Tracking# Assigned';
             }
             //remove unnecessay data
             unset($package->unpacked);
             //convert WC_Item to array
             foreach ($package->packed as $key => $line) {
                 $line = (array) $line;
                 array_shift($line);
                 $package->packed[$key] = $line;
             }
         }
         //save changes to DB
         //self::update_shipment( $order->id, $shipment );
     }
     //return shipment for further processing
     return $shipment;
 }
 /**
  * Do the request
  */
 public function request()
 {
     global $wpdb;
     $this->validate_input(array("start_date", "end_date"));
     header('Content-Type: text/xml');
     $xml = new DOMDocument('1.0', 'utf-8');
     $xml->formatOutput = true;
     $page = max(1, isset($_GET['page']) ? absint($_GET['page']) : 1);
     $exported = 0;
     $tz_offset = get_option('gmt_offset') * 3600;
     $raw_start_date = wc_clean(urldecode($_GET['start_date']));
     $raw_end_date = wc_clean(urldecode($_GET['end_date']));
     // Parse start and end date
     if ($raw_start_date && false === strtotime($raw_start_date)) {
         $month = substr($raw_start_date, 0, 2);
         $day = substr($raw_start_date, 2, 2);
         $year = substr($raw_start_date, 4, 4);
         $time = substr($raw_start_date, 9, 4);
         $start_date = gmdate("Y-m-d H:i:s", strtotime($year . '-' . $month . '-' . $day . ' ' . $time));
     } else {
         $start_date = gmdate("Y-m-d H:i:s", strtotime($raw_start_date));
     }
     if ($raw_end_date && false === strtotime($raw_end_date)) {
         $month = substr($raw_end_date, 0, 2);
         $day = substr($raw_end_date, 2, 2);
         $year = substr($raw_end_date, 4, 4);
         $time = substr($raw_end_date, 9, 4);
         $end_date = gmdate("Y-m-d H:i:s", strtotime($year . '-' . $month . '-' . $day . ' ' . $time));
     } else {
         $end_date = gmdate("Y-m-d H:i:s", strtotime($raw_end_date));
     }
     $order_ids = $wpdb->get_col($wpdb->prepare("\n\t\t\t\t\tSELECT ID FROM {$wpdb->posts}\n\t\t\t\t\tWHERE post_type = 'shop_order'\n\t\t\t\t\tAND post_status IN ( '" . implode("','", WC_ShipStation_Integration::$export_statuses) . "' )\n\t\t\t\t\tAND %s <= post_modified_gmt\n\t\t\t\t\tAND post_modified_gmt <= %s\n\t\t\t\t\tORDER BY post_modified_gmt DESC\n\t\t\t\t\tLIMIT %d, %d\n\t\t\t\t", $start_date, $end_date, WC_SHIPSTATION_EXPORT_LIMIT * ($page - 1), WC_SHIPSTATION_EXPORT_LIMIT));
     $max_results = $wpdb->get_var($wpdb->prepare("\n\t\t\t\t\tSELECT COUNT(ID) FROM {$wpdb->posts}\n\t\t\t\t\tWHERE post_type = 'shop_order'\n\t\t\t\t\tAND post_status IN ( '" . implode("','", WC_ShipStation_Integration::$export_statuses) . "' )\n\t\t\t\t\tAND %s <= post_modified_gmt\n\t\t\t\t\tAND post_modified_gmt <= %s\n\t\t\t\t", $start_date, $end_date));
     $orders_xml = $xml->createElement("Orders");
     foreach ($order_ids as $order_id) {
         if (!apply_filters('woocommerce_shipstation_export_order', true, $order_id)) {
             continue;
         }
         $order = wc_get_order($order_id);
         $order_xml = $xml->createElement("Order");
         $this->xml_append($order_xml, 'OrderNumber', ltrim($order->get_order_number(), '#'));
         $this->xml_append($order_xml, 'OrderDate', gmdate("m/d/Y H:i", strtotime($order->order_date) - $tz_offset), false);
         $this->xml_append($order_xml, 'OrderStatus', $order->get_status());
         $this->xml_append($order_xml, 'LastModified', gmdate("m/d/Y H:i", strtotime($order->modified_date) - $tz_offset), false);
         $this->xml_append($order_xml, 'ShippingMethod', implode(' | ', $this->get_shipping_methods($order)));
         $this->xml_append($order_xml, 'OrderTotal', $order->get_total(), false);
         $this->xml_append($order_xml, 'TaxAmount', $order->get_total_tax(), false);
         if (class_exists('WC_COG')) {
             $this->xml_append($order_xml, 'CostOfGoods', wc_format_decimal($order->wc_cog_order_total_cost), false);
         }
         $this->xml_append($order_xml, 'ShippingAmount', $order->get_total_shipping(), false);
         $this->xml_append($order_xml, 'CustomerNotes', $order->customer_note);
         $this->xml_append($order_xml, 'InternalNotes', implode(" | ", $this->get_order_notes($order)));
         // Custom fields - 1 is used for coupon codes
         $this->xml_append($order_xml, 'CustomField1', implode(" | ", $order->get_used_coupons()));
         // Custom fields 2 and 3 can be mapped to a custom field via the following filters
         if ($meta_key = apply_filters('woocommerce_shipstation_export_custom_field_2', '')) {
             $this->xml_append($order_xml, 'CustomField2', apply_filters('woocommerce_shipstation_export_custom_field_2_value', get_post_meta($order_id, $meta_key, true), $order_id));
         }
         if ($meta_key = apply_filters('woocommerce_shipstation_export_custom_field_3', '')) {
             $this->xml_append($order_xml, 'CustomField3', apply_filters('woocommerce_shipstation_export_custom_field_3_value', get_post_meta($order_id, $meta_key, true), $order_id));
         }
         // Customer data
         $customer_xml = $xml->createElement("Customer");
         $this->xml_append($customer_xml, 'CustomerCode', $order->billing_email);
         $billto_xml = $xml->createElement("BillTo");
         $this->xml_append($billto_xml, 'Name', $order->billing_first_name . " " . $order->billing_last_name);
         $this->xml_append($billto_xml, 'Company', $order->billing_company);
         $this->xml_append($billto_xml, 'Phone', $order->billing_phone);
         $this->xml_append($billto_xml, 'Email', $order->billing_email);
         $customer_xml->appendChild($billto_xml);
         $shipto_xml = $xml->createElement("ShipTo");
         if (empty($order->shipping_country)) {
             $this->xml_append($shipto_xml, 'Name', $order->billing_first_name . " " . $order->billing_last_name);
             $this->xml_append($shipto_xml, 'Company', $order->billing_company);
             $this->xml_append($shipto_xml, 'Address1', $order->billing_address_1);
             $this->xml_append($shipto_xml, 'Address2', $order->billing_address_2);
             $this->xml_append($shipto_xml, 'City', $order->billing_city);
             $this->xml_append($shipto_xml, 'State', $order->billing_state);
             $this->xml_append($shipto_xml, 'PostalCode', $order->billing_postcode);
             $this->xml_append($shipto_xml, 'Country', $order->billing_country);
             $this->xml_append($shipto_xml, 'Phone', $order->billing_phone);
         } else {
             $this->xml_append($shipto_xml, 'Name', $order->shipping_first_name . " " . $order->shipping_last_name);
             $this->xml_append($shipto_xml, 'Company', $order->shipping_company);
             $this->xml_append($shipto_xml, 'Address1', $order->shipping_address_1);
             $this->xml_append($shipto_xml, 'Address2', $order->shipping_address_2);
             $this->xml_append($shipto_xml, 'City', $order->shipping_city);
             $this->xml_append($shipto_xml, 'State', $order->shipping_state);
             $this->xml_append($shipto_xml, 'PostalCode', $order->shipping_postcode);
             $this->xml_append($shipto_xml, 'Country', $order->shipping_country);
             $this->xml_append($shipto_xml, 'Phone', $order->billing_phone);
         }
         $customer_xml->appendChild($shipto_xml);
         $order_xml->appendChild($customer_xml);
         // Item data
         $found_item = false;
         $items_xml = $xml->createElement("Items");
         foreach ($order->get_items() as $item_id => $item) {
             $product = $order->get_product_from_item($item);
             if (!$product || !$product->needs_shipping()) {
                 continue;
             }
             $found_item = true;
             $item_xml = $xml->createElement("Item");
             $image_id = $product->get_image_id();
             if ($image_id) {
                 $image_url = current(wp_get_attachment_image_src($image_id, 'shop_thumbnail'));
             } else {
                 $image_url = '';
             }
             $this->xml_append($item_xml, 'LineItemID', $item_id);
             $this->xml_append($item_xml, 'SKU', $product->get_sku());
             $this->xml_append($item_xml, 'Name', $product->get_title());
             $this->xml_append($item_xml, 'ImageUrl', $image_url);
             $this->xml_append($item_xml, 'Weight', wc_get_weight($product->get_weight(), 'oz'), false);
             $this->xml_append($item_xml, 'WeightUnits', 'Ounces', false);
             $this->xml_append($item_xml, 'Quantity', $item['qty'], false);
             $this->xml_append($item_xml, 'UnitPrice', $order->get_item_subtotal($item, false, true), false);
             if ($item['item_meta']) {
                 if (version_compare(WC_VERSION, '2.4.0', '<')) {
                     $item_meta = new WC_Order_Item_Meta($item['item_meta']);
                 } else {
                     $item_meta = new WC_Order_Item_Meta($item);
                 }
                 $formatted_meta = $item_meta->get_formatted('_');
                 if (!empty($formatted_meta)) {
                     $options_xml = $xml->createElement("Options");
                     foreach ($formatted_meta as $meta_key => $meta) {
                         $option_xml = $xml->createElement("Option");
                         $this->xml_append($option_xml, 'Name', $meta['label']);
                         $this->xml_append($option_xml, 'Value', $meta['value']);
                         $options_xml->appendChild($option_xml);
                     }
                     $item_xml->appendChild($options_xml);
                 }
             }
             $items_xml->appendChild($item_xml);
         }
         if (!$found_item) {
             continue;
         }
         // Append cart level discount line
         if ($order->get_total_discount()) {
             $item_xml = $xml->createElement("Item");
             $this->xml_append($item_xml, 'SKU', "total-discount");
             $this->xml_append($item_xml, 'Name', __('Total Discount', 'woocommerce-shipstation'));
             $this->xml_append($item_xml, 'Adjustment', "true", false);
             $this->xml_append($item_xml, 'Quantity', 1, false);
             $this->xml_append($item_xml, 'UnitPrice', $order->get_total_discount() * -1, false);
             $items_xml->appendChild($item_xml);
         }
         // Append items XML
         $order_xml->appendChild($items_xml);
         $orders_xml->appendChild($order_xml);
         $exported++;
     }
     $orders_xml->setAttribute("page", $page);
     $orders_xml->setAttribute("pages", ceil($max_results / WC_SHIPSTATION_EXPORT_LIMIT));
     $xml->appendChild($orders_xml);
     echo $xml->saveXML();
     $this->log(sprintf(__("Exported %s orders", 'woocommerce-shipstation'), $exported));
 }
 public function get_goods()
 {
     $goods = array();
     $count = 0;
     foreach ($this->package['contents'] as $item_id => $values) {
         $product = $values['data'];
         $qty = $values['quantity'];
         if ($qty > 0 && $product->needs_shipping()) {
             $_height = wc_get_dimension($this->fix_format($product->height), 'cm');
             $_width = wc_get_dimension($this->fix_format($product->width), 'cm');
             $_length = wc_get_dimension($this->fix_format($product->length), 'cm');
             $_weight = wc_get_weight($this->fix_format($product->weight), 'kg');
             $goods[$count]['height'] = !empty($_height) && $_height > 0 ? $_height : $this->minimum_height;
             $goods[$count]['width'] = !empty($_width) && $_width > 0 ? $_width : $this->minimum_width;
             $goods[$count]['length'] = !empty($_length) && $_length > 0 ? $_length : $this->minimum_length;
             $goods[$count]['weight'] = !empty($_weight) && $_weight > 0 ? $_weight : $this->minimum_weight;
             if ($qty > 1) {
                 $n = $count;
                 for ($i = 0; $i < $qty; $i++) {
                     $goods[$n]['height'] = !empty($_height) && $_height > 0 ? $_height : $this->minimum_height;
                     $goods[$n]['width'] = !empty($_width) && $_width > 0 ? $_width : $this->minimum_width;
                     $goods[$n]['length'] = !empty($_length) && $_length > 0 ? $_length : $this->minimum_length;
                     $goods[$n]['weight'] = !empty($_weight) && $_weight > 0 ? $_weight : $this->minimum_weight;
                     $n++;
                 }
                 $count = $n;
             }
             $count++;
         }
     }
     return $goods;
 }
Ejemplo n.º 13
0
 /**
  * calculate_flat_rate_box_rate function.
  *
  * @access private
  * @param mixed $package
  * @return void
  */
 private function calculate_flat_rate_box_rate($package, $box_type = 'priority')
 {
     global $woocommerce;
     $cost = 0;
     if (!class_exists('WF_Boxpack')) {
         include_once 'class-wf-packing.php';
     }
     $boxpack = new WF_Boxpack();
     $domestic = in_array($package['destination']['country'], $this->domestic) ? true : false;
     $added = array();
     // Define boxes
     foreach ($this->flat_rate_boxes as $service_code => $box) {
         if ($box['box_type'] != $box_type) {
             continue;
         }
         $domestic_service = substr($service_code, 0, 1) == 'd' ? true : false;
         if ($domestic && $domestic_service || !$domestic && !$domestic_service) {
             $newbox = $boxpack->add_box($box['length'], $box['width'], $box['height']);
             $newbox->set_max_weight($box['weight']);
             $newbox->set_id($service_code);
             if (isset($box['volume']) && method_exists($newbox, 'set_volume')) {
                 $newbox->set_volume($box['volume']);
             }
             if (isset($box['type']) && method_exists($newbox, 'set_type')) {
                 $newbox->set_type($box['type']);
             }
             $added[] = $service_code . ' - ' . $box['name'] . ' (' . $box['length'] . 'x' . $box['width'] . 'x' . $box['height'] . ')';
         }
     }
     $this->debug('Calculating USPS Flat Rate with boxes: ' . implode(', ', $added));
     // Add items
     foreach ($package['contents'] as $item_id => $values) {
         if (!$values['data']->needs_shipping()) {
             continue;
         }
         if ($values['data']->length && $values['data']->height && $values['data']->width && $values['data']->weight) {
             $dimensions = array($values['data']->length, $values['data']->height, $values['data']->width);
         } else {
             $this->debug(sprintf(__('Product #%d is missing dimensions! Using 1x1x1.', 'usps-woocommerce-shipping'), $item_id), 'error');
             $dimensions = array(1, 1, 1);
         }
         for ($i = 0; $i < $values['quantity']; $i++) {
             $boxpack->add_item(wc_get_dimension($dimensions[2], 'in'), wc_get_dimension($dimensions[1], 'in'), wc_get_dimension($dimensions[0], 'in'), wc_get_weight($values['data']->get_weight(), 'lbs'), $values['data']->get_price(), $item_id);
         }
     }
     // Pack it
     $boxpack->pack();
     // Get packages
     $flat_packages = $boxpack->get_packages();
     if ($flat_packages) {
         foreach ($flat_packages as $flat_package) {
             if (isset($this->flat_rate_boxes[$flat_package->id])) {
                 $this->debug('Packed ' . $flat_package->id . ' - ' . $this->flat_rate_boxes[$flat_package->id]['name']);
                 // Get pricing
                 $box_pricing = $this->settings['shippingrates'] == 'ONLINE' && isset($this->flat_rate_pricing[$flat_package->id]['online']) ? $this->flat_rate_pricing[$flat_package->id]['online'] : $this->flat_rate_pricing[$flat_package->id]['retail'];
                 if (is_array($box_pricing)) {
                     if (isset($box_pricing[$package['destination']['country']])) {
                         $box_cost = $box_pricing[$package['destination']['country']];
                     } else {
                         $box_cost = $box_pricing['*'];
                     }
                 } else {
                     $box_cost = $box_pricing;
                 }
                 // Fees
                 if (!empty($this->flat_rate_fee)) {
                     $sym = substr($this->flat_rate_fee, 0, 1);
                     $fee = $sym == '-' ? substr($this->flat_rate_fee, 1) : $this->flat_rate_fee;
                     if (strstr($fee, '%')) {
                         $fee = str_replace('%', '', $fee);
                         if ($sym == '-') {
                             $box_cost = $box_cost - $box_cost * (floatval($fee) / 100);
                         } else {
                             $box_cost = $box_cost + $box_cost * (floatval($fee) / 100);
                         }
                     } else {
                         if ($sym == '-') {
                             $box_cost = $box_cost - $fee;
                         } else {
                             $box_cost += $fee;
                         }
                     }
                     if ($box_cost < 0) {
                         $box_cost = 0;
                     }
                 }
                 $cost += $box_cost;
             } else {
                 return;
                 // no match
             }
         }
         if ($box_type == 'express') {
             $label = !empty($this->settings['flat_rate_express_title']) ? $this->settings['flat_rate_express_title'] : ($domestic ? '' : 'International ') . 'Priority Mail Express Flat Rate&#0174;';
         } else {
             $label = !empty($this->settings['flat_rate_priority_title']) ? $this->settings['flat_rate_priority_title'] : ($domestic ? '' : 'International ') . 'Priority Mail Flat Rate&#0174;';
         }
         return array('id' => $this->id . ':flat_rate_box_' . $box_type, 'label' => $label, 'cost' => $cost, 'sort' => $box_type == 'express' ? -1 : -2);
     }
 }