/**
  * Get the Products contained in the given Pack.
  *
  * @param Pack $pack
  * @param integer $id_lang Optional
  * @return Array[Product] The products contained in this Pack, with special dynamic attributes [pack_quantity, id_pack_product_attribute]
  */
 public function getPackItems($pack, $id_lang = false)
 {
     if ($id_lang === false) {
         $configuration = Adapter_ServiceLocator::get('Core_Business_ConfigurationInterface');
         $id_lang = (int) $configuration->get('PS_LANG_DEFAULT');
     }
     return Pack::getItems($pack->id, $id_lang);
 }
    public function update_cart_by_site_xml($order_id, $data)
    {
        $xml = simplexml_load_string($data);
        $prefix = _DB_PREFIX_;
        $tablename = $prefix . 'orders';
        $total_amount = 0;
        $total_principal = 0;
        $shipping_amount = 0;
        $total_promo = 0;
        $ClientRequestId = 0;
        $WrappingAmount = 0;
        $gift = 0;
        $gift_message = ' ';
        foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) {
            $SKU = (string) $item->SKU;
            if ($SKU == 'wrapping_fee') {
                $WrappingAmount = (double) $item->Price->Amount;
                $gift = 1;
                $gift_message = (string) $item->Description;
            }
            $Title = (string) $item->Title;
            $Amount = (double) $item->Price->Amount;
            $ClientRequestId = (int) $item->ClientRequestId;
            $other_promo = 0;
            foreach ($item->ItemCharges->Component as $amount_type) {
                $item_charge_type = (string) $amount_type->Type;
                if ($item_charge_type == 'Principal') {
                    $principal = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'Shipping') {
                    $Shipping = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'PrincipalPromo') {
                    $principal_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'ShippingPromo') {
                    $shipping_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'OtherPromo') {
                    $other_promo = (string) $amount_type->Charge->Amount;
                }
            }
            $CurrencyCode = (string) $item->Price->CurrencyCode;
            $Quantity = (int) $item->Quantity;
            /*
             * Total Item Charge = (Principal - PrincipalPromo) + (Shipping - ShippingPromo) + Tax + ShippingTax
             */
            $total_principal += $principal;
            $total_amount += $principal - $principal_promo + ($Shipping - $shipping_promo);
            $shipping_amount += $Shipping;
            $total_promo += $principal_promo + $shipping_promo + $other_promo;
        }
        $total_principal = $total_principal - $WrappingAmount;
        $ShippingServiceLevel = (string) $xml->ProcessedOrder->ShippingServiceLevel;
        $sql = 'UPDATE `' . $prefix . 'pwa_orders` set `shipping_service` = "' . $ShippingServiceLevel . '" , `order_type` = "site" where `prestashop_order_id` = "' . $order_id . '" ';
        Db::getInstance()->Execute($sql);
        $id_cart = $ClientRequestId;
        $this->context = Context::getContext();
        $this->context->cart = new Cart($id_cart);
        if ((int) $this->context->cart->id_customer == 0) {
            $email = (string) $xml->ProcessedOrder->BuyerInfo->BuyerEmailAddress;
            $sql = 'SELECT * from `' . $prefix . 'customer` where email = "' . $email . '" ';
            $results = Db::getInstance()->ExecuteS($sql);
            if (empty($results)) {
                $name = (string) $xml->ProcessedOrder->BuyerInfo->BuyerName;
                $name_arr = explode(' ', $name);
                if (count($name_arr) > 1) {
                    $firstname = '';
                    for ($i = 0; $i <= count($name_arr) - 2; $i++) {
                        $firstname = $firstname . ' ' . $name_arr[$i];
                    }
                    $lastname = $name_arr[count($name_arr) - 1];
                } else {
                    $firstname = $name;
                    $lastname = '.';
                }
                $password = Tools::passwdGen();
                $customer = new Customer();
                $customer->firstname = trim($firstname);
                $customer->lastname = $lastname;
                $customer->email = (string) $xml->ProcessedOrder->BuyerInfo->BuyerEmailAddress;
                $customer->passwd = md5($password);
                $customer->active = 1;
                if (Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
                    $customer->is_guest = 1;
                } else {
                    $customer->is_guest = 0;
                }
                $customer->add();
                $customer_id = $customer->id;
                if (Configuration::get('PS_CUSTOMER_CREATION_EMAIL') && !Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
                    Mail::Send($this->context->language->id, 'account', Mail::l('Welcome!'), array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => $password), $customer->email, $customer->firstname . ' ' . $customer->lastname);
                }
            } else {
                $customer_id = $results[0]['id_customer'];
            }
            $id_country = Country::getByIso((string) $xml->ProcessedOrder->ShippingAddress->CountryCode);
            if ($id_country == 0 || $id_country == '') {
                $id_country = 110;
            }
            $name = (string) $xml->ProcessedOrder->ShippingAddress->Name;
            $name_arr = explode(' ', $name);
            if (count($name_arr) > 1) {
                $firstname = '';
                for ($i = 0; $i <= count($name_arr) - 2; $i++) {
                    $firstname = $firstname . ' ' . $name_arr[$i];
                }
                $lastname = $name_arr[count($name_arr) - 1];
            } else {
                $firstname = $name;
                $lastname = '.';
            }
            $address = new Address();
            $address->id_country = $id_country;
            $address->id_state = 0;
            $address->id_customer = $customer_id;
            $address->alias = 'My Address';
            $address->firstname = trim($firstname);
            $address->lastname = $lastname;
            $address->address1 = (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldOne;
            $address->address2 = (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldTwo;
            $address->postcode = (string) $xml->ProcessedOrder->ShippingAddress->PostalCode;
            $address->city = (string) $xml->ProcessedOrder->ShippingAddress->City . ' ' . (string) $xml->ProcessedOrder->ShippingAddress->State;
            $address->active = 1;
            $address->add();
            $address_id = $address->id;
            $cart = new Cart($id_cart);
            $cart->id_customer = $customer_id;
            $cart->id_address_delivery = $address_id;
            $cart->id_address_invoice = $address_id;
            $cart->update();
        }
        $this->context->cart = new Cart($id_cart);
        $this->context->customer = new Customer($this->context->cart->id_customer);
        $id_order_state = 99;
        // The tax cart is loaded before the customer so re-cache the tax calculation method
        //$this->context->cart->setTaxCalculationMethod();
        $this->context->language = new Language($this->context->cart->id_lang);
        $this->context->shop = $shop ? $shop : new Shop($this->context->cart->id_shop);
        $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency;
        $this->context->currency = new Currency($id_currency, null, $this->context->shop->id);
        $reference = Order::generateReference();
        $cart_rules = $this->context->cart->getCartRules();
        $order = new Order();
        $order->id = $order_id;
        $order->id_customer = (int) $this->context->cart->id_customer;
        $order->id_address_invoice = (int) $this->context->cart->id_address_invoice;
        $order->id_shop = (int) $this->context->shop->id;
        $order->id_shop_group = (int) $this->context->shop->id_shop_group;
        $carrier = null;
        if ((int) $this->context->cart->id_carrier) {
            $carrier = 'yes';
            $id_carrier = (int) $this->context->cart->id_carrier;
        } else {
            $sql = 'SELECT id_carrier from  `' . $prefix . 'carrier` where `active` = 1 and `deleted` = 0 limit 0,1';
            $result = Db::getInstance()->ExecuteS($sql);
            $id_carrier = $result[0]['id_carrier'];
        }
        $sql = 'UPDATE `' . $tablename . '` set 
			  `id_customer` = ' . (int) $this->context->cart->id_customer . ',
			  `id_carrier` = ' . $id_carrier . ',
			  `id_address_invoice` = ' . (int) $this->context->cart->id_address_invoice . ',
			  `id_address_delivery` = ' . (int) $this->context->cart->id_address_delivery . ',
			  `id_currency` = ' . $this->context->currency->id . ',
			  `id_lang` = ' . (int) $this->context->cart->id_lang . ',
			  `id_cart` = ' . (int) $this->context->cart->id . ',
			  `reference` = "' . $reference . '",
			  `id_shop` = ' . (int) $this->context->shop->id . ',
			  `id_shop_group` = ' . (int) $this->context->shop->id_shop_group . ',
			  `secure_key` = "' . $this->context->cart->secure_key . '",
			  `conversion_rate` = ' . $this->context->currency->conversion_rate . ',
			  
			  `total_paid` = ' . $total_amount . ',
			  `total_paid_tax_incl` = ' . $total_amount . ',
			  `total_paid_tax_excl` = ' . $total_amount . ',
			  `total_paid_real` = 0,
			 
			  `total_shipping` = ' . $shipping_amount . ',
			  `total_shipping_tax_incl` = ' . $shipping_amount . ',
			  `total_shipping_tax_excl` = ' . $shipping_amount . ',
			  
			  `total_discounts` = ' . (double) $total_promo . ',
			  `total_discounts_tax_incl` = ' . (double) $total_promo . ',
			  `total_discounts_tax_excl` = ' . (double) $total_promo . ',
			  
			  `total_products` = ' . $total_principal . ',
			  `total_products_wt` = ' . $total_principal . ',
			  
			  `total_wrapping_tax_incl` = ' . $WrappingAmount . ',
			  `total_wrapping_tax_excl` = ' . $WrappingAmount . ',
			  `total_wrapping` = ' . $WrappingAmount . ',
			  
			  `gift` = ' . $gift . ',
			  `gift_message` = "' . $gift_message . '",
			  
			  `invoice_date` = "0000-00-00 00:00:00",
			  `delivery_date` = "0000-00-00 00:00:00"
			  where `id_order` = ' . $order_id . ' ';
        //`round_mode` = '.Configuration::get('PS_PRICE_ROUND_MODE').',
        //`carrier_tax_rate` = '.$carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})).' ,
        Db::getInstance()->Execute($sql);
        $acknowledge_arr = array();
        $i = 0;
        foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) {
            $SKU = (string) $item->SKU;
            if ($SKU == 'wrapping_fee') {
                //Nothing
            } else {
                $AmazonOrderItemCode = (string) $item->AmazonOrderItemCode;
                $Title = (string) $item->Title;
                $Amount = (double) $item->Price->Amount;
                $product_id = (int) $item->ItemCustomData->Item_product_id;
                $product_attribute_id = (int) $item->ItemCustomData->Item_attr_product_id;
                $Item_price_excl_tax = $item->ItemCustomData->Item_price_excl_tax;
                $A_Name = '';
                foreach ($item->ItemCustomData->Item_attribute as $attribute) {
                    if ($A_Name == '') {
                        $A_Name = $attribute->Attribute_name . ' : ' . $attribute->Attribute_val;
                    } else {
                        $A_Name = $A_Name . ', ' . $attribute->Attribute_name . ' : ' . $attribute->Attribute_val;
                    }
                }
                $acknowledge_arr['items'][$i]['AmazonOrderItemCode'] = $AmazonOrderItemCode;
                $acknowledge_arr['items'][$i]['product_id'] = $product_id;
                $Title = $Title . ' - ' . $A_Name;
                $CurrencyCode = (string) $item->Price->CurrencyCode;
                $Quantity = (int) $item->Quantity;
                $other_promo = 0;
                foreach ($item->ItemCharges->Component as $amount_type) {
                    $item_charge_type = (string) $amount_type->Type;
                    if ($item_charge_type == 'Principal') {
                        $principal = (string) $amount_type->Charge->Amount;
                    }
                    if ($item_charge_type == 'Shipping') {
                        $Shipping = (string) $amount_type->Charge->Amount;
                    }
                    if ($item_charge_type == 'PrincipalPromo') {
                        $principal_promo = (string) $amount_type->Charge->Amount;
                    }
                    if ($item_charge_type == 'ShippingPromo') {
                        $shipping_promo = (string) $amount_type->Charge->Amount;
                    }
                    if ($item_charge_type == 'OtherPromo') {
                        $other_promo = (string) $amount_type->Charge->Amount;
                    }
                }
                $sql = 'INSERT into `' . $prefix . 'order_detail` set
							`id_order` = ' . $order_id . ',
							`product_id` = ' . $product_id . ',
							`product_attribute_id` = ' . $product_attribute_id . ',
							`product_name` = "' . $Title . '",
							`product_quantity` = ' . $Quantity . ',
							`product_quantity_in_stock` = ' . $Quantity . ',
							`product_price` = ' . $Amount . ',
							`product_reference` = "' . $SKU . '",
							`total_price_tax_incl` = ' . $Amount * $Quantity . ',
							`total_price_tax_excl` = ' . $Item_price_excl_tax * $Quantity . ',
							`unit_price_tax_incl` = ' . $Amount . ',
							`unit_price_tax_excl` = ' . $Item_price_excl_tax . ',
							`original_product_price` = ' . $Amount . '
							';
                Db::getInstance()->Execute($sql);
                if (Pack::isPack($product_id)) {
                    $product = new Product((int) $product_id);
                    if ($product->pack_stock_type == 1 || $product->pack_stock_type == 2) {
                        $products_pack = Pack::getItems($product_id, (int) Configuration::get('PS_LANG_DEFAULT'));
                        foreach ($products_pack as $product_pack) {
                            $sql = 'UPDATE `' . $prefix . 'stock_available` set
							`quantity` = `quantity` - ' . $product_pack->pack_quantity * $Quantity . '
							where `id_product` = ' . $product_pack->id . ' and
							`id_product_attribute` = 0
									';
                            Db::getInstance()->Execute($sql);
                            $sql = 'UPDATE `' . $prefix . 'stock_available` set
									`quantity` = `quantity` - ' . $product_pack->pack_quantity * $Quantity . '
									where `id_product` = ' . $product_pack->id . ' and
									`id_product_attribute` = ' . $product_pack->id_pack_product_attribute . '
									';
                            Db::getInstance()->Execute($sql);
                        }
                    }
                    if ($product->pack_stock_type == 0 || $product->pack_stock_type == 2 || $product->pack_stock_type == 3 && (Configuration::get('PS_PACK_STOCK_TYPE') == 0 || Configuration::get('PS_PACK_STOCK_TYPE') == 2)) {
                        $sql = 'UPDATE `' . $prefix . 'stock_available` set
							`quantity` = `quantity` - ' . $Quantity . '
							where `id_product` = ' . $product_id . ' and
							`id_product_attribute` = 0
							';
                        Db::getInstance()->Execute($sql);
                        if ($product_attribute_id > 0) {
                            $sql = 'UPDATE `' . $prefix . 'stock_available` set
									`quantity` = `quantity` - ' . $Quantity . '
									where `id_product` = ' . $product_id . ' and
									`id_product_attribute` = ' . $product_attribute_id . '
									';
                            Db::getInstance()->Execute($sql);
                        }
                        $date = date('Y-m-d');
                        $sql = 'UPDATE `' . $prefix . 'product_sale` set
								`quantity` = `quantity` + ' . $Quantity . ',
								`sale_nbr` = `sale_nbr` + ' . $Quantity . ',
								`date_upd` = ' . $date . '
								where `id_product` = ' . $product_id . '
								';
                        Db::getInstance()->Execute($sql);
                    }
                } else {
                    $sql = 'UPDATE `' . $prefix . 'stock_available` set
							`quantity` = `quantity` - ' . $Quantity . '
							where `id_product` = ' . $product_id . ' and
							`id_product_attribute` = 0
							';
                    Db::getInstance()->Execute($sql);
                    if ($product_attribute_id > 0) {
                        $sql = 'UPDATE `' . $prefix . 'stock_available` set
								`quantity` = `quantity` - ' . $Quantity . '
								where `id_product` = ' . $product_id . ' and
								`id_product_attribute` = ' . $product_attribute_id . '
								';
                        Db::getInstance()->Execute($sql);
                    }
                    $date = date('Y-m-d');
                    $sql = 'UPDATE `' . $prefix . 'product_sale` set
							`quantity` = `quantity` + ' . $Quantity . ',
							`sale_nbr` = `sale_nbr` + ' . $Quantity . ',
							`date_upd` = ' . $date . '
							where `id_product` = ' . $product_id . '
							';
                    Db::getInstance()->Execute($sql);
                }
            }
            $i++;
        }
        // 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) $id_carrier;
            $order_carrier->weight = '0';
            $order_carrier->shipping_cost_tax_excl = (double) $shipping_amount;
            $order_carrier->shipping_cost_tax_incl = (double) $shipping_amount;
            $order_carrier->add();
        } else {
            $order_carrier = new OrderCarrier();
            $order_carrier->id_order = (int) $order->id;
            $order_carrier->id_carrier = (int) $id_carrier;
            $order_carrier->weight = '0';
            $order_carrier->shipping_cost_tax_excl = (double) $shipping_amount;
            $order_carrier->shipping_cost_tax_incl = (double) $shipping_amount;
            $order_carrier->add();
        }
        foreach ($cart_rules as $cart_rule) {
            $values['tax_incl'] = $cart_rule['value_real'];
            $values['tax_excl'] = $cart_rule['value_tax_exc'];
            $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping);
        }
        // Set the order status
        $history = new OrderHistory();
        $history->id_order = (int) $order->id;
        $history->changeIdOrderState((int) $id_order_state, $order->id, true);
        $history->addWithemail(true, array(), $this->context);
        if ($total_amount == 0) {
            $date = date('Y-m-d H:i:s');
            $sql = 'INSERT into `' . $prefix . 'order_payment` set 	order_reference = "' . $reference . '",   `id_currency` = "' . $this->context->currency->id . '",  `amount` = "0.0", `payment_method` = "Pay With Amazon", `conversion_rate` = "' . $this->context->currency->conversion_rate . '", `date_add` = "' . $date . '" ';
            Db::getInstance()->Execute($sql);
        }
        $acknowledge_arr['MerchantOrderID'] = (int) $order->id;
    }
 protected function reinjectQuantity($order_detail, $qty_cancel_product, $delete = false)
 {
     // Reinject product
     $reinjectable_quantity = (int) $order_detail->product_quantity - (int) $order_detail->product_quantity_reinjected;
     $quantity_to_reinject = $qty_cancel_product > $reinjectable_quantity ? $reinjectable_quantity : $qty_cancel_product;
     // @since 1.5.0 : Advanced Stock Management
     $product_to_inject = new Product($order_detail->product_id, false, (int) $this->context->language->id, (int) $order_detail->id_shop);
     $product = new Product($order_detail->product_id, false, (int) $this->context->language->id, (int) $order_detail->id_shop);
     if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && $product->advanced_stock_management && $order_detail->id_warehouse != 0) {
         $manager = StockManagerFactory::getManager();
         $movements = StockMvt::getNegativeStockMvts($order_detail->id_order, $order_detail->product_id, $order_detail->product_attribute_id, $quantity_to_reinject);
         $left_to_reinject = $quantity_to_reinject;
         foreach ($movements as $movement) {
             if ($left_to_reinject > $movement['physical_quantity']) {
                 $quantity_to_reinject = $movement['physical_quantity'];
             }
             $left_to_reinject -= $quantity_to_reinject;
             if (Pack::isPack((int) $product->id)) {
                 // Gets items
                 if ($product->pack_stock_type == 1 || $product->pack_stock_type == 2 || $product->pack_stock_type == 3 && Configuration::get('PS_PACK_STOCK_TYPE') > 0) {
                     $products_pack = Pack::getItems((int) $product->id, (int) Configuration::get('PS_LANG_DEFAULT'));
                     // Foreach item
                     foreach ($products_pack as $product_pack) {
                         if ($product_pack->advanced_stock_management == 1) {
                             $manager->addProduct($product_pack->id, $product_pack->id_pack_product_attribute, new Warehouse($movement['id_warehouse']), $product_pack->pack_quantity * $quantity_to_reinject, null, $movement['price_te'], true);
                         }
                     }
                 }
                 if ($product->pack_stock_type == 0 || $product->pack_stock_type == 2 || $product->pack_stock_type == 3 && (Configuration::get('PS_PACK_STOCK_TYPE') == 0 || Configuration::get('PS_PACK_STOCK_TYPE') == 2)) {
                     $manager->addProduct($order_detail->product_id, $order_detail->product_attribute_id, new Warehouse($movement['id_warehouse']), $quantity_to_reinject, null, $movement['price_te'], true);
                 }
             } else {
                 $manager->addProduct($order_detail->product_id, $order_detail->product_attribute_id, new Warehouse($movement['id_warehouse']), $quantity_to_reinject, null, $movement['price_te'], true);
             }
         }
         $id_product = $order_detail->product_id;
         if ($delete) {
             $order_detail->delete();
         }
         StockAvailable::synchronize($id_product);
     } elseif ($order_detail->id_warehouse == 0) {
         StockAvailable::updateQuantity($order_detail->product_id, $order_detail->product_attribute_id, $quantity_to_reinject, $order_detail->id_shop);
         if ($delete) {
             $order_detail->delete();
         }
     } else {
         $this->errors[] = Tools::displayError('This product cannot be re-stocked.');
     }
 }
