Ejemplo n.º 1
0
 public function getInfoFromOrder($orderID, &$delivery)
 {
     $mOrder = new Order((int) $orderID);
     if (NULL !== $mOrder) {
         $mDeliveryAddress = new Address($mOrder->id_address_delivery);
         if (NULL !== $mDeliveryAddress) {
             // receiver address information
             $delivery["receiver_firstname"] = $mDeliveryAddress->firstname;
             $delivery["receiver_name"] = $mDeliveryAddress->lastname;
             if ($mDeliveryAddress->company) {
                 $delivery["receiver_company"] = $mDeliveryAddress->company;
             }
             $delivery["receiver_address"] = $mDeliveryAddress->address1;
             if ($mDeliveryAddress->address2) {
                 $delivery["receiver_address2"] = $mDeliveryAddress->address2;
             }
             $delivery["receiver_zipcode"] = $mDeliveryAddress->postcode;
             $delivery["receiver_city"] = $mDeliveryAddress->city;
             if ($mDeliveryAddress->phone_mobile) {
                 $delivery["receiver_cellphone"] = $mDeliveryAddress->phone_mobile;
             }
             if ($mDeliveryAddress->phone) {
                 $delivery["receiver_phone"] = $mDeliveryAddress->phone;
             }
             if ($mDeliveryAddress->other) {
                 $delivery["receiver_comments"] = $mDeliveryAddress->other;
             }
         }
         $delivery["packet_reference"] = $mOrder->id;
         $id_cart = (int) $mOrder->id_cart;
         /* set weight */
         $cart = new Cart($id_cart);
         $delivery['weight'] = Configuration::get('PS_WEIGHT_UNIT') == 'g' ? (double) ($cart->getTotalWeight() / 1000) : (double) $cart->getTotalWeight();
         /* set dejalaProductID and sender_availability = shipping date */
         $djlCart = new DejalaCart($id_cart);
         if (!is_null($djlCart) && !is_null($djlCart->id)) {
             $mDejalaProductID = (int) $djlCart->id_dejala_product;
             $delivery["product_id"] = (int) $mDejalaProductID;
             $mShippingDate = $djlCart->shipping_date;
             if (is_null($mShippingDate) || empty($mShippingDate)) {
                 $mShippingDate = 0;
             }
             $delivery["shipping_start_utc"] = $mShippingDate;
         }
     }
     return $delivery;
 }
