Jump to content

Programatically create order and Advanced Stock Management


Glauber

Recommended Posts

Hello,

 

I have a code to create an Order and it works fine, deduce product stock quantity, create user if it is not registered, add the addresses, update the status history, etc.. But when I activate the ASM system the product quantity is not deduced, what I need to take care on programatically created order to solve this problem?

 

Below is the create order code that I am using:

                $order = new Order();
		$order->reference = Order::generateReference();
		// my extended field on Order
                $order->skyhub_code = $orderToImport->code;
		$order->id_shop = $context->shop->id;
		$order->id_shop_group = $context->shop->id_shop_group;
		$order->id_address_delivery = $this->deliveryAddress->id;
		$order->id_address_invoice = $this->billingAddress->id;
		$order->id_cart = $this->cart->id;
		$order->id_currency = $id_currency;
		$order->id_lang = $this->getLangId();
		$order->id_customer = $this->customer->id;
		$order->id_carrier = $carrier->id;
		$order->secure_key = $this->customer->secure_key;
		$order->payment = 'skyhub';
		$order->module = 'psskyhub';

		$order->total_paid_real = 0;
		$order->product_list = $this->cart->getProducts();

		// total products
		$totalProducts = 0;
		$totalProductsWt = 0;
		foreach ($orderToImport->items as $item) {
			$totalProducts += (float)$item->qty * (float)$item->original_price;
			$totalProductsWt += (float)$item->qty * (float)$item->original_price;
		}
		$order->total_products = $totalProducts;
		$order->total_products_wt = $totalProductsWt;

		$order->total_discounts_tax_excl = 0;
		$order->total_discounts_tax_incl = 0;
		$order->total_discounts = $order->total_discounts_tax_incl;

    	        $order->total_shipping_tax_excl = $orderToImport->shipping_cost;
    	        $order->total_shipping_tax_incl = $orderToImport->shipping_cost;
		$order->total_shipping = $order->total_shipping_tax_incl;

    	        $order->total_wrapping_tax_excl = 0;
    	        $order->total_wrapping_tax_incl = 0;
    	        $order->total_wrapping = $order->total_wrapping_tax_incl;

    	        $order->total_paid_tax_excl = $orderToImport->total_ordered;
    	        $order->total_paid_tax_incl = $orderToImport->total_ordered;
		$order->total_paid = $orderToImport->total_ordered;

		$order->conversion_rate = $context->currency->conversion_rate;
		if (!is_null($carrier) && Validate::isLoadedObject($carrier)) {
		    $order->carrier_tax_rate = $carrier->getTaxesRate(new Address((int)$this->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
		}

		$order->round_mode = Configuration::get('PS_PRICE_ROUND_MODE');
		$order->round_type = Configuration::get('PS_ROUND_TYPE');

                // some of my custom fields on my extended Order class
		$order->from_skyhub = true;
		$order->skyhub_shipment = json_encode(array(
			'valor_frete' => $orderToImport->shipping_cost,
			'metodo_envio' => $orderToImport->shipping_method,
			'data_estimada' => $orderToImport->estimated_delivery,
			'turno_entrega_agendada' => $orderToImport->estimated_delivery_shift,
		));
		$order->skyhub_extra = json_encode($this->_cartProductsCustomAttributesValues);

		try {
			if (!$order->save()) {
				throw new Exception('Não foi possível salvar o pedido no PS. Verifique override da class Order e se campos criados pelo módulo estão presentes na tabela orders.');
			}
		} catch (Exception $e) {
			$message = sprintf('[Exceção ao salvar pedido no PS: %s - file: %s (%s)] - Pedido sendo importado: %s', $e->getMessage(), $e->getFile(), $e->getLine(), json_encode($orderToImport, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
			throw new Exception($message);
		}

		// order status
		// added check cancelado to process demo store orders
		$id_order_state = $orderToImport->status->code == 'cancelado' ? 6 : $orderToImport->status->code;
		try {
			// Order details
			$orderDetail = new OrderDetail(null, null, Context::getContext());
			$products = $this->cart->getProducts();
                        // OBS I tried pass the warehouse ID on this method but it does not deduced the product quantity
			$orderDetail->createList($order, $this->cart, $id_order_state, $products);
		} catch (Exception $e) {
			$message = sprintf('[Exceção ao salvar detalhes do pedido no PS: %s - file: %s (%s)] - Pedido sendo importado: %s', $e->getMessage(), $e->getFile(), $e->getLine(), json_encode($orderToImport, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
			throw new Exception($message);
		}

		try {
			$history = new OrderHistory();
	                $history->id_order = (int)$order->id;
	                $history->id_employee = 0;
	                $history->changeIdOrderState((int)$id_order_state, $order->id);
		} catch (Exception $e) {
			$message = sprintf('[Exceção ao salvar status do pedido no PS: %s - file: %s (%s)] - Pedido sendo importado: %s', $e->getMessage(), $e->getFile(), $e->getLine(), json_encode($orderToImport, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
			throw new Exception($message);
		}

		try {
	                // Adding an entry in order_carrier table
		 	if (!is_null($carrier)) {
			    $order_carrier = new OrderCarrier();
			    $order_carrier->id_order = (int)$order->id;
			    $order_carrier->id_carrier = (int)$carrier->id;
			    $order_carrier->weight = (float)$order->getTotalWeight();
			    $order_carrier->shipping_cost_tax_excl = (float)$order->total_shipping_tax_excl;
			    $order_carrier->shipping_cost_tax_incl = (float)$order->total_shipping_tax_incl;
			    $order_carrier->add();
			}
		} catch (Exception $e) {
			$message = sprintf('[Exceção ao salvar transportadora do pedido no PS: %s - file: %s (%s)] - Pedido sendo importado: %s', $e->getMessage(), $e->getFile(), $e->getLine(), json_encode($orderToImport, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
			throw new Exception($message);
		}
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...