/**
	 * Returns cart items in a format useful for the
	 * API request
	 *
	 * Also adds discount as a cart item, since this is
	 * how Paypal expects to receive discounts
	 *
	 * @param Cart $cart
	 * @return array
	 */
	private function getItemsFromCart(Cart $cart)
    {
        $items = array();
        foreach($cart->getProducts() as $product)
        {
            $item = new stdClass();
            $item->name = $product->title;
            $item->number = $product->sku;
            $item->description = substr($product->short_description, 0, 127);
            $item->amount = ShopDisplay::numberFormat($product->price);
            $item->quantity = $product->quantity;
            $items[] = $item;
        }

		if($cart->getDiscountAmount() > 0)
		{
			$item = new stdClass();
			$item->name = 'Discount';
			$item->description = $cart->getDiscountName();
			$item->amount = -1 * $cart->getDiscountAmount();
			$item->quantity = 1;
			$items[] = $item;
		}
        return $items;
    }
 public function initContent()
 {
     parent::initContent();
     $params = KwixoURLCallFrontController::ManageUrlCall();
     $payment_ok = $params['payment_status'];
     $errors = $params['errors'];
     $id_order = $params['id_order'];
     if ($id_order != false) {
         $order = new Order($id_order);
         $cart = new Cart($order->id_cart);
         $products = $cart->getProducts();
         $amount = $order->total_paid_tax_incl;
         $total_shipping = $order->total_shipping;
     } else {
         $products = false;
         $amount = false;
         $total_shipping = false;
     }
     $link = new Link();
     $this->context->smarty->assign('payment_ok', $payment_ok);
     $this->context->smarty->assign('errors', $errors);
     $this->context->smarty->assign('amount', $amount);
     $this->context->smarty->assign('total_shipping', $total_shipping);
     $this->context->smarty->assign('products', $products);
     $this->context->smarty->assign('path_order', $link->getPageLink('order', true));
     $this->context->smarty->assign('path_history', $link->getPageLink('history', true));
     $this->context->smarty->assign('path_contact', $link->getPageLink('contact', true));
     $this->setTemplate('urlcall.tpl');
 }
Пример #3
0
 /**
  * @param Request $request
  * @return string
  * @throws Exception
  */
 public function showCartAction(Request $request)
 {
     $cart = new Cart();
     $productsId = $cart->getProducts();
     $args = array('productsId' => $productsId);
     return $this->render('cart', $args);
 }
