public function registerDiscount($id_customer, $register = false, $id_currency = 0)
 {
     $configurations = Configuration::getMultiple(array('REFERRAL_DISCOUNT_TYPE', 'REFERRAL_PERCENTAGE', 'REFERRAL_DISCOUNT_VALUE_' . (int) $id_currency));
     $cartRule = new CartRule();
     if ($configurations['REFERRAL_DISCOUNT_TYPE'] == Discount::PERCENT) {
         $cartRule->reduction_percent = (double) $configurations['REFERRAL_PERCENTAGE'];
     } elseif ($configurations['REFERRAL_DISCOUNT_TYPE'] == Discount::AMOUNT and isset($configurations['REFERRAL_DISCOUNT_VALUE_' . (int) $id_currency])) {
         $cartRule->reduction_amount = (double) $configurations['REFERRAL_DISCOUNT_VALUE_' . (int) $id_currency];
     }
     $cartRule->quantity = 1;
     $cartRule->quantity_per_user = 1;
     $cartRule->date_from = date('Y-m-d H:i:s', time());
     $cartRule->date_to = date('Y-m-d H:i:s', time() + 31536000);
     // + 1 year
     $cartRule->code = $this->getDiscountPrefix() . Tools::passwdGen(6);
     $cartRule->name = Configuration::getInt('REFERRAL_DISCOUNT_DESCRIPTION');
     $cartRule->id_customer = (int) $id_customer;
     $cartRule->id_currency = (int) $id_currency;
     if ($cartRule->add()) {
         if ($register != false) {
             if ($register == 'sponsor') {
                 $this->id_cart_rule_sponsor = (int) $cartRule->id;
             } elseif ($register == 'sponsored') {
                 $this->id_cart_rule = (int) $cartRule->id;
             }
             return $this->save();
         }
         return true;
     }
     return false;
 }
Ejemplo n.º 2
0
 public function registerDiscount($id_customer, $amount, $day, $type, $name)
 {
     $languages = Language::getLanguages(false);
     $cartRule = new CartRule();
     if ($type == 'percent') {
         $cartRule->reduction_percent = $amount;
     } else {
         $cartRule->reduction_amount = $amount;
     }
     $cartRule->quantity = 1;
     $cartRule->quantity_per_user = 1;
     $cartRule->date_from = date('Y-m-d H:i:s', time());
     $cartRule->date_to = date('Y-m-d H:i:s', time() + 86000 * $day);
     //$cartRule->minimum_amount = ''; // Utile ?
     $cartRule->minimum_amount_tax = true;
     $cartRule->code = $name . '_' . strtoupper(Tools::passwdGen(6));
     //$cartRule->code = $name;
     // QUESTION ?
     // It does not work if I do not use languages but it works with the referalprogam module (Prestashop Module)
     foreach ($languages as $lang) {
         $cartRule->name[$lang['id_lang']] = $name . ' Customer ID :' . $id_customer;
     }
     $cartRule->id_customer = (int) $id_customer;
     $cartRule->reduction_tax = true;
     $cartRule->highlight = 1;
     if ($cartRule->add()) {
         return $cartRule;
     }
     return false;
 }
Ejemplo n.º 3
0
 /**
  * Preparing hidden form with payment data before sending it to Dotpay
  */
 public function initContent()
 {
     parent::initContent();
     $this->display_column_left = false;
     $this->display_header = false;
     $this->display_footer = false;
     $cartId = 0;
     if (Tools::getValue('order_id') == false) {
         $cartId = $this->context->cart->id;
         $exAmount = $this->api->getExtrachargeAmount(true);
         if ($exAmount > 0 && !$this->isExVPinCart()) {
             $productId = $this->config->getDotpayExchVPid();
             if ($productId != 0) {
                 $product = new Product($productId, true);
                 $product->price = $exAmount;
                 $product->save();
                 $product->flushPriceCache();
                 $this->context->cart->updateQty(1, $product->id);
                 $this->context->cart->update();
                 $this->context->cart->getPackageList(true);
             }
         }
         $discAmount = $this->api->getDiscountAmount();
         if ($discAmount > 0) {
             $discount = new CartRule($this->config->getDotpayDiscountId());
             $discount->reduction_amount = $this->api->getDiscountAmount();
             $discount->reduction_currency = $this->context->cart->id_currency;
             $discount->reduction_tax = 1;
             $discount->update();
             $this->context->cart->addCartRule($discount->id);
             $this->context->cart->update();
             $this->context->cart->getPackageList(true);
         }
         $result = $this->module->validateOrder($this->context->cart->id, (int) $this->config->getDotpayNewStatusId(), $this->getDotAmount(), $this->module->displayName, NULL, array(), NULL, false, $this->customer->secure_key);
     } else {
         $this->context->cart = Cart::getCartByOrderId(Tools::getValue('order_id'));
         $this->initPersonalData();
         $cartId = $this->context->cart->id;
     }
     $this->api->onPrepareAction(Tools::getValue('dotpay_type'), array('order' => Order::getOrderByCartId($cartId), 'customer' => $this->context->customer->id));
     $sa = new DotpaySellerApi($this->config->getDotpaySellerApiUrl());
     if ($this->config->isDotpayDispInstruction() && $this->config->isApiConfigOk() && $this->api->isChannelInGroup(Tools::getValue('channel'), array(DotpayApi::cashGroup, DotpayApi::transfersGroup)) && $sa->isAccountRight($this->config->getDotpayApiUsername(), $this->config->getDotpayApiPassword(), $this->config->getDotpayApiVersion())) {
         $this->context->cookie->dotpay_channel = Tools::getValue('channel');
         Tools::redirect($this->context->link->getModuleLink($this->module->name, 'confirm', array('order_id' => Order::getOrderByCartId($cartId))));
         die;
     }
     $this->context->smarty->assign(array('hiddenForm' => $this->api->getHiddenForm()));
     $cookie = new Cookie('lastOrder');
     $cookie->orderId = Order::getOrderByCartId($cartId);
     $cookie->write();
     $this->setTemplate("preparing.tpl");
 }
Ejemplo n.º 4
0
 public function hookFooter($params)
 {
     if (!$this->isCached('blockmyaccountfooter.tpl', $this->getCacheId())) {
         $this->smarty->assign(array('voucherAllowed' => CartRule::isFeatureActive(), 'returnAllowed' => (int) Configuration::get('PS_ORDER_RETURN'), 'HOOK_BLOCK_MY_ACCOUNT' => Hook::exec('displayMyAccountBlockfooter')));
     }
     return $this->display(__FILE__, 'blockmyaccountfooter.tpl', $this->getCacheId());
 }
Ejemplo n.º 5
0
 /**
  * Do whatever you have to before redirecting the customer on the website of your payment processor.
  */
 public function postProcess()
 {
     /**
      * Oops, an error occured.
      */
     if (Tools::getValue('action') == 'error') {
         return $this->displayError('An error occurred while trying to redirect the customer');
     } else {
         //First solution to know if refreshed page: http://stackoverflow.com/a/6127748
         $refreshButtonPressed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
         $result = $this->module->callToRest('GET', '/orders?mid=' . Context::getContext()->cart->id, null, false);
         $result['response'] = json_decode($result['response'], true);
         if ($result['code'] == '200' && isset($result['response']['results'][0]['id']) && !$refreshButtonPressed) {
             //The cart exists on Aplazame, we try to send with another ID
             $oldCart = new Cart(Context::getContext()->cart->id);
             $data = $oldCart->duplicate();
             if ($data['success']) {
                 $cart = $data['cart'];
                 Context::getContext()->cart = $cart;
                 CartRule::autoAddToCart(Context::getContext());
                 Context::getContext()->cookie->id_cart = $cart->id;
             } else {
                 $this->module->logError('Error: Cannot duplicate cart ' . Context::getContext()->cart->id);
             }
         }
         $this->context->smarty->assign(array('cart_id' => Context::getContext()->cart->id, 'secure_key' => Context::getContext()->customer->secure_key, 'aplazame_order_json' => json_encode($this->module->getCheckoutSerializer(0, Context::getContext()->cart->id), 128), 'aplazame_version' => ConfigurationCore::get('APLAZAME_API_VERSION', null), 'aplazame_url' => Configuration::get('APLAZAME_API_URL', null), 'aplazame_mode' => Configuration::get('APLAZAME_LIVE_MODE', null) ? 'false' : 'true'));
         return $this->setTemplate('redirect.tpl');
     }
 }
