コード例 #1
0
ファイル: Cart.php プロジェクト: evilscripts/gy
 public function getPackageShippingCost($id_carrier = null, $use_tax = true, Country $default_country = null, $product_list = null, $id_zone = null)
 {
     global $defaultCountry;
     if (!Module::isInstalled('agilesellershipping') or !Module::isInstalled('agilemultipleseller')) {
         return parent::getPackageShippingCost($id_carrier, $use_tax, $default_country, $product_list, $id_zone);
     }
     $order_total = $this->getOrderTotal($use_tax, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING);
     if ($order_total <= 0 and !(int) self::getNbProducts($this->id)) {
         return 0;
     }
     include_once _PS_ROOT_DIR_ . "/modules/agilemultipleseller/agilemultipleseller.php";
     include_once _PS_ROOT_DIR_ . "/modules/agilesellershipping/SellerShipping.php";
     $sellers = AgileMultipleSeller::getSellersByCart($this->id);
     if (empty($sellers)) {
         return parent::getPackageShippingCost($id_carrier, $use_tax, $default_country, $product_list, $id_zone);
     }
     if (isset($this->id_address_delivery) and $this->id_address_delivery and Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
         $id_zone = Address::getZoneById((int) $this->id_address_delivery);
     } else {
         if (!Validate::isLoadedObject($defaultCountry)) {
             $defaultCountry = new Country(Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT'));
         }
         $id_zone = (int) $defaultCountry->id_zone;
     }
     $shipping_cost = 0;
     foreach ($sellers as $seller) {
         $seller_cost = $this->getOrderShippingCostPerSeller($id_zone, intval($seller['id_seller']), $use_tax);
         $shipping_cost += $seller_cost;
     }
     return $shipping_cost;
 }
コード例 #2
0
 public static function get_seller_sales_from_cart($id_cart, $include_shppingcost = true, $after_discounts = false, $include_tax = true)
 {
     $uaqhymrtjtx = "product";
     ${"GLOBALS"}["eyqzktf"] = "seller_sales_amount";
     ${"GLOBALS"}["teitwlrl"] = "seller_sales_amount";
     ${${"GLOBALS"}["esvngpfotb"]} = new Cart(${${"GLOBALS"}["frpscuel"]});
     if (!Validate::isLoadedObject(${${"GLOBALS"}["esvngpfotb"]})) {
         return;
     }
     ${${"GLOBALS"}["teitwlrl"]} = array();
     ${${"GLOBALS"}["vgnwuvdfsxef"]} = 0;
     foreach ($theCart->getProducts() as ${${"GLOBALS"}["uhwljodynle"]} => ${$uaqhymrtjtx}) {
         ${"GLOBALS"}["acnijoxrqy"] = "id_owner";
         ${${"GLOBALS"}["qdndcj"]} = intval(AgileSellerManager::getObjectOwnerID("product", ${${"GLOBALS"}["cloygkl"]}["id_product"]));
         if (!isset(${${"GLOBALS"}["xiinmwl"]}[${${"GLOBALS"}["qdndcj"]}])) {
             ${${"GLOBALS"}["xiinmwl"]}[${${"GLOBALS"}["acnijoxrqy"]}] = 0;
         }
         ${"GLOBALS"}["uqojbaqsiz"] = "id_owner";
         if (${${"GLOBALS"}["vckxyex"]}) {
             $zbnxgflvgb = "lineamount";
             ${$zbnxgflvgb} = ${${"GLOBALS"}["cloygkl"]}["total_wt"];
         } else {
             ${${"GLOBALS"}["xxkdmsnb"]} = ${${"GLOBALS"}["cloygkl"]}["total"];
         }
         ${${"GLOBALS"}["xiinmwl"]}[${${"GLOBALS"}["qdndcj"]}] += ${${"GLOBALS"}["xxkdmsnb"]};
         ${${"GLOBALS"}["vgnwuvdfsxef"]} += ${${"GLOBALS"}["xxkdmsnb"]};
         self::log_message("seller_sales_amount=" . ${${"GLOBALS"}["xiinmwl"]}[${${"GLOBALS"}["uqojbaqsiz"]}]);
     }
     if (${${"GLOBALS"}["vgnwuvdfsxef"]} == 0) {
         return ${${"GLOBALS"}["eyqzktf"]};
     }
     ${${"GLOBALS"}["jkqbidncw"]} = abs($theCart->getOrderTotal(true, CART::ONLY_DISCOUNTS));
     ${"GLOBALS"}["leuhuri"] = "include_tax";
     $wbpixfqq = "total_shipping";
     $hszxeuoysyqb = "seller_sales_amount";
     if (${${"GLOBALS"}["mnciypinfgc"]} and ${${"GLOBALS"}["jkqbidncw"]} > 0) {
         foreach (${${"GLOBALS"}["xiinmwl"]} as ${${"GLOBALS"}["uhwljodynle"]} => ${${"GLOBALS"}["oktrbptlq"]}) {
             $dtpouqmcs = "seller_discount";
             ${"GLOBALS"}["fnnrgrqqtjav"] = "amount";
             $dmncdfpm = "amount";
             ${$dtpouqmcs} = ${$dmncdfpm} * ${${"GLOBALS"}["jkqbidncw"]} / ${${"GLOBALS"}["vgnwuvdfsxef"]};
             $ebwribgtkx = "seller_discount";
             $njucvdl = "seller_sales_amount";
             ${$njucvdl}[${${"GLOBALS"}["uhwljodynle"]}] = Tools::ps_round(${${"GLOBALS"}["fnnrgrqqtjav"]} - ${$ebwribgtkx}, 2);
         }
     }
     ${${"GLOBALS"}["xokzcouuhc"]} = floatval($theCart->getOrderTotal(${${"GLOBALS"}["leuhuri"]}, Cart::ONLY_SHIPPING)) + floatval($theCart->getOrderTotal(${${"GLOBALS"}["vckxyex"]}, Cart::ONLY_WRAPPING));
     if (${${"GLOBALS"}["qxkibmpljxt"]} and ${$wbpixfqq} > 0) {
         $tymywmbyl = "id_zone";
         ${"GLOBALS"}["lnmqfsnuf"] = "seller_sales_amount";
         if (isset($theCart->id_address_delivery) and $theCart->id_address_delivery and Customer::customerHasAddress($theCart->id_customer, $theCart->id_address_delivery)) {
             ${$tymywmbyl} = Address::getZoneById((int) $theCart->id_address_delivery);
         } else {
             ${${"GLOBALS"}["jnnsdlrv"]} = new Country(Configuration::get("PS_COUNTRY_DEFAULT"), Configuration::get("PS_LANG_DEFAULT"));
             ${${"GLOBALS"}["lgkbdx"]} = (int) $defaultCountry->id_zone;
         }
         foreach (${${"GLOBALS"}["lnmqfsnuf"]} as ${${"GLOBALS"}["uhwljodynle"]} => ${${"GLOBALS"}["oktrbptlq"]}) {
             if (Module::isInstalled("agilesellershipping")) {
                 $xiywykxt = "key";
                 ${"GLOBALS"}["vylrbmxbekw"] = "shipping";
                 ${${"GLOBALS"}["vylrbmxbekw"]} = $theCart->getOrderShippingCostPerSeller(${${"GLOBALS"}["lgkbdx"]}, ${$xiywykxt}, ${${"GLOBALS"}["vckxyex"]});
             } else {
                 $adrgkkd = "shipping";
                 ${"GLOBALS"}["yksuovho"] = "amount";
                 ${$adrgkkd} = ${${"GLOBALS"}["yksuovho"]} * ${${"GLOBALS"}["xokzcouuhc"]} / ${${"GLOBALS"}["vgnwuvdfsxef"]};
             }
             $yiahovnnapvj = "seller_sales_amount";
             ${$yiahovnnapvj}[${${"GLOBALS"}["uhwljodynle"]}] = Tools::ps_round(${${"GLOBALS"}["oktrbptlq"]} + ${${"GLOBALS"}["oglsjlnajq"]}, 2);
         }
     }
     return ${$hszxeuoysyqb};
 }
コード例 #3
0
ファイル: AddressController.php プロジェクト: h0n24/leodig
    /**
     * Process changes on an address
     */
    protected function processSubmitAddress()
    {
        $address = new Address();
        $this->errors = $address->validateController();
        $address->id_customer = (int) $this->context->customer->id;
        // Check page token
        if ($this->context->customer->isLogged() && !$this->isTokenValid()) {
            $this->errors[] = Tools::displayError('Invalid token.');
        }
        // Check phone
        if (Configuration::get('PS_ONE_PHONE_AT_LEAST') && !Tools::getValue('phone') && !Tools::getValue('phone_mobile')) {
            $this->errors[] = Tools::displayError('You must register at least one phone number.');
        }
        if ($address->id_country) {
            // Check country
            if (!($country = new Country($address->id_country)) || !Validate::isLoadedObject($country)) {
                throw new PrestaShopException('Country cannot be loaded with address->id_country');
            }
            if ((int) $country->contains_states && !(int) $address->id_state) {
                $this->errors[] = Tools::displayError('This country requires you to chose a State.');
            }
            // US customer: normalize the address
            if ($address->id_country == Country::getByIso('US') && Configuration::get('PS_TAASC')) {
                include_once _PS_TAASC_PATH_ . 'AddressStandardizationSolution.php';
                $normalize = new AddressStandardizationSolution();
                $address->address1 = $normalize->AddressLineStandardization($address->address1);
                $address->address2 = $normalize->AddressLineStandardization($address->address2);
            }
            $postcode = Tools::getValue('postcode');
            /* Check zip code format */
            if ($country->zip_code_format && !$country->checkZipCode($postcode)) {
                $this->errors[] = sprintf(Tools::displayError('The Zip/Postal code you\'ve entered is invalid. It must follow this format: %s'), str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format))));
            } elseif (empty($postcode) && $country->need_zip_code) {
                $this->errors[] = Tools::displayError('A Zip / Postal code is required.');
            } elseif ($postcode && !Validate::isPostCode($postcode)) {
                $this->errors[] = Tools::displayError('The Zip / Postal code is invalid.');
            }
            // Check country DNI nox fix
            /*if ($country->isNeedDni() && (!Tools::getValue('dni') || !Validate::isDniLite(Tools::getValue('dni'))))
            			$this->errors[] = Tools::displayError('The identification number is incorrect or has already been used.');
            		else if (!$country->isNeedDni())
            			$address->dni = null;*/
            if ($country->need_identification_number && (!Tools::getValue('dni') || !Validate::isDniLite(Tools::getValue('dni')))) {
                $this->errors[] = Tools::displayError('The identification number is incorrect or has already been used.');
            } elseif (!$country->need_identification_number) {
                ${$addresses_type}->dni = null;
            }
        }
        // Check if the alias exists
        if (!$this->context->customer->is_guest && !empty($_POST['alias']) && (int) $this->context->customer->id > 0) {
            $id_address = Tools::getValue('id_address');
            if (Configuration::get('PS_ORDER_PROCESS_TYPE') && (int) Tools::getValue('opc_id_address_' . Tools::getValue('type')) > 0) {
                $id_address = Tools::getValue('opc_id_address_' . Tools::getValue('type'));
            }
            if (Db::getInstance()->getValue('
				SELECT count(*)
				FROM ' . _DB_PREFIX_ . 'address
				WHERE `alias` = \'' . pSql($_POST['alias']) . '\'
				AND id_address != ' . (int) $id_address . '
				AND id_customer = ' . (int) $this->context->customer->id . '
				AND deleted = 0') > 0) {
                $this->errors[] = sprintf(Tools::displayError('The alias "%s" has already been used. Please select another one.'), Tools::safeOutput($_POST['alias']));
            }
        }
        // Check the requires fields which are settings in the BO
        $this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());
        // Don't continue this process if we have errors !
        if ($this->errors && !$this->ajax) {
            return;
        }
        // If we edit this address, delete old address and create a new one
        if (Validate::isLoadedObject($this->_address)) {
            if (Validate::isLoadedObject($country) && !$country->contains_states) {
                $address->id_state = 0;
            }
            $address_old = $this->_address;
            if (Customer::customerHasAddress($this->context->customer->id, (int) $address_old->id)) {
                if ($address_old->isUsed()) {
                    $address_old->delete();
                } else {
                    $address->id = (int) $address_old->id;
                    $address->date_add = $address_old->date_add;
                }
            }
        }
        if ($this->ajax && Tools::getValue('type') == 'invoice' && Configuration::get('PS_ORDER_PROCESS_TYPE')) {
            $this->errors = array_unique(array_merge($this->errors, $address->validateController()));
            if (count($this->errors)) {
                $return = array('hasError' => (bool) $this->errors, 'errors' => $this->errors);
                die(Tools::jsonEncode($return));
            }
        }
        // Save address
        if ($result = $address->save()) {
            // Update id address of the current cart if necessary
            if (isset($address_old) && $address_old->isUsed()) {
                $this->context->cart->updateAddressId($address_old->id, $address->id);
            } else {
                // Update cart address
                $this->context->cart->autosetProductAddress();
            }
            if ((bool) Tools::getValue('select_address', false) == true or Tools::getValue('type') == 'invoice' && Configuration::get('PS_ORDER_PROCESS_TYPE')) {
                $this->context->cart->id_address_invoice = (int) $address->id;
            } elseif (Configuration::get('PS_ORDER_PROCESS_TYPE')) {
                $this->context->cart->id_address_invoice = (int) $this->context->cart->id_address_delivery;
            }
            $this->context->cart->update();
            if ($this->ajax) {
                $return = array('hasError' => (bool) $this->errors, 'errors' => $this->errors, 'id_address_delivery' => (int) $this->context->cart->id_address_delivery, 'id_address_invoice' => (int) $this->context->cart->id_address_invoice);
                die(Tools::jsonEncode($return));
            }
            // Redirect to old page or current page
            if ($back = Tools::getValue('back')) {
                if ($back == Tools::secureReferrer(Tools::getValue('back'))) {
                    Tools::redirect(html_entity_decode($back));
                }
                $mod = Tools::getValue('mod');
                Tools::redirect('index.php?controller=' . $back . ($mod ? '&back=' . $mod : ''));
            } else {
                Tools::redirect('index.php?controller=addresses');
            }
        }
        $this->errors[] = Tools::displayError('An error occurred while updating your address.');
    }