Exemple #4
0
    /**
     * @see StockManagerInterface::removeProduct()
     */
    public function removeProduct($id_product, $id_product_attribute = null, Warehouse $warehouse, $quantity, $id_stock_mvt_reason, $is_usable = true, $id_order = null)
    {
        $return = array();
        if (!Validate::isLoadedObject($warehouse) || !$quantity || !$id_product) {
            return $return;
        }
        if (!StockMvtReason::exists($id_stock_mvt_reason)) {
            $id_stock_mvt_reason = Configuration::get('PS_STOCK_MVT_DEC_REASON_DEFAULT');
        }
        $context = Context::getContext();
        // Special case of a pack
        if (Pack::isPack((int) $id_product)) {
            // Gets items
            $products_pack = Pack::getItems((int) $id_product, (int) Configuration::get('PS_LANG_DEFAULT'));
            // Foreach item
            foreach ($products_pack as $product_pack) {
                $pack_id_product_attribute = Product::getDefaultAttribute($product_pack->id, 1);
                if ($product_pack->advanced_stock_management == 1) {
                    $this->removeProduct($product_pack->id, $pack_id_product_attribute, $warehouse, $product_pack->pack_quantity * $quantity, $id_stock_mvt_reason, $is_usable, $id_order);
                }
            }
        } else {
            // gets total quantities in stock for the current product
            $physical_quantity_in_stock = (int) $this->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), false);
            $usable_quantity_in_stock = (int) $this->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), true);
            // check quantity if we want to decrement unusable quantity
            if (!$is_usable) {
                $quantity_in_stock = $physical_quantity_in_stock - $usable_quantity_in_stock;
            } else {
                $quantity_in_stock = $usable_quantity_in_stock;
            }
            // checks if it's possible to remove the given quantity
            if ($quantity_in_stock < $quantity) {
                return $return;
            }
            $stock_collection = $this->getStockCollection($id_product, $id_product_attribute, $warehouse->id);
            $stock_collection->getAll();
            // check if the collection is loaded
            if (count($stock_collection) <= 0) {
                return $return;
            }
            $stock_history_qty_available = array();
            $mvt_params = array();
            $stock_params = array();
            $quantity_to_decrement_by_stock = array();
            $global_quantity_to_decrement = $quantity;
            // switch on MANAGEMENT_TYPE
            switch ($warehouse->management_type) {
                // case CUMP mode
                case 'WA':
                    // There is one and only one stock for a given product in a warehouse in this mode
                    $stock = $stock_collection->current();
                    $mvt_params = array('id_stock' => $stock->id, 'physical_quantity' => $quantity, 'id_stock_mvt_reason' => $id_stock_mvt_reason, 'id_order' => $id_order, 'price_te' => $stock->price_te, 'last_wa' => $stock->price_te, 'current_wa' => $stock->price_te, 'id_employee' => $context->employee->id, 'employee_firstname' => $context->employee->firstname, 'employee_lastname' => $context->employee->lastname, 'sign' => -1);
                    $stock_params = array('physical_quantity' => $stock->physical_quantity - $quantity, 'usable_quantity' => $is_usable ? $stock->usable_quantity - $quantity : $stock->usable_quantity);
                    // saves stock in warehouse
                    $stock->hydrate($stock_params);
                    $stock->update();
                    // saves stock mvt
                    $stock_mvt = new StockMvt();
                    $stock_mvt->hydrate($mvt_params);
                    $stock_mvt->save();
                    $return[$stock->id]['quantity'] = $quantity;
                    $return[$stock->id]['price_te'] = $stock->price_te;
                    break;
                case 'LIFO':
                case 'FIFO':
                    // for each stock, parse its mvts history to calculate the quantities left for each positive mvt,
                    // according to the instant available quantities for this stock
                    foreach ($stock_collection as $stock) {
                        $left_quantity_to_check = $stock->physical_quantity;
                        if ($left_quantity_to_check <= 0) {
                            continue;
                        }
                        $resource = Db::getInstance(_PS_USE_SQL_SLAVE_)->query('
							SELECT sm.`id_stock_mvt`, sm.`date_add`, sm.`physical_quantity`,
								IF ((sm2.`physical_quantity` is null), sm.`physical_quantity`, (sm.`physical_quantity` - SUM(sm2.`physical_quantity`))) as qty
							FROM `' . _DB_PREFIX_ . 'stock_mvt` sm
							LEFT JOIN `' . _DB_PREFIX_ . 'stock_mvt` sm2 ON sm2.`referer` = sm.`id_stock_mvt`
							WHERE sm.`sign` = 1
							AND sm.`id_stock` = ' . (int) $stock->id . '
							GROUP BY sm.`id_stock_mvt`
							ORDER BY sm.`date_add` DESC');
                        while ($row = Db::getInstance()->nextRow($resource)) {
                            // break - in FIFO mode, we have to retreive the oldest positive mvts for which there are left quantities
                            if ($warehouse->management_type == 'FIFO') {
                                if ($row['qty'] == 0) {
                                    break;
                                }
                            }
                            // converts date to timestamp
                            $date = new DateTime($row['date_add']);
                            $timestamp = $date->format('U');
                            // history of the mvt
                            $stock_history_qty_available[$timestamp] = array('id_stock' => $stock->id, 'id_stock_mvt' => (int) $row['id_stock_mvt'], 'qty' => (int) $row['qty']);
                            // break - in LIFO mode, checks only the necessary history to handle the global quantity for the current stock
                            if ($warehouse->management_type == 'LIFO') {
                                $left_quantity_to_check -= (int) $row['physical_quantity'];
                                if ($left_quantity_to_check <= 0) {
                                    break;
                                }
                            }
                        }
                    }
                    if ($warehouse->management_type == 'LIFO') {
                        // orders stock history by timestamp to get newest history first
                        krsort($stock_history_qty_available);
                    } else {
                        // orders stock history by timestamp to get oldest history first
                        ksort($stock_history_qty_available);
                    }
                    // checks each stock to manage the real quantity to decrement for each of them
                    foreach ($stock_history_qty_available as $entry) {
                        if ($entry['qty'] >= $global_quantity_to_decrement) {
                            $quantity_to_decrement_by_stock[$entry['id_stock']][$entry['id_stock_mvt']] = $global_quantity_to_decrement;
                            $global_quantity_to_decrement = 0;
                        } else {
                            $quantity_to_decrement_by_stock[$entry['id_stock']][$entry['id_stock_mvt']] = $entry['qty'];
                            $global_quantity_to_decrement -= $entry['qty'];
                        }
                        if ($global_quantity_to_decrement <= 0) {
                            break;
                        }
                    }
                    // for each stock, decrements it and logs the mvts
                    foreach ($stock_collection as $stock) {
                        if (array_key_exists($stock->id, $quantity_to_decrement_by_stock) && is_array($quantity_to_decrement_by_stock[$stock->id])) {
                            $total_quantity_for_current_stock = 0;
                            foreach ($quantity_to_decrement_by_stock[$stock->id] as $id_mvt_referrer => $qte) {
                                $mvt_params = array('id_stock' => $stock->id, 'physical_quantity' => $qte, 'id_stock_mvt_reason' => $id_stock_mvt_reason, 'id_order' => $id_order, 'price_te' => $stock->price_te, 'sign' => -1, 'referer' => $id_mvt_referrer, 'id_employee' => $context->employee->id);
                                // saves stock mvt
                                $stock_mvt = new StockMvt();
                                $stock_mvt->hydrate($mvt_params);
                                $stock_mvt->save();
                                $total_quantity_for_current_stock += $qte;
                            }
                            $stock_params = array('physical_quantity' => $stock->physical_quantity - $total_quantity_for_current_stock, 'usable_quantity' => $is_usable ? $stock->usable_quantity - $total_quantity_for_current_stock : $stock->usable_quantity);
                            $return[$stock->id]['quantity'] = $total_quantity_for_current_stock;
                            $return[$stock->id]['price_te'] = $stock->price_te;
                            // saves stock in warehouse
                            $stock->hydrate($stock_params);
                            $stock->update();
                        }
                    }
                    break;
            }
        }
        // if we remove a usable quantity, exec hook
        if ($is_usable) {
            Hook::exec('actionProductCoverage', array('id_product' => $id_product, 'id_product_attribute' => $id_product_attribute, 'warehouse' => $warehouse));
        }
        return $return;
    }
    public function update_order_products($order_id, $id_product, $id_product_attribute, $SKU, $Title, $Quantity, $Amount, $Amount_tax_excl)
    {
        $prefix = _DB_PREFIX_;
        $sql = 'SELECT id_order_detail FROM `' . $prefix . 'order_detail` where `id_order` = ' . $order_id . ' AND
							`product_id` = "' . $id_product . '" AND
							`product_attribute_id` = "' . $id_product_attribute . '"';
        $results = Db::getInstance()->ExecuteS($sql);
        $id_lang = (int) $this->context->cart->id_lang;
        $sql = 'select att.id_attribute,attr_grp.name,att.id_attribute_group,att_val.name as value from ' . $prefix . 'product_attribute_combination as att_comb left join ' . $prefix . 'attribute as att on att_comb.id_attribute = att.id_attribute left join ' . $prefix . 'attribute_group_lang as attr_grp on attr_grp.id_attribute_group = att.id_attribute_group left join ' . $prefix . 'attribute_lang as att_val on att_val.id_attribute = att.id_attribute where att_comb.id_product_attribute = "' . $id_product_attribute . '" and att_val.id_lang = "' . $id_lang . '" and attr_grp.id_lang = "' . $id_lang . '"';
        $product_attr = Db::getInstance()->ExecuteS($sql);
        $Title .= ' - ';
        foreach ($product_attr as $attr) {
            $Title .= $attr['name'] . ' : ' . $attr['value'] . ', ';
        }
        $Title = trim($Title);
        $Title = substr($Title, 0, -1);
        if (empty($results)) {
            $sql = 'INSERT into `' . $prefix . 'order_detail` set
							`id_order` = ' . $order_id . ',
							`product_id` = ' . $id_product . ',
							`product_attribute_id` = ' . $id_product_attribute . ',
							`product_name` = "' . $Title . '",
							`product_quantity` = ' . $Quantity . ',
							`product_quantity_in_stock` = ' . $Quantity . ',
							`product_price` = ' . $Amount . ',
							`product_reference` = "' . $SKU . '",
							`total_price_tax_incl` = ' . $Amount * $Quantity . ',
							`total_price_tax_excl` = ' . $Amount_tax_excl * $Quantity . ',
							`unit_price_tax_incl` = ' . $Amount . ',
							`unit_price_tax_excl` = ' . $Amount_tax_excl . ',
							`original_product_price` = ' . $Amount . '
							';
        } else {
            $sql = 'UPDATE `' . $prefix . 'order_detail` set
							`product_name` = "' . $Title . '",
							`product_quantity` = ' . $Quantity . ',
							`product_quantity_in_stock` = ' . $Quantity . ',
							`product_price` = ' . $Amount . ',
							`product_reference` = "' . $SKU . '",
							`total_price_tax_incl` = ' . $Amount * $Quantity . ',
							`total_price_tax_excl` = ' . $Amount_tax_excl * $Quantity . ',
							`unit_price_tax_incl` = ' . $Amount . ',
							`unit_price_tax_excl` = ' . $Amount_tax_excl . ',
							`original_product_price` = ' . $Amount . ' where 
							`id_order` = "' . $order_id . '" AND
							`product_id` = "' . $id_product . '" AND  
							`product_attribute_id` = "' . $id_product_attribute . '"
							';
        }
        Db::getInstance()->Execute($sql);
        if (Pack::isPack($id_product)) {
            $product = new Product((int) $id_product);
            if ($product->pack_stock_type == 1 || $product->pack_stock_type == 2) {
                $products_pack = Pack::getItems($id_product, (int) Configuration::get('PS_LANG_DEFAULT'));
                foreach ($products_pack as $product_pack) {
                    $sql = 'UPDATE `' . $prefix . 'stock_available` set
							`quantity` = `quantity` - ' . $product_pack->pack_quantity * $Quantity . '
							where `id_product` = ' . $product_pack->id . ' and
							`id_product_attribute` = 0
									';
                    Db::getInstance()->Execute($sql);
                    if ($product_pack->id_pack_product_attribute > 0) {
                        $sql = 'UPDATE `' . $prefix . 'stock_available` set
										`quantity` = `quantity` - ' . $product_pack->pack_quantity * $Quantity . '
										where `id_product` = ' . $product_pack->id . ' and
										`id_product_attribute` = ' . $product_pack->id_pack_product_attribute . '
										';
                        Db::getInstance()->Execute($sql);
                    }
                }
            }
            if ($product->pack_stock_type == 0 || $product->pack_stock_type == 2 || $product->pack_stock_type == 3 && (Configuration::get('PS_PACK_STOCK_TYPE') == 0 || Configuration::get('PS_PACK_STOCK_TYPE') == 2)) {
                $sql = 'UPDATE `' . $prefix . 'stock_available` set
							`quantity` = `quantity` - ' . $Quantity . '
							where `id_product` = ' . $id_product . ' and
							`id_product_attribute` = 0
							';
                Db::getInstance()->Execute($sql);
                if ($id_product_attribute > 0) {
                    $sql = 'UPDATE `' . $prefix . 'stock_available` set
									`quantity` = `quantity` - ' . $Quantity . '
									where `id_product` = ' . $id_product . ' and
									`id_product_attribute` = ' . $id_product_attribute . '
									';
                    Db::getInstance()->Execute($sql);
                }
                $date = date('Y-m-d');
                $sql = 'UPDATE `' . $prefix . 'product_sale` set
								`quantity` = `quantity` + ' . $Quantity . ',
								`sale_nbr` = `sale_nbr` + ' . $Quantity . ',
								`date_upd` = ' . $date . '
								where `id_product` = ' . $id_product . '
								';
                Db::getInstance()->Execute($sql);
            }
        } else {
            $sql = 'UPDATE `' . $prefix . 'stock_available` set
							`quantity` = `quantity` - ' . $Quantity . '
							where `id_product` = ' . $id_product . ' and
							`id_product_attribute` = 0
							';
            Db::getInstance()->Execute($sql);
            if ($id_product_attribute > 0) {
                $sql = 'UPDATE `' . $prefix . 'stock_available` set
								`quantity` = `quantity` - ' . $Quantity . '
								where `id_product` = ' . $id_product . ' and
								`id_product_attribute` = ' . $id_product_attribute . '
								';
                Db::getInstance()->Execute($sql);
            }
            $date = date('Y-m-d');
            $sql = 'UPDATE `' . $prefix . 'product_sale` set
							`quantity` = `quantity` + ' . $Quantity . ',
							`sale_nbr` = `sale_nbr` + ' . $Quantity . ',
							`date_upd` = ' . $date . '
							where `id_product` = ' . $id_product . '
							';
            Db::getInstance()->Execute($sql);
        }
    }