Ejemplo n.º 6
0
 public function delete()
 {
     if (!$this->hasMultishopEntries() || Shop::getContext() == Shop::CONTEXT_ALL) {
         $result = Db::getInstance()->executeS('SELECT id_product_attribute FROM ' . _DB_PREFIX_ . 'product_attribute_combination WHERE id_attribute = ' . (int) $this->id);
         $products = array();
         foreach ($result as $row) {
             $combination = new Combination($row['id_product_attribute']);
             $new_request = Db::getInstance()->executeS('SELECT id_product, default_on FROM ' . _DB_PREFIX_ . 'product_attribute WHERE id_product_attribute = ' . (int) $row['id_product_attribute']);
             foreach ($new_request as $value) {
                 if ($value['default_on'] == 1) {
                     $products[] = $value['id_product'];
                 }
             }
             $combination->delete();
         }
         foreach ($products as $product) {
             $result = Db::getInstance()->executeS('SELECT id_product_attribute FROM ' . _DB_PREFIX_ . 'product_attribute WHERE id_product = ' . (int) $product . ' LIMIT 1');
             foreach ($result as $row) {
                 if (Validate::isLoadedObject($product = new Product((int) $product))) {
                     $product->deleteDefaultAttributes();
                     $product->setDefaultAttribute($row['id_product_attribute']);
                 }
             }
         }
         // Delete associated restrictions on cart rules
         CartRule::cleanProductRuleIntegrity('attributes', $this->id);
         /* Reinitializing position */
         $this->cleanPositions((int) $this->id_attribute_group);
     }
     $return = parent::delete();
     if ($return) {
         Hook::exec('actionAttributeDelete', array('id_attribute' => $this->id));
     }
     return $return;
 }
Ejemplo n.º 7
0
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $cart_rules = CartRule::getCustomerCartRules($this->context->language->id, $this->context->customer->id, true, false);
     $nb_cart_rules = count($cart_rules);
     $this->context->smarty->assign(array('nb_cart_rules' => (int) $nb_cart_rules, 'cart_rules' => $cart_rules));
     $this->setTemplate(_PS_THEME_DIR_ . 'discount.tpl');
 }
Ejemplo n.º 8
0
 public function hookDisplayLeftColumn($params)
 {
     if (!$this->context->customer->isLogged()) {
         return false;
     }
     $this->smarty->assign(array('voucherAllowed' => CartRule::isFeatureActive(), 'returnAllowed' => (int) Configuration::get('PS_ORDER_RETURN'), 'HOOK_BLOCK_MY_ACCOUNT' => Hook::exec('displayMyAccountBlock')));
     return $this->display(__FILE__, $this->name . '.tpl');
 }
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $has_address = $this->context->customer->getAddresses($this->context->language->id);
     $this->context->smarty->assign(array('has_customer_an_address' => empty($has_address), 'voucherAllowed' => (int) CartRule::isFeatureActive(), 'returnAllowed' => (int) Configuration::get('PS_ORDER_RETURN')));
     $this->context->smarty->assign('HOOK_CUSTOMER_ACCOUNT', Hook::exec('displayCustomerAccount'));
     $this->setTemplate(_PS_THEME_DIR_ . 'my-account.tpl');
 }
function findCode($code)
{
    if (version_compare(_PS_VERSION_, '1.5', '>=')) {
        return CartRule::getIdByCode($code);
    } else {
        return Discount::getIdByName($code);
    }
}
Ejemplo n.º 11
0
 protected function _assignSummaryInformations()
 {
     $summary = $this->context->cart->getSummaryDetails();
     $customizedDatas = Product::getAllCustomizedDatas($this->context->cart->id);
     // override customization tax rate with real tax (tax rules)
     if ($customizedDatas) {
         foreach ($summary['products'] as &$productUpdate) {
             $productId = (int) isset($productUpdate['id_product']) ? $productUpdate['id_product'] : $productUpdate['product_id'];
             $productAttributeId = (int) isset($productUpdate['id_product_attribute']) ? $productUpdate['id_product_attribute'] : $productUpdate['product_attribute_id'];
             if (isset($customizedDatas[$productId][$productAttributeId])) {
                 $productUpdate['tax_rate'] = Tax::getProductTaxRate($productId, $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             }
         }
         Product::addCustomizationPrice($summary['products'], $customizedDatas);
     }
     $cart_product_context = Context::getContext()->cloneContext();
     foreach ($summary['products'] as $key => &$product) {
         $product['quantity'] = $product['cart_quantity'];
         // for compatibility with 1.2 themes
         if ($cart_product_context->shop->id != $product['id_shop']) {
             $cart_product_context->shop = new Shop((int) $product['id_shop']);
         }
         $product['price_without_specific_price'] = Product::getPriceStatic($product['id_product'], !Product::getTaxCalculationMethod(), $product['id_product_attribute'], _PS_PRICE_COMPUTE_PRECISION_, null, false, false, 1, false, null, null, null, $null, true, true, $cart_product_context);
         /**
          * ABU edit: variable is_discount set à 1 à tord, calcul foireux de presta
          * @bugfix: https://github.com/PrestaShop/PrestaShop/commit/379e28b341730ea95c0b2d6567817305ea841b23
          * @perso: soustraction de l'ecotax au price_without_specific_price @else
          */
         if (Product::getTaxCalculationMethod()) {
             // $product['is_discounted'] = $product['price_without_specific_price'] != Tools::ps_round($product['price'], _PS_PRICE_COMPUTE_PRECISION_);
             $product['is_discounted'] = Tools::ps_round($product['price_without_specific_price'], _PS_PRICE_COMPUTE_PRECISION_) != Tools::ps_round($product['price'], _PS_PRICE_COMPUTE_PRECISION_);
         } else {
             // $product['is_discounted'] = $product['price_without_specific_price'] != Tools::ps_round($product['price_wt'], _PS_PRICE_COMPUTE_PRECISION_);
             $product['is_discounted'] = Tools::ps_round($product['price_without_specific_price'] - $product['ecotax'], _PS_PRICE_COMPUTE_PRECISION_) != Tools::ps_round($product['price_wt'], _PS_PRICE_COMPUTE_PRECISION_);
         }
     }
     // Get available cart rules and unset the cart rules already in the cart
     $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);
     $cart_cart_rules = $this->context->cart->getCartRules();
     foreach ($available_cart_rules as $key => $available_cart_rule) {
         if (!$available_cart_rule['highlight'] || strpos($available_cart_rule['code'], CartRule::BO_ORDER_CODE_PREFIX) === 0) {
             unset($available_cart_rules[$key]);
             continue;
         }
         foreach ($cart_cart_rules as $cart_cart_rule) {
             if ($available_cart_rule['id_cart_rule'] == $cart_cart_rule['id_cart_rule']) {
                 unset($available_cart_rules[$key]);
                 continue 2;
             }
         }
     }
     $show_option_allow_separate_package = !$this->context->cart->isAllProductsInStock(true) && Configuration::get('PS_SHIP_WHEN_AVAILABLE');
     $this->context->smarty->assign($summary);
     $this->context->smarty->assign(array('token_cart' => Tools::getToken(false), 'isLogged' => $this->isLogged, 'isVirtualCart' => $this->context->cart->isVirtualCart(), 'productNumber' => $this->context->cart->nbProducts(), 'voucherAllowed' => CartRule::isFeatureActive(), 'shippingCost' => $this->context->cart->getOrderTotal(true, Cart::ONLY_SHIPPING), 'shippingCostTaxExc' => $this->context->cart->getOrderTotal(false, Cart::ONLY_SHIPPING), 'customizedDatas' => $customizedDatas, 'CUSTOMIZE_FILE' => Product::CUSTOMIZE_FILE, 'CUSTOMIZE_TEXTFIELD' => Product::CUSTOMIZE_TEXTFIELD, 'lastProductAdded' => $this->context->cart->getLastProduct(), 'displayVouchers' => $available_cart_rules, 'show_option_allow_separate_package' => $show_option_allow_separate_package, 'smallSize' => Image::getSize(ImageType::getFormatedName('small'))));
     $this->context->smarty->assign(array('HOOK_SHOPPING_CART' => Hook::exec('displayShoppingCartFooter', $summary), 'HOOK_SHOPPING_CART_EXTRA' => Hook::exec('displayShoppingCart', $summary)));
 }