コード例 #4
0
 protected function _addAddress($step)
 {
     $id_address = (int) Tools::getValue('id_address', 0);
     if ($id_address && !Tools::getValue('address_update', 0)) {
         $address = new Address((int) $id_address);
         if (Validate::isLoadedObject($address) and Customer::customerHasAddress((int) self::$cookie->id_customer, (int) $id_address)) {
             if (Tools::isSubmit('delete')) {
                 if (self::$cart->id_address_invoice == $address->id) {
                     unset(self::$cart->id_address_invoice);
                 }
                 if (self::$cart->id_address_delivery == $address->id) {
                     unset(self::$cart->id_address_delivery);
                 }
                 if ($address->delete()) {
                     Tools::redirect('order.php?step=1');
                 }
                 $this->errors[] = Tools::displayError('This address cannot be deleted.');
             }
             self::$smarty->assign(array('address' => $address, 'id_address' => (int) $id_address));
             if (Tools::isSubmit('id_state') and Tools::getValue('id_state') != NULL and is_numeric(Tools::getValue('id_state'))) {
                 $selected_state = Tools::getValue('id_state');
             } elseif (isset($address) and isset($address->id_state) and !empty($address->id_state) and isset($address->id_state)) {
                 $selected_state = $address->id_state;
             } else {
                 $selected_state = false;
             }
             // default to karnataka.
             if (Tools::isSubmit('id_country') and Tools::getValue('id_country') != NULL and is_numeric(Tools::getValue('id_country'))) {
                 $selected_country = Tools::getValue('id_country');
             } elseif (isset($address) and isset($address->id_country) and !empty($address->id_country) and isset($address->id_state)) {
                 $selected_country = $address->id_country;
             } else {
                 $selected_country = false;
             }
             self::$smarty->assign('selected_country', $selected_country);
             self::$smarty->assign('selected_state', $selected_state);
         }
     }
     if (Tools::isSubmit('submitAddress')) {
         $address = new Address();
         $this->errors = $address->validateControler();
         $address->id_customer = (int) self::$cookie->id_customer;
         if (!Tools::getValue('phone') and !Tools::getValue('phone_mobile')) {
             $this->errors[] = Tools::displayError('Please add your mobile phone number.');
         }
         if (!($country = new Country((int) $address->id_country)) or !Validate::isLoadedObject($country)) {
             die(Tools::displayError());
         }
         //remove zipcode verification
         /*
          $zip_code_format = $country->zip_code_format;
          if ($country->need_zip_code)
          {
          if (($postcode = Tools::getValue('postcode')) AND $zip_code_format)
          {
          $zip_regexp = '/^'.$zip_code_format.'$/ui';
          $zip_regexp = str_replace(' ', '( |)', $zip_regexp);
          $zip_regexp = str_replace('-', '(-|)', $zip_regexp);
          $zip_regexp = str_replace('N', '[0-9]', $zip_regexp);
          $zip_regexp = str_replace('L', '[a-zA-Z]', $zip_regexp);
          $zip_regexp = str_replace('C', $country->iso_code, $zip_regexp);
          if (!preg_match($zip_regexp, $postcode))
          $this->errors[] = '<strong>'.Tools::displayError('Post/Zip Code mentioned is incorrect.').'</strong> ';
          }
          elseif ($zip_code_format)
          $this->errors[] = '<strong>'.Tools::displayError('Post/Zip Code mentioned is incorrect.').'</strong> ';
          elseif ($postcode AND !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode))
          $this->errors[] = '<strong>'.Tools::displayError('Post/Zip Code mentioned is incorrect.').'</strong> ';
          }
         */
         if (!Tools::isSubmit('order_add_address_billing')) {
             //validate pincode and assign possible payment options
             $op = 0;
             $op = Carrier::getPreferredCarriers($country->id);
             if ($op == 0) {
                 $this->errors[] = 'We are sorry but we do not provide service to this region as of now. However, we keep adding new locations with time and would request you to check our website a few weeks later. We apologise for the inconvenience caused. ';
             }
         }
         if (!$country->isNeedDni()) {
             $address->dni = NULL;
         }
         if (Configuration::get('PS_TOKEN_ENABLE') == 1 and strcmp(Tools::getToken(false), Tools::getValue('token')) and self::$cookie->isLogged(true) === true) {
             $this->errors[] = Tools::displayError('Invalid token');
         }
         if ((int) $country->contains_states and !(int) $address->id_state) {
             $this->errors[] = Tools::displayError('Please select a state.');
         }
         if (!sizeof($this->errors)) {
             if (isset($id_address)) {
                 $country = new Country((int) $address->id_country);
                 if (Validate::isLoadedObject($country) and !$country->contains_states) {
                     $address->id_state = 0;
                 }
                 $address_old = new Address((int) $id_address);
                 if (Validate::isLoadedObject($address_old) and Customer::customerHasAddress((int) self::$cookie->id_customer, (int) $address_old->id)) {
                     if ($address_old->isUsed()) {
                         $address_old->delete();
                         if (!Tools::isSubmit('ajax')) {
                             $to_update = false;
                             if (self::$cart->id_address_invoice == $address_old->id) {
                                 $to_update = true;
                                 self::$cart->id_address_invoice = 0;
                             }
                             if (self::$cart->id_address_delivery == $address_old->id) {
                                 $to_update = true;
                                 self::$cart->id_address_delivery = 0;
                             }
                             if ($to_update) {
                                 self::$cart->update();
                             }
                         }
                     } else {
                         $address->id = (int) $address_old->id;
                         $address->date_add = $address_old->date_add;
                     }
                 }
             }
             if ($result = $address->save()) {
                 if (Tools::isSubmit('order_add_address')) {
                     self::$cart->id_address_delivery = (int) $address->id;
                     self::$cart->update();
                     self::$smarty->assign(array('op' => $op));
                 } else {
                     if (Tools::isSubmit('order_add_address_billing')) {
                         self::$cart->id_address_invoice = (int) $address->id;
                         self::$cart->update();
                     }
                 }
             } else {
                 $this->errors[] = Tools::displayError('An error occurred while updating your address.');
             }
         }
         if (sizeof($this->errors)) {
             self::$smarty->assign('errors', $this->errors);
             $this->step = 1;
         }
     }
 }
コード例 #5
0
 public function preProcess()
 {
     parent::preProcess();
     if ($back = Tools::getValue('back')) {
         self::$smarty->assign('back', Tools::safeOutput($back));
     }
     if ($mod = Tools::getValue('mod')) {
         self::$smarty->assign('mod', Tools::safeOutput($mod));
     }
     if (Tools::isSubmit('ajax') and Tools::isSubmit('type')) {
         if (Tools::getValue('type') == 'delivery') {
             $id_address = isset(self::$cart->id_address_delivery) ? (int) self::$cart->id_address_delivery : 0;
         } elseif (Tools::getValue('type') == 'invoice') {
             $id_address = (isset(self::$cart->id_address_invoice) and self::$cart->id_address_invoice != self::$cart->id_address_delivery) ? (int) self::$cart->id_address_invoice : 0;
         } else {
             exit;
         }
     } else {
         $id_address = (int) Tools::getValue('id_address', 0);
     }
     if ($id_address) {
         $this->_address = new Address((int) $id_address);
         if (Validate::isLoadedObject($this->_address) and Customer::customerHasAddress((int) self::$cookie->id_customer, (int) $id_address)) {
             if (Tools::isSubmit('delete')) {
                 if (self::$cart->id_address_invoice == $this->_address->id) {
                     unset(self::$cart->id_address_invoice);
                 }
                 if (self::$cart->id_address_delivery == $this->_address->id) {
                     unset(self::$cart->id_address_delivery);
                 }
                 if ($this->_address->delete()) {
                     Tools::redirect('addresses.php');
                 }
                 $this->errors[] = Tools::displayError('This address cannot be deleted.');
             }
             self::$smarty->assign(array('address' => $this->_address, 'id_address' => (int) $id_address));
         } elseif (Tools::isSubmit('ajax')) {
             exit;
         } else {
             Tools::redirect('addresses.php');
         }
     }
     if (Tools::isSubmit('submitAddress')) {
         $address = new Address();
         $this->errors = $address->validateControler();
         $address->id_customer = (int) self::$cookie->id_customer;
         if (!Tools::getValue('phone') and !Tools::getValue('phone_mobile')) {
             $this->errors[] = Tools::displayError('You must register at least one phone number');
         }
         if (!($country = new Country((int) $address->id_country)) or !Validate::isLoadedObject($country)) {
             die(Tools::displayError());
         }
         /* US customer: normalize the address */
         if ($address->id_country == Country::getByIso('US')) {
             include_once _PS_TAASC_PATH_ . 'AddressStandardizationSolution.php';
             $normalize = new AddressStandardizationSolution();
             $address->address1 = $normalize->AddressLineStandardization($address->address1);
             $address->address2 = $normalize->AddressLineStandardization($address->address2);
         }
         $zip_code_format = $country->zip_code_format;
         if ($country->need_zip_code) {
             if ($postcode = Tools::getValue('postcode') and $zip_code_format) {
                 $zip_regexp = '/^' . $zip_code_format . '$/ui';
                 $zip_regexp = str_replace(' ', '( |)', $zip_regexp);
                 $zip_regexp = str_replace('-', '(-|)', $zip_regexp);
                 $zip_regexp = str_replace('N', '[0-9]', $zip_regexp);
                 $zip_regexp = str_replace('L', '[a-zA-Z]', $zip_regexp);
                 $zip_regexp = str_replace('C', $country->iso_code, $zip_regexp);
                 if (!preg_match($zip_regexp, $postcode)) {
                     $this->errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is invalid.') . '<br />' . Tools::displayError('Must be typed as follows:') . ' ' . str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $zip_code_format)));
                 }
             } elseif ($zip_code_format) {
                 $this->errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is required.');
             } elseif ($postcode and !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode)) {
                 $this->errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is invalid.') . '<br />' . Tools::displayError('Must be typed as follows:') . ' ' . str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $zip_code_format)));
             }
         }
         if ($country->isNeedDni() and !Tools::getValue('dni') and !Validate::isDniLite(Tools::getValue('dni'))) {
             $this->errors[] = Tools::displayError('Identification number is incorrect or has already been used.');
         } elseif (!$country->isNeedDni()) {
             $address->dni = NULL;
         }
         if (Configuration::get('PS_TOKEN_ENABLE') == 1 and strcmp(Tools::getToken(false), Tools::getValue('token')) and self::$cookie->isLogged(true) === true) {
             $this->errors[] = Tools::displayError('Invalid token');
         }
         if ((int) $country->contains_states and !(int) $address->id_state) {
             $this->errors[] = Tools::displayError('This country requires a state selection.');
         }
         if (!sizeof($this->errors)) {
             if (isset($id_address)) {
                 $country = new Country((int) $address->id_country);
                 if (Validate::isLoadedObject($country) and !$country->contains_states) {
                     $address->id_state = 0;
                 }
                 $address_old = new Address((int) $id_address);
                 if (Validate::isLoadedObject($address_old) and Customer::customerHasAddress((int) self::$cookie->id_customer, (int) $address_old->id)) {
                     if (!Tools::isSubmit('ajax')) {
                         if (self::$cart->id_address_invoice == $address_old->id) {
                             unset(self::$cart->id_address_invoice);
                         }
                         if (self::$cart->id_address_delivery == $address_old->id) {
                             unset(self::$cart->id_address_delivery);
                         }
                     }
                     if ($address_old->isUsed()) {
                         $address_old->delete();
                     } else {
                         $address->id = (int) $address_old->id;
                         $address->date_add = $address_old->date_add;
                     }
                 }
             } elseif (self::$cookie->is_guest) {
                 Tools::redirect('addresses.php');
             }
             if ($result = $address->save()) {
                 if ((bool) Tools::getValue('select_address', false) == true or Tools::isSubmit('ajax') and Tools::getValue('type') == 'invoice') {
                     /* This new adress is for invoice_adress, select it */
                     self::$cart->id_address_invoice = (int) $address->id;
                     self::$cart->update();
                 }
                 if (Tools::isSubmit('ajax')) {
                     $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'id_address_delivery' => self::$cart->id_address_delivery, 'id_address_invoice' => self::$cart->id_address_invoice);
                     die(Tools::jsonEncode($return));
                 }
                 Tools::redirect($back ? $mod ? $back . '&back=' . $mod : $back : 'addresses.php');
             }
             $this->errors[] = Tools::displayError('An error occurred while updating your address.');
         }
     } elseif (!$id_address) {
         $customer = new Customer((int) self::$cookie->id_customer);
         if (Validate::isLoadedObject($customer)) {
             $_POST['firstname'] = $customer->firstname;
             $_POST['lastname'] = $customer->lastname;
         }
     }
     if (Tools::isSubmit('ajax') and sizeof($this->errors)) {
         $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors);
         die(Tools::jsonEncode($return));
     }
 }