Exemple #6
0
 protected function initPack(Product $product)
 {
     $this->tpl_form_vars['is_pack'] = $product->id && Pack::isPack($product->id) || Tools::getValue('type_product') == Product::PTYPE_PACK;
     $product->packItems = Pack::getItems($product->id, $this->context->language->id);
     $input_pack_items = '';
     if (Tools::getValue('inputPackItems')) {
         $input_pack_items = Tools::getValue('inputPackItems');
     } else {
         foreach ($product->packItems as $pack_item) {
             $input_pack_items .= $pack_item->pack_quantity . 'x' . $pack_item->id . '-';
         }
     }
     $this->tpl_form_vars['input_pack_items'] = $input_pack_items;
     $input_namepack_items = '';
     if (Tools::getValue('namePackItems')) {
         $input_namepack_items = Tools::getValue('namePackItems');
     } else {
         foreach ($product->packItems as $pack_item) {
             $input_namepack_items .= $pack_item->pack_quantity . ' x ' . $pack_item->name . '¤';
         }
     }
     $this->tpl_form_vars['input_namepack_items'] = $input_namepack_items;
 }
    private function displayPack(Product $obj)
    {
        global $currentIndex, $cookie;
        $boolPack = ($obj->id and Pack::isPack($obj->id) or Tools::getValue('ppack')) ? true : false;
        $packItems = $boolPack ? Pack::getItems($obj->id, $cookie->id_lang) : array();
        echo '
		<tr>
			<td>
				<input type="checkbox" name="ppack" id="ppack" value="1"' . ($boolPack ? ' checked="checked"' : '') . ' onclick="$(\'#ppackdiv\').slideToggle();" />
				<label class="t" for="ppack">' . $this->l('Pack') . '</label>
			</td>
			<td>
				<div id="ppackdiv" ' . ($boolPack ? '' : ' style="display: none;"') . '>
					<div id="divPackItems">';
        foreach ($packItems as $packItem) {
            echo $packItem->pack_quantity . ' x ' . $packItem->name . '<span onclick="delPackItem(' . $packItem->id . ');" style="cursor: pointer;"><img src="../img/admin/delete.gif" /></span><br />';
        }
        echo '		</div>
					<input type="hidden" name="inputPackItems" id="inputPackItems" value="';
        if (Tools::getValue('inputPackItems')) {
            echo Tools::getValue('inputPackItems');
        } else {
            foreach ($packItems as $packItem) {
                echo $packItem->pack_quantity . 'x' . $packItem->id . '-';
            }
        }
        echo '" />
					<input type="hidden" name="namePackItems" id="namePackItems" value="';
        if (Tools::getValue('namePackItems')) {
            echo Tools::getValue('namePackItems');
        } else {
            foreach ($packItems as $packItem) {
                echo $packItem->pack_quantity . ' x ' . $packItem->name . '¤';
            }
        }
        echo '" />
					<input type="hidden" size="2" id="curPackItemId" />

					<p class="clear">' . $this->l('Begin typing the first letters of the product name, then select the product from the drop-down list:') . '
					<br />' . $this->l('You cannot add downloadable products to a pack.') . '</p>
					<input type="text" size="25" id="curPackItemName" />
					<input type="text" name="curPackItemQty" id="curPackItemQty" value="1" size="1" />
					<script language="javascript">
					' . $this->addPackItem() . '
					' . $this->delPackItem() . '

					</script>
					<span onclick="addPackItem();" style="cursor: pointer;"><img src="../img/admin/add.gif" alt="' . $this->l('Add an item to the pack') . '" title="' . $this->l('Add an item to the pack') . '" /></span>
				</td>
			</div>
		</tr>';
        // param multipleSeparator:'||' ajouté à cause de bug dans lib autocomplete
        echo '<script type="text/javascript">
								urlToCall = null;
								/* function autocomplete */
								$(function() {
									$(\'#curPackItemName\')
										.autocomplete(\'ajax_products_list.php\', {
											delay: 100,
											minChars: 1,
											autoFill: true,
											max:20,
											matchContains: true,
											mustMatch:true,
											scroll:false,
											cacheLength:0,
											multipleSeparator:\'||\',
											formatItem: function(item) {
												return item[1]+\' - \'+item[0];
											}
										}).result(function(event, item){
											$(\'#curPackItemId\').val(item[1]);
										});
										$(\'#curPackItemName\').setOptions({
											extraParams: {excludeIds : getSelectedIds(), excludeVirtuals : 1}
										});

								});


								function getSelectedIds()
								{
									// input lines QTY x ID-
									var ids = ' . $obj->id . '+\',\';
									ids += $(\'#inputPackItems\').val().replace(/\\d+x/g, \'\').replace(/\\-/g,\',\');
									ids = ids.replace(/\\,$/,\'\');

									return ids;

								}

								function getAccessorieIds()
								{
									var ids = ' . $obj->id . '+\',\';
									ids += $(\'#inputAccessories\').val().replace(/\\-/g,\',\').replace(/\\,$/,\'\');
									ids = ids.replace(/\\,$/,\'\');

									return ids;
								}

			</script>';
    }
Exemple #8
0
 /**
  * For a given id_product and id_product_attribute updates the quantity available
  *
  * @param int $id_product
  * @param int $id_product_attribute Optional
  * @param int $delta_quantity The delta quantity to update
  * @param int $id_shop Optional
  */
 public static function updateQuantity($id_product, $id_product_attribute, $delta_quantity, $id_shop = null)
 {
     if (!Validate::isUnsignedId($id_product)) {
         return false;
     }
     $id_stock_available = StockAvailable::getStockAvailableIdByProductId($id_product, $id_product_attribute, $id_shop);
     if (!$id_stock_available) {
         return false;
     }
     // Update quantity of the pack products
     if (Pack::isPack($id_product)) {
         $products_pack = Pack::getItems($id_product, (int) Configuration::get('PS_LANG_DEFAULT'));
         foreach ($products_pack as $product_pack) {
             $pack_id_product_attribute = Product::getDefaultAttribute($product_pack->id, 1);
             StockAvailable::updateQuantity($product_pack->id, $pack_id_product_attribute, $product_pack->pack_quantity * $delta_quantity, $id_shop);
         }
     }
     $stock_available = new StockAvailable($id_stock_available);
     $stock_available->quantity = $stock_available->quantity + $delta_quantity;
     $stock_available->update();
     Hook::exec('actionUpdateQuantity', array('id_product' => $id_product, 'id_product_attribute' => $id_product_attribute, 'quantity' => $stock_available->quantity));
 }
 public function initContentForQuantities()
 {
     if ($this->object->id) {
         $tfowlgstly = "show_quantities";
         ${"GLOBALS"}["ygzeqkb"] = "show_quantities";
         $gmgclvkrjy = "attributes";
         ${"GLOBALS"}["jhngqfjufp"] = "attributes";
         $cggvbxsk = "attributes";
         ${${"GLOBALS"}["jhngqfjufp"]} = $this->object->getAttributesResume($this->context->language->id);
         ${"GLOBALS"}["aofqmvff"] = "attribute";
         ${"GLOBALS"}["vyyogyvfbtx"] = "attributes";
         $nfdcluhk = "attributes";
         $khzorwi = "shop_context";
         if (empty(${$nfdcluhk})) {
             ${$cggvbxsk}[] = array("id_product_attribute" => 0, "attribute_designation" => "");
         }
         ${"GLOBALS"}["klqbahrije"] = "shop_context";
         ${${"GLOBALS"}["ldfuknydnzr"]} = array();
         ${${"GLOBALS"}["ymshseez"]} = array();
         ${"GLOBALS"}["lztnksxrb"] = "group_shop";
         foreach (${${"GLOBALS"}["vyyogyvfbtx"]} as ${${"GLOBALS"}["aofqmvff"]}) {
             $rvrxkz = "product_designation";
             $ycvvjwmxtnm = "attribute";
             $dxuqsu = "available_quantity";
             ${$dxuqsu}[${${"GLOBALS"}["iixdipeiyldv"]}["id_product_attribute"]] = StockAvailable::getQuantityAvailableByProduct((int) $this->object->id, ${$ycvvjwmxtnm}["id_product_attribute"]);
             ${$rvrxkz}[${${"GLOBALS"}["iixdipeiyldv"]}["id_product_attribute"]] = rtrim($this->object->name[$this->context->language->id] . " - " . ${${"GLOBALS"}["iixdipeiyldv"]}["attribute_designation"], " - ");
         }
         ${${"GLOBALS"}["ueicxl"]} = true;
         ${$khzorwi} = Shop::getContext();
         ${${"GLOBALS"}["lztnksxrb"]} = $this->context->shop->getGroup();
         $wktpughd = "pack_quantity";
         ${"GLOBALS"}["eukvwdf"] = "advanced_stock_management_warning";
         if (${${"GLOBALS"}["klqbahrije"]} == Shop::CONTEXT_ALL) {
             ${$tfowlgstly} = false;
         } elseif (${${"GLOBALS"}["ohyfjtkcy"]} == Shop::CONTEXT_GROUP) {
             if (!$group_shop->share_stock) {
                 ${${"GLOBALS"}["ueicxl"]} = false;
             }
         } else {
             $eksumjgu = "show_quantities";
             if ($group_shop->share_stock) {
                 ${$eksumjgu} = false;
             }
         }
         self::$smarty->assign("ps_stock_management", Configuration::get("PS_STOCK_MANAGEMENT"));
         self::$smarty->assign("has_attribute", $this->object->hasAttributes());
         if (Combination::isFeatureActive()) {
             self::$smarty->assign("countAttributes", (int) Db::getInstance()->getValue("SELECT COUNT(id_product) FROM " . _DB_PREFIX_ . "product_attribute WHERE id_product = " . (int) $this->object->id));
         }
         ${${"GLOBALS"}["eukvwdf"]} = false;
         if (Configuration::get("PS_ADVANCED_STOCK_MANAGEMENT") && $this->object->advanced_stock_management) {
             ${"GLOBALS"}["awunkp"] = "p_attributes";
             ${"GLOBALS"}["qxobmbos"] = "warehouses";
             ${"GLOBALS"}["cjtetqei"] = "warehouses";
             $ukjfpwyojlf = "p_attribute";
             ${${"GLOBALS"}["iczelyves"]} = Product::getProductAttributesIds($this->object->id);
             ${"GLOBALS"}["kcjlbgqb"] = "advanced_stock_management_warning";
             ${"GLOBALS"}["dlsnuhn"] = "warehouses";
             ${${"GLOBALS"}["qxobmbos"]} = array();
             ${"GLOBALS"}["ojmjigmfve"] = "p_attributes";
             if (!${${"GLOBALS"}["awunkp"]}) {
                 ${${"GLOBALS"}["mdrvdmghqrtc"]}[] = Warehouse::getProductWarehouseList($this->object->id, 0);
             }
             foreach (${${"GLOBALS"}["ojmjigmfve"]} as ${$ukjfpwyojlf}) {
                 ${"GLOBALS"}["uevlubu"] = "ws";
                 ${"GLOBALS"}["fpbyfow"] = "warehouses";
                 ${"GLOBALS"}["inddsyj"] = "ws";
                 ${${"GLOBALS"}["yrbmurnh"]} = Warehouse::getProductWarehouseList($this->object->id, ${${"GLOBALS"}["bhprusfblhn"]}["id_product_attribute"]);
                 if (${${"GLOBALS"}["uevlubu"]}) {
                     ${${"GLOBALS"}["fpbyfow"]}[] = ${${"GLOBALS"}["inddsyj"]};
                 }
             }
             ${${"GLOBALS"}["dlsnuhn"]} = array_unique(${${"GLOBALS"}["cjtetqei"]});
             if (empty(${${"GLOBALS"}["mdrvdmghqrtc"]})) {
                 ${${"GLOBALS"}["kcjlbgqb"]} = true;
             }
         }
         if (${${"GLOBALS"}["uucoxnutvd"]}) {
             $this->displayWarning($this->getMessage("If you wish to use the advanced stock management, you have to:"));
             $this->displayWarning("- " . $this->getMessage("associate your products with warehouses"));
             $this->displayWarning("- " . $this->getMessage("associate your warehouses with carriers"));
             $this->displayWarning("- " . $this->getMessage("associate your warehouses with the appropriate shops"));
         }
         ${${"GLOBALS"}["qbmqjuoutyh"]} = null;
         if (Pack::isPack($this->object->id)) {
             ${"GLOBALS"}["wdcmwsfvsft"] = "pack_quantity";
             $mdjqucflf = "items";
             ${${"GLOBALS"}["wfbswtei"]} = Pack::getItems((int) $this->object->id, Configuration::get("PS_LANG_DEFAULT"));
             $mhikkwxp = "pack_quantities";
             ${"GLOBALS"}["kamnnzyptd"] = "pack_quantities";
             ${${"GLOBALS"}["kamnnzyptd"]} = array();
             foreach (${$mdjqucflf} as ${${"GLOBALS"}["gpnqjgaosuld"]}) {
                 if (!$item->isAvailableWhenOutOfStock((int) $item->out_of_stock)) {
                     $gkwutr = "pack_id_product_attribute";
                     ${${"GLOBALS"}["wkyidmmlbbc"]} = Product::getDefaultAttribute($item->id, 1);
                     ${${"GLOBALS"}["pnfrmcr"]}[] = Product::getQuantity($item->id, ${$gkwutr}) / ($item->pack_quantity !== 0 ? $item->pack_quantity : 1);
                 }
             }
             $oissvbm = "pack_quantities";
             ${${"GLOBALS"}["wdcmwsfvsft"]} = ${$oissvbm}[0];
             foreach (${$mhikkwxp} as ${${"GLOBALS"}["kzwkbwmzgtl"]}) {
                 ${"GLOBALS"}["iwrwjuvdmi"] = "value";
                 if (${${"GLOBALS"}["qbmqjuoutyh"]} > ${${"GLOBALS"}["iwrwjuvdmi"]}) {
                     ${${"GLOBALS"}["qbmqjuoutyh"]} = ${${"GLOBALS"}["kzwkbwmzgtl"]};
                 }
             }
             if (!Warehouse::getPackWarehouses((int) $this->object->id)) {
                 $this->displayWarning($this->getMessage("You must have a common warehouse between this pack and its product."));
             }
         }
         ${${"GLOBALS"}["lixyhrpqnh"]} = new Language($this->id_language);
         self::$smarty->assign("iso_code", $lang->iso_code ? $lang->iso_code : "en");
         self::$smarty->assign(array("attributes" => ${$gmgclvkrjy}, "available_quantity" => ${${"GLOBALS"}["ldfuknydnzr"]}, "pack_quantity" => ${$wktpughd}, "stock_management_active" => Configuration::get("PS_ADVANCED_STOCK_MANAGEMENT"), "product_designation" => ${${"GLOBALS"}["ymshseez"]}, "show_quantities" => ${${"GLOBALS"}["ygzeqkb"]}, "order_out_of_stock" => Configuration::get("PS_ORDER_OUT_OF_STOCK")));
     } else {
         $this->displayWarning($this->getMessage("You must save this product before managing quantities."));
     }
 }
Exemple #10
0
    /**
     * Sets the new state of the given order
     *
     * @param int $new_order_state
     * @param int $id_order
     * @param bool $use_existing_payment
     */
    public function changeIdOrderState($new_order_state, &$id_order, $use_existing_payment = false)
    {
        if (!$new_order_state || !$id_order) {
            return;
        }
        if (!is_object($id_order) && is_numeric($id_order)) {
            $order = new Order((int) $id_order);
        } elseif (is_object($id_order)) {
            $order = $id_order;
        } else {
            return;
        }
        $new_os = new OrderState((int) $new_order_state, $order->id_lang);
        $old_os = $order->getCurrentOrderState();
        $is_validated = $this->isValidated();
        // executes hook
        if ($new_os->id == Configuration::get('PS_OS_PAYMENT')) {
            Hook::exec('actionPaymentConfirmation', array('id_order' => (int) $order->id));
        }
        // executes hook
        Hook::exec('actionOrderStatusUpdate', array('newOrderStatus' => $new_os, 'id_order' => (int) $order->id));
        if (Validate::isLoadedObject($order) && $old_os instanceof OrderState && $new_os instanceof OrderState) {
            // @since 1.5.0 : gets the stock manager
            $manager = null;
            if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                $manager = StockManagerFactory::getManager();
            }
            // foreach products of the order
            foreach ($order->getProductsDetail() as $product) {
                // if becoming logable => adds sale
                if ($new_os->logable && !$old_os->logable) {
                    ProductSale::addProductSale($product['product_id'], $product['product_quantity']);
                    // @since 1.5.0 - Stock Management
                    if (!Pack::isPack($product['product_id']) && ($old_os->id == Configuration::get('PS_OS_ERROR') || $old_os->id == Configuration::get('PS_OS_CANCELED')) && !StockAvailable::dependsOnStock($product['id_product'], (int) $order->id_shop)) {
                        StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], -(int) $product['product_quantity'], $order->id_shop);
                    }
                } elseif (!$new_os->logable && $old_os->logable) {
                    ProductSale::removeProductSale($product['product_id'], $product['product_quantity']);
                    // @since 1.5.0 - Stock Management
                    if (!Pack::isPack($product['product_id']) && ($new_os->id == Configuration::get('PS_OS_ERROR') || $new_os->id == Configuration::get('PS_OS_CANCELED')) && !StockAvailable::dependsOnStock($product['id_product'])) {
                        StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], (int) $product['product_quantity'], $order->id_shop);
                    }
                } elseif (!$new_os->logable && !$old_os->logable && ($new_os->id == Configuration::get('PS_OS_ERROR') || $new_os->id == Configuration::get('PS_OS_CANCELED')) && !StockAvailable::dependsOnStock($product['id_product'])) {
                    StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], (int) $product['product_quantity'], $order->id_shop);
                }
                // @since 1.5.0 : if the order is being shipped and this products uses the advanced stock management :
                // decrements the physical stock using $id_warehouse
                if ($new_os->shipped == 1 && $old_os->shipped == 0 && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && Warehouse::exists($product['id_warehouse']) && $manager != null && ((int) $product['advanced_stock_management'] == 1 || Pack::usesAdvancedStockManagement($product['product_id']))) {
                    // gets the warehouse
                    $warehouse = new Warehouse($product['id_warehouse']);
                    // decrements the stock (if it's a pack, the StockManager does what is needed)
                    $manager->removeProduct($product['product_id'], $product['product_attribute_id'], $warehouse, $product['product_quantity'], Configuration::get('PS_STOCK_CUSTOMER_ORDER_REASON'), true, (int) $order->id);
                } elseif ($new_os->shipped == 0 && $old_os->shipped == 1 && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && Warehouse::exists($product['id_warehouse']) && $manager != null && ((int) $product['advanced_stock_management'] == 1 || Pack::usesAdvancedStockManagement($product['product_id']))) {
                    // if the product is a pack, we restock every products in the pack using the last negative stock mvts
                    if (Pack::isPack($product['product_id'])) {
                        $pack_products = Pack::getItems($product['product_id'], Configuration::get('PS_LANG_DEFAULT'));
                        foreach ($pack_products as $pack_product) {
                            if ($pack_product->advanced_stock_management == 1) {
                                $mvts = StockMvt::getNegativeStockMvts($order->id, $pack_product->id, 0, $pack_product->pack_quantity * $product['product_quantity']);
                                foreach ($mvts as $mvt) {
                                    $manager->addProduct($pack_product->id, 0, new Warehouse($mvt['id_warehouse']), $mvt['physical_quantity'], null, $mvt['price_te'], true);
                                }
                                if (!StockAvailable::dependsOnStock($product['id_product'])) {
                                    StockAvailable::updateQuantity($pack_product->id, 0, (int) $pack_product->pack_quantity * $product['product_quantity'], $order->id_shop);
                                }
                            }
                        }
                    } else {
                        $mvts = StockMvt::getNegativeStockMvts($order->id, $product['product_id'], $product['product_attribute_id'], $product['product_quantity']);
                        foreach ($mvts as $mvt) {
                            $manager->addProduct($product['product_id'], $product['product_attribute_id'], new Warehouse($mvt['id_warehouse']), $mvt['physical_quantity'], null, $mvt['price_te'], true);
                        }
                    }
                }
            }
        }
        $this->id_order_state = (int) $new_order_state;
        // changes invoice number of order ?
        if (!Validate::isLoadedObject($new_os) || !Validate::isLoadedObject($order)) {
            die(Tools::displayError('Invalid new order state'));
        }
        // the order is valid if and only if the invoice is available and the order is not cancelled
        $order->current_state = $this->id_order_state;
        $order->valid = $new_os->logable;
        $order->update();
        if ($new_os->invoice && !$order->invoice_number) {
            $order->setInvoice($use_existing_payment);
        }
        // set orders as paid
        if ($new_os->paid == 1) {
            $invoices = $order->getInvoicesCollection();
            if ($order->total_paid != 0) {
                $payment_method = Module::getInstanceByName($order->module);
            }
            foreach ($invoices as $invoice) {
                $rest_paid = $invoice->getRestPaid();
                if ($rest_paid > 0) {
                    $payment = new OrderPayment();
                    $payment->order_reference = $order->reference;
                    $payment->id_currency = $order->id_currency;
                    $payment->amount = $rest_paid;
                    if ($order->total_paid != 0) {
                        $payment->payment_method = $payment_method->displayName;
                    } else {
                        $payment->payment_method = null;
                    }
                    // Update total_paid_real value for backward compatibility reasons
                    if ($payment->id_currency == $order->id_currency) {
                        $order->total_paid_real += $payment->amount;
                    } else {
                        $order->total_paid_real += Tools::ps_round(Tools::convertPrice($payment->amount, $payment->id_currency, false), 2);
                    }
                    $order->save();
                    $payment->conversion_rate = 1;
                    $payment->save();
                    Db::getInstance()->execute('
					INSERT INTO `' . _DB_PREFIX_ . 'order_invoice_payment`
					VALUES(' . (int) $invoice->id . ', ' . (int) $payment->id . ', ' . (int) $order->id . ')');
                }
            }
        }
        // updates delivery date even if it was already set by another state change
        if ($new_os->delivery) {
            $order->setDelivery();
        }
        // executes hook
        Hook::exec('actionOrderStatusPostUpdate', array('newOrderStatus' => $new_os, 'id_order' => (int) $order->id));
    }