Ejemplo n.º 12
0
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $cart_rules = CartRule::getCustomerCartRules($this->context->language->id, $this->context->customer->id, true, false);
     $nb_cart_rules = count($cart_rules);
     foreach ($cart_rules as &$discount) {
         $discount['value'] = Tools::convertPriceFull($discount['value'], new Currency((int) $discount['reduction_currency']), new Currency((int) $this->context->cart->id_currency));
     }
     $this->context->smarty->assign(array('nb_cart_rules' => (int) $nb_cart_rules, 'cart_rules' => $cart_rules, 'discount' => $cart_rules, 'nbDiscounts' => (int) $nb_cart_rules));
     $this->setTemplate(_PS_THEME_DIR_ . 'discount.tpl');
 }
Ejemplo n.º 13
0
 public function delete()
 {
     $address = new Address($this->id_address);
     if (Validate::isLoadedObject($address) and !$address->delete()) {
         return false;
     }
     if (parent::delete()) {
         CartRule::cleanProductRuleIntegrity('manufacturers', $this->id);
         return $this->deleteImage();
     }
 }
Ejemplo n.º 14
0
 /**
  * Logs a given customer in.
  */
 public static function login_customer($id_customer)
 {
     // Make sure that that the customers exists.
     $sql = "SELECT * FROM `" . _DB_PREFIX_ . "customer` WHERE `id_customer` = '" . pSQL($id_customer) . "'";
     $result = Db::getInstance()->GetRow($sql);
     // The user account has been found!
     if (!empty($result['id_customer'])) {
         // See => CustomerCore::getByEmail
         $customer = new Customer();
         $customer->id = $result['id_customer'];
         foreach ($result as $key => $value) {
             if (key_exists($key, $customer)) {
                 $customer->{$key} = $value;
             }
         }
         // See => AuthControllerCore::processSubmitLogin
         Hook::exec('actionBeforeAuthentication');
         $context = Context::getContext();
         $context->cookie->id_compare = isset($context->cookie->id_compare) ? $context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
         $context->cookie->id_customer = (int) $customer->id;
         $context->cookie->customer_lastname = $customer->lastname;
         $context->cookie->customer_firstname = $customer->firstname;
         $context->cookie->logged = 1;
         $customer->logged = 1;
         $context->cookie->is_guest = $customer->isGuest();
         $context->cookie->passwd = $customer->passwd;
         $context->cookie->email = $customer->email;
         // Add customer to the context
         $context->customer = $customer;
         if (Configuration::get('PS_CART_FOLLOWING') && (empty($context->cookie->id_cart) || Cart::getNbProducts($context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($context->customer->id))) {
             $context->cart = new Cart($id_cart);
         } else {
             $context->cart->id_carrier = 0;
             $context->cart->setDeliveryOption(null);
             $context->cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id);
             $context->cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id);
         }
         $context->cart->id_customer = (int) $customer->id;
         $context->cart->secure_key = $customer->secure_key;
         $context->cart->save();
         $context->cookie->id_cart = (int) $context->cart->id;
         $context->cookie->update();
         $context->cart->autosetProductAddress();
         Hook::exec('actionAuthentication');
         // Login information have changed, so we check if the cart rules still apply
         CartRule::autoRemoveFromCart($context);
         CartRule::autoAddToCart($context);
         // Customer is now logged in.
         return true;
     }
     // Invalid customer specified.
     return false;
 }
Ejemplo n.º 15
0
    /**
     * Transform loyalty point to a voucher
     */
    public function processTransformPoints()
    {
        $customer_points = (int) LoyaltyModule::getPointsByCustomer((int) $this->context->customer->id);
        if ($customer_points > 0) {
            /* Generate a voucher code */
            $voucher_code = null;
            do {
                $voucher_code = 'FID' . rand(1000, 100000);
            } while (CartRule::cartRuleExists($voucher_code));
            // Voucher creation and affectation to the customer
            $cart_rule = new CartRule();
            $cart_rule->code = $voucher_code;
            $cart_rule->id_customer = (int) $this->context->customer->id;
            $cart_rule->reduction_currency = (int) $this->context->currency->id;
            $cart_rule->reduction_amount = LoyaltyModule::getVoucherValue((int) $customer_points);
            $cart_rule->quantity = 1;
            $cart_rule->quantity_per_user = 1;
            // If merchandise returns are allowed, the voucher musn't be usable before this max return date
            $date_from = Db::getInstance()->getValue('
			SELECT UNIX_TIMESTAMP(date_add) n
			FROM ' . _DB_PREFIX_ . 'loyalty
			WHERE id_cart_rule = 0 AND id_customer = ' . (int) $this->context->cookie->id_customer . '
			ORDER BY date_add DESC');
            if (Configuration::get('PS_ORDER_RETURN')) {
                $date_from += 60 * 60 * 24 * (int) Configuration::get('PS_ORDER_RETURN_NB_DAYS');
            }
            $cart_rule->date_from = date('Y-m-d H:i:s', $date_from);
            $cart_rule->date_to = date('Y-m-d H:i:s', strtotime($cart_rule->date_from . ' +1 year'));
            $cart_rule->minimum_amount = (double) Configuration::get('PS_LOYALTY_MINIMAL');
            $cart_rule->active = 1;
            $categories = Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY');
            if ($categories != '' && $categories != 0) {
                $categories = explode(',', Configuration::get('PS_LOYALTY_VOUCHER_CATEGORY'));
            } else {
                die(Tools::displayError());
            }
            $languages = Language::getLanguages(true);
            $default_text = Configuration::get('PS_LOYALTY_VOUCHER_DETAILS', (int) Configuration::get('PS_LANG_DEFAULT'));
            foreach ($languages as $language) {
                $text = Configuration::get('PS_LOYALTY_VOUCHER_DETAILS', (int) $language['id_lang']);
                $cart_rule->name[(int) $language['id_lang']] = $text ? strval($text) : strval($default_text);
            }
            if (is_array($categories) && count($categories)) {
                $cart_rule->add(true, false, $categories);
            } else {
                $cart_rule->add();
            }
            // Register order(s) which contributed to create this voucher
            LoyaltyModule::registerDiscount($cart_rule);
            Tools::redirect($this->context->link->getModuleLink('loyalty', 'default', array('process' => 'summary')));
        }
    }
Ejemplo n.º 16
0
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $this->context->smarty->assign('categoriesTree', Category::getRootCategory()->recurseLiteCategTree(0));
     $this->context->smarty->assign('categoriescmsTree', CMSCategory::getRecurseCategory($this->context->language->id, 1, 1, 1));
     $this->context->smarty->assign('voucherAllowed', (int) CartRule::isFeatureActive());
     $blockmanufacturer = Module::getInstanceByName('blockmanufacturer');
     $blocksupplier = Module::getInstanceByName('blocksupplier');
     $this->context->smarty->assign('display_manufacturer_link', (bool) $blockmanufacturer->active);
     $this->context->smarty->assign('display_supplier_link', (bool) $blocksupplier->active);
     $this->context->smarty->assign('PS_DISPLAY_SUPPLIERS', Configuration::get('PS_DISPLAY_SUPPLIERS'));
     $this->context->smarty->assign('display_store', Configuration::get('PS_STORES_DISPLAY_SITEMAP'));
     $this->setTemplate(_PS_THEME_DIR_ . 'sitemap.tpl');
 }