コード例 #6
0
 /**
  * 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
         $errors = array();
         $address_without_carriers = $this->context->cart->getDeliveryAddressesWithoutCarriers(false, $errors);
         if (count($address_without_carriers) && !$this->context->cart->isVirtualCart()) {
             $flag_error_message = false;
             foreach ($errors as $error) {
                 if ($error == Carrier::SHIPPING_WEIGHT_EXCEPTION && !$flag_error_message) {
                     $this->errors[] = sprintf(Tools::displayError('The product selection cannot be delivered by the available carrier(s): it is too heavy. Please amend your cart to lower its weight.', !Tools::getValue('ajax')));
                     $flag_error_message = true;
                 } elseif ($error == Carrier::SHIPPING_PRICE_EXCEPTION && !$flag_error_message) {
                     $this->errors[] = sprintf(Tools::displayError('The product selection cannot be delivered by the available carrier(s). Please amend your cart.', !Tools::getValue('ajax')));
                     $flag_error_message = true;
                 } elseif ($error == Carrier::SHIPPING_SIZE_EXCEPTION && !$flag_error_message) {
                     $this->errors[] = sprintf(Tools::displayError('The product selection cannot be delivered by the available carrier(s): its size does not fit. Please amend your cart to reduce its size.', !Tools::getValue('ajax')));
                     $flag_error_message = true;
                 }
             }
             if (count($address_without_carriers) > 1 && !$flag_error_message) {
                 $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to some addresses you selected.', !Tools::getValue('ajax')));
             } elseif ($this->context->cart->isMultiAddressDelivery() && !$flag_error_message) {
                 $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to one of the address you selected.', !Tools::getValue('ajax')));
             } elseif (!$flag_error_message) {
                 $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')) {
             $this->ajaxDie('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
         }
         $this->step = 1;
     }
     if ($this->ajax) {
         $this->ajaxDie(true);
     }
 }
コード例 #7
0
 public function postProcess()
 {
     if (!$this->isOpcModuleActive()) {
         return parent::postProcess();
     }
     $inv_first_on = Configuration::get('OPC_INVOICE_FIRST') == "1";
     // handle case when already used address (assigned to an order) is being changed - we need to create new one and save it's reference to order
     if (Tools::isSubmit('submitAddress') && Tools::isSubmit('ajax')) {
         if (Tools::isSubmit('type')) {
             if (Tools::getValue('type') == 'delivery') {
                 if (!$inv_first_on) {
                     $id_address = isset($this->context->cart->id_address_delivery) ? (int) $this->context->cart->id_address_delivery : 0;
                 } else {
                     $id_address = (Tools::isSubmit('id_address') and (int) Tools::getValue('id_address', 0) != $this->context->cart->id_address_invoice) ? (int) Tools::getValue('id_address', 0) : 0;
                 }
             } elseif (Tools::getValue('type') == 'invoice') {
                 //$id_address = (isset($this->context->cart->id_address_invoice) AND $this->context->cart->id_address_invoice != $this->context->cart->id_address_delivery) ? (int)$this->context->cart->id_address_invoice : 0;
                 if (!$inv_first_on) {
                     $id_address = (Tools::isSubmit('id_address') and (int) Tools::getValue('id_address', 0) != $this->context->cart->id_address_delivery) ? (int) Tools::getValue('id_address', 0) : 0;
                 } else {
                     $id_address = isset($this->context->cart->id_address_invoice) ? (int) $this->context->cart->id_address_invoice : 0;
                 }
             } else {
                 exit;
             }
         } else {
             $id_address = (int) Tools::getValue('id_address', 0);
         }
         if (Tools::getValue('alias') == Tools::getValue('default_alias') && Tools::getValue('address1') && trim(Tools::getValue('address1')) != "") {
             $_POST['alias'] = Tools::substr(preg_replace('/[;#]/', '_', Tools::getValue('address1')), 0, 32);
         }
         $address = new Address();
         $this->errors = $address->validateController();
         // AuthController sets (hardocded) invoice address to be same as delivery, because of guest checkout can have
         // only delivery address (in standard OPC)
         if (Tools::getValue('type') == 'invoice' && isset($id_address) && $id_address > 0) {
             $this->context->cart->id_address_invoice = $id_address;
             $this->context->cart->update();
         }
         $address_old = new Address((int) $id_address);
         if (!sizeof($this->errors) && isset($id_address) && (int) $id_address > 0 && Validate::isLoadedObject($address_old) and Customer::customerHasAddress((int) $this->context->cookie->id_customer, (int) $address_old->id)) {
             if ($address_old->isUsed() && $address_old->isDifferent($address)) {
                 // save as new and assing reference to cart
                 $address_1 = new Address();
                 $_POST['alias'] = Tools::substr(preg_replace('/[;#]/', '_', Tools::getValue('address1')), 0, 32);
                 $this->errors = $address_1->validateController();
                 $address_1->id_customer = (int) $this->context->cookie->id_customer;
                 if ((!Tools::getValue('phone') and !Tools::getValue('phone_mobile')) || (!($country = new Country((int) $address_1->id_country)) or !Validate::isLoadedObject($country)) || ($country->isNeedDni() and (!Tools::getValue('dni') or !Validate::isDniLite(Tools::getValue('dni')))) || ((int) $country->contains_states and !(int) $address_1->id_state)) {
                     /* empty */
                 } elseif ($result = $address_1->save()) {
                     $id_address = $address_1->id;
                     if (Tools::getValue('type') == 'delivery') {
                         if ($this->context->cart->id_address_delivery == $this->context->cart->id_address_invoice) {
                             $this->context->cart->id_address_invoice = (int) $address_1->id;
                         }
                         $this->context->cart->id_address_delivery = (int) $address_1->id;
                         $this->context->cart->update();
                     }
                     if (Tools::getValue('type') == 'invoice') {
                         if ($this->context->cart->id_address_delivery == $this->context->cart->id_address_invoice) {
                             $this->context->cart->id_address_delivery = (int) $address_1->id;
                         }
                         $this->context->cart->id_address_invoice = (int) $address_1->id;
                         $this->context->cart->update();
                     }
                 }
             }
             //if ($address_old->isUsed)
         }
         //if (Validate::isLoaded...)
         $this->_processSubmitAddress($id_address, Tools::getValue('type'));
         // parent::postProcess(); // call parent's method anyway, we only wanted to store this new address
     } elseif (Tools::isSubmit('partialSubmitAddress')) {
         // called separately for delivery country/state change and invoice country/state change
         // $this->context->cookie->id_cart by mohol byt kluc ku mazaniu adresy pri vytvoreni skutocneho accountu
         // not-null DB fields: id_address, id_country, alias, lastname, firstname, address1, city
         $is_separate_invoice_address = Tools::getValue('invoice_address');
         $is_separate_delivery_address = Tools::getValue('delivery_address');
         // $type is 'delivery' or 'invoice'
         $type = Tools::getValue('type');
         // Delivery address
         $id_country = Tools::getValue('id_country');
         $id_state = Tools::getValue('id_state');
         $postcode = Tools::getValue('postcode');
         $city = Tools::getValue('city');
         $firstname = Tools::getValue('firstname');
         $lastname = Tools::getValue('lastname');
         $addr1 = Tools::getValue('address1');
         $id_address_delivery = 0;
         $id_address_invoice = 0;
         $create_different_delivery_address = 0;
         $create_different_invoice_address = 0;
         $last_addr_id = 0;
         $last_addr_ids_tmp = Customer::getLastTwoCustomerAddressIds($this->context->cart->id_customer);
         if ($id_country !== false && $id_state !== false) {
             /* type is delivery AND cart's address is used and cart's address is different than form post*/
             if ($type == 'delivery' && isset($this->context->cart->id_address_delivery) && $this->context->cart->id_address_delivery > 0) {
                 $address_old1 = new Address((int) $this->context->cart->id_address_delivery);
                 $address1 = new Address();
                 $errors1 = $address1->validateController();
                 if (Validate::isLoadedObject($address_old1) && $address_old1->isUsed() && $address_old1->isDifferent($address1, true)) {
                     $create_different_delivery_address = 1;
                 }
             }
             if ($is_separate_invoice_address) {
                 if ($this->context->cart->id_address_delivery == $this->context->cart->id_address_invoice) {
                     $create_different_invoice_address = 1;
                 }
                 // check whether we have some recently used addresses (excluded actual delivery address)
                 if (isset($last_addr_ids_tmp) && $last_addr_ids_tmp != false && is_array($last_addr_ids_tmp) && count($last_addr_ids_tmp) > 0) {
                     foreach ($last_addr_ids_tmp as $item) {
                         if ($item != $this->context->cart->id_address_delivery) {
                             $last_addr_id = $item;
                             break;
                         }
                     }
                 }
                 //if (isset($last_addr_ids_tmp)...
             }
             //if  ($is_separate_invoice_address)
             if ($is_separate_delivery_address) {
                 if ($this->context->cart->id_address_delivery == $this->context->cart->id_address_invoice) {
                     $create_different_delivery_address = 1;
                 }
                 // check whether we have some recently used addresses (excluded actual delivery address)
                 if (isset($last_addr_ids_tmp) && $last_addr_ids_tmp != false && is_array($last_addr_ids_tmp) && count($last_addr_ids_tmp) > 0) {
                     foreach ($last_addr_ids_tmp as $item) {
                         if ($item != $this->context->cart->id_address_invoice) {
                             $last_addr_id = $item;
                             break;
                         }
                     }
                 }
                 //if (isset($last_addr_ids_tmp)...
             }
             //if  ($is_separate_delivery_address)
             if ($type == 'delivery') {
                 $id_address_delivery = $last_addr_id > 0 && $create_different_delivery_address ? $last_addr_id : $this->saveAddress($create_different_delivery_address ? $last_addr_id : $this->context->cart->id_address_delivery, $id_country, $id_state, $postcode, $city, $firstname, $lastname, $addr1);
             } else {
                 $id_address_invoice = $last_addr_id > 0 && $create_different_invoice_address ? $last_addr_id : $this->saveAddress($create_different_invoice_address ? $last_addr_id : $this->context->cart->id_address_invoice, $id_country, $id_state, $postcode, $city, $firstname, $lastname, $addr1);
             }
         }
         if ($id_address_delivery > 0) {
             $this->context->cart->id_address_delivery = $id_address_delivery;
             if ($is_separate_invoice_address == 0 && $is_separate_delivery_address == 0) {
                 $this->context->cart->id_address_invoice = $this->context->cart->id_address_delivery;
             }
         } elseif ($id_address_invoice > 0) {
             $this->context->cart->id_address_invoice = $id_address_invoice;
             if ($is_separate_invoice_address == 0 && $is_separate_delivery_address == 0) {
                 $this->context->cart->id_address_delivery = $this->context->cart->id_address_invoice;
             }
         }
         $this->context->cart->update();
         if (Configuration::get('VATNUMBER_MANAGEMENT') and file_exists(dirname(__FILE__) . '/../../modules/vatnumber/vatnumber.php') && VatNumber::isApplicable($id_country) && Configuration::get('VATNUMBER_COUNTRY') != $id_country) {
             $allow_eu_vat = 1;
         } else {
             $allow_eu_vat = 0;
         }
         if (Tools::isSubmit('ajax')) {
             $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'id_address_delivery' => $this->context->cart->id_address_delivery, 'id_address_invoice' => $this->context->cart->id_address_invoice, 'allow_eu_vat' => $allow_eu_vat);
             die(Tools::jsonEncode($return));
         }
     } else {
         # assign pre-guessed address to this customer
         if (Tools::getValue('type') == 'invoice' && (isset($this->context->cart->id_address_invoice) and $this->context->cart->id_address_invoice != $this->context->cart->id_address_delivery) && isset($this->context->cookie->id_customer) and (int) $this->context->cookie->id_customer > 0) {
             $address_a = new Address($this->context->cart->id_address_invoice);
             $address_a->id_customer = (int) $this->context->cookie->id_customer;
             $address_a->save();
         }
         # then call original postProcess to make standard validations and save to DB
         parent::postProcess();
     }
 }