Пример #4
0
    public static function updateProductsTax(AvalaraTax $avalaraModule, Cart $cart, $id_address, $region, $taxable = true)
    {
        $p = array();
        foreach ($cart->getProducts() as $product) {
            $avalaraProducts = array('id_product' => (int) $product['id_product'], 'name' => $product['name'], 'description_short' => $product['description_short'], 'quantity' => 1, 'total' => (double) 1000000, 'tax_code' => $taxable ? $avalaraModule->getProductTaxCode((int) $product['id_product']) : 'NT');
            $p[] = $avalaraProducts;
            // Call Avalara
            $getTaxResult = $avalaraModule->getTax(array($avalaraProducts), array('type' => 'SalesOrder', 'DocCode' => 1, 'taxable' => $taxable));
            // Store the taxrate in cache
            // If taxrate exists (but it's outdated), then update, else insert (REPLACE INTO)
            if (isset($getTaxResult['TotalTax']) && isset($getTaxResult['TotalAmount'])) {
                $total_tax = $getTaxResult['TotalTax'];
                $total_amount = $getTaxResult['TotalAmount'];
                if ($total_amount == 0) {
                    $db_rate = 0;
                } else {
                    $db_rate = (double) ($total_tax * 100 / $total_amount);
                }
                Db::getInstance()->Execute('REPLACE INTO `' . _DB_PREFIX_ . 'avalara_product_cache` (`id_product`, `tax_rate`, `region`, `update_date`, `id_address`)
				VALUES (' . (int) $product['id_product'] . ', ' . $db_rate . ',
				\'' . ($region ? pSQL($region) : '') . '\', \'' . date('Y-m-d H:i:s') . '\', ' . (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')} . ')');
            }
        }
        return $p;
    }
Пример #5
0
 /**
  * Action для главной страницы
  */
 public function actionIndex()
 {
     // Список категорий для левого меню
     $categories = Category::getCategoriesList();
     // Список последних товаров
     $latestProducts = Product::getLatestProducts(6);
     // Список товаров для слайдера
     $sliderProducts = Product::getRecommendedProducts();
     // Показывыем в корзине информацию о добавленных товарах
     $productsInCart = Cart::getProducts();
     if ($productsInCart) {
         // Если в корзине есть товары, получаем полную информацию о товарах для списка
         // Получаем массив только с идентификаторами товаров
         $productsIds = array_keys($productsInCart);
         // Получаем массив с полной информацией о необходимых товарах
         $products = Product::getProdustsByIds($productsIds);
         // Получаем общую стоимость товаров
         $totalPrice = Cart::getTotalPrice($products);
     }
     // Получаем идентификатор пользователя из сессии
     $userId = $_SESSION['user'];
     // Получаем информацию о пользователе из БД
     $user = User::getUserById($userId);
     // Подключаем вид
     require_once ROOT . '/views/site/index.php';
     return true;
 }
Пример #6
0
 /**
  * Action для страницы "Оформление покупки"
  */
 public function actionCheckout()
 {
     $productsInCart = Cart::getProducts();
     if ($productsInCart == false) {
         header("Location: /");
     }
     $categories = Category::getCategoriesList();
     // Находим общую стоимость
     $productsIds = array_keys($productsInCart);
     $products = Product::getProdustsByIds($productsIds);
     $totalPrice = Cart::getTotalPrice($products);
     // Количество товаров
     $totalQuantity = Cart::countItems();
     $userName = false;
     $userPhone = false;
     $userComment = false;
     $result = false;
     if (!User::isGuest()) {
         // Если пользователь не гость
         // Получаем информацию о пользователе из БД
         $userId = User::checkLogged();
         $user = User::getUserById($userId);
         $userName = $user['name'];
     } else {
         // Если гость, поля формы останутся пустыми
         $userId = false;
     }
     if (isset($_POST['submit'])) {
         $userName = $_POST['userName'];
         $userPhone = $_POST['userPhone'];
         $userComment = $_POST['userComment'];
         // Флаг ошибок
         $errors = false;
         if (!User::checkName($userName)) {
             $errors[] = 'Неправильное имя';
         }
         if (!User::checkPhone($userPhone)) {
             $errors[] = 'Неправильный телефон';
         }
         if ($errors == false) {
             // Если ошибок нет
             // Сохраняем заказ в базе данных
             $result = Order::save($userName, $userPhone, $userComment, $userId, $productsInCart);
             if ($result) {
                 // Если заказ успешно сохранен
                 // Оповещаем администратора о новом заказе по почте
                 $adminEmail = '*****@*****.**';
                 $message = '<a href="localhost/admin/orders">Список заказов</a>';
                 $subject = 'Новый заказ!';
                 mail($adminEmail, $subject, $message);
                 // Очищаем корзину
                 Cart::clear();
             }
         }
     }
     // Подключаем вид
     require_once ROOT . '/views/cart/checkout.php';
     return true;
 }
Пример #7
0
 /**
  * @see		ApplicationView::createUserInterface()
  */
 protected function createUserInterface()
 {
     parent::createUserInterface();
     $this->addStyle('/css/cart.css');
     $resourceBundle = Application::getInstance()->getBundle();
     $products = $this->cart->getProducts();
     if (count($products) == 0) {
         $this->contentPanel->addChild(new Heading(2))->addChild(new Text($resourceBundle->getString('CART_NO_PRODUCT')));
     } else {
         $this->contentPanel->addChild(new CartList())->setProductList($products);
         $totalParagraph = $this->contentPanel->addChild(new Paragraph())->addStyle('cart-total');
         //Total do carrinho
         $totalParagraph->addChild(new Strong())->addChild(new Text($resourceBundle->getString('CART_TOTAL')));
         $totalParagraph->addChild(new Span())->addChild(new Text(money_format($resourceBundle->getString('MONEY_FORMAT'), $this->cart->getTotal())));
         //Botão de checkout
         $totalParagraph->addChild(new Anchor('/?c=cart&a=checkout'))->addStyle('checkout')->addChild(new Text($resourceBundle->getString('CART_CHECKOUT')));
     }
 }
    public function sendCampaign()
    {
        // get abandoned cart :
        $sql = "SELECT * FROM (\n\t\tSELECT\n\t\tCONCAT(LEFT(c.`firstname`, 1), '. ', c.`lastname`) `customer`, a.id_cart total, ca.name carrier, c.id_customer, a.id_cart, a.date_upd,a.date_add,\n\t\t\t\tIF (IFNULL(o.id_order, 'Non ordered') = 'Non ordered', IF(TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', a.`date_add`)) > 86400, 'Abandoned cart', 'Non ordered'), o.id_order) id_order, IF(o.id_order, 1, 0) badge_success, IF(o.id_order, 0, 1) badge_danger, IF(co.id_guest, 1, 0) id_guest\n\t\tFROM `" . _DB_PREFIX_ . "cart` a  \n\t\t\t\tJOIN `" . _DB_PREFIX_ . "customer` c ON (c.id_customer = a.id_customer)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "currency` cu ON (cu.id_currency = a.id_currency)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "carrier` ca ON (ca.id_carrier = a.id_carrier)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "orders` o ON (o.id_cart = a.id_cart)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "connections` co ON (a.id_guest = co.id_guest AND TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', co.`date_add`)) < 1800)\n\t\t) AS toto WHERE id_order='Abandoned cart'";
        $currency = Context::getContext()->currency->sign;
        $defaultLanguage = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
        $abandoned_carts = Db::getInstance()->ExecuteS($sql);
        // get all available campaigns
        $sqlCampaigns = 'SELECT * FROM `' . _DB_PREFIX_ . 'campaign` WHERE active=1';
        $allCampaigns = Db::getInstance()->ExecuteS($sqlCampaigns);
        // loop on all abandoned carts
        foreach ($abandoned_carts as $abncart) {
            // loop on all available campaigns
            foreach ($allCampaigns as $camp) {
                $cartIsOnCampaign = $this->checkIfCartIsOnCampaign($abncart['date_add'], $camp['execution_time_day'], $camp['execution_time_hour']);
                if ($cartIsOnCampaign) {
                    $id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
                    $customer = new Customer($abncart['id_customer']);
                    $cR = new CartRule($camp['id_voucher'], $id_lang);
                    $cart = new Cart($abncart['id_cart']);
                    $products = $cart->getProducts();
                    $campM = new Campaign($camp['id_campaign']);
                    if (!empty($products)) {
                        $cart_content = $campM->getCartContentHeader();
                    } else {
                        $cart_content = '';
                    }
                    foreach ($products as $prod) {
                        $p = new Product($prod['id_product'], true, $id_lang);
                        $price_no_tax = Product::getPriceStatic($p->id, false, null, 2, null, false, true, 1, false, null, $abncart['id_cart'], null, $null, true, true, null, false, false);
                        $total_no_tax = $prod['cart_quantity'] * $price_no_tax;
                        $images = Image::getImages((int) $id_lang, (int) $p->id);
                        $link = new Link();
                        $cart_content .= '<tr >
										<td align="center" ><img src="' . $link->getImageLink($p->link_rewrite, $images[0]['id_image']) . '" width="80"/></td>
										<td align="center" ><a href="' . $link->getProductLink($p) . '"/>' . $p->name . '</a></td>
										<td align="center" >' . Tools::displayprice($price_no_tax) . '</td>
										<td align="center" >' . $prod['cart_quantity'] . '</td>
										<td align="center" >' . Tools::displayprice($total_no_tax) . '</td>
									</tr>';
                    }
                    $tpl_vars = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{coupon_name}' => $cR->name, '{coupon_code}' => $cR->code, '{cart_content}' => $cart_content, '{coupon_value}' => $camp['voucher_amount_type'] == 'percent' ? $cR->reduction_percent . '%' : $currency . $cR->reduction_amount, '{coupon_valid_to}' => date('d/m/Y', strtotime($cR->date_to)), '{campaign_name}' => $camp['name']);
                    $path = _PS_ROOT_DIR_ . '/modules/superabandonedcart/mails/';
                    // send email to customer :
                    Mail::Send($id_lang, $campM->getFileName(), $camp['name'], $tpl_vars, $customer->email, null, null, null, null, null, $path, false, Context::getContext()->shop->id);
                    // Email to admin :
                    Mail::Send($id_lang, $campM->getFileName(), Mail::l(sprintf('Email sent to %s %s for campaign %s', $customer->lastname, $customer->firstname, $camp['name'])), $tpl_vars, Configuration::get('PS_SHOP_EMAIL'), null, null, null, null, null, $path, false, Context::getContext()->shop->id);
                    //	echo 'ID ' . $abncart['id_cart'];
                }
            }
        }
    }
Пример #9
0
 public function actionIndex()
 {
     $catObj = new Category();
     $categories = $catObj->getCategoriesList();
     $productsInCart = Cart::getProducts() ? Cart::getProducts() : false;
     if ($productsInCart) {
         $productIds = array_keys($productsInCart);
         $products = Product::getProductsByIds($productIds);
         $totalPrice = Cart::getTotalPrice($products);
     }
     require_once ROOT . '/views/cart/index.php';
     return true;
 }
Пример #10
0
 private function LoginedAction()
 {
     global $cookie, $smarty;
     if (!isset($cookie->id_cart)) {
         die('Shpping cart is empty!');
     }
     $cart = new Cart((int) $cookie->id_cart);
     $user = new User((int) $cart->id_user);
     $addresses = $user->getAddresses();
     $carriers = Carrier::loadData();
     $payments = PaymentModule::getHookPayment();
     $smarty->assign(array('cart' => $cart, 'addresses' => $addresses, 'carriers' => $carriers, 'payments' => $payments, 'products' => $cart->getProducts(), 'discount' => $cart->discount, 'total' => $cart->getProductTotal()));
 }
Пример #11
0
	/**
	 * Calculates shipping rates
	 *
	 * @param Cart $cart SHipping cart for which to calculate shipping
	 * @param null $service
	 * @internal param \Address $shipping_address Address to which products should be shipped
	 * @return int|mixed
	 */
    public function calculateShipping(Cart $cart, $service = NULL)
    {
        if($this->type == 'per_item')
        {
            $products = $cart->getProducts();
            $total_quantity = 0;
            foreach($products as $product)
                $total_quantity += $product->quantity;
            return $total_quantity * $this->price;
        }

        return $this->price;
    }
 /**
  * @return bool
  * Метод для оформления заказа
  */
 public function actionCheckout()
 {
     $productsInCart = Cart::getProducts();
     if ($productsInCart == false) {
         //Если корзина пустая,пользователь перенаправляется на главную
         header("Location: /");
     }
     $categories = Category::getCategoriesList();
     $productsIds = array_keys($productsInCart);
     $products = Product::getProductsByIds($productsIds);
     $totalPrice = Cart::getTotalPrice($products);
     $totalItems = Cart::countItems();
     //общее кол-во товаров
     $userName = '';
     $userPhone = '';
     $userMessage = '';
     $res = false;
     //флаг успешного оформления заказа
     $fail = '';
     if (!User::isGuest()) {
         $userId = User::isLogged();
         //если пользователь не гость,получаем инфу о нем из БД
         $user = User::getUserById($userId);
         $userName = $user['name'];
     } else {
         $userId = false;
     }
     if (isset($_POST['submit'])) {
         //Если форма отправлена,получаем данные для полей
         $userName = $_POST['userName'];
         $userPhone = $_POST['userPhone'];
         $userMessage = $_POST['userMessage'];
         if (!User::isValidNamePhone($userName, $userPhone)) {
             $fail = 'Номер должен быть больше 9 символов/имя не может быть пустым';
         }
         //Если все ок,записываем заказ в БД
         if ($fail == false) {
             $res = Order::save($userName, $userPhone, $userId, $userMessage, $productsInCart);
             if ($res) {
                 Cart::clearCart();
             }
         }
     }
     $args = array('categories' => $categories, 'productsInCart' => $productsInCart, 'productsIds' => $productsIds, 'products' => $products, 'totalPrice' => $totalPrice, 'totalItems' => $totalItems, 'fail' => $fail, 'res' => $res, 'userName' => $userName, 'userPhone' => $userPhone, 'userMessage' => $userMessage);
     return self::render('checkout', $args);
 }
Пример #13
0
 public function confirmOrder($custom)
 {
     $cart = new Cart((int) $custom['id_cart']);
     $cart_details = $cart->getSummaryDetails(null, true);
     $cart_hash = sha1(serialize($cart->nbProducts()));
     $this->context->cart = $cart;
     $address = new Address((int) $cart->id_address_invoice);
     $this->context->country = new Country((int) $address->id_country);
     $this->context->customer = new Customer((int) $cart->id_customer);
     $this->context->language = new Language((int) $cart->id_lang);
     $this->context->currency = new Currency((int) $cart->id_currency);
     if (isset($cart->id_shop)) {
         $this->context->shop = new Shop($cart->id_shop);
     }
     $this->createLog($cart->getProducts(true));
     $mc_gross = Tools::getValue('mc_gross');
     $total_price = Tools::ps_round($cart_details['total_price'], 2);
     $message = null;
     $result = $this->verify();
     if (strcmp($result, VERIFIED) == 0) {
         if ($mc_gross != $total_price) {
             $payment = (int) Configuration::get('PS_OS_ERROR');
             $message = $this->l('Price payed on paypal is not the same that on PrestaShop.') . '<br />';
         } elseif ($custom['hash'] != $cart_hash) {
             $payment = (int) Configuration::get('PS_OS_ERROR');
             $message = $this->l('Cart changed, please retry.') . '<br />';
         } else {
             $payment = (int) Configuration::get('PS_OS_WS_PAYMENT');
             $message = $this->l('Payment accepted.') . '<br />';
         }
         $customer = new Customer((int) $cart->id_customer);
         $id_order = (int) Order::getOrderByCartId((int) $cart->id);
         $transaction = array('currency' => pSQL(Tools::getValue(CURRENCY)), 'id_invoice' => pSQL(Tools::getValue(ID_INVOICE)), 'id_transaction' => pSQL(Tools::getValue(ID_TRANSACTION)), 'payment_date' => pSQL(Tools::getValue(PAYMENT_DATE)), 'shipping' => (double) Tools::getValue(SHIPPING), 'total_paid' => (double) Tools::getValue(TOTAL_PAID));
         $this->validateOrder($cart->id, $payment, $total_price, $this->displayName, $message, $transaction, $cart->id_currency, false, $customer->secure_key);
         $history = new OrderHistory();
         $history->id_order = (int) $id_order;
         $history->changeIdOrderState((int) $payment, (int) $id_order);
         $history->addWithemail();
         $history->add();
     }
 }
 public function initContent()
 {
     parent::initContent();
     $currency = new Currency((int) $this->context->cart->id_currency);
     $paylater = new Paylater();
     $id_module = $paylater->id;
     if (Tools::getValue('c')) {
         $cart = new Cart((int) Tools::getValue('c'));
         $order_id = Order::getOrderByCartId((int) $cart->id);
         $order = new Order($order_id);
         $cart_products = $cart->getProducts();
         $items = array();
         foreach ($cart_products as $p) {
             $items[] = array('id' => $p['id_product'], 'name' => $p['name'], 'sku' => $p['reference'], 'category' => $p['category'], 'price' => $p['price'], 'quantity' => $p['quantity']);
         }
         $analitics = Configuration::get('PAYLATER_ANALYTICS');
         $this->context->smarty->assign(array('total' => $order->total_paid, 'currency' => $currency, 'currency_iso' => $currency->iso_code, 'id_module' => $id_module, 'id_cart' => $cart, 'order_id' => $order_id, 'shop_name' => Configuration::get('PS_SHOP_NAME'), 'shipping' => $order->total_shipping_tax_excl, 'total_w_tax' => $order->total_paid_tax_excl, 'tax' => $order->total_paid_tax_incl - $order->total_paid_tax_excl, 'items' => $items, 'analitics' => $analitics));
         return $this->setTemplate('confirmation.tpl');
     } else {
         return $this->setTemplate('error.tpl');
     }
 }
Пример #15
0
 public function hookDisplayPayment($params)
 {
     include_once _PS_MODULE_DIR_ . '/bluepay/bluepay_customers.php';
     $cart = new Cart($this->context->cart->id);
     $cart_contents = '';
     foreach ($cart->getProducts() as $product) {
         foreach ($product as $key => $value) {
             if ($key == 'cart_quantity') {
                 $cart_contents .= $value . ' ';
             }
             if ($key == 'name') {
                 $cart_contents .= $value . '|';
             }
         }
     }
     $address = new Address((int) $cart->id_address_invoice);
     $state = new State($address->id_state);
     $cards = array();
     $cards['visa'] = Configuration::get('BP_CARD_TYPES_VISA') == 'on';
     $cards['mastercard'] = Configuration::get('BP_CARD_TYPES_MC') == 'on';
     $cards['discover'] = Configuration::get('BP_CARD_TYPES_DISC') == 'on';
     $cards['amex'] = Configuration::get('BP_CARD_TYPES_AMEX') == 'on';
     $expiration_month = array();
     for ($i = 1; $i < 13; $i++) {
         $expiration_month[$i] = str_pad($i, 2, '0', STR_PAD_LEFT);
     }
     $expiration_year = array();
     for ($i = 13; $i < 25; $i++) {
         $expiration_year[$i] = $i;
     }
     $this->context->smarty->assign(array('payment_type' => Configuration::get('BP_PAYMENT_TYPE'), 'display_logo' => Configuration::get('BP_DISPLAY_LOGO'), 'secret_key' => Configuration::get('BP_SECRET_KEY'), 'account_id' => Configuration::get('BP_ACCOUNT_ID'), 'transaction_type' => Configuration::get('BP_TRANSACTION_TYPE'), 'payment_type' => Configuration::get('BP_PAYMENT_TYPE'), 'mode' => Configuration::get('BP_TRANSACTION_MODE'), 'customer' => $params['cookie']->customer_firstname . ' ' . $params['cookie']->customer_lastname, 'customer_address' => Tools::safeOutput($address->address1 . ' ' . $address->address2), 'customer_city' => Tools::safeOutput($address->city), 'customer_state' => $state->name, 'customer_zip' => Tools::safeOutput($address->postcode), 'customer_email' => $this->context->cookie->email, 'customer_country' => $address->country, 'invoice_id' => (int) $params['cart']->id, 'cards' => $cards, 'this_path' => $this->_path, 'cart' => $cart_contents, 'require_cvv2' => Configuration::get('BP_REQUIRE_CVV2'), 'allow_stored_payments' => Configuration::get('BP_ALLOW_STORED_PAYMENTS'), 'use_iframe' => Configuration::get('BP_CHECKOUT_IFRAME'), 'has_saved_payment_information' => BluePayCustomer::customerHasStoredPayment($params['cookie']->id_customer), 'has_saved_cc_payment_information' => BluePayCustomer::customerHasStoredCCPayment($params['cookie']->id_customer), 'saved_payment_information' => BluePayCustomer::getCustomerById($params['cookie']->id_customer), 'card_expiration_mm' => $expiration_month, 'card_expiration_yy' => $expiration_year, 'ach_account_types' => array('C' => 'Checking', 'S' => 'Savings')));
     if (Configuration::get('BP_CHECKOUT_IFRAME') == 'No') {
         return $this->display(__FILE__, 'views/templates/hook/payment.tpl');
     }
     return $this->display(__FILE__, 'views/templates/hook/payment_iframe.tpl');
 }
Пример #16
0
 public function makePayPalAPIValidation($cookie, $cart, $id_currency, $payerID, $type)
 {
     global $cookie;
     if (!$this->active) {
         return;
     }
     if (!$this->_isPayPalAPIAvailable()) {
         return;
     }
     // Filling-in vars
     $id_cart = (int) $cart->id;
     $currency = new Currency((int) $id_currency);
     $iso_currency = $currency->iso_code;
     $token = $cookie->paypal_token;
     $total = (double) $cart->getOrderTotal(true, PayPal::BOTH);
     $paymentType = Configuration::get('PAYPAL_CAPTURE') == 1 ? 'Authorization' : 'Sale';
     $serverName = urlencode($_SERVER['SERVER_NAME']);
     $bn = $type == 'express' ? 'ECS' : 'ECM';
     $notifyURL = urlencode(PayPal::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/paypal/ipn.php');
     // Getting address
     if (isset($cookie->id_cart) and $cookie->id_cart) {
         $cart = new Cart((int) $cookie->id_cart);
     }
     if (isset($cart->id_address_delivery) and $cart->id_address_delivery) {
         $address = new Address((int) $cart->id_address_delivery);
     }
     $requestAddress = '';
     if (Validate::isLoadedObject($address)) {
         $country = new Country((int) $address->id_country);
         $state = new State((int) $address->id_state);
         $requestAddress = '&SHIPTONAME=' . urlencode($address->company . ' ' . $address->firstname . ' ' . $address->lastname) . '&SHIPTOSTREET=' . urlencode($address->address1 . ' ' . $address->address2) . '&SHIPTOCITY=' . urlencode($address->city) . '&SHIPTOSTATE=' . urlencode($address->id_state ? $state->iso_code : $country->iso_code) . '&SHIPTOCOUNTRYCODE=' . urlencode($country->iso_code) . '&SHIPTOZIP=' . urlencode($address->postcode);
     }
     // Making request
     $request = '&TOKEN=' . urlencode($token) . '&PAYERID=' . urlencode($payerID) . '&PAYMENTACTION=' . $paymentType . '&AMT=' . $total . '&CURRENCYCODE=' . $iso_currency . '&IPADDRESS=' . $serverName . '&NOTIFYURL=' . $notifyURL . '&BUTTONSOURCE=PRESTASHOP_' . $bn . $requestAddress;
     $discounts = (double) $cart->getOrderTotal(true, PayPal::ONLY_DISCOUNTS);
     if ($discounts == 0) {
         $products = $cart->getProducts();
         $amt = 0;
         for ($i = 0; $i < sizeof($products); $i++) {
             $request .= '&L_NAME' . $i . '=' . substr(urlencode($products[$i]['name'] . (isset($products[$i]['attributes']) ? ' - ' . $products[$i]['attributes'] : '') . (isset($products[$i]['instructions']) ? ' - ' . $products[$i]['instructions'] : '')), 0, 127);
             $request .= '&L_AMT' . $i . '=' . urlencode($this->PayPalRound($products[$i]['price']));
             $request .= '&L_QTY' . $i . '=' . urlencode($products[$i]['cart_quantity']);
             $amt += $this->PayPalRound($products[$i]['price']) * $products[$i]['cart_quantity'];
         }
         $shipping = $this->PayPalRound($cart->getOrderShippingCost($cart->id_carrier, false));
         $request .= '&ITEMAMT=' . urlencode($amt);
         $request .= '&SHIPPINGAMT=' . urlencode($shipping);
         $request .= '&TAXAMT=' . urlencode((double) max($this->PayPalRound($total - $amt - $shipping), 0));
     } else {
         $products = $cart->getProducts();
         $description = 0;
         for ($i = 0; $i < sizeof($products); $i++) {
             $description .= ($description == '' ? '' : ', ') . $products[$i]['cart_quantity'] . " x " . $products[$i]['name'] . (isset($products[$i]['attributes']) ? ' - ' . $products[$i]['attributes'] : '') . (isset($products[$i]['instructions']) ? ' - ' . $products[$i]['instructions'] : '');
         }
         $request .= '&ORDERDESCRIPTION=' . urlencode(substr($description, 0, 120));
     }
     // Calling PayPal API
     include_once _PS_MODULE_DIR_ . 'paypal/api/paypallib.php';
     $ppAPI = new PaypalLib();
     $result = $ppAPI->makeCall($this->getAPIURL(), $this->getAPIScript(), 'DoExpressCheckoutPayment', $request);
     $this->_logs = array_merge($this->_logs, $ppAPI->getLogs());
     // Checking PayPal result
     if (!is_array($result) or !sizeof($result)) {
         $this->displayPayPalAPIError($this->l('Authorization to PayPal failed.'), $this->_logs);
     } elseif (!isset($result['ACK']) or strtoupper($result['ACK']) != 'SUCCESS') {
         $this->displayPayPalAPIError($this->l('PayPal return error.'), $this->_logs);
     } elseif (!isset($result['TOKEN']) or $result['TOKEN'] != $cookie->paypal_token) {
         $logs[] = '<b>' . $ppExpress->l('Token given by PayPal is not the same as the cookie token', 'submit') . '</b>';
         $ppExpress->displayPayPalAPIError($ppExpress->l('PayPal return error.', 'submit'), $logs);
     }
     // Making log
     $id_transaction = $result['TRANSACTIONID'];
     if (Configuration::get('PAYPAL_CAPTURE')) {
         $this->_logs[] = $this->l('Authorization for deferred payment granted by PayPal.');
     } else {
         $this->_logs[] = $this->l('Order finished with PayPal!');
     }
     $message = Tools::htmlentitiesUTF8(strip_tags(implode("\n", $this->_logs)));
     // Order status
     switch ($result['PAYMENTSTATUS']) {
         case 'Completed':
             $id_order_state = Configuration::get('PS_OS_PAYMENT');
             break;
         case 'Pending':
             if ($result['PENDINGREASON'] != 'authorization') {
                 $id_order_state = Configuration::get('PS_OS_PAYPAL');
             } else {
                 $id_order_state = (int) Configuration::get('PAYPAL_OS_AUTHORIZATION');
             }
             break;
         default:
             $id_order_state = Configuration::get('PS_OS_ERROR');
     }
     // Call payment validation method
     $this->validateOrder($id_cart, $id_order_state, (double) $cart->getOrderTotal(true, PayPal::BOTH), $this->displayName, $message, array('transaction_id' => $id_transaction, 'payment_status' => $result['PAYMENTSTATUS'], 'pending_reason' => $result['PENDINGREASON']), $id_currency, false, $cart->secure_key);
     // Clean cookie
     unset($cookie->paypal_token);
     // Displaying output
     $order = new Order((int) $this->currentOrder);
     Tools::redirectLink(__PS_BASE_URI__ . 'order-confirmation.php?id_cart=' . (int) $id_cart . '&id_module=' . (int) $this->id . '&id_order=' . (int) $this->currentOrder . '&key=' . $order->secure_key);
 }
Пример #17
0
 /**
  * Calculate additional shipping price sum of each product in order cart
  *
  * @param Cart $cart
  * @param $products
  * @return float
  */
 private function calculateAdditionalShippingCost(Cart $cart, $products)
 {
     $additional_shipping_price = 0;
     $cart_products = empty($products) ? $cart->getProducts() : $products;
     foreach ($cart_products as $product) {
         $additional_shipping_price += (int) $product['cart_quantity'] * (double) $product['additional_shipping_cost'];
     }
     return (double) $additional_shipping_price;
 }
Пример #18
0
    public function hookOrderConfirmation($params)
    {
        global $country_infos;
        $country_infos = array('id_group' => 0, 'id_tax' => 1);
        $cart = new Cart(intval($params['objOrder']->id_cart));
        $products = $cart->getProducts();
        $strproducts = '';
        $i = 0;
        foreach ($products as $product) {
            $strproducts .= 'i' . ++$i . '=' . $product['id_product'] . '&p' . $i . '=' . $product['price'] . '&q' . $i . '=' . $product['quantity'] . '&';
        }
        $strproducts = substr($strproducts, 0, -1);
        return '<script type="text/javascript">
		//<![CDATA[
		document.write(\'<div id="cto_tr_' . Configuration::get('CRITEO_ID_CONVERSION') . '_ac" style="display:none">\\
						<div class="ctoWidgetServer">' . Configuration::get('CRITEO_URL_WIDGET') . '</div>\\
						<div class="ctoDataType">transaction</div>\\
						<div class="ctoParams">wi=' . Configuration::get('CRITEO_ID_CONVERSION') . '&t=' . intval($params['objOrder']->id) . '&s=1&' . rtrim($strproducts, '&') . '</div>\\
						</div>\');
		//]]>
		</script>';
    }
Пример #19
0
require_once '../../config/settings.inc.php';
require_once '../../config/defines.inc.php';
if (_PS_VERSION_ < '1.5') {
    require_once 'KwixoUrlCallFrontController.php';
    $kwixo = new KwixoPayment();
    if (Tools::getValue('token') == Tools::getAdminToken($kwixo->getSiteid() . $kwixo->getAuthkey())) {
        global $smarty;
        //Manage urlcall push, for PS 1.4
        $params = KwixoURLCallFrontController::ManageUrlCall();
        $payment_ok = $params['payment_status'];
        $errors = $params['errors'];
        $id_order = $params['id_order'];
        if ($id_order != false) {
            $order = new Order($id_order);
            $cart = new Cart($order->id_cart);
            $products = $cart->getProducts();
            $amount = $order->total_paid_real;
            $total_shipping = $order->total_shipping;
        } else {
            $products = false;
            $amount = false;
            $total_shipping = false;
        }
        $smarty->assign('payment_ok', $payment_ok);
        $smarty->assign('errors', $errors);
        $smarty->assign('amount', $amount);
        $smarty->assign('products', $products);
        $smarty->assign('total_shipping', $total_shipping);
        $smarty->assign('path_order', __PS_BASE_URI__ . 'order.php');
        $smarty->assign('path_history', __PS_BASE_URI__ . 'history.php');
        $smarty->assign('path_contact', __PS_BASE_URI__ . 'contact-form.php');
Пример #20
0
function sendOrderStatusMail()
{
    // Select all Orders which are not in (4,5,6,10) state
    // Select id_order, payment and is_queued atleast once
    $sql = "select \n                o.id_order, \n                o.payment, \n                position('3' IN group_concat(oh.id_order_state)) as is_queued  \n            from \n                ps_orders o \n            inner join ps_order_history oh \n                on oh.id_order = o.id_order \n            inner join ps_order_history h  \n                on h.id_order = o.id_order \n            inner join \n                (select id_order, max(date_add) max_date_add from ps_order_history group by id_order) t2  \n                    on (h.id_order = t2.id_order and h.date_add = t2.max_date_add) \n            where \n                h.id_order_state not in (4,5,6,10,20,34) \n            group by \n                o.id_order";
    $total_orders = $not_shipped = $in_sourcing = $in_cust = $on_track = 0;
    $result = Db::getInstance()->ExecuteS($sql);
    $reports = array();
    foreach ($result as $order) {
        $total_orders++;
        $id_order = (int) $order['id_order'];
        $payment = (string) $order['payment'];
        $is_queued = (int) $order['is_queued'] === 0 ? false : true;
        if ($payment === 'Bank Wire' && $is_queued === false) {
            continue;
        }
        $order = new Order($id_order);
        $orderHistory = new OrderHistory();
        $orderStateObj = $orderHistory->getLastOrderState($id_order);
        $customer = new Customer($order->id_customer);
        $cart = new Cart($order->id_cart);
        $products = $cart->getProducts();
        $order_placed_date = date_create((string) $order->date_add);
        $actual_expected_shipping_date = date_create((string) $order->actual_expected_shipping_date);
        $current_expected_shipping_date = date_create((string) $order->expected_shipping_date);
        $status_updated_date = date_create((string) $orderStateObj->date_add);
        $curr_date = new Datetime();
        $same_order = false;
        foreach ($products as $product) {
            $reportObject = array();
            $reportObject['id_order'] = $id_order;
            $reportObject["name"] = $product['name'];
            $reportObject["reference"] = $product['reference'];
            $reportObject['customer_name'] = (string) $customer->firstname . ' ' . (string) $customer->lastname;
            $reportObject['email'] = (string) $customer->email;
            $reportObject['total_paid'] = (double) $order->total_paid;
            $reportObject['order_state'] = (string) $orderStateObj->name;
            $reportObject['order_placed_date'] = (string) $order_placed_date->format('Y-m-d');
            $reportObject['actual_expected_shipping_date'] = (string) $actual_expected_shipping_date->format('Y-m-d');
            $reportObject['current_expected_shipping_date'] = (string) $current_expected_shipping_date->format('Y-m-d');
            $reportObject['status_updated_date'] = (string) $status_updated_date->format('Y-m-d');
            $reportObject['flags'] = array();
            if ($actual_expected_shipping_date < $curr_date || $current_expected_shipping_date < $curr_date) {
                if (!$same_order) {
                    $not_shipped++;
                }
                array_push($reportObject['flags'], "not shipped");
            }
            if ($reportObject['order_state'] === 'Customization in Progress' && $status_updated_date->add(new DateInterval('P5D')) < $curr_date) {
                if (!$same_order) {
                    $in_cust++;
                }
                array_push($reportObject['flags'], "> 5days in cust");
            }
            //(DATEDIFF(o.expected_shipping_date, o.date_add)/2 > DATEDIFF(o.expected_shipping_date, t1.date_add))
            if ($reportObject['order_state'] === 'Sourcing in Progress') {
                $sourcing_flag = false;
                if ($current_expected_shipping_date > $curr_date) {
                    $total_days_avail = (int) $current_expected_shipping_date->diff($order_placed_date)->days;
                    $curr_days_avail = (int) $curr_date->diff($current_expected_shipping_date)->days;
                    if ($total_days_avail / 2 > $curr_days_avail) {
                        $sourcing_flag = true;
                    }
                } else {
                    $sourcing_flag = true;
                }
                if ($sourcing_flag) {
                    if (!$same_order) {
                        $in_sourcing++;
                    }
                    array_push($reportObject['flags'], "in sourcing");
                }
            }
            if (empty($reportObject['flags'])) {
                if (!$same_order) {
                    $on_track++;
                }
                $reportObject['flags'] = 'on track';
            } else {
                $reportObject['flags'] = implode(",", $reportObject['flags']);
            }
            array_push($reports, $reportObject);
            $same_order = true;
        }
    }
    $headers = array(array("order_id", "40px"), array("pname", "100px"), array("pcode", "40px"), array("customer_name", "100px"), array("customer_email", "100px"), array("total_paid", "40px"), array("current_status", "100px"), array("placed_date", "50px"), array("original_shipping_date", "50px"), array("current_shipping_date", "50px"), array("order_status_updated_date", "50px"), array("urgency_level", "40px"));
    global $smarty;
    $smarty->assign("headers", $headers);
    $smarty->assign("total_orders", $total_orders);
    $smarty->assign("not_shipped", $not_shipped);
    $smarty->assign("in_cust", $in_cust);
    $smarty->assign("in_sourcing", $in_sourcing);
    $smarty->assign("on_track", $on_track);
    $smarty->assign("result", $reports);
    $line = '';
    foreach ($headers as $header) {
        $value = str_replace('"', '""', $header[0]);
        $value = '"' . $value . '"' . ",";
        $line .= $value;
    }
    $data = trim($line) . "\n";
    foreach ($reports as $row) {
        $line = '';
        foreach ($row as $value) {
            if (!isset($value) || $value == "") {
                $value = ",";
            } else {
                $value = str_replace('"', '""', $value);
                $value = '"' . $value . '"' . ",";
            }
            $line .= $value;
        }
        $data .= trim($line) . "\n";
    }
    $data = str_replace("\r", "", $data);
    if ($data == "") {
        $data = "\nNo Records Found!\n";
    }
    $fileAttachment['content'] = $data;
    $fileAttachment['name'] = 'IndusdivaOrderDailyStatus' . date("d-m-Y") . '.csv';
    $fileAttachment['mime'] = 'text/csv';
    $templateVars = array();
    $templateVars['{today_date}'] = date('d-m-y');
    $templateVars['{report_summary}'] = $smarty->fetch(_PS_THEME_DIR_ . 'order-daily-summary.tpl');
    $templateVars['{report_content}'] = $smarty->fetch(_PS_THEME_DIR_ . 'order-daily-status.tpl');
    $to = array('*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**');
    $subject = "Order Daily Status - " . date('d-m-y');
    @Mail::Send(1, 'order_daily_status', $subject, $templateVars, $to, null, '*****@*****.**', 'Indusdiva.com', $fileAttachment, NULL, _PS_MAIL_DIR_, false);
}
 /**
  * @param Cart $cart
  * @param $dp
  *
  * @return bool
  *
  * @author Panagiotis Vagenas <*****@*****.**>
  * @since ${VERSION}
  */
 public function packageShippingCost(Cart $cart, $dp)
 {
     $addressObj = new Address($cart->id_address_delivery);
     if ($addressObj->country != 'Greece' && $addressObj->country != 'Ελλάδα') {
         return false;
     }
     $weight = 0;
     $volume = 0;
     /* @var Product $product */
     foreach ($cart->getProducts() as $product) {
         $weight += $product['weight'] > 0 ? $product['weight'] : 0.1;
         if (is_numeric($product['width']) && is_numeric($product['height']) && is_numeric($product['depth'])) {
             $value = $product['width'] * $product['height'] * $product['depth'] / 5000;
             $volume += $value > 0 ? $value : 0.1;
         }
     }
     $address = array('street' => $addressObj->address1 . ($addressObj->address2 ? $addressObj->address2 : ''), 'number' => null, 'pc' => $addressObj->postcode, 'area' => $addressObj->city);
     $soap = \acsws\classes\ACSWS::getInstance();
     if ($dp && !$soap->isDisprosito($address)) {
         return false;
     }
     $stationId = $soap->getStationIdFromAddress($address);
     if (!$stationId) {
         return false;
     }
     $price = $soap->getPrice('ΑΘ', $stationId, max($weight, $volume), false, $dp ? \acsws\classes\Defines::$_prod_Disprosita : false);
     return $price;
 }
Пример #22
0
} else {
    $shippingAddress = new Address((int) $cart->id_address_delivery);
    $shippingCountry = new Country((int) $shippingAddress->id_country);
    $shippingState = NULL;
    if ($shippingAddress->id_state) {
        $shippingState = new State((int) $shippingAddress->id_state);
    }
}
$customer = new Customer((int) $cart->id_customer);
$business = Configuration::get('PAYPAL_BUSINESS');
$header = Configuration::get('PAYPAL_HEADER');
$currency_order = new Currency((int) $cart->id_currency);
$currency_module = $paypal->getCurrency((int) $cart->id_currency);
if (empty($business) or !Validate::isEmail($business)) {
    die($paypal->getL('Paypal error: (invalid or undefined business account email)'));
}
if (!Validate::isLoadedObject($billingAddress) or !Validate::isLoadedObject($shippingAddress) or !Validate::isLoadedObject($customer) or !Validate::isLoadedObject($currency_module)) {
    die($paypal->getL('Paypal error: (invalid address or customer)'));
}
// check currency of payment
if ($currency_order->id != $currency_module->id) {
    $cookie->id_currency = $currency_module->id;
    $cart->id_currency = $currency_module->id;
    $cart->update();
}
$smarty->assign(array('redirect_text' => $paypal->getL('Please wait, redirecting to Paypal... Thanks.'), 'cancel_text' => $paypal->getL('Cancel'), 'cart_text' => $paypal->getL('My cart'), 'return_text' => $paypal->getL('Return to shop'), 'paypal_url' => $paypal->getPaypalIntegralEvolutionUrl(), 'billing_address' => $billingAddress, 'billing_country' => $billingCountry, 'billing_state' => $billingState, 'shipping_address' => $shippingAddress, 'shipping_country' => $shippingCountry, 'shipping_state' => $shippingState, 'amount' => (double) $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), 'customer' => $customer, 'total' => (double) $cart->getOrderTotal(true, Cart::BOTH), 'shipping' => Tools::ps_round((double) $cart->getOrderShippingCost() + (double) $cart->getOrderTotal(true, Cart::ONLY_WRAPPING), 2), 'discount' => $cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS), 'business' => $business, 'currency_module' => $currency_module, 'cart_id' => (int) $cart->id . '_' . pSQL($cart->secure_key), 'products' => $cart->getProducts(), 'paypal_id' => (int) $paypal->id, 'header' => $header, 'template' => 'Template' . Configuration::get('PAYPAL_TEMPLATE'), 'url' => Tools::getShopDomain(true, true) . __PS_BASE_URI__, 'paymentaction' => Configuration::get('PAYPAL_CAPTURE') ? 'authorization' : 'sale'));
if (is_file(_PS_THEME_DIR_ . 'modules/paypal/integral_evolution/redirect.tpl')) {
    $smarty->display(_PS_THEME_DIR_ . 'modules/' . $paypal->name . '/integral_evolution/redirect.tpl');
} else {
    $smarty->display(_PS_MODULE_DIR_ . $paypal->name . '/integral_evolution/redirect.tpl');
}
Пример #23
0
$paypal = new Paypal();
$cart = new Cart((int) $cookie->id_cart);
$address = new Address((int) $cart->id_address_delivery);
$country = new Country((int) $address->id_country);
$state = NULL;
if ($address->id_state) {
    $state = new State((int) $address->id_state);
}
$customer = new Customer((int) $cart->id_customer);
$business = Configuration::get('PAYPAL_BUSINESS');
$header = Configuration::get('PAYPAL_HEADER');
$currency_order = new Currency((int) $cart->id_currency);
$currency_module = $paypal->getCurrency((int) $cart->id_currency);
if (empty($business) or !Validate::isEmail($business)) {
    die($paypal->getL('Paypal error: (invalid or undefined business account email)'));
}
if (!Validate::isLoadedObject($address) or !Validate::isLoadedObject($customer) or !Validate::isLoadedObject($currency_module)) {
    die($paypal->getL('Paypal error: (invalid address or customer)'));
}
// check currency of payment
if ($currency_order->id != $currency_module->id) {
    $cookie->id_currency = $currency_module->id;
    $cart->id_currency = $currency_module->id;
    $cart->update();
}
$smarty->assign(array('redirect_text' => $paypal->getL('Please wait, redirecting to Paypal... Thanks.'), 'cancel_text' => $paypal->getL('Cancel'), 'cart_text' => $paypal->getL('My cart'), 'return_text' => $paypal->getL('Return to shop'), 'paypal_url' => $paypal->getPaypalStandardUrl(), 'address' => $address, 'country' => $country, 'state' => $state, 'amount' => (double) $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), 'customer' => $customer, 'total' => (double) $cart->getOrderTotal(true, Cart::BOTH), 'shipping' => Tools::ps_round((double) $cart->getOrderShippingCost() + (double) $cart->getOrderTotal(true, Cart::ONLY_WRAPPING), 2), 'discount' => $cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS), 'business' => $business, 'currency_module' => $currency_module, 'cart_id' => (int) $cart->id . '_' . pSQL($cart->secure_key), 'products' => $cart->getProducts(), 'paypal_id' => (int) $paypal->id, 'header' => $header, 'url' => Tools::getShopDomain(true, true) . __PS_BASE_URI__));
if (is_file(_PS_THEME_DIR_ . 'modules/paypal/standard/redirect.tpl')) {
    $smarty->display(_PS_THEME_DIR_ . 'modules/' . $paypal->name . '/standard/redirect.tpl');
} else {
    $smarty->display(_PS_MODULE_DIR_ . $paypal->name . '/standard/redirect.tpl');
}
Пример #24
0
 /**
  * To track transactions
  */
 public function hookOrderConfirmation($params)
 {
     $order = $params['objOrder'];
     if (Validate::isLoadedObject($order) && $order->getCurrentState() != (int) Configuration::get('PS_OS_ERROR')) {
         $ga_order_sent = Db::getInstance()->getValue('SELECT id_order FROM `' . _DB_PREFIX_ . 'ganalytics` WHERE id_order = ' . (int) $order->id);
         if ($ga_order_sent === false) {
             Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'ganalytics` (id_order, id_shop, sent, date_add) VALUES (' . (int) $order->id . ', ' . (int) $this->context->shop->id . ', 0, NOW())');
             if ($order->id_customer == $this->context->cookie->id_customer) {
                 $order_products = array();
                 $cart = new Cart($order->id_cart);
                 foreach ($cart->getProducts() as $order_product) {
                     $order_products[] = $this->wrapProduct($order_product, array(), 0, true);
                 }
                 $transaction = array('id' => $order->id, 'affiliation' => version_compare(_PS_VERSION_, '1.5', '>=') && Shop::isFeatureActive() ? $this->context->shop->name : Configuration::get('PS_SHOP_NAME'), 'revenue' => $order->total_paid, 'shipping' => $order->total_shipping, 'tax' => $order->total_paid_tax_incl - $order->total_paid_tax_excl, 'url' => $this->context->link->getModuleLink('ganalytics', 'ajax', array(), true), 'customer' => $order->id_customer);
                 $ga_scripts = $this->addTransaction($order_products, $transaction);
                 $this->js_state = 1;
                 return $this->_runJs($ga_scripts);
             }
         }
     }
 }
 private function hasCartVirtualProduct(Cart $cart)
 {
     $products = $cart->getProducts();
     if (!count($products)) {
         return false;
     }
     foreach ($products as $product) {
         if ($product['is_virtual']) {
             return true;
         }
     }
     return false;
 }