Ejemplo n.º 17
0
 private function duplicateCart(Cart $oldCart)
 {
     $data = $oldCart->duplicate();
     if (!$data || !$data['success']) {
         $this->module->log(Aplazame::LOG_WARNING, 'Cannot duplicate cart', $oldCart->id);
         return $oldCart;
     }
     $cart = $data['cart'];
     $this->context->cookie->id_cart = $cart->id;
     $this->context->cart = $cart;
     CartRule::autoAddToCart($this->context);
     $this->context->cookie->write();
     return $cart;
 }
 public function getWidgetVariables($hookName = null, array $configuration = [])
 {
     $link = $this->context->link;
     $my_account_urls = array(0 => array('title' => $this->l('Orders'), 'url' => $link->getPageLink('history', true)), 2 => array('title' => $this->l('Credit slips'), 'url' => $link->getPageLink('order-slip', true)), 3 => array('title' => $this->l('Addresses'), 'url' => $link->getPageLink('addresses', true)), 4 => array('title' => $this->l('Personal info'), 'url' => $link->getPageLink('identity', true)));
     if ((int) Configuration::get('PS_ORDER_RETURN')) {
         $my_account_urls[1] = array('title' => $this->l('Merchandise returns'), 'url' => $link->getPageLink('order-follow', true));
     }
     if (CartRule::isFeatureActive()) {
         $my_account_urls[5] = array('title' => $this->l('Vouchers'), 'url' => $link->getPageLink('discount', true));
     }
     // Sort Account links base in his title, keeping the keys
     asort($my_account_urls);
     return array('my_account_urls' => $my_account_urls, 'logout_url' => $link->getPageLink('index', true, null, "mylogout"));
 }
Ejemplo n.º 19
0
 public function initContent()
 {
     parent::initContent();
     if ($orders = Order::getCustomerOrders($this->context->customer->id)) {
         foreach ($orders as &$order) {
             $myOrder = new Order((int) $order['id_order']);
             if (Validate::isLoadedObject($myOrder)) {
                 $order['virtual'] = $myOrder->isVirtual(false);
             }
         }
     }
     $has_address = $this->context->customer->getAddresses($this->context->language->id);
     $this->context->smarty->assign(array('orders' => $orders, 'invoiceAllowed' => (int) Configuration::get('PS_INVOICE'), 'reorderingAllowed' => !(bool) Configuration::get('PS_DISALLOW_HISTORY_REORDERING'), 'slowValidation' => Tools::isSubmit('slowvalidation'), 'has_customer_an_address' => empty($has_address), 'voucherAllowed' => (int) CartRule::isFeatureActive(), 'returnAllowed' => (int) Configuration::get('PS_ORDER_RETURN')));
     $this->context->smarty->assign('HOOK_CUSTOMER_ACCOUNT', Hook::exec('displayCustomerAccount'));
     $this->setTemplate(_PS_THEME_DIR_ . 'my-account.tpl');
 }
Ejemplo n.º 20
0
 public function delete()
 {
     if (!$this->hasMultishopEntries()) {
         $result = Db::getInstance()->executeS('SELECT id_product_attribute FROM ' . _DB_PREFIX_ . 'product_attribute_combination WHERE id_attribute = ' . (int) $this->id);
         foreach ($result as $row) {
             $combination = new Combination($row['id_product_attribute']);
             $combination->delete();
         }
         // Delete associated restrictions on cart rules
         CartRule::cleanProductRuleIntegrity('attributes', $this->id);
         /* Reinitializing position */
         $this->cleanPositions((int) $this->id_attribute_group);
     }
     $return = parent::delete();
     if ($return) {
         Hook::exec('actionAttributeDelete', array('id_attribute' => $this->id));
     }
     return $return;
 }
Ejemplo n.º 21
0
 public function submit()
 {
     if ($this->validate()) {
         Hook::exec('actionAuthenticationBefore');
         $customer = new Customer();
         $authentication = $customer->getByEmail($this->getValue('email'), $this->getValue('password'));
         if (isset($authentication->active) && !$authentication->active) {
             $this->errors[''][] = $this->translator->trans('Your account isn\'t available at this time, please contact us', [], 'Shop.Notifications.Error');
         } elseif (!$authentication || !$customer->id || $customer->is_guest) {
             $this->errors[''][] = $this->translator->trans('Authentication failed.', [], 'Shop.Notifications.Error');
         } else {
             $this->context->updateCustomer($customer);
             Hook::exec('actionAuthentication', ['customer' => $this->context->customer]);
             // Login information have changed, so we check if the cart rules still apply
             CartRule::autoRemoveFromCart($this->context);
             CartRule::autoAddToCart($this->context);
         }
     }
     return !$this->hasErrors();
 }
Ejemplo n.º 22
0
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     $cart_rules = CartRule::getCustomerCartRules($this->context->language->id, $this->context->customer->id, true, true, true);
     $nb_cart_rules = count($cart_rules);
     foreach ($cart_rules as $key => &$discount) {
         if ($discount['quantity_for_user'] === 0) {
             unset($cart_rules[$key]);
         }
         $discount['value'] = Tools::convertPriceFull($discount['value'], new Currency((int) $discount['reduction_currency']), new Currency((int) $this->context->cart->id_currency));
         if ($discount['gift_product'] !== 0) {
             $product = new Product((int) $discount['gift_product']);
             if (isset($product->name)) {
                 $discount['gift_product_name'] = current($product->name);
             }
         }
     }
     $this->context->smarty->assign(array('nb_cart_rules' => (int) $nb_cart_rules, 'cart_rules' => $cart_rules, 'discount' => $cart_rules, 'nbDiscounts' => (int) $nb_cart_rules));
     $this->setTemplate(_PS_THEME_DIR_ . 'discount.tpl');
 }
Ejemplo n.º 23
0
 public function postProcess()
 {
     parent::postProcess();
     if (Tools::isSubmit('submitReorder') && ($id_order = (int) Tools::getValue('id_order'))) {
         $oldCart = new Cart(Order::getCartIdStatic($id_order, $this->context->customer->id));
         $duplication = $oldCart->duplicate();
         if (!$duplication || !Validate::isLoadedObject($duplication['cart'])) {
             $this->errors[] = $this->trans('Sorry. We cannot renew your order.', array(), 'Shop.Notifications.Error');
         } elseif (!$duplication['success']) {
             $this->errors[] = $this->trans('Some items are no longer available, and we are unable to renew your order.', array(), 'Shop.Notifications.Error');
         } else {
             $this->context->cookie->id_cart = $duplication['cart']->id;
             $context = $this->context;
             $context->cart = $duplication['cart'];
             CartRule::autoAddToCart($context);
             $this->context->cookie->write();
             Tools::redirect('index.php?controller=order');
         }
     }
     $this->bootstrap();
 }
Ejemplo n.º 24
0
 public function getTemplateVarCartRules()
 {
     $cart_rules = [];
     $vouchers = CartRule::getCustomerCartRules($this->context->language->id, $this->context->customer->id, true, false);
     foreach ($vouchers as $key => $voucher) {
         $cart_rules[$key] = $voucher;
         $cart_rules[$key]['voucher_date'] = Tools::displayDate($voucher['date_to'], null, false);
         $cart_rules[$key]['voucher_minimal'] = $voucher['minimum_amount'] > 0 ? Tools::displayPrice($voucher['minimum_amount'], (int) $voucher['minimum_amount_currency']) : $this->trans('None', array(), 'Shop.Theme');
         $cart_rules[$key]['voucher_cumulable'] = $voucher['cumulable'] ? $this->trans('Yes', array(), 'Shop.Theme') : $this->trans('No', array(), 'Shop.Theme');
         if ($voucher['id_discount_type'] == 1) {
             $cart_rules[$key]['value'] = sprintf('%s%%', $voucher['value']);
         } elseif ($voucher['id_discount_type'] == 2) {
             $cart_rules[$key]['value'] = sprintf('%s ' . ($voucher['reduction_tax'] ? $this->trans('Tax included', array(), 'Shop.Theme.Checkout') : $this->trans('Tax excluded', array(), 'Shop.Theme.Checkout')), Tools::displayPrice($voucher['value'], (int) $voucher['reduction_currency']));
         } elseif ($voucher['id_discount_type'] == 3) {
             $cart_rules[$key]['value'] = $this->trans('Free shipping', array(), 'Shop.Theme.Checkout');
         } else {
             $cart_rules[$key]['value'] = '-';
         }
     }
     return $cart_rules;
 }