コード例 #8
0
ファイル: Cart.php プロジェクト: juanchog/modules-1.6.0.12
 public function getPackageShippingCost($id_carrier = null, $use_tax = true, Country $default_country = null, $product_list = null, $id_zone = null)
 {
     if (!Configuration::get('LEGAL_SHIPTAXMETH')) {
         return parent::getPackageShippingCost($id_carrier, $use_tax, $default_country, $product_list, $id_zone);
     }
     if ($this->isVirtualCart()) {
         return 0;
     }
     if (!$default_country) {
         $default_country = Context::getContext()->country;
     }
     if (!is_null($product_list)) {
         foreach ($product_list as $key => $value) {
             if ($value['is_virtual'] == 1) {
                 unset($product_list[$key]);
             }
         }
     }
     $complete_product_list = $this->getProducts();
     if (is_null($product_list)) {
         $products = $complete_product_list;
     } else {
         $products = $product_list;
     }
     if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice') {
         $address_id = (int) $this->id_address_invoice;
     } elseif (count($product_list)) {
         $prod = current($product_list);
         $address_id = (int) $prod['id_address_delivery'];
     } else {
         $address_id = null;
     }
     if (!Address::addressExists($address_id)) {
         $address_id = null;
     }
     $cache_id = 'getPackageShippingCost_' . (int) $this->id . '_' . (int) $address_id . '_' . (int) $id_carrier . '_' . (int) $use_tax . '_' . (int) $default_country->id;
     if ($products) {
         foreach ($products as $product) {
             $cache_id .= '_' . (int) $product['id_product'] . '_' . (int) $product['id_product_attribute'];
         }
     }
     if (Cache::isStored($cache_id)) {
         return Cache::retrieve($cache_id);
     }
     // Order total in default currency without fees
     $order_total = $this->getOrderTotal(true, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING, $product_list);
     // Start with shipping cost at 0
     $shipping_cost = 0;
     // If no product added, return 0
     if (!count($products)) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     if (!isset($id_zone)) {
         // Get id zone
         if (!$this->isMultiAddressDelivery() && isset($this->id_address_delivery) && $this->id_address_delivery && Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
             $id_zone = Address::getZoneById((int) $this->id_address_delivery);
         } else {
             if (!Validate::isLoadedObject($default_country)) {
                 $default_country = new Country(Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT'));
             }
             $id_zone = (int) $default_country->id_zone;
         }
     }
     if ($id_carrier && !$this->isCarrierInRange((int) $id_carrier, (int) $id_zone)) {
         $id_carrier = '';
     }
     if (empty($id_carrier) && $this->isCarrierInRange((int) Configuration::get('PS_CARRIER_DEFAULT'), (int) $id_zone)) {
         $id_carrier = (int) Configuration::get('PS_CARRIER_DEFAULT');
     }
     $total_package_without_shipping_tax_inc = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING, $product_list);
     if (empty($id_carrier)) {
         if ((int) $this->id_customer) {
             $customer = new Customer((int) $this->id_customer);
             $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone, $customer->getGroups());
             unset($customer);
         } else {
             $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone);
         }
         foreach ($result as $k => $row) {
             if ($row['id_carrier'] == Configuration::get('PS_CARRIER_DEFAULT')) {
                 continue;
             }
             if (!isset(self::$_carriers[$row['id_carrier']])) {
                 self::$_carriers[$row['id_carrier']] = new Carrier((int) $row['id_carrier']);
             }
             $carrier = self::$_carriers[$row['id_carrier']];
             // Get only carriers that are compliant with shipping method
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && $carrier->getMaxDeliveryPriceByWeight((int) $id_zone) === false || $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && $carrier->getMaxDeliveryPriceByPrice((int) $id_zone) === false) {
                 unset($result[$k]);
                 continue;
             }
             // If out-of-range behavior carrier is set on "Desactivate carrier"
             if ($row['range_behavior']) {
                 $check_delivery_price_by_weight = Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $this->getTotalWeight(), (int) $id_zone);
                 $total_order = $total_package_without_shipping_tax_inc;
                 $check_delivery_price_by_price = Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $total_order, (int) $id_zone, (int) $this->id_currency);
                 // Get only carriers that have a range compatible with cart
                 if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && !$check_delivery_price_by_weight || $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && !$check_delivery_price_by_price) {
                     unset($result[$k]);
                     continue;
                 }
             }
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping = $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), (int) $id_zone);
             } else {
                 $shipping = $carrier->getDeliveryPriceByPrice($order_total, (int) $id_zone, (int) $this->id_currency);
             }
             if (!isset($min_shipping_price)) {
                 $min_shipping_price = $shipping;
             }
             if ($shipping <= $min_shipping_price) {
                 $id_carrier = (int) $row['id_carrier'];
                 $min_shipping_price = $shipping;
             }
         }
     }
     if (empty($id_carrier)) {
         $id_carrier = Configuration::get('PS_CARRIER_DEFAULT');
     }
     if (!isset(self::$_carriers[$id_carrier])) {
         self::$_carriers[$id_carrier] = new Carrier((int) $id_carrier, Configuration::get('PS_LANG_DEFAULT'));
     }
     $carrier = self::$_carriers[$id_carrier];
     // No valid Carrier or $id_carrier <= 0 ?
     if (!Validate::isLoadedObject($carrier)) {
         Cache::store($cache_id, 0);
         return 0;
     }
     if (!$carrier->active) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     // Free fees if free carrier
     if ($carrier->is_free == 1) {
         Cache::store($cache_id, 0);
         return 0;
     }
     // Select carrier tax
     if ($use_tax && !Tax::excludeTaxeOption()) {
         $address = Address::initialize((int) $address_id);
         $carrier_tax = $carrier->getTaxesRate($address);
     }
     $configuration = Configuration::getMultiple(array('PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT'));
     // Free fees
     $free_fees_price = 0;
     if (isset($configuration['PS_SHIPPING_FREE_PRICE'])) {
         $free_fees_price = Tools::convertPrice((double) $configuration['PS_SHIPPING_FREE_PRICE'], Currency::getCurrencyInstance((int) $this->id_currency));
     }
     $orderTotalwithDiscounts = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING, null, null, false);
     if ($orderTotalwithDiscounts >= (double) $free_fees_price && (double) $free_fees_price > 0) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     if (isset($configuration['PS_SHIPPING_FREE_WEIGHT']) && $this->getTotalWeight() >= (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] && (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] > 0) {
         Cache::store($cache_id, $shipping_cost);
         return $shipping_cost;
     }
     // Get shipping cost using correct method
     if ($carrier->range_behavior) {
         if (!isset($id_zone)) {
             // Get id zone
             if (isset($this->id_address_delivery) && $this->id_address_delivery && Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
                 $id_zone = Address::getZoneById((int) $this->id_address_delivery);
             } else {
                 $id_zone = (int) $default_country->id_zone;
             }
         }
         if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && !Carrier::checkDeliveryPriceByWeight($carrier->id, $this->getTotalWeight(), (int) $id_zone) || $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && !Carrier::checkDeliveryPriceByPrice($carrier->id, $total_package_without_shipping_tax_inc, $id_zone, (int) $this->id_currency)) {
             $shipping_cost += 0;
         } else {
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), $id_zone);
             } else {
                 // by price
                 $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
             }
         }
     } else {
         if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
             $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), $id_zone);
         } else {
             $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
         }
     }
     // Adding handling charges
     if (isset($configuration['PS_SHIPPING_HANDLING']) && $carrier->shipping_handling) {
         $shipping_cost += (double) $configuration['PS_SHIPPING_HANDLING'];
     }
     // Additional Shipping Cost per product
     foreach ($products as $product) {
         if (!$product['is_virtual']) {
             $shipping_cost += $product['additional_shipping_cost'] * $product['cart_quantity'];
         }
     }
     $shipping_cost = Tools::convertPrice($shipping_cost, Currency::getCurrencyInstance((int) $this->id_currency));
     //get external shipping cost from module
     if ($carrier->shipping_external) {
         $module_name = $carrier->external_module_name;
         $module = Module::getInstanceByName($module_name);
         if (Validate::isLoadedObject($module)) {
             if (array_key_exists('id_carrier', $module)) {
                 $module->id_carrier = $carrier->id;
             }
             if ($carrier->need_range) {
                 if (method_exists($module, 'getPackageShippingCost')) {
                     $shipping_cost = $module->getPackageShippingCost($this, $shipping_cost, $products);
                 } else {
                     $shipping_cost = $module->getOrderShippingCost($this, $shipping_cost);
                 }
             } else {
                 $shipping_cost = $module->getOrderShippingCostExternal($this);
             }
             // Check if carrier is available
             if ($shipping_cost === false) {
                 Cache::store($cache_id, false);
                 return false;
             }
         } else {
             Cache::store($cache_id, false);
             return false;
         }
     }
     $shipping_cost = (double) Tools::ps_round((double) $shipping_cost, 2);
     Cache::store($cache_id, $shipping_cost);
     return $shipping_cost;
 }