Exemple #11
0
 /**
  * For a given id_product, synchronizes StockAvailable::quantity with Stock::usable_quantity
  *
  * @param int $id_product
  */
 public static function synchronize($id_product, $order_id_shop = null)
 {
     if (!Validate::isUnsignedId($id_product)) {
         return false;
     }
     //if product is pack sync recursivly product in pack
     if (Pack::isPack($id_product)) {
         if (Validate::isLoadedObject($product = new Product((int) $id_product))) {
             if ($product->pack_stock_type == 1 || $product->pack_stock_type == 2 || $product->pack_stock_type == 3 && Configuration::get('PS_PACK_STOCK_TYPE') > 0) {
                 $products_pack = Pack::getItems($id_product, (int) Configuration::get('PS_LANG_DEFAULT'));
                 foreach ($products_pack as $product_pack) {
                     StockAvailable::synchronize($product_pack->id, $order_id_shop);
                 }
             }
         } else {
             return false;
         }
     }
     // gets warehouse ids grouped by shops
     $ids_warehouse = Warehouse::getWarehousesGroupedByShops();
     if ($order_id_shop !== null) {
         $order_warehouses = array();
         $wh = Warehouse::getWarehouses(false, (int) $order_id_shop);
         foreach ($wh as $warehouse) {
             $order_warehouses[] = $warehouse['id_warehouse'];
         }
     }
     // gets all product attributes ids
     $ids_product_attribute = array();
     foreach (Product::getProductAttributesIds($id_product) as $id_product_attribute) {
         $ids_product_attribute[] = $id_product_attribute['id_product_attribute'];
     }
     // Allow to order the product when out of stock?
     $out_of_stock = StockAvailable::outOfStock($id_product);
     $manager = StockManagerFactory::getManager();
     // loops on $ids_warehouse to synchronize quantities
     foreach ($ids_warehouse as $id_shop => $warehouses) {
         // first, checks if the product depends on stock for the given shop $id_shop
         if (StockAvailable::dependsOnStock($id_product, $id_shop)) {
             // init quantity
             $product_quantity = 0;
             // if it's a simple product
             if (empty($ids_product_attribute)) {
                 $allowed_warehouse_for_product = WareHouse::getProductWarehouseList((int) $id_product, 0, (int) $id_shop);
                 $allowed_warehouse_for_product_clean = array();
                 foreach ($allowed_warehouse_for_product as $warehouse) {
                     $allowed_warehouse_for_product_clean[] = (int) $warehouse['id_warehouse'];
                 }
                 $allowed_warehouse_for_product_clean = array_intersect($allowed_warehouse_for_product_clean, $warehouses);
                 if ($order_id_shop != null && !count(array_intersect($allowed_warehouse_for_product_clean, $order_warehouses))) {
                     continue;
                 }
                 $product_quantity = $manager->getProductRealQuantities($id_product, null, $allowed_warehouse_for_product_clean, true);
                 Hook::exec('actionUpdateQuantity', array('id_product' => $id_product, 'id_product_attribute' => 0, 'quantity' => $product_quantity, 'id_shop' => $id_shop));
             } else {
                 foreach ($ids_product_attribute as $id_product_attribute) {
                     $allowed_warehouse_for_combination = WareHouse::getProductWarehouseList((int) $id_product, (int) $id_product_attribute, (int) $id_shop);
                     $allowed_warehouse_for_combination_clean = array();
                     foreach ($allowed_warehouse_for_combination as $warehouse) {
                         $allowed_warehouse_for_combination_clean[] = (int) $warehouse['id_warehouse'];
                     }
                     $allowed_warehouse_for_combination_clean = array_intersect($allowed_warehouse_for_combination_clean, $warehouses);
                     if ($order_id_shop != null && !count(array_intersect($allowed_warehouse_for_combination_clean, $order_warehouses))) {
                         continue;
                     }
                     $quantity = $manager->getProductRealQuantities($id_product, $id_product_attribute, $allowed_warehouse_for_combination_clean, true);
                     $query = new DbQuery();
                     $query->select('COUNT(*)');
                     $query->from('stock_available');
                     $query->where('id_product = ' . (int) $id_product . ' AND id_product_attribute = ' . (int) $id_product_attribute . StockAvailable::addSqlShopRestriction(null, $id_shop));
                     if ((int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query)) {
                         $query = array('table' => 'stock_available', 'data' => array('quantity' => $quantity), 'where' => 'id_product = ' . (int) $id_product . ' AND id_product_attribute = ' . (int) $id_product_attribute . StockAvailable::addSqlShopRestriction(null, $id_shop));
                         Db::getInstance()->update($query['table'], $query['data'], $query['where']);
                     } else {
                         $query = array('table' => 'stock_available', 'data' => array('quantity' => $quantity, 'depends_on_stock' => 1, 'out_of_stock' => $out_of_stock, 'id_product' => (int) $id_product, 'id_product_attribute' => (int) $id_product_attribute));
                         StockAvailable::addSqlShopParams($query['data'], $id_shop);
                         Db::getInstance()->insert($query['table'], $query['data']);
                     }
                     $product_quantity += $quantity;
                     Hook::exec('actionUpdateQuantity', array('id_product' => $id_product, 'id_product_attribute' => $id_product_attribute, 'quantity' => $quantity, 'id_shop' => $id_shop));
                 }
             }
             // updates
             // if $id_product has attributes, it also updates the sum for all attributes
             if ($order_id_shop != null && array_intersect($warehouses, $order_warehouses) || $order_id_shop == null) {
                 $query = array('table' => 'stock_available', 'data' => array('quantity' => $product_quantity), 'where' => 'id_product = ' . (int) $id_product . ' AND id_product_attribute = 0' . StockAvailable::addSqlShopRestriction(null, $id_shop));
                 Db::getInstance()->update($query['table'], $query['data'], $query['where']);
             }
         }
     }
     // In case there are no warehouses, removes product from StockAvailable
     if (count($ids_warehouse) == 0 && StockAvailable::dependsOnStock((int) $id_product)) {
         Db::getInstance()->update('stock_available', array('quantity' => 0), 'id_product = ' . (int) $id_product);
     }
     Cache::clean('StockAvailable::getQuantityAvailableByProduct_' . (int) $id_product . '*');
 }
 /**
  * On récupères les anciens produits qui composé ce pack
  * @param $iIdProduct
  * @return string
  */
 public function getOldProductsPacks($iIdProduct)
 {
     $aProductsPacks = Pack::getItems($iIdProduct, $this->context->language->id);
     $sProductsPacks = '<ul>';
     foreach ($aProductsPacks as $oProductPack) {
         $sProductsPacks .= '<li>' . sprintf($this->module->l('%1$s (Id product: %2$s, Reference: %3$s, Quantity: %4$d)', 'AdminNowImportPacks'), $oProductPack->name, $oProductPack->id, $oProductPack->reference, $oProductPack->pack_quantity) . '</li>';
     }
     $sProductsPacks .= '</ul>';
     return $sProductsPacks;
 }