Ejemplo n.º 25
0
 /**
  * This checks if the template set is available for mobile themes,
  * otherwise the front template is choosen.
  */
 public function setMobileTemplate($template)
 {
     // Needed for site map
     $blockmanufacturer = Module::getInstanceByName('blockmanufacturer');
     $blocksupplier = Module::getInstanceByName('blocksupplier');
     $this->context->smarty->assign('categoriesTree', Category::getRootCategory()->recurseLiteCategTree(0));
     $this->context->smarty->assign('categoriescmsTree', CMSCategory::getRecurseCategory($this->context->language->id, 1, 1, 1));
     $this->context->smarty->assign('voucherAllowed', (int) CartRule::isFeatureActive());
     $this->context->smarty->assign('display_manufacturer_link', (bool) $blockmanufacturer->active);
     $this->context->smarty->assign('display_supplier_link', (bool) $blocksupplier->active);
     $this->context->smarty->assign('PS_DISPLAY_SUPPLIERS', Configuration::get('PS_DISPLAY_SUPPLIERS'));
     $this->context->smarty->assign('PS_DISPLAY_BEST_SELLERS', Configuration::get('PS_DISPLAY_BEST_SELLERS'));
     $this->context->smarty->assign('display_store', Configuration::get('PS_STORES_DISPLAY_SITEMAP'));
     $this->context->smarty->assign('conditions', Configuration::get('PS_CONDITIONS'));
     $this->context->smarty->assign('id_cgv', Configuration::get('PS_CONDITIONS_CMS_ID'));
     $this->context->smarty->assign('PS_SHOP_NAME', Configuration::get('PS_SHOP_NAME'));
     $template = $this->getTemplatePath($template);
     $assign = array();
     $assign['tpl_file'] = basename($template, '.tpl');
     if (isset($this->php_self)) {
         $assign['controller_name'] = $this->php_self;
     }
     $this->context->smarty->assign($assign);
     $this->template = $template;
 }
 /**
  * Manage address
  */
 public function processAddress()
 {
     $same = Tools::isSubmit('same');
     if (!Tools::getValue('id_address_invoice', false) && !$same) {
         $same = true;
     }
     if (!Customer::customerHasAddress($this->context->customer->id, (int) Tools::getValue('id_address_delivery')) || !$same && Tools::getValue('id_address_delivery') != Tools::getValue('id_address_invoice') && !Customer::customerHasAddress($this->context->customer->id, (int) Tools::getValue('id_address_invoice'))) {
         $this->errors[] = Tools::displayError('Invalid address', !Tools::getValue('ajax'));
     } else {
         $this->context->cart->id_address_delivery = (int) Tools::getValue('id_address_delivery');
         $this->context->cart->id_address_invoice = $same ? $this->context->cart->id_address_delivery : (int) Tools::getValue('id_address_invoice');
         CartRule::autoRemoveFromCart($this->context);
         CartRule::autoAddToCart($this->context);
         if (!$this->context->cart->update()) {
             $this->errors[] = Tools::displayError('An error occurred while updating your cart.', !Tools::getValue('ajax'));
         }
         if (!$this->context->cart->isMultiAddressDelivery()) {
             $this->context->cart->setNoMultishipping();
         }
         // If there is only one delivery address, set each delivery address lines with the main delivery address
         if (Tools::isSubmit('message')) {
             $this->_updateMessage(Tools::getValue('message'));
         }
         // Add checking for all addresses
         $address_without_carriers = $this->context->cart->getDeliveryAddressesWithoutCarriers();
         if (count($address_without_carriers) && !$this->context->cart->isVirtualCart()) {
             if (count($address_without_carriers) > 1) {
                 $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to some addresses you selected.', !Tools::getValue('ajax')));
             } elseif ($this->context->cart->isMultiAddressDelivery()) {
                 $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to one of the address you selected.', !Tools::getValue('ajax')));
             } else {
                 $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to the address you selected.', !Tools::getValue('ajax')));
             }
         }
     }
     if ($this->errors) {
         if (Tools::getValue('ajax')) {
             die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
         }
         $this->step = 1;
     }
     if ($this->ajax) {
         die(true);
     }
 }
Ejemplo n.º 27
0
 /**
  * This checks if the template set is available for mobile themes,
  * otherwise the front template is choosen.
  */
 public function setMobileTemplate($template)
 {
     // Needed for site map
     $blockmanufacturer = Module::getInstanceByName('blockmanufacturer');
     $blocksupplier = Module::getInstanceByName('blocksupplier');
     $this->context->smarty->assign('categoriesTree', Category::getRootCategory()->recurseLiteCategTree(0));
     $this->context->smarty->assign('categoriescmsTree', CMSCategory::getRecurseCategory($this->context->language->id, 1, 1, 1));
     $this->context->smarty->assign('voucherAllowed', (int) CartRule::isFeatureActive());
     $this->context->smarty->assign('display_manufacturer_link', (bool) $blockmanufacturer->active);
     $this->context->smarty->assign('display_supplier_link', (bool) $blocksupplier->active);
     $this->context->smarty->assign('PS_DISPLAY_SUPPLIERS', Configuration::get('PS_DISPLAY_SUPPLIERS'));
     $this->context->smarty->assign('display_store', Configuration::get('PS_STORES_DISPLAY_SITEMAP'));
     $this->context->smarty->assign('conditions', Configuration::get('PS_CONDITIONS'));
     $this->context->smarty->assign('id_cgv', Configuration::get('PS_CONDITIONS_CMS_ID'));
     $this->context->smarty->assign('PS_SHOP_NAME', Configuration::get('PS_SHOP_NAME'));
     $mobile_template = '';
     $tpl_file = basename($template);
     $dirname = dirname($template) . (substr(dirname($template), -1, 1) == '/' ? '' : '/');
     if ($dirname == _PS_THEME_DIR_) {
         if (file_exists(_PS_THEME_MOBILE_DIR_ . $tpl_file)) {
             $template = _PS_THEME_MOBILE_DIR_ . $tpl_file;
         }
     } elseif ($dirname == _PS_THEME_MOBILE_DIR_) {
         if (!file_exists(_PS_THEME_MOBILE_DIR_ . $tpl_file) && file_exists(_PS_THEME_DIR_ . $tpl_file)) {
             $template = _PS_THEME_DIR_ . $tpl_file;
         }
     }
     $assign = array();
     $assign['tpl_file'] = basename($tpl_file, '.tpl');
     if (isset($this->php_self)) {
         $assign['controller_name'] = $this->php_self;
     }
     $this->context->smarty->assign($assign);
     $this->template = $template;
 }
