public function ajaxProcessAddProductOnOrder() { // Load object $order = new Order((int) Tools::getValue('id_order')); if (!Validate::isLoadedObject($order)) { die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The order object cannot be loaded.')))); } if ($order->hasBeenShipped()) { die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('You cannot add products to delivered orders. ')))); } $product_informations = $_POST['add_product']; if (isset($_POST['add_invoice'])) { $invoice_informations = $_POST['add_invoice']; } else { $invoice_informations = array(); } $product = new Product($product_informations['product_id'], false, $order->id_lang); if (!Validate::isLoadedObject($product)) { die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The product object cannot be loaded.')))); } if (isset($product_informations['product_attribute_id']) && $product_informations['product_attribute_id']) { $combination = new Combination($product_informations['product_attribute_id']); if (!Validate::isLoadedObject($combination)) { die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The combination object cannot be loaded.')))); } } // Total method $total_method = Cart::BOTH_WITHOUT_SHIPPING; // Create new cart $cart = new Cart(); $cart->id_shop_group = $order->id_shop_group; $cart->id_shop = $order->id_shop; $cart->id_customer = $order->id_customer; $cart->id_carrier = $order->id_carrier; $cart->id_address_delivery = $order->id_address_delivery; $cart->id_address_invoice = $order->id_address_invoice; $cart->id_currency = $order->id_currency; $cart->id_lang = $order->id_lang; $cart->secure_key = $order->secure_key; // Save new cart $cart->add(); // Save context (in order to apply cart rule) $this->context->cart = $cart; $this->context->customer = new Customer($order->id_customer); // always add taxes even if there are not displayed to the customer $use_taxes = true; $initial_product_price_tax_incl = Product::getPriceStatic($product->id, $use_taxes, isset($combination) ? $combination->id : null, 2, null, false, true, 1, false, $order->id_customer, $cart->id, $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)}); // Creating specific price if needed if ($product_informations['product_price_tax_incl'] != $initial_product_price_tax_incl) { $specific_price = new SpecificPrice(); $specific_price->id_shop = 0; $specific_price->id_shop_group = 0; $specific_price->id_currency = 0; $specific_price->id_country = 0; $specific_price->id_group = 0; $specific_price->id_customer = $order->id_customer; $specific_price->id_product = $product->id; if (isset($combination)) { $specific_price->id_product_attribute = $combination->id; } else { $specific_price->id_product_attribute = 0; } $specific_price->price = $product_informations['product_price_tax_excl']; $specific_price->from_quantity = 1; $specific_price->reduction = 0; $specific_price->reduction_type = 'amount'; $specific_price->from = '0000-00-00 00:00:00'; $specific_price->to = '0000-00-00 00:00:00'; $specific_price->add(); } // Add product to cart $update_quantity = $cart->updateQty($product_informations['product_quantity'], $product->id, isset($product_informations['product_attribute_id']) ? $product_informations['product_attribute_id'] : null, isset($combination) ? $combination->id : null, 'up', 0, new Shop($cart->id_shop)); if ($update_quantity < 0) { // If product has attribute, minimal quantity is set with minimal quantity of attribute $minimal_quantity = $product_informations['product_attribute_id'] ? Attribute::getAttributeMinimalQty($product_informations['product_attribute_id']) : $product->minimal_quantity; die(Tools::jsonEncode(array('error' => sprintf(Tools::displayError('You must add %d minimum quantity', false), $minimal_quantity)))); } elseif (!$update_quantity) { die(Tools::jsonEncode(array('error' => Tools::displayError('You already have the maximum quantity available for this product.', false)))); } // If order is valid, we can create a new invoice or edit an existing invoice if ($order->hasInvoice()) { $order_invoice = new OrderInvoice($product_informations['invoice']); // Create new invoice if ($order_invoice->id == 0) { // If we create a new invoice, we calculate shipping cost $total_method = Cart::BOTH; // Create Cart rule in order to make free shipping if (isset($invoice_informations['free_shipping']) && $invoice_informations['free_shipping']) { $cart_rule = new CartRule(); $cart_rule->id_customer = $order->id_customer; $cart_rule->name = array(Configuration::get('PS_LANG_DEFAULT') => $this->l('[Generated] CartRule for Free Shipping')); $cart_rule->date_from = date('Y-m-d H:i:s', time()); $cart_rule->date_to = date('Y-m-d H:i:s', time() + 24 * 3600); $cart_rule->quantity = 1; $cart_rule->quantity_per_user = 1; $cart_rule->minimum_amount_currency = $order->id_currency; $cart_rule->reduction_currency = $order->id_currency; $cart_rule->free_shipping = true; $cart_rule->active = 1; $cart_rule->add(); // Add cart rule to cart and in order $cart->addCartRule($cart_rule->id); $values = array('tax_incl' => $cart_rule->getContextualValue(true), 'tax_excl' => $cart_rule->getContextualValue(false)); $order->addCartRule($cart_rule->id, $cart_rule->name[Configuration::get('PS_LANG_DEFAULT')], $values); } $order_invoice->id_order = $order->id; if ($order_invoice->number) { Configuration::updateValue('PS_INVOICE_START_NUMBER', false, false, null, $order->id_shop); } else { $order_invoice->number = Order::getLastInvoiceNumber() + 1; } $invoice_address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)}); $carrier = new Carrier((int) $order->id_carrier); $tax_calculator = $carrier->getTaxCalculator($invoice_address); $order_invoice->total_paid_tax_excl = Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2); $order_invoice->total_paid_tax_incl = Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2); $order_invoice->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order_invoice->total_products_wt = (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS); $order_invoice->total_shipping_tax_excl = (double) $cart->getTotalShippingCost(null, false); $order_invoice->total_shipping_tax_incl = (double) $cart->getTotalShippingCost(); $order_invoice->total_wrapping_tax_excl = abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING)); $order_invoice->total_wrapping_tax_incl = abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING)); $order_invoice->shipping_tax_computation_method = (int) $tax_calculator->computation_method; // Update current order field, only shipping because other field is updated later $order->total_shipping += $order_invoice->total_shipping_tax_incl; $order->total_shipping_tax_excl += $order_invoice->total_shipping_tax_excl; $order->total_shipping_tax_incl += $use_taxes ? $order_invoice->total_shipping_tax_incl : $order_invoice->total_shipping_tax_excl; $order->total_wrapping += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING)); $order->total_wrapping_tax_excl += abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING)); $order->total_wrapping_tax_incl += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING)); $order_invoice->add(); $order_invoice->saveCarrierTaxCalculator($tax_calculator->getTaxesAmount($order_invoice->total_shipping_tax_excl)); $order_carrier = new OrderCarrier(); $order_carrier->id_order = (int) $order->id; $order_carrier->id_carrier = (int) $order->id_carrier; $order_carrier->id_order_invoice = (int) $order_invoice->id; $order_carrier->weight = (double) $cart->getTotalWeight(); $order_carrier->shipping_cost_tax_excl = (double) $order_invoice->total_shipping_tax_excl; $order_carrier->shipping_cost_tax_incl = $use_taxes ? (double) $order_invoice->total_shipping_tax_incl : (double) $order_invoice->total_shipping_tax_excl; $order_carrier->add(); } else { $order_invoice->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2); $order_invoice->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2); $order_invoice->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order_invoice->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS); $order_invoice->update(); } } // Create Order detail information $order_detail = new OrderDetail(); $order_detail->createList($order, $cart, $order->getCurrentOrderState(), $cart->getProducts(), isset($order_invoice) ? $order_invoice->id : 0, $use_taxes, (int) Tools::getValue('add_product_warehouse')); // update totals amount of order $order->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS); $order->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS); $order->total_paid += Tools::ps_round((double) $cart->getOrderTotal(true, $total_method), 2); $order->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2); $order->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2); if (isset($order_invoice) && Validate::isLoadedObject($order_invoice)) { $order->total_shipping = $order_invoice->total_shipping_tax_incl; $order->total_shipping_tax_incl = $order_invoice->total_shipping_tax_incl; $order->total_shipping_tax_excl = $order_invoice->total_shipping_tax_excl; } // discount $order->total_discounts += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); $order->total_discounts_tax_excl += (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)); $order->total_discounts_tax_incl += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); // Save changes of order $order->update(); // Update weight SUM $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier()); if (Validate::isLoadedObject($order_carrier)) { $order_carrier->weight = (double) $order->getTotalWeight(); if ($order_carrier->update()) { $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight); } } // Update Tax lines $order_detail->updateTaxAmount($order); // Delete specific price if exists if (isset($specific_price)) { $specific_price->delete(); } $products = $this->getProducts($order); // Get the last product $product = end($products); $resume = OrderSlip::getProductSlipResume((int) $product['id_order_detail']); $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity']; $product['amount_refundable'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl']; $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl']); $product['return_history'] = OrderReturn::getProductReturnDetail((int) $product['id_order_detail']); $product['refund_history'] = OrderSlip::getProductSlipDetail((int) $product['id_order_detail']); if ($product['id_warehouse'] != 0) { $warehouse = new Warehouse((int) $product['id_warehouse']); $product['warehouse_name'] = $warehouse->name; } else { $product['warehouse_name'] = '--'; } // Get invoices collection $invoice_collection = $order->getInvoicesCollection(); $invoice_array = array(); foreach ($invoice_collection as $invoice) { $invoice->name = $invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop); $invoice_array[] = $invoice; } // Assign to smarty informations in order to show the new product line $this->context->smarty->assign(array('product' => $product, 'order' => $order, 'currency' => new Currency($order->id_currency), 'can_edit' => $this->tabAccess['edit'], 'invoices_collection' => $invoice_collection, 'current_id_lang' => Context::getContext()->language->id, 'link' => Context::getContext()->link, 'current_index' => self::$currentIndex, 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'))); $this->sendChangedNotification($order); die(Tools::jsonEncode(array('result' => true, 'view' => $this->createTemplate('_product_line.tpl')->fetch(), 'can_edit' => $this->tabAccess['add'], 'order' => $order, 'invoices' => $invoice_array, 'documents_html' => $this->createTemplate('_documents.tpl')->fetch(), 'shipping_html' => $this->createTemplate('_shipping.tpl')->fetch(), 'discount_form_html' => $this->createTemplate('_discount_form.tpl')->fetch()))); }
public function ajaxProcessUpdateQty() { if ($this->tabAccess['edit'] === '1') { $errors = array(); if (!$this->context->cart->id) { return; } if ($this->context->cart->OrderExists()) { $errors[] = Tools::displayError('An order has already been placed with this cart.'); } elseif (!($id_product = (int) Tools::getValue('id_product')) || !($product = new Product((int) $id_product, true, $this->context->language->id))) { $errors[] = Tools::displayError('Invalid product'); } elseif (!($qty = Tools::getValue('qty')) || $qty == 0) { $errors[] = Tools::displayError('Invalid quantity'); } // Don't try to use a product if not instanciated before due to errors if (isset($product) && $product->id) { if (($id_product_attribute = Tools::getValue('id_product_attribute')) != 0) { if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty((int) $id_product_attribute, (int) $qty)) { $errors[] = Tools::displayError('There is not enough product in stock.'); } } else { if (!$product->checkQty((int) $qty)) { $errors[] = Tools::displayError('There is not enough product in stock.'); } } if (!($id_customization = (int) Tools::getValue('id_customization', 0)) && !$product->hasAllRequiredCustomizableFields()) { $errors[] = Tools::displayError('Please fill in all the required fields.'); } $this->context->cart->save(); } else { $errors[] = Tools::displayError('This product cannot be added to the cart.'); } if (!count($errors)) { if ((int) $qty < 0) { $qty = str_replace('-', '', $qty); $operator = 'down'; } else { $operator = 'up'; } if (!($qty_upd = $this->context->cart->updateQty($qty, $id_product, (int) $id_product_attribute, (int) $id_customization, $operator))) { $errors[] = Tools::displayError('You already have the maximum quantity available for this product.'); } elseif ($qty_upd < 0) { $minimal_qty = $id_product_attribute ? Attribute::getAttributeMinimalQty((int) $id_product_attribute) : $product->minimal_quantity; $errors[] = sprintf(Tools::displayError('You must add a minimum quantity of %d', false), $minimal_qty); } } echo Tools::jsonEncode(array_merge($this->ajaxReturnVars(), array('errors' => $errors))); } }
/** * Update product quantity * * @param integer $quantity Quantity to add (or substract) * @param integer $id_product Product ID * @param integer $id_product_attribute Attribute ID if needed * @param string $operator Indicate if quantity must be increased or decreased */ public function updateQty($quantity, $id_product, $id_product_attribute = null, $id_customization = false, $operator = 'up', $id_address_delivery = 0, Shop $shop = null, $auto_add_cart_rule = true) { if (!$shop) { $shop = Context::getContext()->shop; } if (Context::getContext()->customer->id) { if ($id_address_delivery == 0 && (int) $this->id_address_delivery) { // The $id_address_delivery is null, use the cart delivery address $id_address_delivery = $this->id_address_delivery; } elseif ($id_address_delivery == 0) { // The $id_address_delivery is null, get the default customer address $id_address_delivery = (int) Address::getFirstCustomerAddressId((int) Context::getContext()->customer->id); } elseif (!Customer::customerHasAddress(Context::getContext()->customer->id, $id_address_delivery)) { // The $id_address_delivery must be linked with customer $id_address_delivery = 0; } } $quantity = (int) $quantity; $id_product = (int) $id_product; $id_product_attribute = (int) $id_product_attribute; $product = new Product($id_product, false, Configuration::get('PS_LANG_DEFAULT'), $shop->id); if ($id_product_attribute) { $combination = new Combination((int) $id_product_attribute); if ($combination->id_product != $id_product) { return false; } } /* If we have a product combination, the minimal quantity is set with the one of this combination */ if (!empty($id_product_attribute)) { $minimal_quantity = (int) Attribute::getAttributeMinimalQty($id_product_attribute); } else { $minimal_quantity = (int) $product->minimal_quantity; } if (!Validate::isLoadedObject($product)) { die(Tools::displayError()); } if (isset(self::$_nbProducts[$this->id])) { unset(self::$_nbProducts[$this->id]); } if (isset(self::$_totalWeight[$this->id])) { unset(self::$_totalWeight[$this->id]); } if ((int) $quantity <= 0) { return $this->deleteProduct($id_product, $id_product_attribute, (int) $id_customization); } elseif (!$product->available_for_order || Configuration::get('PS_CATALOG_MODE')) { return false; } else { /* Check if the product is already in the cart */ $result = $this->containsProduct($id_product, $id_product_attribute, (int) $id_customization, (int) $id_address_delivery); /* Update quantity if product already exist */ if ($result) { if ($operator == 'up') { $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity FROM ' . _DB_PREFIX_ . 'product p ' . Product::sqlStock('p', $id_product_attribute, true, $shop) . ' WHERE p.id_product = ' . $id_product; $result2 = Db::getInstance()->getRow($sql); $product_qty = (int) $result2['quantity']; // Quantity for product pack if (Pack::isPack($id_product)) { $product_qty = Pack::getQuantity($id_product, $id_product_attribute); } $new_qty = (int) $result['quantity'] + (int) $quantity; $qty = '+ ' . (int) $quantity; if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) { if ($new_qty > $product_qty) { return false; } } } else { if ($operator == 'down') { $qty = '- ' . (int) $quantity; $new_qty = (int) $result['quantity'] - (int) $quantity; if ($new_qty < $minimal_quantity && $minimal_quantity > 1) { return -1; } } else { return false; } } /* Delete product from cart */ if ($new_qty <= 0) { return $this->deleteProduct((int) $id_product, (int) $id_product_attribute, (int) $id_customization); } else { if ($new_qty < $minimal_quantity) { return -1; } else { Db::getInstance()->execute(' UPDATE `' . _DB_PREFIX_ . 'cart_product` SET `quantity` = `quantity` ' . $qty . ', `date_add` = NOW() WHERE `id_product` = ' . (int) $id_product . (!empty($id_product_attribute) ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '') . ' AND `id_cart` = ' . (int) $this->id . (Configuration::get('PS_ALLOW_MULTISHIPPING') && $this->isMultiAddressDelivery() ? ' AND `id_address_delivery` = ' . (int) $id_address_delivery : '') . ' LIMIT 1'); } } } elseif ($operator == 'up') { $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity FROM ' . _DB_PREFIX_ . 'product p ' . Product::sqlStock('p', $id_product_attribute, true, $shop) . ' WHERE p.id_product = ' . $id_product; $result2 = Db::getInstance()->getRow($sql); // Quantity for product pack if (Pack::isPack($id_product)) { $result2['quantity'] = Pack::getQuantity($id_product, $id_product_attribute); } if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) { if ((int) $quantity > $result2['quantity']) { return false; } } if ((int) $quantity < $minimal_quantity) { return -1; } $result_add = Db::getInstance()->insert('cart_product', array('id_product' => (int) $id_product, 'id_product_attribute' => (int) $id_product_attribute, 'id_cart' => (int) $this->id, 'id_address_delivery' => (int) $id_address_delivery, 'id_shop' => $shop->id, 'quantity' => (int) $quantity, 'date_add' => date('Y-m-d H:i:s'))); if (!$result_add) { return false; } } } // refresh cache of self::_products $this->_products = $this->getProducts(true); $this->update(true); $context = Context::getContext()->cloneContext(); $context->cart = $this; Cache::clean('getContextualValue_*'); if ($auto_add_cart_rule) { CartRule::autoAddToCart($context); } if ($product->customizable) { return $this->_updateCustomizationQuantity((int) $quantity, (int) $id_customization, (int) $id_product, (int) $id_product_attribute, (int) $id_address_delivery, $operator); } else { return true; } }
/** * This process add or update a product in the cart */ protected function processChangeProductInCart() { $mode = Tools::getIsset('update') && $this->id_product ? 'update' : 'add'; if ($this->qty == 0) { $this->errors[] = Tools::displayError('Null quantity.', !Tools::getValue('ajax')); } elseif (!$this->id_product) { $this->errors[] = Tools::displayError('Product not found', !Tools::getValue('ajax')); } $product = new Product($this->id_product, true, $this->context->language->id); if (!$product->id || !$product->active || !$product->checkAccess($this->context->cart->id_customer)) { $this->errors[] = Tools::displayError('This product is no longer available.', !Tools::getValue('ajax')); return; } $qty_to_check = $this->qty; $cart_products = $this->context->cart->getProducts(); if (is_array($cart_products)) { foreach ($cart_products as $cart_product) { if ((!isset($this->id_product_attribute) || $cart_product['id_product_attribute'] == $this->id_product_attribute) && (isset($this->id_product) && $cart_product['id_product'] == $this->id_product)) { $qty_to_check = $cart_product['cart_quantity']; if (Tools::getValue('op', 'up') == 'down') { $qty_to_check -= $this->qty; } else { $qty_to_check += $this->qty; } break; } } } // Check product quantity availability if ($this->id_product_attribute) { if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $qty_to_check)) { $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax')); } } elseif ($product->hasAttributes()) { $minimumQuantity = $product->out_of_stock == 2 ? !Configuration::get('PS_ORDER_OUT_OF_STOCK') : !$product->out_of_stock; $this->id_product_attribute = Product::getDefaultAttribute($product->id, $minimumQuantity); // @todo do something better than a redirect admin !! if (!$this->id_product_attribute) { Tools::redirectAdmin($this->context->link->getProductLink($product)); } elseif (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $qty_to_check)) { $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax')); } } elseif (!$product->checkQty($qty_to_check)) { $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax')); } // If no errors, process product addition if (!$this->errors && $mode == 'add') { // Add cart if no cart found if (!$this->context->cart->id) { if (Context::getContext()->cookie->id_guest) { $guest = new Guest(Context::getContext()->cookie->id_guest); $this->context->cart->mobile_theme = $guest->mobile_theme; } $this->context->cart->add(); if ($this->context->cart->id) { $this->context->cookie->id_cart = (int) $this->context->cart->id; } } // Check customizable fields if (!$product->hasAllRequiredCustomizableFields() && !$this->customization_id) { $this->errors[] = Tools::displayError('Please fill in all of the required fields, and then save your customizations.', !Tools::getValue('ajax')); } if (!$this->errors) { $cart_rules = $this->context->cart->getCartRules(); $available_cart_rules = CartRule::getCustomerCartRules($this->context->language->id, isset($this->context->customer->id) ? $this->context->customer->id : 0, true, true, true, $this->context->cart, false, true); $update_quantity = $this->context->cart->updateQty($this->qty, $this->id_product, $this->id_product_attribute, $this->customization_id, Tools::getValue('op', 'up'), $this->id_address_delivery); if ($update_quantity < 0) { // If product has attribute, minimal quantity is set with minimal quantity of attribute $minimal_quantity = $this->id_product_attribute ? Attribute::getAttributeMinimalQty($this->id_product_attribute) : $product->minimal_quantity; $this->errors[] = sprintf(Tools::displayError('You must add %d minimum quantity', !Tools::getValue('ajax')), $minimal_quantity); } elseif (!$update_quantity) { $this->errors[] = Tools::displayError('You already have the maximum quantity available for this product.', !Tools::getValue('ajax')); } elseif ((int) Tools::getValue('allow_refresh')) { // If the cart rules has changed, we need to refresh the whole cart $cart_rules2 = $this->context->cart->getCartRules(); if (count($cart_rules2) != count($cart_rules)) { $this->ajax_refresh = true; } elseif (count($cart_rules2)) { $rule_list = array(); foreach ($cart_rules2 as $rule) { $rule_list[] = $rule['id_cart_rule']; } foreach ($cart_rules as $rule) { if (!in_array($rule['id_cart_rule'], $rule_list)) { $this->ajax_refresh = true; break; } } } else { $available_cart_rules2 = CartRule::getCustomerCartRules($this->context->language->id, isset($this->context->customer->id) ? $this->context->customer->id : 0, true, true, true, $this->context->cart, false, true); if (count($available_cart_rules2) != count($available_cart_rules)) { $this->ajax_refresh = true; } elseif (count($available_cart_rules2)) { $rule_list = array(); foreach ($available_cart_rules2 as $rule) { $rule_list[] = $rule['id_cart_rule']; } foreach ($cart_rules2 as $rule) { if (!in_array($rule['id_cart_rule'], $rule_list)) { $this->ajax_refresh = true; break; } } } } } } } $removed = CartRule::autoRemoveFromCart(); CartRule::autoAddToCart(); if (count($removed) && (int) Tools::getValue('allow_refresh')) { $this->ajax_refresh = true; } }
protected function insertOrderItems(ShopgateOrder $order) { $this->log('start insertOrderItems()', ShopgateLogger::LOGTYPE_DEBUG); $products = array(); //Check product quantitys $settings = Configuration::getMultiple(array('SHOPGATE_MIN_QUANTITY_CHECK', 'SHOPGATE_OUT_OF_STOCK_CHECK')); // complete weight of the order foreach ($order->getItems() as $i) { list($id_product, $id_product_attribute) = $this->getProductIdentifiers($i); if ($id_product == 0) { continue; } $wantedQty = (int) $i->getQuantity(); $product = new Product($id_product, true, (int) Configuration::get('PS_LANG_DEFAULT')); $minQty = 1; if ((int) $id_product_attribute) { $stockQty = (int) Product::getQuantity((int) $id_product, (int) $id_product_attribute); if (version_compare(_PS_VERSION_, '1.4.0.7', '>=')) { // this attribute doesn't exist before 1.4.0.7 $minQty = Attribute::getAttributeMinimalQty((int) $id_product_attribute); } } else { $stockQty = (int) Product::getQuantity((int) $id_product, NULL); if (version_compare(_PS_VERSION_, '1.4.0.2', '>=')) { // this attribute doesn't exist before 1.4.0.2 $minQty = (int) $product->minimal_quantity; } } $oos_available = Product::isAvailableWhenOutOfStock($product->out_of_stock); $qtyDifference = 0; if (!$oos_available && $wantedQty > $stockQty) { $qtyDifference = $wantedQty - $stockQty; } $p = array(); $p['id_product'] = (int) $id_product; $p['id_product_attribute'] = (int) $id_product_attribute; $p['name'] = $product->name; $p['quantity'] = $wantedQty; $p['quantity_in_stock'] = $stockQty; $p['quantity_difference'] = $qtyDifference; if (empty($p['name'])) { $p['name'] = $i->getName(); } if ($oos_available) { $stockQty = $wantedQty; } if ((bool) $settings['SHOPGATE_MIN_QUANTITY_CHECK'] && $wantedQty < $minQty) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Minimum quantity required', true); } if ((bool) $settings['SHOPGATE_OUT_OF_STOCK_CHECK'] && $wantedQty > $stockQty) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Out of stock', true); } array_push($products, $p); } $this->log('end insertOrderItems()', ShopgateLogger::LOGTYPE_DEBUG); return $products; }
public function preProcess() { parent::preProcess(); $orderTotal = self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS); $this->cartDiscounts = self::$cart->getDiscounts(); foreach ($this->cartDiscounts as $k => $this->cartDiscount) { if ($error = self::$cart->checkDiscountValidity(new Discount((int) $this->cartDiscount['id_discount']), $this->cartDiscounts, $orderTotal, self::$cart->getProducts())) { self::$cart->deleteDiscount((int) $this->cartDiscount['id_discount']); } } $add = Tools::getIsset('add') ? 1 : 0; $delete = Tools::getIsset('delete') ? 1 : 0; if (Configuration::get('PS_TOKEN_ENABLE') == 1 && strcasecmp(Tools::getToken(false), strval(Tools::getValue('token'))) && self::$cookie->isLogged() === true) { $this->errors[] = Tools::displayError('Invalid token'); } // Update the cart ONLY if $this->cookies are available, in order to avoid ghost carts created by bots if (($add or Tools::getIsset('update') or $delete) and isset(self::$cookie->date_add)) { //get the values $idProduct = (int) Tools::getValue('id_product', NULL); $idProductAttribute = (int) Tools::getValue('id_product_attribute', Tools::getValue('ipa')); $customizationId = (int) Tools::getValue('id_customization', 0); $qty = (int) abs(Tools::getValue('qty', 1)); if ($qty == 0) { $this->errors[] = Tools::displayError('Null quantity'); } elseif (!$idProduct) { $this->errors[] = Tools::displayError('Product not found'); } else { $producToAdd = new Product((int) $idProduct, true, (int) self::$cookie->id_lang); if ((!$producToAdd->id or !$producToAdd->active) and !$delete) { if (Tools::getValue('ajax') == 'true') { die('{"hasError" : true, "errors" : ["' . Tools::displayError('Pproduct is no longer available.', false) . '"]}'); } else { $this->errors[] = Tools::displayError('Pproduct is no longer available.', false); } } else { /* Check the quantity availability */ if ($idProductAttribute and is_numeric($idProductAttribute)) { if (!$delete and !$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty((int) $idProductAttribute, (int) $qty)) { if (Tools::getValue('ajax') == 'true') { die('{"hasError" : true, "errors" : ["' . Tools::displayError('There is not enough product in stock.', false) . '"]}'); } else { $this->errors[] = Tools::displayError('There is not enough product in stock.'); } } } elseif ($producToAdd->hasAttributes() and !$delete) { $idProductAttribute = Product::getDefaultAttribute((int) $producToAdd->id, (int) $producToAdd->out_of_stock == 2 ? !(int) Configuration::get('PS_ORDER_OUT_OF_STOCK') : !(int) $producToAdd->out_of_stock); if (!$idProductAttribute) { Tools::redirectAdmin($link->getProductLink($producToAdd)); } elseif (!$delete and !$producToAdd->isAvailableWhenOutOfStock($producToAdd->out_of_stock) and !Attribute::checkAttributeQty((int) $idProductAttribute, (int) $qty)) { if (Tools::getValue('ajax') == 'true') { die('{"hasError" : true, "errors" : ["' . Tools::displayError('There is not enough product in stock.', false) . '"]}'); } else { $this->errors[] = Tools::displayError('There is not enough product in stock.'); } } } elseif (!$delete and !$producToAdd->checkQty((int) $qty)) { if (Tools::getValue('ajax') == 'true') { die('{"hasError" : true, "errors" : ["' . Tools::displayError('There is not enough product in stock.') . '"]}'); } else { $this->errors[] = Tools::displayError('There is not enough product in stock.'); } } /* Check vouchers compatibility */ if ($add and ($producToAdd->specificPrice and (double) $producToAdd->specificPrice['reduction'] or $producToAdd->on_sale)) { $discounts = self::$cart->getDiscounts(); foreach ($discounts as $discount) { if (!$discount['cumulable_reduction']) { $this->errors[] = Tools::displayError('Cannot add this product because current voucher does not allow additional discounts.'); } } } if (!sizeof($this->errors)) { if ($add and $qty >= 0) { /* Product addition to the cart */ if (!isset(self::$cart->id) or !self::$cart->id) { self::$cart->add(); if (self::$cart->id) { self::$cookie->id_cart = (int) self::$cart->id; } } if ($add and !$producToAdd->hasAllRequiredCustomizableFields() and !$customizationId) { $this->errors[] = Tools::displayError('Please fill in all required fields, then save the customization.'); } if (!sizeof($this->errors)) { $updateQuantity = self::$cart->updateQty((int) $qty, (int) $idProduct, (int) $idProductAttribute, $customizationId, Tools::getValue('op', 'up')); if ($updateQuantity < 0) { /* if product has attribute, minimal quantity is set with minimal quantity of attribute*/ if ((int) $idProductAttribute) { $minimal_quantity = Attribute::getAttributeMinimalQty((int) $idProductAttribute); } else { $minimal_quantity = $producToAdd->minimal_quantity; } if (Tools::getValue('ajax') == 'true') { die('{"hasError" : true, "errors" : ["' . Tools::displayError('You must add', false) . ' ' . $minimal_quantity . ' ' . Tools::displayError('Minimum quantity', false) . '"]}'); } else { $this->errors[] = Tools::displayError('You must add') . ' ' . $minimal_quantity . ' ' . Tools::displayError('Minimum quantity') . ((isset($_SERVER['HTTP_REFERER']) and basename($_SERVER['HTTP_REFERER']) == 'order.php' or !Tools::isSubmit('ajax') and substr(basename($_SERVER['REQUEST_URI']), 0, strlen('cart.php')) == 'cart.php') ? '<script language="javascript">setTimeout("history.back()",5000);</script><br />- ' . Tools::displayError('You will be redirected to your cart in a few seconds.') : ''); } } elseif (!$updateQuantity) { if (Tools::getValue('ajax') == 'true') { die('{"hasError" : true, "errors" : ["' . Tools::displayError('You already have the maximum quantity available for this product.', false) . '"]}'); } else { $this->errors[] = Tools::displayError('You already have the maximum quantity available for this product.') . ((isset($_SERVER['HTTP_REFERER']) and basename($_SERVER['HTTP_REFERER']) == 'order.php' or !Tools::isSubmit('ajax') and substr(basename($_SERVER['REQUEST_URI']), 0, strlen('cart.php')) == 'cart.php') ? '<script language="javascript">setTimeout("history.back()",5000);</script><br />- ' . Tools::displayError('You will be redirected to your cart in a few seconds.') : ''); } } } } elseif ($delete) { if (self::$cart->deleteProduct((int) $idProduct, (int) $idProductAttribute, (int) $customizationId)) { if (!Cart::getNbProducts((int) self::$cart->id)) { self::$cart->id_carrier = 0; self::$cart->gift = 0; self::$cart->gift_message = ''; self::$cart->update(); } } } } $discounts = self::$cart->getDiscounts(); foreach ($discounts as $discount) { $discountObj = new Discount((int) $discount['id_discount'], (int) self::$cookie->id_lang); if ($error = self::$cart->checkDiscountValidity($discountObj, $discounts, self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), self::$cart->getProducts())) { self::$cart->deleteDiscount((int) $discount['id_discount']); self::$cart->update(); $errors[] = $error; } } if (!sizeof($this->errors)) { $queryString = Tools::safeOutput(Tools::getValue('query', NULL)); if ($queryString and !Configuration::get('PS_CART_REDIRECT')) { Tools::redirect('search.php?search=' . $queryString); } if (isset($_SERVER['HTTP_REFERER'])) { // Redirect to previous page preg_match('!http(s?)://(.*)/(.*)!', $_SERVER['HTTP_REFERER'], $regs); if (isset($regs[3]) and !Configuration::get('PS_CART_REDIRECT') and Tools::getValue('ajax') != 'true') { Tools::redirect($regs[3]); } } } } if (Tools::getValue('ajax') != 'true' and !sizeof($this->errors)) { Tools::redirect('order.php?' . (isset($idProduct) ? 'ipa=' . (int) $idProduct : '')); } } } }
/** * Update product quantity * * @param integer $quantity Quantity to add (or substract) * @param integer $id_product Product ID * @param integer $id_product_attribute Attribute ID if needed * @param string $operator Indicate if quantity must be increased or decreased */ public function updateQty($quantity, $id_product, $id_product_attribute = NULL, $id_customization = false, $operator = 'up') { $product = new Product((int) $id_product, false, (int) Configuration::get('PS_LANG_DEFAULT')); /* If we have a product combination, the minimal quantity is set with the one of this combination */ if (!empty($id_product_attribute)) { $minimalQuantity = (int) Attribute::getAttributeMinimalQty((int) $id_product_attribute); } else { $minimalQuantity = (int) $product->minimal_quantity; } if (!Validate::isLoadedObject($product)) { die(Tools::displayError()); } if (isset(self::$_nbProducts[$this->id])) { unset(self::$_nbProducts[$this->id]); } if (isset(self::$_totalWeight[$this->id])) { unset(self::$_totalWeight[$this->id]); } if ((int) $quantity <= 0) { return $this->deleteProduct((int) $id_product, (int) $id_product_attribute, (int) $id_customization); } else { if (!$product->available_for_order or Configuration::get('PS_CATALOG_MODE')) { return false; } else { /* Check if the product is already in the cart */ $result = $this->containsProduct((int) $id_product, (int) $id_product_attribute, (int) $id_customization); /* Update quantity if product already exist */ if ($result) { if ($operator == 'up') { $result2 = Db::getInstance()->getRow(' SELECT ' . (!empty($id_product_attribute) ? 'pa' : 'p') . '.`quantity`, p.`out_of_stock` FROM `' . _DB_PREFIX_ . 'product` p ' . (!empty($id_product_attribute) ? 'LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON p.`id_product` = pa.`id_product`' : '') . ' WHERE p.`id_product` = ' . (int) $id_product . (!empty($id_product_attribute) ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '')); $productQty = (int) $result2['quantity']; $newQty = (int) $result['quantity'] + (int) $quantity; $qty = '+ ' . (int) $quantity; if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) { if ($newQty > $productQty) { return false; } } } elseif ($operator == 'down') { $qty = '- ' . (int) $quantity; $newQty = (int) $result['quantity'] - (int) $quantity; if ($newQty < $minimalQuantity and $minimalQuantity > 1) { return -1; } } else { return false; } /* Delete product from cart */ if ($newQty <= 0) { return $this->deleteProduct((int) $id_product, (int) $id_product_attribute, (int) $id_customization); } else { if ($newQty < $minimalQuantity) { return -1; } else { Db::getInstance()->Execute(' UPDATE `' . _DB_PREFIX_ . 'cart_product` SET `quantity` = `quantity` ' . $qty . ', `date_add` = NOW() WHERE `id_product` = ' . (int) $id_product . (!empty($id_product_attribute) ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '') . ' AND `id_cart` = ' . (int) $this->id . ' LIMIT 1'); } } } else { $result2 = Db::getInstance()->getRow(' SELECT ' . (!empty($id_product_attribute) ? 'pa' : 'p') . '.`quantity`, p.`out_of_stock` FROM `' . _DB_PREFIX_ . 'product` p ' . (!empty($id_product_attribute) ? 'LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON p.`id_product` = pa.`id_product`' : '') . ' WHERE p.`id_product` = ' . (int) $id_product . (!empty($id_product_attribute) ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '')); if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) { if ((int) $quantity > $result2['quantity']) { return false; } } if ((int) $quantity < $minimalQuantity) { return -1; } if (!Db::getInstance()->AutoExecute(_DB_PREFIX_ . 'cart_product', array('id_product' => (int) $id_product, 'id_product_attribute' => (int) $id_product_attribute, 'id_cart' => (int) $this->id, 'quantity' => (int) $quantity, 'date_add' => date('Y-m-d H:i:s')), 'INSERT')) { return false; } } } } // refresh cache of self::_products $this->_products = $this->getProducts(true); $this->update(true); if ($product->customizable) { return $this->_updateCustomizationQuantity((int) $quantity, (int) $id_customization, (int) $id_product, (int) $id_product_attribute, $operator); } else { return true; } }
public function renderExpressCheckoutForm($type) { if (!Configuration::get('PAYPAL_EXPRESS_CHECKOUT_SHORTCUT') && !$this->useMobile() || !in_array(ECS, $this->getPaymentMethods()) || (int) Configuration::get('PAYPAL_BUSINESS') == 1 && (int) Configuration::get('PAYPAL_PAYMENT_METHOD') == HSS && !$this->useMobile()) { return; } $id_product = (int) Tools::getValue('id_product'); $id_product_attribute = (int) Product::getDefaultAttribute($id_product); if ($id_product_attribute) { $minimal_quantity = Attribute::getAttributeMinimalQty($id_product_attribute); } else { $product = new Product($id_product); $minimal_quantity = $product->minimal_quantity; } $this->context->smarty->assign(array('PayPal_payment_type' => $type, 'PayPal_current_page' => $this->getCurrentUrl(), 'id_product_attribute' => $id_product_attribute, 'product_minimal_quantity' => $minimal_quantity, 'PayPal_tracking_code' => $this->getTrackingCode((int) Configuration::get('PAYPAL_PAYMENT_METHOD')))); return $this->fetchTemplate('express_checkout_shortcut_form.tpl'); }
public function processGlobalCartProductQuantityUpdate($op, $qty, $producToAdd, $idProduct, $idProductAttribute, &$errors) { global $cart; // code taken from CartController preProcess() $updateQuantity = $cart->updateQty($qty, $idProduct, $idProductAttribute, false, $op); if ($updateQuantity < 0) { /* if product has attribute, minimal quantity is set with minimal quantity of attribute*/ if ((int) $idProductAttribute) { $minimal_quantity = Attribute::getAttributeMinimalQty((int) $idProductAttribute); } else { $minimal_quantity = $producToAdd->minimal_quantity; } $errors[] = Tools::displayError('You must add', false) . ' ' . $minimal_quantity . ' ' . Tools::displayError('Minimum quantity', false); // improvement: when adding below minimum quantity, add the minimum quantity (to make life easier for the user) $currentQuantity = $this->getCurrentGlobalCartProductQuantity($idProduct, $idProductAttribute); $cart->updateQty((int) $minimal_quantity - (int) $currentQuantity, $idProduct, $idProductAttribute, false, 'up'); // end improvement return false; } elseif (!$updateQuantity) { $errors[] = Tools::displayError('You already have the maximum quantity available for this product.', false); return false; } if (!$this->validateGlobalCartDiscounts($errors)) { return false; } return true; }
public function hookheader($params) { //Change context Shop to be default if ($this->isVersionOneDotFive() && Shop::isFeatureActive()) { $oldContextShop = $this->getContextShop(); $this->setContextShop(); } //End of change // Check if the module is configured if (!Configuration::get('EBAY_PAYPAL_EMAIL')) { return false; } // Fix hook update product attribute $this->hookupdateProductAttributeEbay(); // init date to check from if (Configuration::get('EBAY_INSTALL_DATE') < date('Y-m-d', strtotime('-30 days')) . 'T' . date('H:i:s', strtotime('-30 days'))) { //If it is more than 30 days that we installed the module $dateToCheckFrom = Configuration::get('EBAY_ORDER_LAST_UPDATE'); $dateToCheckFromArray = explode('T', $dateToCheckFrom); $dateToCheckFrom = date("Y-m-d", strtotime($dateToCheckFromArray[0] . " -30 day")); $dateToCheckFrom .= 'T' . $dateToCheckFromArray[1]; } else { //If it is less than 30 days that we installed the module $dateToCheckFrom = Configuration::get('EBAY_INSTALL_DATE'); $dateToCheckFromArray = explode('T', $dateToCheckFrom); $dateToCheckFrom = date("Y-m-d", strtotime($dateToCheckFromArray[0] . " -1 day")); $dateToCheckFrom .= 'T' . $dateToCheckFromArray[1]; } if (Configuration::get('EBAY_ORDER_LAST_UPDATE') < date('Y-m-d', strtotime('-30 minutes')) . 'T' . date('H:i:s', strtotime('-30 minutes')) . '.000Z') { $dateNew = date('Y-m-d') . 'T' . date('H:i:s') . '.000Z'; $this->setConfiguration('EBAY_ORDER_LAST_UPDATE', $dateNew); // eBay Request $ebay = new eBayRequest(); $page = 1; $orderList = array(); $orderCount = 0; $orderCountTmp = 100; while ($orderCountTmp == 100 && $page < 10) { $orderListTmp = $ebay->getOrders($dateToCheckFrom, $dateNew, $page); $orderCountTmp = count($orderListTmp); $orderList = array_merge((array) $orderList, (array) $orderListTmp); $orderCount += $orderCountTmp; $page++; } // Lock if ($orderList) { foreach ($orderList as $korder => $order) { if ($order['status'] == 'Complete' && $order['amount'] > 0.1 && isset($order['product_list']) && count($order['product_list'])) { if (!Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `' . _DB_PREFIX_ . 'ebay_order` WHERE `id_order_ref` = \'' . pSQL($order['id_order_ref']) . '\'')) { // Check for empty name $order['firstname'] = trim($order['firstname']); $order['familyname'] = trim($order['familyname']); if (empty($order['familyname'])) { $order['familyname'] = $order['firstname']; } if (empty($order['firstname'])) { $order['firstname'] = $order['familyname']; } if (empty($order['phone']) || !Validate::isPhoneNumber($order['phone'])) { $order['phone'] = '0100000000'; } if (Validate::isEmail($order['email']) && !empty($order['firstname']) && !empty($order['familyname'])) { // Getting the customer $id_customer = (int) Db::getInstance()->getValue('SELECT `id_customer` FROM `' . _DB_PREFIX_ . 'customer` WHERE `active` = 1 AND `email` = \'' . pSQL($order['email']) . '\' AND `deleted` = 0' . (substr(_PS_VERSION_, 0, 3) == '1.3' ? '' : ' AND `is_guest` = 0')); // Add customer if he doesn't exist if ($id_customer < 1) { $customer = new Customer(); $customer->id_gender = 0; $customer->id_default_group = 1; $customer->secure_key = md5(uniqid(rand(), true)); $customer->email = $order['email']; $customer->passwd = md5(pSQL(_COOKIE_KEY_ . rand())); $customer->last_passwd_gen = pSQL(date('Y-m-d H:i:s')); $customer->newsletter = 0; $customer->lastname = pSQL($order['familyname']); $customer->firstname = pSQL($order['firstname']); $customer->active = 1; $customer->add(); $id_customer = $customer->id; } // Search if address exists $id_address = (int) Db::getInstance()->getValue('SELECT `id_address` FROM `' . _DB_PREFIX_ . 'address` WHERE `id_customer` = ' . (int) $id_customer . ' AND `alias` = \'eBay\''); if ($id_address > 0) { $address = new Address((int) $id_address); } else { $address = new Address(); $address->id_customer = (int) $id_customer; } $address->id_country = (int) Country::getByIso($order['country_iso_code']); $address->alias = 'eBay'; $address->lastname = pSQL($order['familyname']); $address->firstname = pSQL($order['firstname']); $address->address1 = pSQL($order['address1']); $address->address2 = pSQL($order['address2']); $address->postcode = pSQL($order['postalcode']); $address->city = pSQL($order['city']); $address->phone = pSQL($order['phone']); $address->active = 1; if ($id_address > 0 && Validate::isLoadedObject($address)) { $address->update(); } else { $address->add(); } $id_address = $address->id; $flag = 1; foreach ($order['product_list'] as $product) { if ((int) $product['id_product'] < 1 || !Db::getInstance()->getValue('SELECT `id_product` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . (int) $product['id_product'])) { $flag = 0; } if (isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 && !Db::getInstance()->getValue('SELECT `id_product_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `id_product` = ' . (int) $product['id_product'] . ' AND `id_product_attribute` = ' . (int) $product['id_product_attribute'])) { $flag = 0; } } if ($flag == 1) { //Create a Cart for the order $cartNbProducts = 0; $cartAdd = new Cart(); Context::getContext()->customer = new Customer($id_customer); $cartAdd->id_customer = $id_customer; $cartAdd->id_address_invoice = $id_address; $cartAdd->id_address_delivery = $id_address; $cartAdd->id_carrier = 0; $cartAdd->id_lang = $this->id_lang; $cartAdd->id_currency = Currency::getIdByIsoCode('EUR'); $cartAdd->recyclable = 0; $cartAdd->gift = 0; $cartAdd->add(); $id_lang = (int) Configuration::get('PS_LANG_DEFAULT'); foreach ($order['product_list'] as $product) { $prod = new Product($product['id_product'], false, $id_lang); // Qty of product or attribute if (isset($product['id_product_attribute']) && !empty($product['id_product_attribute'])) { $minimalQty = (int) Attribute::getAttributeMinimalQty($product['id_product_attribute']); } else { $minimalQty = $prod->minimal_quantity; } if ($product['quantity'] >= $minimalQty) { if ($this->isVersionOneDotFive()) { $update = $cartAdd->updateQty((int) $product['quantity'], (int) $product['id_product'], isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 ? $product['id_product_attribute'] : NULL, false, 'up', 0, new Shop(Configuration::get('PS_SHOP_DEFAULT'))); if ($update === TRUE) { $cartNbProducts++; } } elseif ($cartAdd->updateQty((int) $product['quantity'], (int) $product['id_product'], isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 ? $product['id_product_attribute'] : NULL)) { $cartNbProducts++; } } else { $templateVars = array('{name_product}' => $prod->name, '{min_qty}' => $minimalQty, '{cart_qty}' => $product['quantity']); Mail::Send((int) Configuration::get('PS_LANG_DEFAULT'), 'alertEbay', Mail::l('Product quantity', $id_lang), $templateVars, strval(Configuration::get('PS_SHOP_EMAIL')), NULL, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/mails/'); } } $cartAdd->update(); // Check number of products in the cart and check if order has already been taken if ($cartNbProducts > 0 && !Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `' . _DB_PREFIX_ . 'ebay_order` WHERE `id_order_ref` = \'' . pSQL($order['id_order_ref']) . '\'')) { // Fix on sending e-mail Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => 'NOSEND-EBAY'), 'UPDATE', '`id_customer` = ' . (int) $id_customer); $customerClear = new Customer(); if (method_exists($customerClear, 'clearCache')) { $customerClear->clearCache(true); } $paiement = new eBayPayment(); // Validate order if ($this->isVersionOneDotFive()) { $customer = new Customer($id_customer); $paiement->validateOrder(intval($cartAdd->id), Configuration::get('PS_OS_PAYMENT'), floatval($cartAdd->getOrderTotal(true, 3)), 'eBay ' . $order['payment_method'] . ' ' . $order['id_order_seller'], NULL, array(), intval($cartAdd->id_currency), false, $customer->secure_key, new Shop(Configuration::get('PS_SHOP_DEFAULT'))); } else { $customer = new Customer($id_customer); $paiement->validateOrder(intval($cartAdd->id), Configuration::get('PS_OS_PAYMENT'), floatval($cartAdd->getOrderTotal(true, 3)), 'eBay ' . $order['payment_method'] . ' ' . $order['id_order_seller'], NULL, array(), intval($cartAdd->id_currency), false, $customer->secure_key); } $id_order = $paiement->currentOrder; // Fix on date Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', array('date_add' => pSQL($order['date_add'])), 'UPDATE', '`id_order` = ' . (int) $id_order); // Fix on sending e-mail Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => pSQL($order['email'])), 'UPDATE', '`id_customer` = ' . (int) $id_customer); // Update price (because of possibility of price impact) foreach ($order['product_list'] as $product) { $tax_rate = Db::getInstance()->getValue('SELECT `tax_rate` FROM `' . _DB_PREFIX_ . 'order_detail` WHERE `id_order` = ' . (int) $id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute']); Db::getInstance()->autoExecute(_DB_PREFIX_ . 'order_detail', array('product_price' => floatval($product['price'] / (1 + $tax_rate / 100)), 'reduction_percent' => 0), 'UPDATE', '`id_order` = ' . (int) $id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute']); } $updateOrder = array('total_paid' => floatval($order['amount']), 'total_paid_real' => floatval($order['amount']), 'total_products' => floatval(Db::getInstance()->getValue('SELECT SUM(`product_price`) FROM `' . _DB_PREFIX_ . 'order_detail` WHERE `id_order` = ' . (int) $id_order)), 'total_products_wt' => floatval($order['amount'] - $order['shippingServiceCost']), 'total_shipping' => floatval($order['shippingServiceCost'])); Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', $updateOrder, 'UPDATE', '`id_order` = ' . (int) $id_order); // Register the ebay order ref Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_order', array('id_order_ref' => pSQL($order['id_order_ref']), 'id_order' => (int) $id_order), 'INSERT'); if (!$this->isVersionOneDotFive()) { //Fix on eBay not updating $params = array(); foreach ($order['product_list'] as $product) { $params['product'] = new Product((int) $product['id_product']); $this->hookaddproduct($params); } } } else { $cartAdd->delete(); $orderList[$korder]['errors'][] = $this->l('Could not add product to cart (maybe your stock quantity is 0)'); } } else { $orderList[$korder]['errors'][] = $this->l('Could not found products in database'); } } else { $orderList[$korder]['errors'][] = $this->l('Invalid e-mail'); } } else { $orderList[$korder]['errors'][] = $this->l('Order already imported'); } } else { $orderList[$korder]['errors'][] = $this->l('Status not complete or amount less than 0.1 or no product matching'); } } file_put_contents(dirname(__FILE__) . '/log/orders.php', "<?php\n\n" . '$dateLastImport = ' . "'" . date('d/m/Y H:i:s') . "';\n\n" . '$orderList = ' . var_export($orderList, true) . ";\n\n"); } } // Set old Context Shop if ($this->isVersionOneDotFive() && Shop::isFeatureActive()) { $this->setContextShop($oldContextShop); } }
public function updateCartQuantities() { $id_lang = (int) Configuration::get('PS_LANG_DEFAULT'); $cart_nb_products = 0; foreach ($this->product_list as $product) { $prod = new Product($product['id_product'], false, $id_lang); $minimal_quantity = empty($product['id_product_attribute']) ? $prod->minimal_quantity : (int) Attribute::getAttributeMinimalQty($product['id_product_attribute']); if ($product['quantity'] >= $minimal_quantity) { $id_product_attribute = empty($product['id_product_attribute']) ? null : $product['id_product_attribute']; if (version_compare(_PS_VERSION_, '1.5', '>')) { $update = $this->cart->updateQty((int) $product['quantity'], (int) $product['id_product'], $id_product_attribute, false, 'up', 0, new Shop(Configuration::get('PS_SHOP_DEFAULT'))); if ($update === true) { $cart_nb_products++; } } elseif ($this->cart->updateQty((int) $product['quantity'], (int) $product['id_product'], $id_product_attribute)) { $cart_nb_products++; } } else { // minimal quantity for purchase not met $this->_sendMinimalQtyAlertEmail($prod->name, $minimal_quantity, $product['quantity']); } } $this->cart->update(); if (version_compare(_PS_VERSION_, '1.5', '>')) { $this->cart->getProducts(true); $this->cart->getPackageList(true); $this->cart->getDeliveryOptionList(null, true); } return (bool) $cart_nb_products; }
/** * Update product quantity * * @param integer $quantity Quantity to add (or substract) * @param integer $id_product Product ID * @param integer $id_product_attribute Attribute ID if needed * @param string $operator Indicate if quantity must be increased or decreased */ public function updateQty($quantity, $id_product, $id_product_attribute = null, $id_customization = false, $operator = 'up') { /* Check if the product exists in Db and is available for order (+ handle product removal from cart) */ if ($id_product > 0) { $product = Db::getInstance()->getRow(' SELECT id_product, available_for_order, minimal_quantity, customizable FROM ' . _DB_PREFIX_ . 'product WHERE id_product = ' . (int) $id_product . ' AND active = 1'); } if (!isset($product) || !$product) { return false; } if (isset(self::$_nbProducts[$this->id])) { unset(self::$_nbProducts[$this->id]); } if (isset(self::$_totalWeight[$this->id])) { unset(self::$_totalWeight[$this->id]); } if ((int) $quantity <= 0) { return $this->deleteProduct((int) $id_product, (int) $id_product_attribute, (int) $id_customization); } elseif (!$product['available_for_order'] || Configuration::get('PS_CATALOG_MODE')) { return false; } else { if ($id_product_attribute) { $combination = new Combination((int) $id_product_attribute); if ($combination->id_product != $id_product) { return false; } } /* If we have a product combination, the minimal quantity is set with the one of this combination */ $minimalQuantity = !empty($id_product_attribute) ? (int) Attribute::getAttributeMinimalQty((int) $id_product_attribute) : (int) $product['minimal_quantity']; /* Check if the product is already in the cart */ $result = $this->containsProduct((int) $id_product, (int) $id_product_attribute, (int) $id_customization); /* Update the current quantity if the product already exist in the cart */ if ($result) { if ($operator == 'up') { /* We need to check if the product is in stock (or can be ordered without stock) */ $result2 = Db::getInstance()->getRow(' SELECT ' . (!empty($id_product_attribute) ? 'pa' : 'p') . '.`quantity`, p.`out_of_stock` FROM `' . _DB_PREFIX_ . 'product` p ' . (!empty($id_product_attribute) ? 'LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product`)' : '') . ' WHERE p.`id_product` = ' . (int) $id_product . (!empty($id_product_attribute) ? ' AND pa.`id_product_attribute` = ' . (int) $id_product_attribute : '')); $newQty = (int) $result['quantity'] + (int) $quantity; $qty = '+ ' . (int) $quantity; /* If the total quantity asked is greater than the stock, we need to make sure that the product can be ordered without stock */ if ($newQty > (int) $result2['quantity'] && !Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) { return false; } } elseif ($operator == 'down') { $qty = '- ' . (int) $quantity; $newQty = (int) $result['quantity'] - (int) $quantity; } else { return false; } /* If the new product quantity is lower or equal to zero, we can remove this product from the cart */ if ($newQty <= 0) { return $this->deleteProduct((int) $id_product, (int) $id_product_attribute, (int) $id_customization); } elseif ($minimalQuantity > 1 && $newQty < $minimalQuantity) { return -1; } else { Db::getInstance()->Execute(' UPDATE `' . _DB_PREFIX_ . 'cart_product` SET `quantity` = `quantity` ' . $qty . ', `date_add` = NOW() WHERE `id_product` = ' . (int) $id_product . (!empty($id_product_attribute) ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '') . ' AND `id_cart` = ' . (int) $this->id . ' LIMIT 1'); } } else { $result2 = Db::getInstance()->getRow(' SELECT ' . (!empty($id_product_attribute) ? 'pa' : 'p') . '.`quantity`, p.`out_of_stock` FROM `' . _DB_PREFIX_ . 'product` p ' . (!empty($id_product_attribute) ? 'LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON p.`id_product` = pa.`id_product`' : '') . ' WHERE p.`id_product` = ' . (int) $id_product . (!empty($id_product_attribute) ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '')); /* If the quantity asked is greater than the stock, we need to make sure that the product can be ordered without stock */ if ((int) $quantity > $result2['quantity'] && !Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) { return false; } /* If the new product quantity does not match the minimal quantity to buy the product (default = 1), return -1 */ if ($minimalQuantity > 1 && $quantity < $minimalQuantity) { return -1; } if (!Db::getInstance()->Execute(' INSERT INTO ' . _DB_PREFIX_ . 'cart_product (id_product, id_product_attribute, id_cart, quantity, date_add) VALUES (' . (int) $id_product . ', ' . ($id_product_attribute ? (int) $id_product_attribute : 0) . ', ' . (int) $this->id . ', ' . (int) $quantity . ', NOW())')) { return false; } } } /* If it's a customizable product, we need to update the related table. The function will also refresh the cache and update the cart itself */ if ($product['customizable']) { return $this->_updateCustomizationQuantity((int) $quantity, (int) $id_customization, (int) $id_product, (int) $id_product_attribute, $operator); } else { $this->_products = $this->getProducts(true); $this->update(true); return true; } }
/** * @param $cart * @return array */ protected function _addItems($cart) { $resultItems = array(); foreach ($cart->getItems() as $item) { list($productId, $attributeId) = ShopgateHelper::getProductIdentifiers($item); /** @var ProductCore $product */ $product = new Product($productId); $resultItem = new ShopgateCartItem(); $resultItem->setItemNumber($item->getItemNumber()); $resultItem->setStockQuantity($product->getQuantity($product->id, $attributeId)); $resultItem->setUnitAmount($product->getPrice(false, $attributeId)); $resultItem->setUnitAmountWithTax($product->getPrice(true, $attributeId)); $resultItem->setOptions($item->getOptions()); $resultItem->setAttributes($item->getAttributes()); $resultItem->setInputs($item->getInputs()); /** * validate product */ if (!$this->_validateProduct($product, $attributeId)) { $this->_addItemException($resultItem, ShopgateLibraryException::CART_ITEM_PRODUCT_NOT_FOUND, sprintf('ProductId #%s AttributeId #%s', $productId, $attributeId)); $resultItems[] = $resultItem; continue; } $addItemResult = $this->getPlugin()->getContext()->cart->updateQty($item->getQuantity(), $productId, $attributeId, false, 'up', $this->_deliveryAddress && $this->_deliveryAddress->id ? $this->_deliveryAddress->id : 0); $this->getPlugin()->getContext()->cart->save(); if ($addItemResult != 1) { $resultItem->setIsBuyable(false); $resultItem->setQtyBuyable($product->getQuantity($productId, $attributeId)); /** * add error */ switch ($addItemResult) { case -1: $resultItem->setQtyBuyable($attributeId ? (int) Attribute::getAttributeMinimalQty($attributeId) : (int) $product->minimal_quantity); $minimalQuantity = $attributeId ? (int) Attribute::getAttributeMinimalQty($attributeId) : (int) $product->minimal_quantity; $this->_addItemException($resultItem, ShopgateLibraryException::CART_ITEM_REQUESTED_QUANTITY_UNDER_MINIMUM_QUANTITY, sprintf(Tools::displayError('You must add %d minimum quantity'), $minimalQuantity)); break; default: $this->_addItemException($resultItem, ShopgateLibraryException::CART_ITEM_REQUESTED_QUANTITY_NOT_AVAILABLE, Tools::displayError('There isn\'t enough product in stock.')); break; } } else { $resultItem->setIsBuyable(true); $resultItem->setQtyBuyable((int) $item->getQuantity()); } $resultItems[] = $resultItem; } return $resultItems; }
public function updateCartQuantities($ebay_profile) { $id_lang = (int) Configuration::get('PS_LANG_DEFAULT'); $cart_nb_products = 0; $products_by_shop = $this->getProductsAndProfileByShop(); if (isset($products_by_shop[$ebay_profile->id_shop])) { $product_list = $products_by_shop[$ebay_profile->id_shop]['id_products']; } else { $product_list = array(); } // foreach ($product_list as $id_product) // { // foreach($this->product_list as $product) // if ($id_product == $product['id_product']) // break; foreach ($product_list as $p) { //Nombre de produit donc nombre de tour foreach ($this->product_list as $product) { if ($p['id_product'] == $product['id_product'] && $p['id_product_attribute'] == $product['id_product_attribute']) { break; } } // check if product is in this cart // if (!count($this->carts[$ebay_profile->id_shop]->getProducts(false, $product['id_product']))) // continue; $prod = new Product($product['id_product'], false, $id_lang); $minimal_quantity = empty($product['id_product_attribute']) ? $prod->minimal_quantity : (int) Attribute::getAttributeMinimalQty($product['id_product_attribute']); if ($product['quantity'] >= $minimal_quantity) { $id_product_attribute = empty($product['id_product_attribute']) ? null : $product['id_product_attribute']; if (version_compare(_PS_VERSION_, '1.5', '>')) { $update = $this->carts[$ebay_profile->id_shop]->updateQty((int) $product['quantity'], (int) $product['id_product'], $id_product_attribute, false, 'up', 0, new Shop($ebay_profile->id_shop)); if ($update === true) { $cart_nb_products++; } } elseif ($this->carts[$ebay_profile->id_shop]->updateQty((int) $product['quantity'], (int) $product['id_product'], $id_product_attribute)) { $cart_nb_products++; } } else { // minimal quantity for purchase not met $this->_sendMinimalQtyAlertEmail($prod->name, $minimal_quantity, $product['quantity']); } } $this->carts[$ebay_profile->id_shop]->update(); if (version_compare(_PS_VERSION_, '1.5', '>')) { $this->carts[$ebay_profile->id_shop]->getProducts(true); $this->carts[$ebay_profile->id_shop]->getPackageList(true); $this->carts[$ebay_profile->id_shop]->getDeliveryOptionList(null, true); } return (bool) $cart_nb_products; }