コード例 #9
0
 public function preProcess()
 {
     parent::preProcess();
     if ($back = Tools::getValue('back')) {
         self::$smarty->assign('back', Tools::safeOutput($back));
     }
     if ($mod = Tools::getValue('mod')) {
         self::$smarty->assign('mod', Tools::safeOutput($mod));
     }
     if (Tools::isSubmit('ajax') and Tools::isSubmit('type')) {
         if (Tools::getValue('type') == 'delivery') {
             $id_address = isset(self::$cart->id_address_delivery) ? (int) self::$cart->id_address_delivery : 0;
         } elseif (Tools::getValue('type') == 'invoice') {
             $id_address = (isset(self::$cart->id_address_invoice) and self::$cart->id_address_invoice != self::$cart->id_address_delivery) ? (int) self::$cart->id_address_invoice : 0;
         } else {
             exit;
         }
     } else {
         $id_address = (int) Tools::getValue('id_address', 0);
     }
     if ($id_address) {
         $this->_address = new Address((int) $id_address);
         if (Validate::isLoadedObject($this->_address) and Customer::customerHasAddress((int) self::$cookie->id_customer, (int) $id_address)) {
             if (Tools::isSubmit('delete')) {
                 if (self::$cart->id_address_invoice == $this->_address->id) {
                     unset(self::$cart->id_address_invoice);
                 }
                 if (self::$cart->id_address_delivery == $this->_address->id) {
                     unset(self::$cart->id_address_delivery);
                 }
                 if ($this->_address->delete()) {
                     Tools::redirect('addresses.php');
                 }
                 $this->errors[] = Tools::displayError('This address cannot be deleted.');
             }
             self::$smarty->assign(array('address' => $this->_address, 'id_address' => (int) $id_address));
         } elseif (Tools::isSubmit('ajax')) {
             exit;
         } else {
             Tools::redirect('addresses.php');
         }
     }
     if (Tools::isSubmit('submitAddress')) {
         $address = new Address();
         $this->errors = $address->validateControler();
         $address->id_customer = (int) self::$cookie->id_customer;
         if (!Tools::getValue('phone') and !Tools::getValue('phone_mobile')) {
             $this->errors[] = Tools::displayError('You must register at least one phone number');
         }
         if (!($country = new Country((int) $address->id_country)) or !Validate::isLoadedObject($country)) {
             die(Tools::displayError());
         }
         /* US customer: normalize the address */
         if ($address->id_country == Country::getByIso('US')) {
             include_once _PS_TAASC_PATH_ . 'AddressStandardizationSolution.php';
             $normalize = new AddressStandardizationSolution();
             $address->address1 = $normalize->AddressLineStandardization($address->address1);
             $address->address2 = $normalize->AddressLineStandardization($address->address2);
         }
         //remove zipcode verification
         /*
         $zip_code_format = $country->zip_code_format;
         if ($country->need_zip_code)
         {
         	if (($postcode = Tools::getValue('postcode')) AND $zip_code_format)
         	{
         		$zip_regexp = '/^'.$zip_code_format.'$/ui';
         		$zip_regexp = str_replace(' ', '( |)', $zip_regexp);
         		$zip_regexp = str_replace('-', '(-|)', $zip_regexp);
         		$zip_regexp = str_replace('N', '[0-9]', $zip_regexp);
         		$zip_regexp = str_replace('L', '[a-zA-Z]', $zip_regexp);
         		$zip_regexp = str_replace('C', $country->iso_code, $zip_regexp);
         		if (!preg_match($zip_regexp, $postcode))
         			$this->errors[] = '<strong>'.Tools::displayError('Post/Zip Code mentioned is incorrect.').'</strong> ';
         	}
         	elseif ($zip_code_format)
         		$this->errors[] = '<strong>'.Tools::displayError('Post/Zip Code mentioned is incorrect.').'</strong> ';
         	elseif ($postcode AND !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode))
         			$this->errors[] = '<strong>'.Tools::displayError('Post/Zip Code mentioned is incorrect.').'</strong> ';
         }
         */
         //validate pincode and assign possible payment options
         $op = $cod = 0;
         Carrier::getPreferredCarriers($postcode, $cod, $op);
         if ($op == 0 && $cod == 0) {
             $this->errors[] = 'We are sorry but we do not provide service to this region as of now. However, we keep adding new locations with time and would request you to check our website a few weeks later. We apologise for the inconvenience caused. ';
         }
         if ($country->isNeedDni() and (!Tools::getValue('dni') or !Validate::isDniLite(Tools::getValue('dni')))) {
             $this->errors[] = Tools::displayError('Identification number is incorrect or has already been used.');
         } elseif (!$country->isNeedDni()) {
             $address->dni = NULL;
         }
         if (Configuration::get('PS_TOKEN_ENABLE') == 1 and strcmp(Tools::getToken(false), Tools::getValue('token')) and self::$cookie->isLogged(true) === true) {
             $this->errors[] = Tools::displayError('Invalid token');
         }
         if ((int) $country->contains_states and !(int) $address->id_state) {
             $this->errors[] = Tools::displayError('This country requires a state selection.');
         }
         if (!sizeof($this->errors)) {
             if (isset($id_address)) {
                 $country = new Country((int) $address->id_country);
                 if (Validate::isLoadedObject($country) and !$country->contains_states) {
                     $address->id_state = 0;
                 }
                 $address_old = new Address((int) $id_address);
                 if (Validate::isLoadedObject($address_old) and Customer::customerHasAddress((int) self::$cookie->id_customer, (int) $address_old->id)) {
                     if ($address_old->isUsed()) {
                         $address_old->delete();
                         if (!Tools::isSubmit('ajax')) {
                             $to_update = false;
                             if (self::$cart->id_address_invoice == $address_old->id) {
                                 $to_update = true;
                                 self::$cart->id_address_invoice = 0;
                             }
                             if (self::$cart->id_address_delivery == $address_old->id) {
                                 $to_update = true;
                                 self::$cart->id_address_delivery = 0;
                             }
                             if ($to_update) {
                                 self::$cart->update();
                             }
                         }
                     } else {
                         $address->id = (int) $address_old->id;
                         $address->date_add = $address_old->date_add;
                     }
                 }
             } elseif (self::$cookie->is_guest) {
                 Tools::redirect('addresses.php');
             }
             if ($result = $address->save()) {
                 /* In order to select this new address : order-address.tpl */
                 if ((bool) Tools::getValue('select_address', false) == true or Tools::isSubmit('ajax') and Tools::getValue('type') == 'invoice') {
                     /* This new adress is for invoice_adress, select it */
                     self::$cart->id_address_invoice = (int) $address->id;
                     self::$cart->update();
                 }
                 if (Tools::isSubmit('ajax')) {
                     $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'id_address_delivery' => self::$cart->id_address_delivery, 'id_address_invoice' => self::$cart->id_address_invoice);
                     die(Tools::jsonEncode($return));
                 }
                 if (Tools::isSubmit('order_add_address')) {
                     self::$cart->id_address_invoice = (int) $address->id;
                     self::$cart->id_address_delivery = (int) $address->id;
                     self::$cart->update();
                     $back = $back . '&id_address_delivery=' . $address->id . '&id_address_invoice=' . $address->id . '&id_carrier=' . Tools::getValue('id_carrier');
                 }
                 Tools::redirect($back ? $mod ? $back . '&back=' . $mod : $back : 'addresses.php');
             }
             $this->errors[] = Tools::displayError('An error occurred while updating your address.');
         }
     } elseif (!$id_address) {
         $customer = new Customer((int) self::$cookie->id_customer);
         if (Validate::isLoadedObject($customer)) {
             $_POST['firstname'] = $customer->firstname;
             $_POST['lastname'] = $customer->lastname;
         }
     }
     if (Tools::isSubmit('ajax') and sizeof($this->errors)) {
         $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors);
         die(Tools::jsonEncode($return));
     }
 }
コード例 #10
0
     $errors[] = Tools::displayError('invalid token');
 }
 if (!($country = new Country($address->id_country)) or !Validate::isLoadedObject($country)) {
     die(Tools::displayError());
 }
 if (intval($country->contains_states) and !intval($address->id_state)) {
     $errors[] = Tools::displayError('this country require a state selection');
 }
 if (!sizeof($errors)) {
     if (isset($id_address)) {
         $country = new Country(intval($address->id_country));
         if (Validate::isLoadedObject($country) and !$country->contains_states) {
             $address->id_state = false;
         }
         $address_old = new Address(intval($id_address));
         if (Validate::isLoadedObject($address_old) and Customer::customerHasAddress(intval($cookie->id_customer), intval($address_old->id))) {
             if ($cart->id_address_invoice == $address_old->id) {
                 unset($cart->id_address_invoice);
             }
             if ($cart->id_address_delivery == $address_old->id) {
                 unset($cart->id_address_delivery);
             }
             if ($address_old->isUsed()) {
                 $address_old->delete();
             } else {
                 $address->id = intval($address_old->id);
                 $address->date_add = $address_old->date_add;
             }
         }
     }
     if ($result = $address->save()) {
コード例 #11
0
    /**
     * Process changes on an address
     */
    protected function processSubmitAddress()
    {
        /*if ($this->context->customer->is_guest)
        		Tools::redirect('index.php?controller=addresses');*/
        $address = new Address();
        $this->errors = $address->validateController();
        $address->id_customer = (int) $this->context->customer->id;
        // Check page token
        if ($this->context->customer->isLogged() && !$this->isTokenValid()) {
            $this->errors[] = Tools::displayError('Invalid token');
        }
        // Check phone
        if (!Tools::getValue('phone') && !Tools::getValue('phone_mobile')) {
            $this->errors[] = Tools::displayError('You must register at least one phone number');
        }
        if ($address->id_country) {
            // Check country
            if (!($country = new Country($address->id_country)) || !Validate::isLoadedObject($country)) {
                throw new PrestaShopException('Country cannot be loaded with address->id_country');
            }
            if ((int) $country->contains_states && !(int) $address->id_state) {
                $this->errors[] = Tools::displayError('This country requires a state selection.');
            }
            // US customer: normalize the address
            if ($address->id_country == Country::getByIso('US')) {
                include_once _PS_TAASC_PATH_ . 'AddressStandardizationSolution.php';
                $normalize = new AddressStandardizationSolution();
                $address->address1 = $normalize->AddressLineStandardization($address->address1);
                $address->address2 = $normalize->AddressLineStandardization($address->address2);
            }
            // Check country zip code
            $zip_code_format = $country->zip_code_format;
            if ($country->need_zip_code) {
                if (($postcode = Tools::getValue('postcode')) && $zip_code_format) {
                    if (!$country->checkZipCode($postcode)) {
                        $this->errors[] = sprintf(Tools::displayError('Zip/Postal code is invalid. Must be typed as follows: %s'), str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format))));
                    }
                } else {
                    if ($zip_code_format) {
                        $this->errors[] = Tools::displayError('Zip/Postal code is required.');
                    } else {
                        if ($postcode && !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode)) {
                            $this->errors[] = sprintf(Tools::displayError('Zip/Postal code is invalid. Must be typed as follows: %s'), str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format))));
                        }
                    }
                }
            }
            // Check country DNI
            if ($country->isNeedDni() && (!Tools::getValue('dni') || !Validate::isDniLite(Tools::getValue('dni')))) {
                $this->errors[] = Tools::displayError('Identification number is incorrect or has already been used.');
            } else {
                if (!$country->isNeedDni()) {
                    $address->dni = null;
                }
            }
        }
        // Check if the alias exists
        if (!empty($_POST['alias']) && (int) $this->context->customer->id > 0 && Db::getInstance()->getValue('
				SELECT count(*)
				FROM ' . _DB_PREFIX_ . 'address
				WHERE `alias` = \'' . pSql($_POST['alias']) . '\'
				AND id_address != ' . (int) Tools::getValue('id_address') . '
				AND id_customer = ' . (int) $this->context->customer->id . '
				AND deleted = 0') > 0) {
            $this->errors[] = sprintf(Tools::displayError('The alias "%s" is already used, please chose another one.'), Tools::safeOutput($_POST['alias']));
        }
        // Check the requires fields which are settings in the BO
        $this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());
        // Don't continue this process if we have errors !
        if ($this->errors && !$this->ajax) {
            return;
        }
        // If we edit this address, delete old address and create a new one
        if (Validate::isLoadedObject($this->_address)) {
            if (Validate::isLoadedObject($country) && !$country->contains_states) {
                $address->id_state = 0;
            }
            $address_old = $this->_address;
            if (Customer::customerHasAddress($this->context->customer->id, (int) $address_old->id)) {
                if ($address_old->isUsed()) {
                    $address_old->delete();
                } else {
                    $address->id = (int) $address_old->id;
                    $address->date_add = $address_old->date_add;
                }
            }
        }
        // Save address
        if ($result = $address->save()) {
            // Update id address of the current cart if necessary
            if (isset($address_old) && $address_old->isUsed()) {
                $this->context->cart->updateAddressId($address_old->id, $address->id);
            } else {
                // Update cart address
                $this->context->cart->autosetProductAddress();
            }
            if ($this->ajax) {
                $return = array('hasError' => (bool) $this->errors, 'errors' => $this->errors, 'id_address_delivery' => $this->context->cart->id_address_delivery, 'id_address_invoice' => $this->context->cart->id_address_invoice);
                die(Tools::jsonEncode($return));
            }
            // Redirect to old page or current page
            if ($back = Tools::getValue('back')) {
                $mod = Tools::getValue('mod');
                Tools::redirect('index.php?controller=' . $back . ($mod ? '&back=' . $mod : ''));
            } else {
                Tools::redirect('index.php?controller=addresses');
            }
        }
        $this->errors[] = Tools::displayError('An error occurred while updating your address.');
    }