Ejemplo n.º 28
0
 public function getOrderTotal($with_taxes = true, $type = Cart::BOTH, $products = null, $id_carrier = null, $use_cache = true)
 {
     /* 
      * EU-Legal
      * correct calculation of prices -> Problem with inaccuracy at high number of items
      */
     static $address = null;
     if (!$this->id) {
         return 0;
     }
     $type = (int) $type;
     $array_type = array(Cart::ONLY_PRODUCTS, Cart::ONLY_DISCOUNTS, Cart::BOTH, Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_SHIPPING, Cart::ONLY_WRAPPING, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING);
     $taxes = $this->getTaxDetails();
     $order_total_products_taxed = 0;
     // Define virtual context to prevent case where the cart is not the in the global context
     $virtual_context = Context::getContext()->cloneContext();
     $virtual_context->cart = $this;
     if (!in_array($type, $array_type)) {
         die(Tools::displayError());
     }
     $with_shipping = in_array($type, array(Cart::BOTH, Cart::ONLY_SHIPPING));
     // if cart rules are not used
     if ($type == Cart::ONLY_DISCOUNTS && !CartRule::isFeatureActive()) {
         return 0;
     }
     // no shipping cost if is a cart with only virtuals products
     $virtual = $this->isVirtualCart();
     if ($virtual && $type == Cart::ONLY_SHIPPING) {
         return 0;
     }
     if ($virtual && $type == Cart::BOTH) {
         $type = Cart::BOTH_WITHOUT_SHIPPING;
     }
     if (!Configuration::get('LEGAL_SHIPTAXMETH')) {
         if ($with_shipping) {
             if (is_null($products) && is_null($id_carrier)) {
                 $shipping_fees = $this->getTotalShippingCost(null, (bool) $with_taxes);
             } else {
                 $shipping_fees = $this->getPackageShippingCost($id_carrier, (bool) $with_taxes, null, $products);
             }
         } else {
             $shipping_fees = 0;
         }
     } else {
         if (!in_array($type, array(Cart::BOTH_WITHOUT_SHIPPING, Cart::ONLY_PRODUCTS, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING))) {
             if (is_null($products) && is_null($id_carrier)) {
                 $shipping_fees_taxed = $this->getTotalShippingCost(null, false);
             } else {
                 $shipping_fees_taxed = $this->getPackageShippingCost($id_carrier, false, null, $products);
             }
         } else {
             $shipping_fees_taxed = 0;
         }
         $shipping_fees = Order::calculateCompundTaxPrice($shipping_fees_taxed, $taxes);
         if ($with_taxes) {
             $shipping_fees = $shipping_fees_taxed;
         }
     }
     if ($type == Cart::ONLY_SHIPPING) {
         return $shipping_fees;
     }
     if ($type == Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING) {
         $type = Cart::ONLY_PRODUCTS;
     }
     $param_product = true;
     if (is_null($products)) {
         $param_product = false;
         $products = $this->getProducts();
     }
     if ($type == Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING) {
         foreach ($products as $key => $product) {
             if ($product['is_virtual']) {
                 unset($products[$key]);
             }
         }
         $type = Cart::ONLY_PRODUCTS;
     }
     $order_total = 0;
     if (Tax::excludeTaxeOption()) {
         $with_taxes = false;
     }
     $specific_price_output = false;
     $null = false;
     $products_total = array();
     $ecotax_total = 0;
     foreach ($products as $product) {
         if ($virtual_context->shop->id != $product['id_shop']) {
             $virtual_context->shop = new Shop((int) $product['id_shop']);
         }
         if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
             $id_address = (int) $this->id_address_invoice;
         } else {
             $id_address = (int) $product['id_address_delivery'];
         }
         // Get delivery address of the product from the cart
         if (!Address::addressExists($id_address)) {
             $id_address = null;
         }
         $price = Product::getPriceStatic((int) $product['id_product'], false, (int) $product['id_product_attribute'], 6, null, false, true, $product['cart_quantity'], false, (int) $this->id_customer ? (int) $this->id_customer : null, (int) $this->id, $id_address, $null, false, true, $virtual_context);
         if (Configuration::get('PS_USE_ECOTAX')) {
             $ecotax = $product['ecotax'];
             if (isset($product['attribute_ecotax']) && $product['attribute_ecotax'] > 0) {
                 $ecotax = $product['attribute_ecotax'];
             }
         } else {
             $ecotax = 0;
         }
         $address = Address::initialize($id_address, true);
         if ($with_taxes) {
             $id_tax_rules_group = Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product'], $virtual_context);
             $tax_calculator = TaxManagerFactory::getManager($address, $id_tax_rules_group)->getTaxCalculator();
             if ($ecotax) {
                 $ecotax_tax_calculator = TaxManagerFactory::getManager($address, (int) Configuration::get('PS_ECOTAX_TAX_RULES_GROUP_ID'))->getTaxCalculator();
             }
         } else {
             $id_tax_rules_group = 0;
         }
         if (in_array(Configuration::get('PS_ROUND_TYPE'), array(Order::ROUND_ITEM, Order::ROUND_LINE))) {
             if (!isset($products_total[$id_tax_rules_group])) {
                 $products_total[$id_tax_rules_group] = 0;
             }
         } else {
             if (!isset($products_total[$id_tax_rules_group . '_' . $id_address])) {
                 $products_total[$id_tax_rules_group . '_' . $id_address] = 0;
             }
         }
         switch (Configuration::get('PS_ROUND_TYPE')) {
             case Order::ROUND_TOTAL:
                 $products_total[$id_tax_rules_group . '_' . $id_address] += $price * (int) $product['cart_quantity'];
                 if ($ecotax) {
                     $ecotax_total += $ecotax * (int) $product['cart_quantity'];
                 }
                 break;
             case Order::ROUND_LINE:
                 $product_price = $price * $product['cart_quantity'];
                 if ($with_taxes) {
                     $products_total[$id_tax_rules_group] += Tools::ps_round($product_price + $tax_calculator->getTaxesTotalAmount($product_price), _PS_PRICE_COMPUTE_PRECISION_);
                 } else {
                     $products_total[$id_tax_rules_group] += Tools::ps_round($product_price, _PS_PRICE_COMPUTE_PRECISION_);
                 }
                 if ($ecotax) {
                     $ecotax_price = $ecotax * (int) $product['cart_quantity'];
                     if ($with_taxes) {
                         $ecotax_total += Tools::ps_round($ecotax_price + $ecotax_tax_calculator->getTaxesTotalAmount($ecotax_price), _PS_PRICE_COMPUTE_PRECISION_);
                     } else {
                         $ecotax_total += Tools::ps_round($ecotax_price, _PS_PRICE_COMPUTE_PRECISION_);
                     }
                 }
                 break;
             case Order::ROUND_ITEM:
             default:
                 $product_price = $with_taxes ? $tax_calculator->addTaxes($price) : $price;
                 $products_total[$id_tax_rules_group] += Tools::ps_round($product_price, _PS_PRICE_COMPUTE_PRECISION_) * (int) $product['cart_quantity'];
                 if ($ecotax) {
                     $ecotax_price = $with_taxes ? $ecotax_tax_calculator->addTaxes($ecotax) : $ecotax;
                     $ecotax_total += Tools::ps_round($ecotax_price, _PS_PRICE_COMPUTE_PRECISION_) * (int) $product['cart_quantity'];
                 }
                 break;
         }
     }
     foreach ($products_total as $key => $price) {
         if ($with_taxes && Configuration::get('PS_ROUND_TYPE') == Order::ROUND_TOTAL) {
             $tmp = explode('_', $key);
             $address = Address::initialize((int) $tmp[1], true);
             $tax_calculator = TaxManagerFactory::getManager($address, $tmp[0])->getTaxCalculator();
             $order_total += Tools::ps_round($price + $tax_calculator->getTaxesTotalAmount($price), _PS_PRICE_COMPUTE_PRECISION_);
         } else {
             $order_total += $price;
         }
     }
     if ($ecotax_total && $with_taxes && Configuration::get('PS_ROUND_TYPE') == Order::ROUND_TOTAL) {
         $ecotax_total = Tools::ps_round($ecotax_total, _PS_PRICE_COMPUTE_PRECISION_) + Tools::ps_round($ecotax_tax_calculator->getTaxesTotalAmount($ecotax_total), _PS_PRICE_COMPUTE_PRECISION_);
     }
     $order_total += $ecotax_total;
     $order_total_products = $order_total;
     if ($type == Cart::ONLY_DISCOUNTS) {
         $order_total = 0;
     }
     // Wrapping Fees
     $wrapping_fees = 0;
     if ($this->gift) {
         $wrapping_fees = Tools::convertPrice(Tools::ps_round($this->getGiftWrappingPrice($with_taxes), _PS_PRICE_COMPUTE_PRECISION_), Currency::getCurrencyInstance((int) $this->id_currency));
     }
     if ($type == Cart::ONLY_WRAPPING) {
         return $wrapping_fees;
     }
     $order_total_discount = 0;
     $order_shipping_discount = 0;
     if (!in_array($type, array(Cart::ONLY_SHIPPING, Cart::ONLY_PRODUCTS)) && CartRule::isFeatureActive()) {
         // First, retrieve the cart rules associated to this "getOrderTotal"
         if ($with_shipping || $type == Cart::ONLY_DISCOUNTS) {
             $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_ALL);
         } else {
             $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_REDUCTION);
             // Cart Rules array are merged manually in order to avoid doubles
             foreach ($this->getCartRules(CartRule::FILTER_ACTION_GIFT) as $tmp_cart_rule) {
                 $flag = false;
                 foreach ($cart_rules as $cart_rule) {
                     if ($tmp_cart_rule['id_cart_rule'] == $cart_rule['id_cart_rule']) {
                         $flag = true;
                     }
                 }
                 if (!$flag) {
                     $cart_rules[] = $tmp_cart_rule;
                 }
             }
         }
         $id_address_delivery = 0;
         if (isset($products[0])) {
             $id_address_delivery = is_null($products) ? $this->id_address_delivery : $products[0]['id_address_delivery'];
         }
         $package = array('id_carrier' => $id_carrier, 'id_address' => $id_address_delivery, 'products' => $products);
         // Then, calculate the contextual value for each one
         $flag = false;
         foreach ($cart_rules as $cart_rule) {
             // If the cart rule offers free shipping, add the shipping cost
             if (($with_shipping || $type == Cart::ONLY_DISCOUNTS) && $cart_rule['obj']->free_shipping && !$flag) {
                 $order_shipping_discount = (double) Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_SHIPPING, $param_product ? $package : null, $use_cache), _PS_PRICE_COMPUTE_PRECISION_);
                 $flag = true;
             }
             // If the cart rule is a free gift, then add the free gift value only if the gift is in this package
             if ((int) $cart_rule['obj']->gift_product) {
                 $in_order = false;
                 if (is_null($products)) {
                     $in_order = true;
                 } else {
                     foreach ($products as $product) {
                         if ($cart_rule['obj']->gift_product == $product['id_product'] && $cart_rule['obj']->gift_product_attribute == $product['id_product_attribute']) {
                             $in_order = true;
                         }
                     }
                 }
                 if ($in_order) {
                     $order_total_discount += $cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_GIFT, $package, $use_cache);
                 }
             }
             // If the cart rule offers a reduction, the amount is prorated (with the products in the package)
             if ($cart_rule['obj']->reduction_percent != 0 || $cart_rule['obj']->reduction_amount != 0) {
                 $order_total_discount += Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_REDUCTION, $package, $use_cache), _PS_PRICE_COMPUTE_PRECISION_);
             }
         }
         $order_total_discount = min(Tools::ps_round($order_total_discount, 2), (double) $order_total_products) + (double) $order_shipping_discount;
         $order_total -= $order_total_discount;
     }
     if ($type == Cart::BOTH) {
         $order_total += $shipping_fees + $wrapping_fees;
     }
     if ($order_total < 0 && $type != Cart::ONLY_DISCOUNTS) {
         return 0;
     }
     if ($type == Cart::ONLY_DISCOUNTS) {
         return $order_total_discount;
     }
     return Tools::ps_round((double) $order_total, _PS_PRICE_COMPUTE_PRECISION_);
 }
 public function displayAjaxSearchCartRuleVouchers()
 {
     $found = false;
     if ($vouchers = CartRule::getCartsRuleByCode(Tools::getValue('q'), (int) $this->context->language->id, true)) {
         $found = true;
     }
     echo Tools::jsonEncode(array('found' => $found, 'vouchers' => $vouchers));
 }