Ejemplo n.º 2
0
 public function ajaxProcessAddProductOnOrder()
 {
     // Load object
     $order = new Order((int) Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The order object cannot be loaded.'))));
     }
     if ($order->hasBeenShipped()) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('You cannot add products to delivered orders. '))));
     }
     $product_informations = $_POST['add_product'];
     if (isset($_POST['add_invoice'])) {
         $invoice_informations = $_POST['add_invoice'];
     } else {
         $invoice_informations = array();
     }
     $product = new Product($product_informations['product_id'], false, $order->id_lang);
     if (!Validate::isLoadedObject($product)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The product object cannot be loaded.'))));
     }
     if (isset($product_informations['product_attribute_id']) && $product_informations['product_attribute_id']) {
         $combination = new Combination($product_informations['product_attribute_id']);
         if (!Validate::isLoadedObject($combination)) {
             die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The combination object cannot be loaded.'))));
         }
     }
     // Total method
     $total_method = Cart::BOTH_WITHOUT_SHIPPING;
     // Create new cart
     $cart = new Cart();
     $cart->id_shop_group = $order->id_shop_group;
     $cart->id_shop = $order->id_shop;
     $cart->id_customer = $order->id_customer;
     $cart->id_carrier = $order->id_carrier;
     $cart->id_address_delivery = $order->id_address_delivery;
     $cart->id_address_invoice = $order->id_address_invoice;
     $cart->id_currency = $order->id_currency;
     $cart->id_lang = $order->id_lang;
     $cart->secure_key = $order->secure_key;
     // Save new cart
     $cart->add();
     // Save context (in order to apply cart rule)
     $this->context->cart = $cart;
     $this->context->customer = new Customer($order->id_customer);
     // always add taxes even if there are not displayed to the customer
     $use_taxes = true;
     $initial_product_price_tax_incl = Product::getPriceStatic($product->id, $use_taxes, isset($combination) ? $combination->id : null, 2, null, false, true, 1, false, $order->id_customer, $cart->id, $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)});
     // Creating specific price if needed
     if ($product_informations['product_price_tax_incl'] != $initial_product_price_tax_incl) {
         $specific_price = new SpecificPrice();
         $specific_price->id_shop = 0;
         $specific_price->id_shop_group = 0;
         $specific_price->id_currency = 0;
         $specific_price->id_country = 0;
         $specific_price->id_group = 0;
         $specific_price->id_customer = $order->id_customer;
         $specific_price->id_product = $product->id;
         if (isset($combination)) {
             $specific_price->id_product_attribute = $combination->id;
         } else {
             $specific_price->id_product_attribute = 0;
         }
         $specific_price->price = $product_informations['product_price_tax_excl'];
         $specific_price->from_quantity = 1;
         $specific_price->reduction = 0;
         $specific_price->reduction_type = 'amount';
         $specific_price->from = '0000-00-00 00:00:00';
         $specific_price->to = '0000-00-00 00:00:00';
         $specific_price->add();
     }
     // Add product to cart
     $update_quantity = $cart->updateQty($product_informations['product_quantity'], $product->id, isset($product_informations['product_attribute_id']) ? $product_informations['product_attribute_id'] : null, isset($combination) ? $combination->id : null, 'up', 0, new Shop($cart->id_shop));
     if ($update_quantity < 0) {
         // If product has attribute, minimal quantity is set with minimal quantity of attribute
         $minimal_quantity = $product_informations['product_attribute_id'] ? Attribute::getAttributeMinimalQty($product_informations['product_attribute_id']) : $product->minimal_quantity;
         die(Tools::jsonEncode(array('error' => sprintf(Tools::displayError('You must add %d minimum quantity', false), $minimal_quantity))));
     } elseif (!$update_quantity) {
         die(Tools::jsonEncode(array('error' => Tools::displayError('You already have the maximum quantity available for this product.', false))));
     }
     // If order is valid, we can create a new invoice or edit an existing invoice
     if ($order->hasInvoice()) {
         $order_invoice = new OrderInvoice($product_informations['invoice']);
         // Create new invoice
         if ($order_invoice->id == 0) {
             // If we create a new invoice, we calculate shipping cost
             $total_method = Cart::BOTH;
             // Create Cart rule in order to make free shipping
             if (isset($invoice_informations['free_shipping']) && $invoice_informations['free_shipping']) {
                 $cart_rule = new CartRule();
                 $cart_rule->id_customer = $order->id_customer;
                 $cart_rule->name = array(Configuration::get('PS_LANG_DEFAULT') => $this->l('[Generated] CartRule for Free Shipping'));
                 $cart_rule->date_from = date('Y-m-d H:i:s', time());
                 $cart_rule->date_to = date('Y-m-d H:i:s', time() + 24 * 3600);
                 $cart_rule->quantity = 1;
                 $cart_rule->quantity_per_user = 1;
                 $cart_rule->minimum_amount_currency = $order->id_currency;
                 $cart_rule->reduction_currency = $order->id_currency;
                 $cart_rule->free_shipping = true;
                 $cart_rule->active = 1;
                 $cart_rule->add();
                 // Add cart rule to cart and in order
                 $cart->addCartRule($cart_rule->id);
                 $values = array('tax_incl' => $cart_rule->getContextualValue(true), 'tax_excl' => $cart_rule->getContextualValue(false));
                 $order->addCartRule($cart_rule->id, $cart_rule->name[Configuration::get('PS_LANG_DEFAULT')], $values);
             }
             $order_invoice->id_order = $order->id;
             if ($order_invoice->number) {
                 Configuration::updateValue('PS_INVOICE_START_NUMBER', false, false, null, $order->id_shop);
             } else {
                 $order_invoice->number = Order::getLastInvoiceNumber() + 1;
             }
             $invoice_address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)});
             $carrier = new Carrier((int) $order->id_carrier);
             $tax_calculator = $carrier->getTaxCalculator($invoice_address);
             $order_invoice->total_paid_tax_excl = Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
             $order_invoice->total_paid_tax_incl = Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
             $order_invoice->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
             $order_invoice->total_products_wt = (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
             $order_invoice->total_shipping_tax_excl = (double) $cart->getTotalShippingCost(null, false);
             $order_invoice->total_shipping_tax_incl = (double) $cart->getTotalShippingCost();
             $order_invoice->total_wrapping_tax_excl = abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING));
             $order_invoice->total_wrapping_tax_incl = abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order_invoice->shipping_tax_computation_method = (int) $tax_calculator->computation_method;
             // Update current order field, only shipping because other field is updated later
             $order->total_shipping += $order_invoice->total_shipping_tax_incl;
             $order->total_shipping_tax_excl += $order_invoice->total_shipping_tax_excl;
             $order->total_shipping_tax_incl += $use_taxes ? $order_invoice->total_shipping_tax_incl : $order_invoice->total_shipping_tax_excl;
             $order->total_wrapping += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order->total_wrapping_tax_excl += abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING));
             $order->total_wrapping_tax_incl += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order_invoice->add();
             $order_invoice->saveCarrierTaxCalculator($tax_calculator->getTaxesAmount($order_invoice->total_shipping_tax_excl));
             $order_carrier = new OrderCarrier();
             $order_carrier->id_order = (int) $order->id;
             $order_carrier->id_carrier = (int) $order->id_carrier;
             $order_carrier->id_order_invoice = (int) $order_invoice->id;
             $order_carrier->weight = (double) $cart->getTotalWeight();
             $order_carrier->shipping_cost_tax_excl = (double) $order_invoice->total_shipping_tax_excl;
             $order_carrier->shipping_cost_tax_incl = $use_taxes ? (double) $order_invoice->total_shipping_tax_incl : (double) $order_invoice->total_shipping_tax_excl;
             $order_carrier->add();
         } else {
             $order_invoice->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
             $order_invoice->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
             $order_invoice->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
             $order_invoice->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
             $order_invoice->update();
         }
     }
     // Create Order detail information
     $order_detail = new OrderDetail();
     $order_detail->createList($order, $cart, $order->getCurrentOrderState(), $cart->getProducts(), isset($order_invoice) ? $order_invoice->id : 0, $use_taxes, (int) Tools::getValue('add_product_warehouse'));
     // update totals amount of order
     $order->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
     $order->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
     $order->total_paid += Tools::ps_round((double) $cart->getOrderTotal(true, $total_method), 2);
     $order->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
     $order->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
     if (isset($order_invoice) && Validate::isLoadedObject($order_invoice)) {
         $order->total_shipping = $order_invoice->total_shipping_tax_incl;
         $order->total_shipping_tax_incl = $order_invoice->total_shipping_tax_incl;
         $order->total_shipping_tax_excl = $order_invoice->total_shipping_tax_excl;
     }
     // discount
     $order->total_discounts += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
     $order->total_discounts_tax_excl += (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS));
     $order->total_discounts_tax_incl += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
     // Save changes of order
     $order->update();
     // Update weight SUM
     $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
     if (Validate::isLoadedObject($order_carrier)) {
         $order_carrier->weight = (double) $order->getTotalWeight();
         if ($order_carrier->update()) {
             $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
         }
     }
     // Update Tax lines
     $order_detail->updateTaxAmount($order);
     // Delete specific price if exists
     if (isset($specific_price)) {
         $specific_price->delete();
     }
     $products = $this->getProducts($order);
     // Get the last product
     $product = end($products);
     $resume = OrderSlip::getProductSlipResume((int) $product['id_order_detail']);
     $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
     $product['amount_refundable'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
     $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl']);
     $product['return_history'] = OrderReturn::getProductReturnDetail((int) $product['id_order_detail']);
     $product['refund_history'] = OrderSlip::getProductSlipDetail((int) $product['id_order_detail']);
     if ($product['id_warehouse'] != 0) {
         $warehouse = new Warehouse((int) $product['id_warehouse']);
         $product['warehouse_name'] = $warehouse->name;
     } else {
         $product['warehouse_name'] = '--';
     }
     // Get invoices collection
     $invoice_collection = $order->getInvoicesCollection();
     $invoice_array = array();
     foreach ($invoice_collection as $invoice) {
         $invoice->name = $invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop);
         $invoice_array[] = $invoice;
     }
     // Assign to smarty informations in order to show the new product line
     $this->context->smarty->assign(array('product' => $product, 'order' => $order, 'currency' => new Currency($order->id_currency), 'can_edit' => $this->tabAccess['edit'], 'invoices_collection' => $invoice_collection, 'current_id_lang' => Context::getContext()->language->id, 'link' => Context::getContext()->link, 'current_index' => self::$currentIndex, 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')));
     $this->sendChangedNotification($order);
     die(Tools::jsonEncode(array('result' => true, 'view' => $this->createTemplate('_product_line.tpl')->fetch(), 'can_edit' => $this->tabAccess['add'], 'order' => $order, 'invoices' => $invoice_array, 'documents_html' => $this->createTemplate('_documents.tpl')->fetch(), 'shipping_html' => $this->createTemplate('_shipping.tpl')->fetch(), 'discount_form_html' => $this->createTemplate('_discount_form.tpl')->fetch())));
 }
 /**
  * Return price calculated by PrestaShop system
  *
  * @param  $id_carrier string | int - carrier id
  * @param  $id_cart string | int - cart id
  * @param  $id_zone string | int - Zone Id 1 -> Global?
  * @return string - Price
  */
 public static function systemPriceCalculate($id_carrier, $id_cart, $id_zone)
 {
     $cart = new Cart($id_cart);
     $total_weight = $cart->getTotalWeight();
     $carrier = new Carrier($id_carrier);
     $price = $carrier->getDeliveryPriceByWeight($total_weight, $id_zone);
     return $price;
 }
 /**
  * @param \Cart $cart
  *
  * @return bool|float|int
  * @throws \Exception
  *
  * @author Panagiotis Vagenas <*****@*****.**>
  * @since ${VERSION}
  */
 public function getOrderShippingCostExternal($cart)
 {
     $addressObj = new \Address($cart->id_address_delivery);
     $country = mb_strtolower($addressObj->country);
     $countryChecks = array('greece', 'ελλάδα', 'ελλαδα', 'ελλας', 'ελλάς', 'el', 'el_gr', 'ellada', 'ellas', 'hellas', 'gr');
     if (!in_array($country, $countryChecks)) {
         return false;
     }
     if ($cart->getOrderTotal(true, \Cart::ONLY_PRODUCTS) > $this->Options->getValue('freeShippingAbove')) {
         return 0;
     }
     return $this->calculatePrice($cart->getTotalWeight());
 }
Ejemplo n.º 5
0
	/**
	 * Generates the XML needed for the making a request to the Rating API
	 *
	 * @param      $ups_config
	 * @param Cart $cart
	 * @param      $RequestOption
	 * @param null $service
	 * @return string
	 */
	public function getRatingServiceSelectionRequestXML($ups_config, Cart $cart, $RequestOption /* Rate or Shop */, $service = NULL)
	{
		$shipping_address = $cart->getShippingAddress();
		$request = "<?xml version=\"1.0\" ?>
			<RatingServiceSelectionRequest>
				<Request>
					<TransactionReference>
						<CustomerContext>Rating and Service</CustomerContext>
						<XpciVersion>1.0</XpciVersion>
					</TransactionReference>
					<RequestAction>Rate</RequestAction>
			        <RequestOption>$RequestOption</RequestOption>
				</Request>
				<PickupType>
					<Code>$ups_config->pickup_type</Code>
				</PickupType>
				<Shipment>
					<Shipper>
						<ShipperNumber>$ups_config->shipper_number</ShipperNumber>
						<Address>
							<PostalCode>$ups_config->postal_code</PostalCode>
							<CountryCode>$ups_config->country_code</CountryCode>
						</Address>
					</Shipper>
					<ShipFrom>
						<Address>
							<PostalCode>$ups_config->postal_code</PostalCode>
							<CountryCode>$ups_config->country_code</CountryCode>
						</Address>
					</ShipFrom>
					<ShipTo>
						<!--<CompanyName>$shipping_address->company</CompanyName>
						<AttentionName>$shipping_address->firstname $shipping_address->lastname</AttentionName>
						<PhoneNumber>$shipping_address->telephone</PhoneNumber>-->
						<Address>
							<!-- <AddressLine1>$shipping_address->address</AddressLine1>
							<City>$shipping_address->city</City> -->
							<PostalCode>$shipping_address->postal_code</PostalCode>
							<CountryCode>$shipping_address->country</CountryCode>
						</Address>
					</ShipTo>";
			$request .= ( $service ? "<Service><Code>$service</Code></Service>" : '');
			$request .=	"<Package>
						<PackagingType>
							<Code>$ups_config->package_type</Code>
						</PackagingType>
						<!-- Dimensions are required if Packaging Type if not Letter, Express Tube,
						or Express Box; Required for GB to GB and Poland to Poland shipments -->
						<!-- <Dimensions>
							<UnitOfMeasurement>
								<Code>CM</Code>
							</UnitOfMeasurement>
							<Length>$length</Length>
							<Width>$width</Width>
							<Height>$height</Height>
						</Dimensions>-->
						<!-- Weight allowed for letters/envelopes.-->
						<PackageWeight>
    						<UnitOfMeasurement>";

			$request .= "<Code>" . ($cart->getUnitOfMeasure() == ShopInfo::UNIT_OF_MEASURE_KGS ? "KGS" : "LBS") . "</Code>";


			$cart_weight = $cart->getTotalWeight();
    		$request .=			"</UnitOfMeasurement>
    						<Weight>$cart_weight</Weight>
    					</PackageWeight>
					</Package>
					<ShipmentServiceOptions />
				</Shipment>
			</RatingServiceSelectionRequest>";
		return $request;
	}
Ejemplo n.º 6
0
require_once "../includes/init.inc.php";
function calculate_freight($service, $cep_origin, $cep_destination, $weight, $own_hand, $declared_value, $notice_receipt)
{
    $own_hand = strtolower($own_hand) == 's' ? 's' : 'n';
    $notice_receipt = strtolower($notice_receipt) == 's' ? 's' : 'n';
    $url = 'http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?nCdEmpresa=&sDsSenha=&sCepOrigem=' . $cep_origin . '&sCepDestino=' . $cep_destination . '&nVlPeso=' . $weight . '&nCdFormato=1&nVlComprimento=20&nVlAltura=5&nVlLargura=15&sCdMaoPropria=' . $own_hand . '&nVlValorDeclarado=' . $declared_value . '&sCdAvisoRecebimento=' . $notice_receipt . '&nCdServico=' . $service . '&nVlDiametro=0&StrRetorno=xml';
    $freight_calculate = simplexml_load_string(file_get_contents($url));
    $freight = $freight_calculate->cServico;
    if ($freight->Erro == '0') {
        $response[0] = (double) str_replace(',', '.', $freight->Valor);
        $response[1] = $freight->PrazoEntrega . ' dia' . ($freight->PrazoEntrega != 1 ? "s" : "");
    } elseif ($freight->Erro == '7') {
        $response[0] = 0;
        $response[1] = 'Serviço temporariamente indisponível, tente novamente mais tarde.';
    } else {
        $response[0] = 0;
        $response[1] = 'Erro no cálculo do frete: ' . $freight->MsgErro;
    }
    return $response;
}
if (isset($_GET['cep_destination'])) {
    $cep_destination = $_GET['cep_destination'];
    $_SESSION['cep_destination'] = $cep_destination;
    $cep_destination = str_replace('-', '', $cep_destination);
    $_SESSION['freight'] = calculate_freight('40010', '35400000', $cep_destination, Cart::getTotalWeight(), 'n', '0', 's');
} else {
    unset($_SESSION['freight']);
    unset($_SESSION['cep_destination']);
}
header("location: ../carrinho");
Ejemplo n.º 7
0
	/**
	 * Calculates shipping rates
	 *
	 * @param Cart   $cart    Shipping cart for which to calculate shipping; includes shipping address
	 * @param String $service Represents the specific service for which to calcualte shipping (e.g. Standard or Priority)
	 * @return null
	 */
	public function calculateShipping(Cart $cart, $service = NULL)
	{
		/** @var $unit The thing we will compare to the table rates: price, weight or item count */
		$unit = NULL;
		switch($this->type){
			case TableRateShipping::TYPE_PRICE_DESTINATION:
				$unit = $cart->getItemTotal(); // TODO Check if maybe getTotalAfterDiscount should be used instead
				break;
			case TableRateShipping::TYPE_WEIGHT_DESTINATION:
				$unit = $cart->getTotalWeight();
				break;
			case TableRateShipping::TYPE_ITEMS_COUNT_DESTINATION:
				$unit = count($cart->getProducts());
				break;
		}

		$shipping_address = $cart->getShippingAddress();
		$shipping_country = $shipping_address->country;

		$table_rates = $this->getTableRatesForCountry($shipping_country);
		$shipping_price = NULL;
		foreach($table_rates as $table_rate)
		{
			if($table_rate->unit <= $unit)
			{
				$shipping_price = $table_rate->price;
			}
			else
			{
				break;
			}
		}

		// If no shipping price was calculated, just take the last
		if(is_null($shipping_price))
		{
			ShopLogger::log("Couldn't match any rules from the table;");
			$shipping_price = $table_rate->price;
		}

		return $shipping_price;
	}