コード例 #12
0
ファイル: Cart.php プロジェクト: paolobattistella/aphro
    /**
     * Update product quantity
     *
     * @param int $quantity Quantity to add (or substract)
     * @param int $id_product Product ID
     * @param int $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)
    {
        //error_log(__LINE__.'@'.__FILE__);
        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]);
        }
        Hook::exec('actionBeforeCartUpdateQty', array('cart' => $this, 'product' => $product, 'id_product_attribute' => $id_product_attribute, 'id_customization' => $id_customization, 'quantity' => $quantity, 'operator' => $operator, 'id_address_delivery' => $id_address_delivery, 'shop' => $shop, 'auto_add_cart_rule' => $auto_add_cart_rule));
        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') && !defined('_PS_ADMIN_DIR_')) {
            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;
                        }
                    }
                } elseif ($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);
                } elseif ($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;
                }
                $context = Context::getContext();
                $context->shop->id = Tools::getIsset('ids') ? Tools::getValue('ids') : $shop->id;
                $specific_price = SpecificPrice::getSpecificPrice($id_product, $context->shop->id, null, null, null, 1, null, 0, 0, 0);
                $delivery_date = Tools::getIsset('delivery_date') ? Tools::getValue('delivery_date') : '';
                $delivery_time_from = Tools::getIsset('delivery_time_from') ? Tools::getValue('delivery_time_from') : '';
                $delivery_time_to = Tools::getIsset('delivery_time_to') ? Tools::getValue('delivery_time_to') : '';
                // $price = Product::getPriceStatic($id_product, true, 0, 2, null, false, true, 1, false, null, null, null, $specific_price, true, true, $context, true, $delivery_date, $delivery_time_from, $delivery_time_to);
                // if (empty($price))
                //     $price = $product->price;
                $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' => Tools::getIsset('ids') ? Tools::getValue('ids') : $shop->id, 'quantity' => (int) $quantity, 'date_add' => date('Y-m-d H:i:s'), 'delivery_date' => $delivery_date, 'delivery_time_from' => $delivery_time_from, 'delivery_time_to' => $delivery_time_to));
                if (!$result_add) {
                    return false;
                }
            }
        }
        // refresh cache of self::_products
        $this->_products = $this->getProducts(true);
        $this->update();
        $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;
        }
    }
コード例 #13
0
 public function processAddress()
 {
     $same = Tools::isSubmit('same');
     if (!Tools::getValue('id_address_invoice', false) && !$same) {
         $same = true;
     }
     if (!Customer::customerHasAddress((int) self::$cookie->id_customer, (int) Tools::getValue('id_address_delivery')) || !$same && !Customer::customerHasAddress((int) self::$cookie->id_customer, (int) Tools::getValue('id_address_invoice'))) {
         $this->errors[] = Tools::displayError('Invalid address');
     } elseif (!Tools::isSubmit('id_address_delivery') || !Address::isCountryActiveById((int) Tools::getValue('id_address_delivery'))) {
         $this->errors[] = Tools::displayError('This address is not in a valid area.');
     } else {
         self::$cart->id_address_delivery = (int) Tools::getValue('id_address_delivery');
         self::$cart->id_address_invoice = $same ? self::$cart->id_address_delivery : (int) Tools::getValue('id_address_invoice');
         if (!self::$cart->update()) {
             $this->errors[] = Tools::displayError('An error occurred while updating your cart.');
         }
         if (Tools::isSubmit('message')) {
             $this->_updateMessage(Tools::getValue('message'));
         }
     }
     if (sizeof($this->errors)) {
         if (Tools::getValue('ajax')) {
             die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
         }
         $this->step = 1;
     }
     if (Tools::getValue('ajax')) {
         die(true);
     }
 }
コード例 #14
0
 public function postProcess()
 {
     if (!$this->isOpcModuleActive()) {
         return parent::postProcess();
     }
     $inv_first_on = Configuration::get('OPC_INVOICE_FIRST') == "1";
     if (Tools::isSubmit('submitAddress') && Tools::isSubmit('ajax')) {
         if (Tools::isSubmit('type')) {
             if (Tools::getValue('type') == 'delivery') {
                 if (!$inv_first_on) {
                     $id_address = isset($this->context->cart->id_address_delivery) ? (int) $this->context->cart->id_address_delivery : 0;
                 } else {
                     $id_address = (Tools::isSubmit('id_address') and (int) Tools::getValue('id_address', 0) != $this->context->cart->id_address_invoice) ? (int) Tools::getValue('id_address', 0) : 0;
                 }
             } elseif (Tools::getValue('type') == 'invoice') {
                 if (!$inv_first_on) {
                     $id_address = (Tools::isSubmit('id_address') and (int) Tools::getValue('id_address', 0) != $this->context->cart->id_address_delivery) ? (int) Tools::getValue('id_address', 0) : 0;
                 } else {
                     $id_address = isset($this->context->cart->id_address_invoice) ? (int) $this->context->cart->id_address_invoice : 0;
                 }
             } else {
                 exit;
             }
         } else {
             $id_address = (int) Tools::getValue('id_address', 0);
         }
         if (Tools::getValue('alias') == Tools::getValue('default_alias') && Tools::getValue('address1') && trim(Tools::getValue('address1')) != "") {
             $_POST['alias'] = Tools::substr(preg_replace('/[;#]/', '_', Tools::getValue('address1')), 0, 32);
         }
         $address = new Address();
         $this->errors = $address->validateController();
         if (Tools::getValue('type') == 'invoice' && isset($id_address) && $id_address > 0) {
             $this->context->cart->id_address_invoice = $id_address;
             $this->context->cart->update();
         }
         $address_old = new Address((int) $id_address);
         if (!sizeof($this->errors) && isset($id_address) && (int) $id_address > 0 && Validate::isLoadedObject($address_old) and Customer::customerHasAddress((int) $this->context->cookie->id_customer, (int) $address_old->id)) {
             if ($address_old->isUsed() && $address_old->isDifferent($address)) {
                 $address_1 = new Address();
                 $_POST['alias'] = Tools::substr(preg_replace('/[;#]/', '_', Tools::getValue('address1')), 0, 32);
                 $this->errors = $address_1->validateController();
                 $address_1->id_customer = (int) $this->context->cookie->id_customer;
                 if ((!Tools::getValue('phone') and !Tools::getValue('phone_mobile')) || (!($country = new Country((int) $address_1->id_country)) or !Validate::isLoadedObject($country)) || ($country->isNeedDni() and (!Tools::getValue('dni') or !Validate::isDniLite(Tools::getValue('dni')))) || ((int) $country->contains_states and !(int) $address_1->id_state)) {
                 } elseif ($result = $address_1->save()) {
                     $id_address = $address_1->id;
                     if (Tools::getValue('type') == 'delivery') {
                         if ($this->context->cart->id_address_delivery == $this->context->cart->id_address_invoice) {
                             $this->context->cart->id_address_invoice = (int) $address_1->id;
                         }
                         $this->context->cart->id_address_delivery = (int) $address_1->id;
                         $this->context->cart->update();
                     }
                     if (Tools::getValue('type') == 'invoice') {
                         if ($this->context->cart->id_address_delivery == $this->context->cart->id_address_invoice) {
                             $this->context->cart->id_address_delivery = (int) $address_1->id;
                         }
                         $this->context->cart->id_address_invoice = (int) $address_1->id;
                         $this->context->cart->update();
                     }
                 }
             }
         }
         $this->_processSubmitAddress($id_address, Tools::getValue('type'));
     } elseif (Tools::isSubmit('partialSubmitAddress')) {
         // called separately for delivery country/state change and invoice country/state change
         $is_separate_invoice_address = Tools::getValue('invoice_address');
         $is_separate_delivery_address = Tools::getValue('delivery_address');
         $type = Tools::getValue('type');
         $id_country = Tools::getValue('id_country');
         $id_state = Tools::getValue('id_state');
         $postcode = Tools::getValue('postcode');
         $city = Tools::getValue('city');
         $firstname = Tools::getValue('firstname');
         $lastname = Tools::getValue('lastname');
         $addr1 = Tools::getValue('address1');
         $id_address_delivery = 0;
         $id_address_invoice = 0;
         $create_different_delivery_address = 0;
         $create_different_invoice_address = 0;
         $last_addr_id = 0;
         $last_addr_ids_tmp = Customer::getLastTwoCustomerAddressIds($this->context->cart->id_customer);
         if ($id_country !== false && $id_state !== false) {
             if ($type == 'delivery' && isset($this->context->cart->id_address_delivery) && $this->context->cart->id_address_delivery > 0) {
                 $address_old1 = new Address((int) $this->context->cart->id_address_delivery);
                 $address1 = new Address();
                 $errors1 = $address1->validateController();
                 if (Validate::isLoadedObject($address_old1) && $address_old1->isUsed() && $address_old1->isDifferent($address1, true)) {
                     $create_different_delivery_address = 1;
                 }
             }
             if ($is_separate_invoice_address) {
                 if ($this->context->cart->id_address_delivery == $this->context->cart->id_address_invoice) {
                     $create_different_invoice_address = 1;
                 }
                 if (isset($last_addr_ids_tmp) && $last_addr_ids_tmp != false && is_array($last_addr_ids_tmp) && count($last_addr_ids_tmp) > 0) {
                     foreach ($last_addr_ids_tmp as $item) {
                         if ($item != $this->context->cart->id_address_delivery) {
                             $last_addr_id = $item;
                             break;
                         }
                     }
                 }
             }
             if ($is_separate_delivery_address) {
                 if ($this->context->cart->id_address_delivery == $this->context->cart->id_address_invoice) {
                     $create_different_delivery_address = 1;
                 }
                 if (isset($last_addr_ids_tmp) && $last_addr_ids_tmp != false && is_array($last_addr_ids_tmp) && count($last_addr_ids_tmp) > 0) {
                     foreach ($last_addr_ids_tmp as $item) {
                         if ($item != $this->context->cart->id_address_invoice) {
                             $last_addr_id = $item;
                             break;
                         }
                     }
                 }
             }
             if ($type == 'delivery') {
                 $id_address_delivery = $last_addr_id > 0 && $create_different_delivery_address ? $last_addr_id : $this->saveAddress($create_different_delivery_address ? $last_addr_id : $this->context->cart->id_address_delivery, $id_country, $id_state, $postcode, $city, $firstname, $lastname, $addr1);
             } else {
                 $id_address_invoice = $last_addr_id > 0 && $create_different_invoice_address ? $last_addr_id : $this->saveAddress($create_different_invoice_address ? $last_addr_id : $this->context->cart->id_address_invoice, $id_country, $id_state, $postcode, $city, $firstname, $lastname, $addr1);
             }
         }
         if ($id_address_delivery > 0) {
             $this->context->cart->id_address_delivery = $id_address_delivery;
             if ($is_separate_invoice_address == 0 && $is_separate_delivery_address == 0) {
                 $this->context->cart->id_address_invoice = $this->context->cart->id_address_delivery;
             }
         } elseif ($id_address_invoice > 0) {
             $this->context->cart->id_address_invoice = $id_address_invoice;
             if ($is_separate_invoice_address == 0 && $is_separate_delivery_address == 0) {
                 $this->context->cart->id_address_delivery = $this->context->cart->id_address_invoice;
             }
         }
         $this->context->cart->update();
         if (Configuration::get('VATNUMBER_MANAGEMENT') and file_exists(dirname(__FILE__) . '/../../modules/vatnumber/vatnumber.php') && VatNumber::isApplicable($id_country) && Configuration::get('VATNUMBER_COUNTRY') != $id_country) {
             $allow_eu_vat = 1;
         } else {
             $allow_eu_vat = 0;
         }
         if (Tools::isSubmit('ajax')) {
             $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'id_address_delivery' => $this->context->cart->id_address_delivery, 'id_address_invoice' => $this->context->cart->id_address_invoice, 'allow_eu_vat' => $allow_eu_vat);
             die(Tools::jsonEncode($return));
         }
     } else {
         # assign pre-guessed address to this customer
         if (Tools::getValue('type') == 'invoice' && (isset($this->context->cart->id_address_invoice) and $this->context->cart->id_address_invoice != $this->context->cart->id_address_delivery) && isset($this->context->cookie->id_customer) and (int) $this->context->cookie->id_customer > 0) {
             $address_a = new Address($this->context->cart->id_address_invoice);
             $address_a->id_customer = (int) $this->context->cookie->id_customer;
             $address_a->save();
         }
         # then call original postProcess to make standard validations and save to DB
         parent::postProcess();
     }
 }
コード例 #15
0
ファイル: Cart.php プロジェクト: srikanthash09/codetestdatld
 /**
  * Return shipping total
  *
  * @param integer $id_carrier Carrier ID (default : current carrier)
  * @return float Shipping total
  */
 function getOrderShippingCost($id_carrier = NULL, $useTax = true)
 {
     global $defaultCountry;
     if ($this->isVirtualCart()) {
         return 0;
     }
     // Checking discounts in cart
     $products = $this->getProducts();
     $discounts = $this->getDiscounts(true);
     if ($discounts) {
         foreach ($discounts as $id_discount) {
             if ($id_discount['id_discount_type'] == 3) {
                 if ($id_discount['minimal'] > 0) {
                     $total_cart = 0;
                     $categories = Discount::getCategories((int) $id_discount['id_discount']);
                     if (sizeof($categories)) {
                         foreach ($products as $product) {
                             if (Product::idIsOnCategoryId((int) $product['id_product'], $categories)) {
                                 $total_cart += $product['total_wt'];
                             }
                         }
                     }
                     if ($total_cart >= $id_discount['minimal']) {
                         return 0;
                     }
                 } else {
                     return 0;
                 }
             }
         }
     }
     // Order total in default currency without fees
     $order_total = $this->getOrderTotal(true, Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING);
     // Start with shipping cost at 0
     $shipping_cost = 0;
     // If no product added, return 0
     if ($order_total <= 0 and !(int) self::getNbProducts($this->id)) {
         return $shipping_cost;
     }
     // Get id zone
     if (isset($this->id_address_delivery) and $this->id_address_delivery and Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
         $id_zone = Address::getZoneById((int) $this->id_address_delivery);
     } else {
         // This method can be called from the backend, and $defaultCountry won't be defined
         if (!Validate::isLoadedObject($defaultCountry)) {
             $defaultCountry = new Country(Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT'));
         }
         $id_zone = (int) $defaultCountry->id_zone;
     }
     // If no carrier, select default one
     if (!$id_carrier) {
         $id_carrier = $this->id_carrier;
     }
     if ($id_carrier && !$this->isCarrierInRange($id_carrier, $id_zone)) {
         $id_carrier = '';
     }
     if (empty($id_carrier) && $this->isCarrierInRange(Configuration::get('PS_CARRIER_DEFAULT'), $id_zone)) {
         $id_carrier = (int) Configuration::get('PS_CARRIER_DEFAULT');
     }
     if (empty($id_carrier)) {
         if ((int) $this->id_customer) {
             $customer = new Customer((int) $this->id_customer);
             $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone, $customer->getGroups());
             unset($customer);
         } else {
             $result = Carrier::getCarriers((int) Configuration::get('PS_LANG_DEFAULT'), true, false, (int) $id_zone);
         }
         foreach ($result as $k => $row) {
             if ($row['id_carrier'] == Configuration::get('PS_CARRIER_DEFAULT')) {
                 continue;
             }
             if (!isset(self::$_carriers[$row['id_carrier']])) {
                 self::$_carriers[$row['id_carrier']] = new Carrier((int) $row['id_carrier']);
             }
             $carrier = self::$_carriers[$row['id_carrier']];
             // Get only carriers that are compliant with shipping method
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT and $carrier->getMaxDeliveryPriceByWeight($id_zone) === false or $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE and $carrier->getMaxDeliveryPriceByPrice($id_zone) === false) {
                 unset($result[$k]);
                 continue;
             }
             // If out-of-range behavior carrier is set on "Desactivate carrier"
             if ($row['range_behavior']) {
                 // Get only carriers that have a range compatible with cart
                 if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT and !Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $this->getTotalWeight(), $id_zone) or $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE and !Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, (int) $this->id_currency)) {
                     unset($result[$k]);
                     continue;
                 }
             }
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping = $carrier->getDeliveryPriceByWeight($this->getTotalWeight(), $id_zone);
             } else {
                 $shipping = $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
             }
             if (!isset($minShippingPrice)) {
                 $minShippingPrice = $shipping;
             }
             if ($shipping <= $minShippingPrice) {
                 $id_carrier = (int) $row['id_carrier'];
                 $minShippingPrice = $shipping;
             }
         }
     }
     if (empty($id_carrier)) {
         $id_carrier = Configuration::get('PS_CARRIER_DEFAULT');
     }
     if (!isset(self::$_carriers[$id_carrier])) {
         self::$_carriers[$id_carrier] = new Carrier((int) $id_carrier, Configuration::get('PS_LANG_DEFAULT'));
     }
     $carrier = self::$_carriers[$id_carrier];
     if (!Validate::isLoadedObject($carrier)) {
         die(Tools::displayError('Fatal error: "no default carrier"'));
     }
     if (!$carrier->active) {
         return $shipping_cost;
     }
     // Free fees if free carrier
     if ($carrier->is_free == 1) {
         return 0;
     }
     // Select carrier tax
     if ($useTax and !Tax::excludeTaxeOption()) {
         $carrierTax = Tax::getCarrierTaxRate((int) $carrier->id, (int) $this->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     }
     $configuration = Configuration::getMultiple(array('PS_SHIPPING_FREE_PRICE', 'PS_SHIPPING_HANDLING', 'PS_SHIPPING_METHOD', 'PS_SHIPPING_FREE_WEIGHT'));
     // Free fees
     $free_fees_price = 0;
     if (isset($configuration['PS_SHIPPING_FREE_PRICE'])) {
         $free_fees_price = Tools::convertPrice((double) $configuration['PS_SHIPPING_FREE_PRICE'], Currency::getCurrencyInstance((int) $this->id_currency));
     }
     $orderTotalwithDiscounts = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING);
     if ($orderTotalwithDiscounts >= (double) $free_fees_price and (double) $free_fees_price > 0) {
         return $shipping_cost;
     }
     if (isset($configuration['PS_SHIPPING_FREE_WEIGHT']) and $this->getTotalWeight() >= (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] and (double) $configuration['PS_SHIPPING_FREE_WEIGHT'] > 0) {
         return $shipping_cost;
     }
     // Get shipping cost using correct method
     if ($carrier->range_behavior) {
         // Get id zone
         if (isset($this->id_address_delivery) and $this->id_address_delivery and Customer::customerHasAddress($this->id_customer, $this->id_address_delivery)) {
             $id_zone = Address::getZoneById((int) $this->id_address_delivery);
         } else {
             $id_zone = (int) $defaultCountry->id_zone;
         }
         if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT and !Carrier::checkDeliveryPriceByWeight($carrier->id, $this->getTotalWeight(), $id_zone) or $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE and !Carrier::checkDeliveryPriceByPrice($carrier->id, $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, (int) $this->id_currency)) {
             $shipping_cost += 0;
         } else {
             if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
                 $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight(), $id_zone);
             } else {
                 // by price
                 $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
             }
         }
     } else {
         if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) {
             $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight(), $id_zone);
         } else {
             $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int) $this->id_currency);
         }
     }
     // Adding handling charges
     if (isset($configuration['PS_SHIPPING_HANDLING']) and $carrier->shipping_handling) {
         $shipping_cost += (double) $configuration['PS_SHIPPING_HANDLING'];
     }
     // Additional Shipping Cost per product
     foreach ($products as $product) {
         $shipping_cost += $product['additional_shipping_cost'] * $product['cart_quantity'];
     }
     $shipping_cost = Tools::convertPrice($shipping_cost, Currency::getCurrencyInstance((int) $this->id_currency));
     //get external shipping cost from module
     if ($carrier->shipping_external) {
         $moduleName = $carrier->external_module_name;
         $module = Module::getInstanceByName($moduleName);
         if (Validate::isLoadedObject($module)) {
             if (array_key_exists('id_carrier', $module)) {
                 $module->id_carrier = $carrier->id;
             }
             if ($carrier->need_range) {
                 $shipping_cost = $module->getOrderShippingCost($this, $shipping_cost);
             } else {
                 $shipping_cost = $module->getOrderShippingCostExternal($this);
             }
             // Check if carrier is available
             if ($shipping_cost === false) {
                 return false;
             }
         } else {
             return false;
         }
     }
     // Apply tax
     if (isset($carrierTax)) {
         $shipping_cost *= 1 + $carrierTax / 100;
     }
     return (double) Tools::ps_round((double) $shipping_cost, 2);
 }