Ejemplo n.º 30
0
 public function ajaxProcessAddProductOnOrder()
 {
     // Load object
     $order = new Order((int) Tools::getValue('id_order'));
     if (!Validate::isLoadedObject($order)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The order object cannot be loaded.'))));
     }
     if ($order->hasBeenShipped()) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('You cannot add products to delivered orders. '))));
     }
     $product_informations = $_POST['add_product'];
     if (isset($_POST['add_invoice'])) {
         $invoice_informations = $_POST['add_invoice'];
     } else {
         $invoice_informations = array();
     }
     $product = new Product($product_informations['product_id'], false, $order->id_lang);
     if (!Validate::isLoadedObject($product)) {
         die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The product object cannot be loaded.'))));
     }
     if (isset($product_informations['product_attribute_id']) && $product_informations['product_attribute_id']) {
         $combination = new Combination($product_informations['product_attribute_id']);
         if (!Validate::isLoadedObject($combination)) {
             die(Tools::jsonEncode(array('result' => false, 'error' => Tools::displayError('The combination object cannot be loaded.'))));
         }
     }
     // Total method
     $total_method = Cart::BOTH_WITHOUT_SHIPPING;
     // Create new cart
     $cart = new Cart();
     $cart->id_shop_group = $order->id_shop_group;
     $cart->id_shop = $order->id_shop;
     $cart->id_customer = $order->id_customer;
     $cart->id_carrier = $order->id_carrier;
     $cart->id_address_delivery = $order->id_address_delivery;
     $cart->id_address_invoice = $order->id_address_invoice;
     $cart->id_currency = $order->id_currency;
     $cart->id_lang = $order->id_lang;
     $cart->secure_key = $order->secure_key;
     // Save new cart
     $cart->add();
     // Save context (in order to apply cart rule)
     $this->context->cart = $cart;
     $this->context->customer = new Customer($order->id_customer);
     // always add taxes even if there are not displayed to the customer
     $use_taxes = true;
     $initial_product_price_tax_incl = Product::getPriceStatic($product->id, $use_taxes, isset($combination) ? $combination->id : null, 2, null, false, true, 1, false, $order->id_customer, $cart->id, $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)});
     // Creating specific price if needed
     if ($product_informations['product_price_tax_incl'] != $initial_product_price_tax_incl) {
         $specific_price = new SpecificPrice();
         $specific_price->id_shop = 0;
         $specific_price->id_shop_group = 0;
         $specific_price->id_currency = 0;
         $specific_price->id_country = 0;
         $specific_price->id_group = 0;
         $specific_price->id_customer = $order->id_customer;
         $specific_price->id_product = $product->id;
         if (isset($combination)) {
             $specific_price->id_product_attribute = $combination->id;
         } else {
             $specific_price->id_product_attribute = 0;
         }
         $specific_price->price = $product_informations['product_price_tax_excl'];
         $specific_price->from_quantity = 1;
         $specific_price->reduction = 0;
         $specific_price->reduction_type = 'amount';
         $specific_price->from = '0000-00-00 00:00:00';
         $specific_price->to = '0000-00-00 00:00:00';
         $specific_price->add();
     }
     // Add product to cart
     $update_quantity = $cart->updateQty($product_informations['product_quantity'], $product->id, isset($product_informations['product_attribute_id']) ? $product_informations['product_attribute_id'] : null, isset($combination) ? $combination->id : null, 'up', 0, new Shop($cart->id_shop));
     if ($update_quantity < 0) {
         // If product has attribute, minimal quantity is set with minimal quantity of attribute
         $minimal_quantity = $product_informations['product_attribute_id'] ? Attribute::getAttributeMinimalQty($product_informations['product_attribute_id']) : $product->minimal_quantity;
         die(Tools::jsonEncode(array('error' => sprintf(Tools::displayError('You must add %d minimum quantity', false), $minimal_quantity))));
     } elseif (!$update_quantity) {
         die(Tools::jsonEncode(array('error' => Tools::displayError('You already have the maximum quantity available for this product.', false))));
     }
     // If order is valid, we can create a new invoice or edit an existing invoice
     if ($order->hasInvoice()) {
         $order_invoice = new OrderInvoice($product_informations['invoice']);
         // Create new invoice
         if ($order_invoice->id == 0) {
             // If we create a new invoice, we calculate shipping cost
             $total_method = Cart::BOTH;
             // Create Cart rule in order to make free shipping
             if (isset($invoice_informations['free_shipping']) && $invoice_informations['free_shipping']) {
                 $cart_rule = new CartRule();
                 $cart_rule->id_customer = $order->id_customer;
                 $cart_rule->name = array(Configuration::get('PS_LANG_DEFAULT') => $this->l('[Generated] CartRule for Free Shipping'));
                 $cart_rule->date_from = date('Y-m-d H:i:s', time());
                 $cart_rule->date_to = date('Y-m-d H:i:s', time() + 24 * 3600);
                 $cart_rule->quantity = 1;
                 $cart_rule->quantity_per_user = 1;
                 $cart_rule->minimum_amount_currency = $order->id_currency;
                 $cart_rule->reduction_currency = $order->id_currency;
                 $cart_rule->free_shipping = true;
                 $cart_rule->active = 1;
                 $cart_rule->add();
                 // Add cart rule to cart and in order
                 $cart->addCartRule($cart_rule->id);
                 $values = array('tax_incl' => $cart_rule->getContextualValue(true), 'tax_excl' => $cart_rule->getContextualValue(false));
                 $order->addCartRule($cart_rule->id, $cart_rule->name[Configuration::get('PS_LANG_DEFAULT')], $values);
             }
             $order_invoice->id_order = $order->id;
             if ($order_invoice->number) {
                 Configuration::updateValue('PS_INVOICE_START_NUMBER', false, false, null, $order->id_shop);
             } else {
                 $order_invoice->number = Order::getLastInvoiceNumber() + 1;
             }
             $invoice_address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE', null, null, $order->id_shop)});
             $carrier = new Carrier((int) $order->id_carrier);
             $tax_calculator = $carrier->getTaxCalculator($invoice_address);
             $order_invoice->total_paid_tax_excl = Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
             $order_invoice->total_paid_tax_incl = Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
             $order_invoice->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
             $order_invoice->total_products_wt = (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
             $order_invoice->total_shipping_tax_excl = (double) $cart->getTotalShippingCost(null, false);
             $order_invoice->total_shipping_tax_incl = (double) $cart->getTotalShippingCost();
             $order_invoice->total_wrapping_tax_excl = abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING));
             $order_invoice->total_wrapping_tax_incl = abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order_invoice->shipping_tax_computation_method = (int) $tax_calculator->computation_method;
             // Update current order field, only shipping because other field is updated later
             $order->total_shipping += $order_invoice->total_shipping_tax_incl;
             $order->total_shipping_tax_excl += $order_invoice->total_shipping_tax_excl;
             $order->total_shipping_tax_incl += $use_taxes ? $order_invoice->total_shipping_tax_incl : $order_invoice->total_shipping_tax_excl;
             $order->total_wrapping += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order->total_wrapping_tax_excl += abs($cart->getOrderTotal(false, Cart::ONLY_WRAPPING));
             $order->total_wrapping_tax_incl += abs($cart->getOrderTotal($use_taxes, Cart::ONLY_WRAPPING));
             $order_invoice->add();
             $order_invoice->saveCarrierTaxCalculator($tax_calculator->getTaxesAmount($order_invoice->total_shipping_tax_excl));
             $order_carrier = new OrderCarrier();
             $order_carrier->id_order = (int) $order->id;
             $order_carrier->id_carrier = (int) $order->id_carrier;
             $order_carrier->id_order_invoice = (int) $order_invoice->id;
             $order_carrier->weight = (double) $cart->getTotalWeight();
             $order_carrier->shipping_cost_tax_excl = (double) $order_invoice->total_shipping_tax_excl;
             $order_carrier->shipping_cost_tax_incl = $use_taxes ? (double) $order_invoice->total_shipping_tax_incl : (double) $order_invoice->total_shipping_tax_excl;
             $order_carrier->add();
         } else {
             $order_invoice->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
             $order_invoice->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
             $order_invoice->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
             $order_invoice->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
             $order_invoice->update();
         }
     }
     // Create Order detail information
     $order_detail = new OrderDetail();
     $order_detail->createList($order, $cart, $order->getCurrentOrderState(), $cart->getProducts(), isset($order_invoice) ? $order_invoice->id : 0, $use_taxes, (int) Tools::getValue('add_product_warehouse'));
     // update totals amount of order
     $order->total_products += (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
     $order->total_products_wt += (double) $cart->getOrderTotal($use_taxes, Cart::ONLY_PRODUCTS);
     $order->total_paid += Tools::ps_round((double) $cart->getOrderTotal(true, $total_method), 2);
     $order->total_paid_tax_excl += Tools::ps_round((double) $cart->getOrderTotal(false, $total_method), 2);
     $order->total_paid_tax_incl += Tools::ps_round((double) $cart->getOrderTotal($use_taxes, $total_method), 2);
     if (isset($order_invoice) && Validate::isLoadedObject($order_invoice)) {
         $order->total_shipping = $order_invoice->total_shipping_tax_incl;
         $order->total_shipping_tax_incl = $order_invoice->total_shipping_tax_incl;
         $order->total_shipping_tax_excl = $order_invoice->total_shipping_tax_excl;
     }
     // discount
     $order->total_discounts += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
     $order->total_discounts_tax_excl += (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS));
     $order->total_discounts_tax_incl += (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
     // Save changes of order
     $order->update();
     // Update weight SUM
     $order_carrier = new OrderCarrier((int) $order->getIdOrderCarrier());
     if (Validate::isLoadedObject($order_carrier)) {
         $order_carrier->weight = (double) $order->getTotalWeight();
         if ($order_carrier->update()) {
             $order->weight = sprintf("%.3f " . Configuration::get('PS_WEIGHT_UNIT'), $order_carrier->weight);
         }
     }
     // Update Tax lines
     $order_detail->updateTaxAmount($order);
     // Delete specific price if exists
     if (isset($specific_price)) {
         $specific_price->delete();
     }
     $products = $this->getProducts($order);
     // Get the last product
     $product = end($products);
     $resume = OrderSlip::getProductSlipResume((int) $product['id_order_detail']);
     $product['quantity_refundable'] = $product['product_quantity'] - $resume['product_quantity'];
     $product['amount_refundable'] = $product['total_price_tax_incl'] - $resume['amount_tax_incl'];
     $product['amount_refund'] = Tools::displayPrice($resume['amount_tax_incl']);
     $product['return_history'] = OrderReturn::getProductReturnDetail((int) $product['id_order_detail']);
     $product['refund_history'] = OrderSlip::getProductSlipDetail((int) $product['id_order_detail']);
     if ($product['id_warehouse'] != 0) {
         $warehouse = new Warehouse((int) $product['id_warehouse']);
         $product['warehouse_name'] = $warehouse->name;
     } else {
         $product['warehouse_name'] = '--';
     }
     // Get invoices collection
     $invoice_collection = $order->getInvoicesCollection();
     $invoice_array = array();
     foreach ($invoice_collection as $invoice) {
         $invoice->name = $invoice->getInvoiceNumberFormatted(Context::getContext()->language->id, (int) $order->id_shop);
         $invoice_array[] = $invoice;
     }
     // Assign to smarty informations in order to show the new product line
     $this->context->smarty->assign(array('product' => $product, 'order' => $order, 'currency' => new Currency($order->id_currency), 'can_edit' => $this->tabAccess['edit'], 'invoices_collection' => $invoice_collection, 'current_id_lang' => Context::getContext()->language->id, 'link' => Context::getContext()->link, 'current_index' => self::$currentIndex, 'display_warehouse' => (int) Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')));
     $this->sendChangedNotification($order);
     die(Tools::jsonEncode(array('result' => true, 'view' => $this->createTemplate('_product_line.tpl')->fetch(), 'can_edit' => $this->tabAccess['add'], 'order' => $order, 'invoices' => $invoice_array, 'documents_html' => $this->createTemplate('_documents.tpl')->fetch(), 'shipping_html' => $this->createTemplate('_shipping.tpl')->fetch(), 'discount_form_html' => $this->createTemplate('_discount_form.tpl')->fetch())));
 }