Exemple #13
0
 /**
  * For a given id_product and id_product_attribute updates the quantity available
  *
  * @param int $id_product
  * @param int $id_product_attribute Optional
  * @param int $delta_quantity The delta quantity to update
  * @param int $id_shop Optional
  */
 public static function updateQuantity($id_product, $id_product_attribute, $delta_quantity, $id_shop = null)
 {
     if (!Validate::isUnsignedId($id_product)) {
         return false;
     }
     $id_stock_available = StockAvailable::getStockAvailableIdByProductId($id_product, $id_product_attribute, $id_shop);
     if (!$id_stock_available) {
         return false;
     }
     // Update quantity of the pack products
     if (Pack::isPack($id_product)) {
         if (Validate::isLoadedObject($product = new Product((int) $id_product))) {
             if ($product->pack_stock_type == 1 || $product->pack_stock_type == 2 || $product->pack_stock_type == 3 && Configuration::get('PS_PACK_STOCK_TYPE') > 0) {
                 $products_pack = Pack::getItems($id_product, (int) Configuration::get('PS_LANG_DEFAULT'));
                 foreach ($products_pack as $product_pack) {
                     StockAvailable::updateQuantity($product_pack->id, $product_pack->id_pack_product_attribute, $product_pack->pack_quantity * $delta_quantity, $id_shop);
                 }
             }
             $stock_available = new StockAvailable($id_stock_available);
             $stock_available->quantity = $stock_available->quantity + $delta_quantity;
             if ($product->pack_stock_type == 0 || $product->pack_stock_type == 2 || $product->pack_stock_type == 3 && (Configuration::get('PS_PACK_STOCK_TYPE') == 0 || Configuration::get('PS_PACK_STOCK_TYPE') == 2)) {
                 $stock_available->update();
             }
         } else {
             return false;
         }
     } else {
         $stock_available = new StockAvailable($id_stock_available);
         $stock_available->quantity = $stock_available->quantity + $delta_quantity;
         $stock_available->update();
     }
     Cache::clean('StockAvailable::getQuantityAvailableByProduct_' . (int) $id_product . '*');
     Hook::exec('actionUpdateQuantity', array('id_product' => $id_product, 'id_product_attribute' => $id_product_attribute, 'quantity' => $stock_available->quantity));
     return true;
 }