コード例 #16
0
ファイル: socialuserprofile.php プロジェクト: jpodracky/dogs
 /**
  * Update user address
  */
 public function updateUserAddress()
 {
     $address = null;
     $id_address = Tools::getValue('id_address');
     if (isset($id_address)) {
         $address = new Address($id_address);
         if (Validate::isLoadedObject($address) && Customer::customerHasAddress($this->context->cookie->id_customer, $id_address)) {
             $this->errors = $address->validateController();
             $address->id_customer = (int) $this->context->customer->id;
             $address->address1 = Tools::getValue('address1');
             $address->address2 = Tools::getValue('address2');
             $address->city = Tools::getValue('city');
             $address->phone = Tools::getValue('phone');
             $address->phone_mobile = Tools::getValue('phone_mobile');
             $address->alias = Tools::getValue('alias');
             $address->other = Tools::getValue('other');
             $address->id_country = Tools::getValue('id_country');
             $address->postcode = Tools::getValue('postcode');
             $address->update();
             /*
             
             		        // Check page token
             		        if ($this->context->customer->isLogged()) {
             		            $this->errors[] = Tools::displayError('Invalid token.');
             		        }
             
             		        // Check phone
             		        if (Configuration::get('PS_ONE_PHONE_AT_LEAST') && !Tools::getValue('phone') && !Tools::getValue('phone_mobile')) {
             		            $this->errors[] = Tools::displayError('You must register at least one phone number.');
             		        }
             
             		        if (Tools::getValue('id_country')) {
             		            // Check country
             		            if (!($country = new Country($address->id_country)) || !Validate::isLoadedObject($country)) {
             		                throw new PrestaShopException('Country cannot be loaded with address->id_country');
             		            }
             
             		            if ((int)$country->contains_states && !(int)$address->id_state) {
             		                $this->errors[] = Tools::displayError('This country requires you to chose a State.');
             		            }
             
             		            if (!$country->active) {
             		                $this->errors[] = Tools::displayError('This country is not active.');
             		            }
             
             		            $address->id_country = $country->id_country;
             		            $postcode = Tools::getValue('postcode');
             		            /* Check zip code format */
             /*    if ($country->zip_code_format && !$country->checkZipCode($postcode)) {
             		                $this->errors[] = sprintf(Tools::displayError('The Zip/Postal code you\'ve entered is invalid. It must follow this format: %s'), str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format))));
             		            } elseif (empty($postcode) && $country->need_zip_code) {
             		                $this->errors[] = Tools::displayError('A Zip/Postal code is required.');
             		            } elseif ($postcode && !Validate::isPostCode($postcode)) {
             		                $this->errors[] = Tools::displayError('The Zip/Postal code is invalid.');
             		            }
             
             		            // Check country DNI
             		            /*
             		            if ($country->isNeedDni() && (!Tools::getValue('dni') || !Validate::isDniLite(Tools::getValue('dni')))) {
             		                $this->errors[] = Tools::displayError('The identification number is incorrect or has already been used.');
             		            } elseif (!$country->isNeedDni()) {
             		                $address->dni = null;
             		            }
             		            */
             /* }
             
             		        // Check if the alias exists
             		        if (!$this->context->customer->is_guest && !empty($_POST['alias']) && (int)$this->context->customer->id > 0) {
             		            $id_address = Tools::getValue('id_address');
             		            if (Configuration::get('PS_ORDER_PROCESS_TYPE') && (int)Tools::getValue('opc_id_address_'.Tools::getValue('type')) > 0) {
             		                $id_address = Tools::getValue('opc_id_address_'.Tools::getValue('type'));
             		            }
             
             		            if (Address::aliasExist(Tools::getValue('alias'), (int)$id_address, (int)$this->context->customer->id)) {
             		                $this->errors[] = sprintf(Tools::displayError('The alias "%s" has already been used. Please select another one.'), Tools::safeOutput(Tools::getValue('alias')));
             		            }
             		        }
             
             		        // Check the requires fields which are settings in the BO
             		        $this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());
             
             		        // Don't continue this process if we have errors !
             		        if ($this->errors) {
             		            return;
             		        }
             
             		        // If we edit this address, delete old address and create a new one
             		        if (Validate::isLoadedObject($this->_address)) {
             		            if (Validate::isLoadedObject($country) && !$country->contains_states) {
             		                $address->id_state = 0;
             		            }
             		            $address_old = $this->_address;
             		            if (Customer::customerHasAddress($this->context->customer->id, (int)$address_old->id)) {
             		                if ($address_old->isUsed()) {
             		                    $address_old->delete();
             		                } else {
             		                    $address->id = (int)$address_old->id;
             		                    $address->date_add = $address_old->date_add;
             		                }
             		            }
             		        }
             
             		        // Save address
             		        if ($result = $address->update())
             		     		Tools::redirect('index.php?controller=my-account&profile=personal');
                             
                         }  
                         else 
                         {
                             $this->errors[] = Tools::displayError('An error occurred while updating your address.');
                         }
                         */
         }
     }
 }