Пример #26
0
$module_name = 'sharezblock';
$module_active = false;
if (Module::isInstalled($module_name) && ($module_instance = Module::getInstanceByName($module_name)) && $module_instance->active) {
    $module_active = true;
}
if (!$module_active) {
    exit;
}
// флаг для обозначения проверки правил аукциона при попытки добавить аукционный товар в корзину
$check_share = Tools::getvalue('check_share');
if (!is_numeric($check_share) || !array_key_exists((int) $check_share, $module_instance->quantity_prop)) {
    exit;
}
$cart = new Cart((int) Tools::getvalue('id_cart'));
$total = $cart->getOrderTotal(true, $cart::ONLY_PRODUCTS);
$res = $cart->getProducts(true);
$id_share_product = (int) Tools::getvalue('id_share_product');
$id_sal_product = (int) Tools::getvalue('id_sal_product');
if ((int) Tools::getvalue('check_price')) {
    $price = (double) Tools::getvalue('price');
    if ($total > 0 && $total >= $price) {
        if ($module_instance::findProductInProductsArray($res, $id_share_product)) {
            echo '0';
        } else {
            echo '1';
        }
        // позволить добавить товар
        exit;
    } elseif ($total < $price) {
        echo '6';
        // не набрана сумма заказа для бесплатного товара
Пример #27
0
    public function updateOrderStatus($idOrder, $refresh = false)
    {
        $order = new Order($idOrder);
        if (!$order->id) {
            return false;
        }
        $address = new Address($order->id_address_delivery);
        $customer = new Customer($order->id_customer);
        $carrier = new Carrier($order->id_carrier);
        $cart = new Cart($order->id_cart);
        $products = $cart->getProducts();
        $packageList = array();
        foreach ($products as $product) {
            $packageList[] = array('code' => !empty($product['reference']) ? pSQL($product['reference']) : (int) $product['id_product_attribute'], 'quantity' => (int) $product['cart_quantity']);
        }
        switch ($order->id_carrier) {
            default:
            case Configuration::get('SHIPWIRE_GD'):
                $shippingType = 'GD';
                break;
            case Configuration::get('SHIPWIRE_1D'):
                $shippingType = '1D';
                break;
            case Configuration::get('SHIPWIRE_2D'):
                $shippingType = '2D';
                break;
            case Configuration::get('SHIPWIRE_INTL'):
                $shippingType = 'INTL';
                break;
        }
        $this->_shipWireOrder->addOrder(array('orderId' => $order->id, 'name' => $customer->firstname . '.' . $customer->lastname, 'address1' => $address->address1, 'address2' => $address->address2, 'city' => $address->city, 'country' => $address->country, 'zip' => $address->postcode, 'phone' => $address->phone, 'mail' => $customer->email, 'shippingType' => $shippingType, 'packageList' => $packageList), $refresh);
        $r = $this->_shipWireOrder->sendData();
        if ($r['Status']) {
            $this->_displayConfirmation($this->l('An error occured on the remote server: ') . $r['ErrorMessage'], 'error');
        }
        if (isset($r['OrderInformation'])) {
            foreach ($r['OrderInformation'] as $o) {
                if ($o['@attributes']['number'] != $order->id) {
                    $this->_displayConfirmation($this->l('An unkown error occured with order Id.'), 'error');
                }
                //$val = Db::getInstance()->getValue('SELECT `transaction_ref` FROM `'._DB_PREFIX_.'shipwire_order`
                //										WHERE `id_order` = '.(int)$order->id);
                $orderExists = Db::getInstance()->ExecuteS('SELECT `id_order` FROM `' . _DB_PREFIX_ . 'shipwire_order`
															WHERE `id_order` = ' . (int) $order->id . ' LIMIT 1');
                if (isset($orderExists[0]['id_order']) && $orderExists[0]['id_order']) {
                    Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'shipwire_order`
										SET `transaction_ref` = \'' . pSQL($o['@attributes']['id']) . '\',
										`order_ref` = \'' . pSQL($o['@attributes']['number']) . '\',
										`status` = \'' . pSQL($o['@attributes']['status']) . '\'
										WHERE `id_order` = ' . (int) $order->id);
                } else {
                    Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'shipwire_order`
					(`id_order`, `transaction_ref`, `status`, `id_shop`, `id_group_shop`)
					VALUES (
					\'' . pSQL($order->id) . '\'' . (isset($o['id']) ? ',\'' . pSQL($o['id']) . '\'' : ',\'\'') . (isset($o['status']) ? ',\'' . pSQL($o['status']) . '\'' : ',\'\'') . (isset($this->context->shop->id_group_shop) ? ',\'' . (int) $this->context->shop->id_group_shop . '\'' : ',\'\'') . (isset($this->context->shop->id) ? ',\'' . (int) $this->context->shop->id . '\'' : ',\'\'') . '
					)');
                }
                $this->log((int) $order->id, $o['@attributes']['id']);
            }
        }
        return true;
    }
Пример #28
0
$address = new Address(intval($cart->id_address_invoice));
$country = new Country(intval($address->id_country));
$state = NULL;
if ($address->id_state) {
    $state = new State(intval($address->id_state));
}
$customer = new Customer(intval($cart->id_customer));
$affilie = Configuration::get('SMT_AFFILIE');
$currency_order = new Currency(intval($cart->id_currency));
$currency_module = $currency_order;
$Value = floatval($cart->getOrderTotal(true, 3));
$decimals = log10(abs($Value));
$decimals = -(intval(min($decimals, 0)) - 3);
$format = "%." . $decimals . "f";
$amount = sprintf($format, $Value);
if (!Validate::isLoadedObject($address) or !Validate::isLoadedObject($customer)) {
    die($smt->l('Erreur de paiement : Addresse ou Client inconnu'));
}
$ref = $cart->id + 22002;
$randNumber = rand(999, 100000);
$ref = "CMD" . $ref . "TN-" . $randNumber;
$smarty->assign(array('reference' => $ref, 'redirect_text' => $smt->l('Veuillez patienter nous allons vous rediriger vers le serveur de paiement... Merci.'), 'cancel_text' => $smt->l('Annuler'), 'cart_text' => $smt->l('Mon panier'), 'return_text' => $smt->l('Retour &agrave; la boutique'), 'smt_url' => $smt->getSMTUrl(), 'address' => $address, 'country' => $country, 'state' => $state, 'amount' => $amount, 'customer' => $customer, 'sid' => $customer->secure_key, 'total' => floatval($cart->getOrderTotal(true, 3)), 'shipping' => Tools::ps_round(floatval($cart->getOrderShippingCost()) + floatval($cart->getOrderTotal(true, 6)), 2), 'discount' => $cart->getOrderTotal(true, 2), 'affilie' => $affilie, 'currency_module' => $currency_module, 'cart_id' => intval($cart->id), 'products' => $cart->getProducts(), 'smt_id' => intval($smt->id), 'url' => Tools::getHttpHost(false, true) . __PS_BASE_URI__));
/*

			<input type="hidden" name="return" value="http://{$url}order-confirmation.php?key={$customer->secure_key}&id_cart={$cart_id}&id_module={$paypal_id}&slowvalidation" />
*/
if (is_file(_PS_THEME_DIR_ . 'modules/smtsps/redirect.tpl')) {
    $smarty->display(_PS_THEME_DIR_ . 'modules/' . $smt->name . '/redirect.tpl');
} else {
    $smarty->display(_PS_MODULE_DIR_ . $smt->name . '/redirect.tpl');
}
Пример #29
0
 /**
  * Set the values of the fields that will be exported
  *
  * @param array $kiala_order content of the KialaOrder object
  * @return array|bool fields to be exported or false
  */
 public function initRecordData($kiala_order, $dspid)
 {
     if (!Validate::isLoadedObject($kiala_order)) {
         return false;
     }
     $order = new Order($kiala_order->id_order);
     $cart = new Cart($order->id_cart);
     $customer = new Customer($kiala_order->id_customer);
     $address = new Address($order->id_address_delivery);
     if (!Validate::isLoadedObject($order) || !Validate::isLoadedObject($customer) || !Validate::isLoadedObject($address)) {
         return false;
     }
     $products = $cart->getProducts();
     $width = 1;
     $height = 1;
     $depth = 1;
     foreach ($products as $product) {
         $width = $width < $product['width'] ? $product['width'] : $width;
         $height = $height < $product['height'] ? $product['height'] : $height;
         $depth = $depth < $product['depth'] ? $product['depth'] : $depth;
     }
     // volume in liters
     $volume = $width * $height * $depth / 1000;
     if ($volume < 1) {
         $volume = 1;
     }
     $prefix = Configuration::get('KIALA_NUMBER_PREFIX');
     $fields = array();
     $fields['partnerId']['value'] = $dspid;
     // Parcel information
     $fields['parcelBarcode']['value'] = '';
     $fields['parcelNumber']['value'] = $prefix . $kiala_order->id;
     $fields['orderNumber']['value'] = $prefix . $kiala_order->id;
     $fields['orderDate']['value'] = $this->formatDate($order->date_add);
     $fields['invoiceNumber']['value'] = $order->invoice_number ? $order->invoice_number : '';
     $fields['invoiceDate']['value'] = $this->formatDate($order->invoice_date);
     $fields['shipmentNumber']['value'] = '';
     // @todo Need to check currency = EUR
     if ($order->module == 'cashondelivery') {
         $cod_amount = $order->total_paid;
     } else {
         $cod_amount = '0';
     }
     $fields['CODAmount']['value'] = sprintf('%.2f', $cod_amount);
     $fields['CODCurrency']['value'] = 'EUR';
     $fields['commercialValue']['value'] = sprintf('%.2f', $kiala_order->commercialValue);
     $fields['commercialCurrency']['value'] = 'EUR';
     $fields['parcelWeight']['value'] = sprintf('%.3f', $order->getTotalWeight());
     $fields['parcelVolume']['value'] = sprintf('%.3f', $volume);
     $fields['parcelDescription']['value'] = $kiala_order->parcelDescription;
     // Point information
     $fields['kialaPoint']['value'] = $kiala_order->point_short_id;
     $fields['backupKialaPoint']['value'] = '';
     // Recipient information
     $fields['customerId']['value'] = $customer->id;
     $fields['customerName']['value'] = $customer->lastname;
     $fields['customerFirstName']['value'] = $customer->firstname;
     switch ($customer->id_gender) {
         case '1':
             $title = $this->kiala_instance->l('Mr.');
             break;
         case '2':
             $title = $this->kiala_instance->l('Ms.');
             break;
         default:
             $title = '';
     }
     $fields['customerTitle']['value'] = $title;
     $fields['customerExtraAddressLine']['value'] = $address->address2;
     $fields['customerStreet']['value'] = $address->address1;
     $fields['customerStreetNumber']['value'] = '';
     $fields['customerLocality']['value'] = State::getNameById($address->id_state);
     $fields['customerZip']['value'] = $address->postcode;
     $fields['customerCity']['value'] = $address->city;
     $fields['customerCountry']['value'] = Country::getIsoById($address->id_country);
     $fields['customerLanguage']['value'] = strtolower(Language::getIsoById($order->id_lang));
     $fields['positiveNotificationRequested']['value'] = 'Y';
     $fields['customerPhone1']['value'] = $address->phone;
     $fields['customerPhone2']['value'] = $address->phone_mobile;
     $fields['customerPhone3']['value'] = '';
     $fields['customerEmail1']['value'] = $customer->email;
     $fields['customerEmail2']['value'] = '';
     $fields['customerEmail3']['value'] = '';
     return $fields;
 }
Пример #30
0
    public function sendCampaign()
    {
        // get abandoned cart :
        $sql = "SELECT * FROM (\n\t\tSELECT\n\t\tCONCAT(LEFT(c.`firstname`, 1), '. ', c.`lastname`) `customer`, a.id_cart total, ca.name carrier, c.id_customer, a.id_cart, a.date_upd,a.date_add,\n\t\t\t\tIF (IFNULL(o.id_order, 'Non ordered') = 'Non ordered', IF(TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', a.`date_add`)) > 86000, 'Abandoned cart', 'Non ordered'), o.id_order) id_order, IF(o.id_order, 1, 0) badge_success, IF(o.id_order, 0, 1) badge_danger, IF(co.id_guest, 1, 0) id_guest\n\t\tFROM `" . _DB_PREFIX_ . "cart` a  \n\t\t\t\tJOIN `" . _DB_PREFIX_ . "customer` c ON (c.id_customer = a.id_customer)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "currency` cu ON (cu.id_currency = a.id_currency)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "carrier` ca ON (ca.id_carrier = a.id_carrier)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "orders` o ON (o.id_cart = a.id_cart)\n\t\t\t\tLEFT JOIN `" . _DB_PREFIX_ . "connections` co ON (a.id_guest = co.id_guest AND TIME_TO_SEC(TIMEDIFF('" . date('Y-m-d H:i:s') . "', co.`date_add`)) < 1800)\n\t\t\t\tWHERE a.date_add > (NOW() - INTERVAL 60 DAY) ORDER BY a.id_cart DESC \n\t\t) AS toto WHERE id_order='Abandoned cart'";
        $currency = Context::getContext()->currency->sign;
        $defaultLanguage = new Language((int) Configuration::get('PS_LANG_DEFAULT'));
        $abandoned_carts = Db::getInstance()->ExecuteS($sql);
        // get all available campaigns
        $sqlCampaigns = 'SELECT * FROM `' . _DB_PREFIX_ . 'campaign` WHERE active=1';
        $allCampaigns = Db::getInstance()->ExecuteS($sqlCampaigns);
        if (!$allCampaigns || empty($allCampaigns)) {
            die('NO CAMPAIGN');
        }
        // loop on all abandoned carts
        foreach ($abandoned_carts as $abncart) {
            if (Cart::getNbProducts((int) $abncart['id_cart']) > 0) {
                $emailsSent = 0;
                // loop on all available campaigns
                foreach ($allCampaigns as $camp) {
                    if (DEBUG_SAC) {
                        echo 'IdCustomer : ' . $abncart['id_customer'] . ' - IdCart : ' . $abncart['id_cart'] . '<br/>';
                    }
                    $cartIsOnCampaign = $this->checkIfCartIsOnCampaign($abncart['date_add'], $camp['execution_time_day'], $camp['execution_time_hour']);
                    if ($cartIsOnCampaign) {
                        if (DEBUG_SAC) {
                            echo 'Cart on campaign</br>';
                        }
                        $id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
                        $customer = new Customer($abncart['id_customer']);
                        $cart = new Cart($abncart['id_cart']);
                        $products = $cart->getProducts();
                        $tpl_vars = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{campaign_name}' => $camp['name'], '{track_url}' => $this->getBaseURL() . '?id_cart=' . (int) $abncart['id_cart'] . '&id_customer=' . (int) $abncart['id_customer'], '{track_request}' => '?id_cart=' . (int) $abncart['id_cart'] . '&id_customer=' . (int) $abncart['id_customer']);
                        $campM = new Campaign($camp['id_campaign']);
                        if ($campM->voucher_amount && $campM->voucher_day && $campM->voucher_amount_type) {
                            $campM->clean_old_reduction($campM->voucher_prefix);
                            $customerVoucher = $campM->registerDiscount($customer->id, $campM->voucher_amount, $campM->voucher_day, $campM->voucher_amount_type, $campM->voucher_prefix);
                            $tpl_vars['{coupon_name}'] = $customerVoucher->name;
                            $tpl_vars['{coupon_code}'] = $customerVoucher->code;
                            $tpl_vars['{coupon_value}'] = $camp['voucher_amount_type'] == 'percent' ? $customerVoucher->reduction_percent . '%' : Tools::displayprice($customerVoucher->reduction_amount);
                            $tpl_vars['{coupon_valid_to}'] = date('d/m/Y', strtotime($customerVoucher->date_to));
                        }
                        if (!empty($products)) {
                            $cart_content = $campM->getCartContentHeader();
                        } else {
                            $cart_content = '';
                        }
                        foreach ($products as $prod) {
                            $p = new Product($prod['id_product'], true, $id_lang);
                            $price_no_tax = Product::getPriceStatic($p->id, false, null, 2, null, false, true, 1, false, null, $abncart['id_cart'], null, $null, true, true, null, false, false);
                            $total_no_tax = $prod['cart_quantity'] * $price_no_tax;
                            $images = Image::getImages((int) $id_lang, (int) $p->id);
                            $link = new Link();
                            $cart_content .= '<tr>
											<td align="center" ><img src="' . Tools::getShopProtocol() . $link->getImageLink($p->link_rewrite, $images[0]['id_image']) . '" width="80"/></td>
											<td align="center" ><a href="' . $link->getProductLink($p) . '?id_cart=' . (int) $abncart['id_cart'] . '&id_customer=' . (int) $abncart['id_customer'] . '"/>' . $p->name . '</a></td>
											<td align="center" >' . Tools::displayprice($price_no_tax) . '</td>
											<td align="center" >' . $prod['cart_quantity'] . '</td>
											<td align="center" >' . Tools::displayprice($total_no_tax) . '</td>
										</tr>';
                        }
                        $cart_content .= '</table>';
                        $tpl_vars['{cart_content}'] = $cart_content;
                        $path = _PS_ROOT_DIR_ . '/modules/superabandonedcart/mails/';
                        // send email to customer :
                        $mailUser = Mail::Send($id_lang, $campM->getFileName(), $camp['name'], $tpl_vars, $customer->email, null, null, null, null, null, $path, false, Context::getContext()->shop->id);
                        // if mail user is successfully sent :
                        if ($mailUser) {
                            $history = new CampaignHistory();
                            $history->id_campaign = (int) $camp['id_campaign'];
                            $history->id_customer = $abncart['id_customer'];
                            $history->id_cart = $abncart['id_cart'];
                            $history->id_cart_rule = isset($customerVoucher->id) ? $customerVoucher->id : 0;
                            $history->click = 0;
                            $history->converted = 0;
                            $history->date_update = date('Y-m-d H:i:s', time());
                            $history->save();
                            // Email to admin :
                            Mail::Send($id_lang, $campM->getFileName(), Mail::l(sprintf('Email sent to %s %s for campaign %s', $customer->lastname, $customer->firstname, $camp['name'])), $tpl_vars, Configuration::get('PS_SHOP_EMAIL'), null, null, null, null, null, $path, false, Context::getContext()->shop->id);
                            ++$emailsSent;
                        } else {
                            PrestaShopLogger::addLog('Error when sending user email (tpl:' . $campM->getFileName() . ',customer:' . $customer->email . ', campagne : ' . $camp['name'], 3);
                        }
                    }
                }
                // log emailing results :
                if ($emailsSent > 0) {
                    PrestaShopLogger::addLog($emailsSent . ' emails sent for ' . $camp['name'] . ' campaign', 1);
                }
            }
        }
    }