Exemple #14
0
 /**
  * For a given pack, returns the warehouse it can be shipped from
  *
  * @param int $id_product
  * @return int|bool id_warehouse or false
  */
 public static function getPackWarehouses($id_product, $id_shop = null)
 {
     if (!Pack::isPack($id_product)) {
         return false;
     }
     if (is_null($id_shop)) {
         $id_shop = Context::getContext()->shop->id;
     }
     // warehouses of the pack
     $pack_warehouses = WarehouseProductLocation::getCollection((int) $id_product);
     // products in the pack
     $products = Pack::getItems((int) $id_product, Configuration::get('PS_LANG_DEFAULT'));
     // array with all warehouses id to check
     $list = array();
     // fills $list
     foreach ($pack_warehouses as $pack_warehouse) {
         $list['pack_warehouses'][] = (int) $pack_warehouse->id_warehouse;
     }
     // for each products in the pack
     foreach ($products as $product) {
         if ($product->advanced_stock_management) {
             // gets the warehouses of one product
             $product_warehouses = Warehouse::getProductWarehouseList((int) $product->id, 0, (int) $id_shop);
             $list[(int) $product->id] = array();
             // fills array with warehouses for this product
             foreach ($product_warehouses as $product_warehouse) {
                 $list[(int) $product->id][] = $product_warehouse['id_warehouse'];
             }
         }
     }
     $res = false;
     // returns final list
     if (count($list) > 1) {
         $res = call_user_func_array('array_intersect', $list);
     }
     return $res;
 }