コード例 #17
0
ファイル: Cart.php プロジェクト: dev-lav/htdocs
    public function duplicateProduct($id_product, $id_product_attribute, $id_address_delivery, $new_id_address_delivery, $quantity = 1, $keep_quantity = false)
    {
        // Check address is linked with the customer
        if (!Customer::customerHasAddress(Context::getContext()->customer->id, $new_id_address_delivery)) {
            return false;
        }
        // Checking the product do not exist with the new address
        $sql = new DbQuery();
        $sql->select('count(*)');
        $sql->from('cart_product', 'c');
        $sql->where('id_product = ' . (int) $id_product);
        $sql->where('id_product_attribute = ' . (int) $id_product_attribute);
        $sql->where('id_address_delivery = ' . (int) $new_id_address_delivery);
        $sql->where('id_cart = ' . (int) $this->id);
        $result = Db::getInstance()->getValue($sql);
        if ($result > 0) {
            return false;
        }
        // Duplicating cart_product line
        $sql = 'INSERT INTO ' . _DB_PREFIX_ . 'cart_product
			(`id_cart`, `id_product`, `id_shop`, `id_product_attribute`, `quantity`, `date_add`, `id_address_delivery`)
			values(
				' . (int) $this->id . ',
				' . (int) $id_product . ',
				' . (int) $this->id_shop . ',
				' . (int) $id_product_attribute . ',
				' . (int) $quantity . ',
				NOW(),
				' . (int) $new_id_address_delivery . ')';
        Db::getInstance()->execute($sql);
        if (!$keep_quantity) {
            $sql = new DbQuery();
            $sql->select('quantity');
            $sql->from('cart_product', 'c');
            $sql->where('id_product = ' . (int) $id_product);
            $sql->where('id_product_attribute = ' . (int) $id_product_attribute);
            $sql->where('id_address_delivery = ' . (int) $id_address_delivery);
            $sql->where('id_cart = ' . (int) $this->id);
            $duplicatedQuantity = Db::getInstance()->getValue($sql);
            if ($duplicatedQuantity > $quantity) {
                $sql = 'UPDATE ' . _DB_PREFIX_ . 'cart_product
					SET `quantity` = `quantity` - ' . (int) $quantity . '
					WHERE id_cart = ' . (int) $this->id . '
					AND id_product = ' . (int) $id_product . '
					AND id_shop = ' . (int) $this->id_shop . '
					AND id_product_attribute = ' . (int) $id_product_attribute . '
					AND id_address_delivery = ' . (int) $id_address_delivery;
                Db::getInstance()->execute($sql);
            }
        }
        // Checking if there is customizations
        $sql = new DbQuery();
        $sql->select('*');
        $sql->from('customization', 'c');
        $sql->where('id_product = ' . (int) $id_product);
        $sql->where('id_product_attribute = ' . (int) $id_product_attribute);
        $sql->where('id_address_delivery = ' . (int) $id_address_delivery);
        $sql->where('id_cart = ' . (int) $this->id);
        $results = Db::getInstance()->executeS($sql);
        foreach ($results as $customization) {
            // Duplicate customization
            $sql = 'INSERT INTO ' . _DB_PREFIX_ . 'customization
				(`id_product_attribute`, `id_address_delivery`, `id_cart`, `id_product`, `quantity`, `in_cart`)
				VALUES (
					' . $customization['id_product_attribute'] . ',
					' . $new_id_address_delivery . ',
					' . $customization['id_cart'] . ',
					' . $customization['id_product'] . ',
					' . $quantity . ',
					' . $customization['in_cart'] . ')';
            Db::getInstance()->execute($sql);
            $sql = 'INSERT INTO ' . _DB_PREFIX_ . 'customized_data(`id_customization`, `type`, `index`, `value`)
				(
					SELECT ' . (int) Db::getInstance()->Insert_ID() . ' `id_customization`, `type`, `index`, `value`
					FROM customized_data
					WHERE id_customization = ' . $customization['id_customization'] . '
				)';
            Db::getInstance()->execute($sql);
        }
        $customization_count = count($results);
        if ($customization_count > 0) {
            $sql = 'UPDATE ' . _DB_PREFIX_ . 'cart_product
				SET `quantity` = `quantity` = ' . (int) $customization_count * $quantity . '
				WHERE id_cart = ' . (int) $this->id . '
				AND id_product = ' . (int) $id_product . '
				AND id_shop = ' . (int) $this->id_shop . '
				AND id_product_attribute = ' . (int) $id_product_attribute . '
				AND id_address_delivery = ' . (int) $new_id_address_delivery;
            Db::getInstance()->execute($sql);
        }
        return true;
    }
コード例 #18
0
 /**
  * Process changes on an address
  */
 protected function processSubmitAddress()
 {
     $address = new Address();
     $this->errors = $address->validateController();
     $address->id_customer = (int) $this->context->customer->id;
     // Check page token
     if ($this->context->customer->isLogged() && !$this->isTokenValid()) {
         $this->errors[] = Tools::displayError('Invalid token.');
     }
     // Check phone
     if (Configuration::get('PS_ONE_PHONE_AT_LEAST') && !Tools::getValue('phone') && !Tools::getValue('phone_mobile')) {
         $this->errors[] = Tools::displayError('You must register at least one phone number.');
     }
     if ($address->id_country) {
         // Check country
         if (!($country = new Country($address->id_country)) || !Validate::isLoadedObject($country)) {
             throw new PrestaShopException('Country cannot be loaded with address->id_country');
         }
         // if ((int)$country->contains_states && !(int)$address->id_state)
         // 	$this->errors[] = Tools::displayError('This country requires you to chose a State.');
         if (!$country->active) {
             $this->errors[] = Tools::displayError('This country is not active.');
         }
         // Check country DNI
         if ($country->isNeedDni() && (!Tools::getValue('dni') || !Validate::isDniLite(Tools::getValue('dni')))) {
             $this->errors[] = Tools::displayError('The identification number is incorrect or has already been used.');
         } elseif (!$country->isNeedDni()) {
             $address->dni = null;
         }
     }
     // Check if the alias exists
     if (!$this->context->customer->is_guest && !empty($_POST['alias']) && (int) $this->context->customer->id > 0) {
         $id_address = Tools::getValue('id_address');
         if (Configuration::get('PS_ORDER_PROCESS_TYPE') && (int) Tools::getValue('opc_id_address_' . Tools::getValue('type')) > 0) {
             $id_address = Tools::getValue('opc_id_address_' . Tools::getValue('type'));
         }
         if (Address::aliasExist(Tools::getValue('alias'), (int) $id_address, (int) $this->context->customer->id)) {
             $this->errors[] = sprintf(Tools::displayError('The alias "%s" has already been used. Please select another one.'), Tools::safeOutput(Tools::getValue('alias')));
         }
     }
     // Check the requires fields which are settings in the BO
     $this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());
     // Don't continue this process if we have errors !
     if ($this->errors && !$this->ajax) {
         return;
     }
     // If we edit this address, delete old address and create a new one
     if (Validate::isLoadedObject($this->_address)) {
         if (Validate::isLoadedObject($country) && !$country->contains_states) {
             $address->id_state = 0;
         }
         $address_old = $this->_address;
         if (Customer::customerHasAddress($this->context->customer->id, (int) $address_old->id)) {
             if ($address_old->isUsed()) {
                 $address_old->delete();
             } else {
                 $address->id = (int) $address_old->id;
                 $address->date_add = $address_old->date_add;
             }
         }
     }
     if ($this->ajax && Configuration::get('PS_ORDER_PROCESS_TYPE')) {
         $this->errors = array_unique(array_merge($this->errors, $address->validateController()));
         if (count($this->errors)) {
             $return = array('hasError' => (bool) $this->errors, 'errors' => $this->errors);
             $this->ajaxDie(Tools::jsonEncode($return));
         }
     }
     // Save address
     if ($result = $address->save()) {
         // Update id address of the current cart if necessary
         if (isset($address_old) && $address_old->isUsed()) {
             $this->context->cart->updateAddressId($address_old->id, $address->id);
         } else {
             // Update cart address
             $this->context->cart->autosetProductAddress();
         }
         if ((bool) Tools::getValue('select_address', false) == true || Tools::getValue('type') == 'invoice' && Configuration::get('PS_ORDER_PROCESS_TYPE')) {
             $this->context->cart->id_address_invoice = (int) $address->id;
         } elseif (Configuration::get('PS_ORDER_PROCESS_TYPE')) {
             $this->context->cart->id_address_invoice = (int) $this->context->cart->id_address_delivery;
         }
         $this->context->cart->update();
         if ($this->ajax) {
             $return = array('hasError' => (bool) $this->errors, 'errors' => $this->errors, 'id_address_delivery' => (int) $this->context->cart->id_address_delivery, 'id_address_invoice' => (int) $this->context->cart->id_address_invoice);
             $this->ajaxDie(Tools::jsonEncode($return));
         }
         // Redirect to old page or current page
         if ($back = Tools::getValue('back')) {
             if ($back == Tools::secureReferrer(Tools::getValue('back'))) {
                 Tools::redirect(html_entity_decode($back));
             }
             $mod = Tools::getValue('mod');
             Tools::redirect('index.php?controller=' . $back . ($mod ? '&back=' . $mod : ''));
         } else {
             Tools::redirect('index.php?controller=addresses');
         }
     }
     $this->errors[] = Tools::displayError('An error occurred while updating your address.');
 }
 /**
  * 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);
     }
 }
コード例 #20
0
ファイル: Cart.php プロジェクト: Oldwo1f/yakaboutique
    public function duplicate()
    {
        if (!Validate::isLoadedObject($this)) {
            return false;
        }
        $cart = new Cart($this->id);
        $cart->id = null;
        $cart->id_shop = $this->id_shop;
        $cart->id_shop_group = $this->id_shop_group;
        if (!Customer::customerHasAddress((int) $cart->id_customer, (int) $cart->id_address_delivery)) {
            $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $cart->id_customer);
        }
        if (!Customer::customerHasAddress((int) $cart->id_customer, (int) $cart->id_address_invoice)) {
            $cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $cart->id_customer);
        }
        if ($cart->id_customer) {
            $cart->secure_key = Cart::$_customer->secure_key;
        }
        $cart->add();
        if (!Validate::isLoadedObject($cart)) {
            return false;
        }
        $success = true;
        $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT * FROM `' . _DB_PREFIX_ . 'cart_product` WHERE `id_cart` = ' . (int) $this->id);
        $product_gift = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT cr.`gift_product`, cr.`gift_product_attribute` FROM `' . _DB_PREFIX_ . 'cart_rule` cr LEFT JOIN `' . _DB_PREFIX_ . 'order_cart_rule` ocr ON (ocr.`id_order` = ' . (int) $this->id . ') WHERE ocr.`id_cart_rule` = cr.`id_cart_rule`');
        $id_address_delivery = Configuration::get('PS_ALLOW_MULTISHIPPING') ? $cart->id_address_delivery : 0;
        foreach ($products as $product) {
            if ($id_address_delivery) {
                if (Customer::customerHasAddress((int) $cart->id_customer, $product['id_address_delivery'])) {
                    $id_address_delivery = $product['id_address_delivery'];
                }
            }
            foreach ($product_gift as $gift) {
                if (isset($gift['gift_product']) && isset($gift['gift_product_attribute']) && (int) $gift['gift_product'] == (int) $product['id_product'] && (int) $gift['gift_product_attribute'] == (int) $product['id_product_attribute']) {
                    $product['quantity'] = (int) $product['quantity'] - 1;
                }
            }
            $success &= $cart->updateQty(PP::resolveQty($product['quantity'], $product['quantity_fractional']), (int) $product['id_product'], (int) $product['id_product_attribute'], null, 'up', (int) $id_address_delivery, new Shop((int) $cart->id_shop), false);
        }
        // Customized products
        $customs = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
			SELECT *
			FROM ' . _DB_PREFIX_ . 'customization c
			LEFT JOIN ' . _DB_PREFIX_ . 'customized_data cd ON cd.id_customization = c.id_customization
			WHERE c.id_cart = ' . (int) $this->id);
        // Get datas from customization table
        $customs_by_id = array();
        foreach ($customs as $custom) {
            if (!isset($customs_by_id[$custom['id_customization']])) {
                $customs_by_id[$custom['id_customization']] = array('id_product_attribute' => $custom['id_product_attribute'], 'id_product' => $custom['id_product'], 'quantity' => $custom['quantity'], 'quantity_fractional' => $custom['quantity_fractional']);
            }
        }
        // Insert new customizations
        $custom_ids = array();
        foreach ($customs_by_id as $customization_id => $val) {
            // TODO: update id_cart_product
            Db::getInstance()->execute('
				INSERT INTO `' . _DB_PREFIX_ . 'customization` (id_cart, id_product_attribute, id_product, `id_address_delivery`, quantity, quantity_fractional, `quantity_refunded`, `quantity_returned`, `in_cart`)
				VALUES(' . (int) $cart->id . ', ' . (int) $val['id_product_attribute'] . ', ' . (int) $val['id_product'] . ', ' . (int) $id_address_delivery . ', ' . (int) $val['quantity'] . ', ' . (double) $val['quantity_fractional'] . ', 0, 0, 1)');
            $custom_ids[$customization_id] = Db::getInstance(_PS_USE_SQL_SLAVE_)->Insert_ID();
        }
        // Insert customized_data
        if (count($customs)) {
            $first = true;
            $sql_custom_data = 'INSERT INTO ' . _DB_PREFIX_ . 'customized_data (`id_customization`, `type`, `index`, `value`) VALUES ';
            foreach ($customs as $custom) {
                if (!$first) {
                    $sql_custom_data .= ',';
                } else {
                    $first = false;
                }
                $sql_custom_data .= '(' . (int) $custom_ids[$custom['id_customization']] . ', ' . (int) $custom['type'] . ', ' . (int) $custom['index'] . ', \'' . pSQL($custom['value']) . '\')';
            }
            Db::getInstance()->execute($sql_custom_data);
        }
        return array('cart' => $cart, 'success' => $success);
    }