Exemple #15
0
    /**
     * Sets the new state of the given order
     *
     * @param int $new_order_state
     * @param int/object $id_order
     * @param bool $use_existing_payment
     */
    public function changeIdOrderState($new_order_state, $id_order, $use_existing_payment = false)
    {
        if (!$new_order_state || !$id_order) {
            return;
        }
        if (!is_object($id_order) && is_numeric($id_order)) {
            $order = new Order((int) $id_order);
        } elseif (is_object($id_order)) {
            $order = $id_order;
        } else {
            return;
        }
        ShopUrl::cacheMainDomainForShop($order->id_shop);
        $new_os = new OrderState((int) $new_order_state, $order->id_lang);
        $old_os = $order->getCurrentOrderState();
        $is_validated = $this->isValidated();
        // executes hook
        if (in_array($new_os->id, array(Configuration::get('PS_OS_PAYMENT'), Configuration::get('PS_OS_WS_PAYMENT')))) {
            Hook::exec('actionPaymentConfirmation', array('id_order' => (int) $order->id), null, false, true, false, $order->id_shop);
        }
        // executes hook
        Hook::exec('actionOrderStatusUpdate', array('newOrderStatus' => $new_os, 'id_order' => (int) $order->id), null, false, true, false, $order->id_shop);
        if (Validate::isLoadedObject($order) && $new_os instanceof OrderState) {
            // An email is sent the first time a virtual item is validated
            $virtual_products = $order->getVirtualProducts();
            if ($virtual_products && (!$old_os || !$old_os->logable) && $new_os && $new_os->logable) {
                $context = Context::getContext();
                $assign = array();
                foreach ($virtual_products as $key => $virtual_product) {
                    $id_product_download = ProductDownload::getIdFromIdProduct($virtual_product['product_id']);
                    $product_download = new ProductDownload($id_product_download);
                    // If this virtual item has an associated file, we'll provide the link to download the file in the email
                    if ($product_download->display_filename != '') {
                        $assign[$key]['name'] = $product_download->display_filename;
                        $dl_link = $product_download->getTextLink(false, $virtual_product['download_hash']) . '&id_order=' . (int) $order->id . '&secure_key=' . $order->secure_key;
                        $assign[$key]['link'] = $dl_link;
                        if (isset($virtual_product['download_deadline']) && $virtual_product['download_deadline'] != '0000-00-00 00:00:00') {
                            $assign[$key]['deadline'] = Tools::displayDate($virtual_product['download_deadline']);
                        }
                        if ($product_download->nb_downloadable != 0) {
                            $assign[$key]['downloadable'] = (int) $product_download->nb_downloadable;
                        }
                    }
                }
                $customer = new Customer((int) $order->id_customer);
                $links = '<ul>';
                foreach ($assign as $product) {
                    $links .= '<li>';
                    $links .= '<a href="' . $product['link'] . '">' . Tools::htmlentitiesUTF8($product['name']) . '</a>';
                    if (isset($product['deadline'])) {
                        $links .= '&nbsp;' . Tools::htmlentitiesUTF8(Tools::displayError('expires on', false)) . '&nbsp;' . $product['deadline'];
                    }
                    if (isset($product['downloadable'])) {
                        $links .= '&nbsp;' . Tools::htmlentitiesUTF8(sprintf(Tools::displayError('downloadable %d time(s)', false), (int) $product['downloadable']));
                    }
                    $links .= '</li>';
                }
                $links .= '</ul>';
                $data = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => (int) $order->id, '{order_name}' => $order->getUniqReference(), '{nbProducts}' => count($virtual_products), '{virtualProducts}' => $links);
                // If there's at least one downloadable file
                if (!empty($assign)) {
                    Mail::Send((int) $order->id_lang, 'download_product', Mail::l('Virtual product to download', $order->id_lang), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop);
                }
            }
            // @since 1.5.0 : gets the stock manager
            $manager = null;
            if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
                $manager = StockManagerFactory::getManager();
            }
            $errorOrCanceledStatuses = array(Configuration::get('PS_OS_ERROR'), Configuration::get('PS_OS_CANCELED'));
            // foreach products of the order
            if (Validate::isLoadedObject($old_os)) {
                foreach ($order->getProductsDetail() as $product) {
                    // if becoming logable => adds sale
                    if ($new_os->logable && !$old_os->logable) {
                        ProductSale::addProductSale($product['product_id'], $product['product_quantity']);
                        // @since 1.5.0 - Stock Management
                        if (!Pack::isPack($product['product_id']) && in_array($old_os->id, $errorOrCanceledStatuses) && !StockAvailable::dependsOnStock($product['id_product'], (int) $order->id_shop)) {
                            StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], -(int) $product['product_quantity'], $order->id_shop);
                        }
                    } elseif (!$new_os->logable && $old_os->logable) {
                        ProductSale::removeProductSale($product['product_id'], $product['product_quantity']);
                        // @since 1.5.0 - Stock Management
                        if (!Pack::isPack($product['product_id']) && in_array($new_os->id, $errorOrCanceledStatuses) && !StockAvailable::dependsOnStock($product['id_product'])) {
                            StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], (int) $product['product_quantity'], $order->id_shop);
                        }
                    } elseif (!$new_os->logable && !$old_os->logable && in_array($new_os->id, $errorOrCanceledStatuses) && !in_array($old_os->id, $errorOrCanceledStatuses) && !StockAvailable::dependsOnStock($product['id_product'])) {
                        StockAvailable::updateQuantity($product['product_id'], $product['product_attribute_id'], (int) $product['product_quantity'], $order->id_shop);
                    }
                    // @since 1.5.0 : if the order is being shipped and this products uses the advanced stock management :
                    // decrements the physical stock using $id_warehouse
                    if ($new_os->shipped == 1 && $old_os->shipped == 0 && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && Warehouse::exists($product['id_warehouse']) && $manager != null && ((int) $product['advanced_stock_management'] == 1 || Pack::usesAdvancedStockManagement($product['product_id']))) {
                        // gets the warehouse
                        $warehouse = new Warehouse($product['id_warehouse']);
                        // decrements the stock (if it's a pack, the StockManager does what is needed)
                        $manager->removeProduct($product['product_id'], $product['product_attribute_id'], $warehouse, $product['product_quantity'], Configuration::get('PS_STOCK_CUSTOMER_ORDER_REASON'), true, (int) $order->id);
                    } elseif ($new_os->shipped == 0 && $old_os->shipped == 1 && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') && Warehouse::exists($product['id_warehouse']) && $manager != null && ((int) $product['advanced_stock_management'] == 1 || Pack::usesAdvancedStockManagement($product['product_id']))) {
                        // if the product is a pack, we restock every products in the pack using the last negative stock mvts
                        if (Pack::isPack($product['product_id'])) {
                            $pack_products = Pack::getItems($product['product_id'], Configuration::get('PS_LANG_DEFAULT', null, null, $order->id_shop));
                            foreach ($pack_products as $pack_product) {
                                if ($pack_product->advanced_stock_management == 1) {
                                    $mvts = StockMvt::getNegativeStockMvts($order->id, $pack_product->id, 0, $pack_product->pack_quantity * $product['product_quantity']);
                                    foreach ($mvts as $mvt) {
                                        $manager->addProduct($pack_product->id, 0, new Warehouse($mvt['id_warehouse']), $mvt['physical_quantity'], null, $mvt['price_te'], true);
                                    }
                                    if (!StockAvailable::dependsOnStock($product['id_product'])) {
                                        StockAvailable::updateQuantity($pack_product->id, 0, (int) $pack_product->pack_quantity * $product['product_quantity'], $order->id_shop);
                                    }
                                }
                            }
                        } else {
                            $mvts = StockMvt::getNegativeStockMvts($order->id, $product['product_id'], $product['product_attribute_id'], $product['product_quantity']);
                            foreach ($mvts as $mvt) {
                                $manager->addProduct($product['product_id'], $product['product_attribute_id'], new Warehouse($mvt['id_warehouse']), $mvt['physical_quantity'], null, $mvt['price_te'], true);
                            }
                        }
                    }
                }
            }
        }
        $this->id_order_state = (int) $new_order_state;
        // changes invoice number of order ?
        if (!Validate::isLoadedObject($new_os) || !Validate::isLoadedObject($order)) {
            die(Tools::displayError('Invalid new order state'));
        }
        // the order is valid if and only if the invoice is available and the order is not cancelled
        $order->current_state = $this->id_order_state;
        $order->valid = $new_os->logable;
        $order->update();
        if ($new_os->invoice && !$order->invoice_number) {
            $order->setInvoice($use_existing_payment);
        }
        // set orders as paid
        if ($new_os->paid == 1) {
            $invoices = $order->getInvoicesCollection();
            if ($order->total_paid != 0) {
                $payment_method = Module::getInstanceByName($order->module);
            }
            foreach ($invoices as $invoice) {
                $rest_paid = $invoice->getRestPaid();
                if ($rest_paid > 0) {
                    $payment = new OrderPayment();
                    $payment->order_reference = $order->reference;
                    $payment->id_currency = $order->id_currency;
                    $payment->amount = $rest_paid;
                    if ($order->total_paid != 0) {
                        $payment->payment_method = $payment_method->displayName;
                    } else {
                        $payment->payment_method = null;
                    }
                    // Update total_paid_real value for backward compatibility reasons
                    if ($payment->id_currency == $order->id_currency) {
                        $order->total_paid_real += $payment->amount;
                    } else {
                        $order->total_paid_real += Tools::ps_round(Tools::convertPrice($payment->amount, $payment->id_currency, false), 2);
                    }
                    $order->save();
                    $payment->conversion_rate = 1;
                    $payment->save();
                    Db::getInstance()->execute('
					INSERT INTO `' . _DB_PREFIX_ . 'order_invoice_payment`
					VALUES(' . (int) $invoice->id . ', ' . (int) $payment->id . ', ' . (int) $order->id . ')');
                }
            }
        }
        // updates delivery date even if it was already set by another state change
        if ($new_os->delivery) {
            $order->setDelivery();
        }
        // executes hook
        Hook::exec('actionOrderStatusPostUpdate', array('newOrderStatus' => $new_os, 'id_order' => (int) $order->id), null, false, true, false, $order->id_shop);
        ShopUrl::resetMainDomainCache();
    }
    private function displayPack(Product $obj)
    {
        global $currentIndex, $cookie;
        $boolPack = ($obj->id and Pack::isPack($obj->id) or Tools::getValue('ppack')) ? true : false;
        $packItems = $boolPack ? Pack::getItems($obj->id, $cookie->id_lang) : array();
        echo '
		<tr>
			<td>
				<input type="checkbox" name="ppack" id="ppack" value="1"' . ($boolPack ? ' checked="checked"' : '') . ' onchange="openCloseLayer(\'ppackdiv\');" />
				<label class="t" for="ppack">' . $this->l('Pack') . '</label>
			</td>
			<td>
				<div id="ppackdiv" ' . ($boolPack ? '' : ' style="display: none;"') . '>
					<div id="divPackItems">';
        foreach ($packItems as $packItem) {
            echo $packItem->pack_quantity . ' x ' . $packItem->name . '<span onclick="delPackItem(' . $packItem->id . ');" style="cursor: pointer;"><img src="../img/admin/delete.gif" /></span><br />';
        }
        echo '		</div>
					<input type="hidden" name="inputPackItems" id="inputPackItems" value="';
        if (Tools::getValue('inputPackItems')) {
            echo Tools::getValue('inputPackItems');
        } else {
            foreach ($packItems as $packItem) {
                echo $packItem->pack_quantity . 'x' . $packItem->id . '-';
            }
        }
        echo '" />
					<input type="hidden" name="namePackItems" id="namePackItems" value="';
        if (Tools::getValue('namePackItems')) {
            echo Tools::getValue('namePackItems');
        } else {
            foreach ($packItems as $packItem) {
                echo $packItem->pack_quantity . 'x ' . $packItem->name . '¤';
            }
        }
        echo '" />
					<script type="text/javascript">
						var formProduct;
						var packItems = new Array();
						' . $this->fillPackItems($obj) . '
						' . $this->addPackItem() . '
						' . $this->delPackItem() . '
						delPackItem(0);
					</script>
					<select id="selectPackItems" name="selectPackItems" style="width: 380px;" onfocus="fillPackItems();">
						<option value="0" selected="selected">-- ' . $this->l('Choose') . ' --</option>
					</select>
					<input type="text" name="quantityPackItems" id="quantityPackItems" value="1" size="1" />
					<span onclick="addPackItem();" style="cursor: pointer;"><img src="../img/admin/add.gif" alt="' . $this->l('Add an item to the pack') . '" title="' . $this->l('Add an item to the pack') . '" /></span>
					<br />' . $this->l('Filter:') . ' <input type="text" size="25" name="filterPack" onkeyup="fillPackItems();" class="space" />
				</td>
			</div>
		</tr>';
    }
 /**
  * @param int $id_customization
  * @return bool
  * @deprecated
  */
 public function deleteCustomizedDatas($id_customization)
 {
     Tools::displayAsDeprecated();
     if (Pack::isPack((int) $product['id_product'])) {
         $products_pack = Pack::getItems((int) $product['id_product'], (int) Configuration::get('PS_LANG_DEFAULT'));
         foreach ($products_pack as $product_pack) {
             $tab_product_pack['id_product'] = (int) $product_pack->id;
             $tab_product_pack['id_product_attribute'] = self::getDefaultAttribute($tab_product_pack['id_product'], 1);
             $tab_product_pack['cart_quantity'] = (int) ($product_pack->pack_quantity * $product['cart_quantity']);
             self::updateQuantity($tab_product_pack);
         }
     }
     if (($result = Db::getInstance()->ExecuteS('SELECT `value` FROM `' . _DB_PREFIX_ . 'customized_data` WHERE `id_customization` = ' . (int) $id_customization . ' AND `type` = ' . _CUSTOMIZE_FILE_)) === false) {
         return false;
     }
     foreach ($result as $row) {
         if (!@unlink(_PS_UPLOAD_DIR_ . $row['value']) or !@unlink(_PS_UPLOAD_DIR_ . $row['value'] . '_small')) {
             return false;
         }
     }
     return Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'customization` WHERE `id_customization` = ' . (int) $id_customization) and Db::getInstance()->Execute('DELETE FROM `' . _DB_PREFIX_ . 'customized_data` WHERE `id_customization` = ' . (int) $id_customization);
 }
Exemple #18
0
 /**
  * For a given pack, tells if all products using the advanced stock management
  *
  * @param int $id_product id_pack
  * @return bool
  */
 public static function allUsesAdvancedStockManagement($id_product)
 {
     if (!Pack::isPack($id_product)) {
         return false;
     }
     $products = Pack::getItems($id_product, Configuration::get('PS_LANG_DEFAULT'));
     foreach ($products as $product) {
         // if one product uses the advanced stock management
         if ($product->advanced_stock_management == 0) {
             return false;
         }
     }
     // not used
     return true;
 }
Exemple #19
0
 public static function noPackPrice($product_id)
 {
     $sum = 0;
     $price_display_method = !self::$_taxCalculationMethod;
     $items = Pack::getItems($id_product, Configuration::get('PS_LANG_DEFAULT'));
     foreach ($items as $item) {
         $sum += $item->getPrice($price_display_method) * $item->pack_quantity;
     }
     return $sum;
 }