Esempio n. 1
0
 /**
  * Initialize order controller
  * @see FrontController::init()
  */
 public function init()
 {
     global $orderTotal;
     parent::init();
     $this->step = (int) Tools::getValue('step');
     if (!$this->nbProducts) {
         $this->step = -1;
     }
     // If some products have disappear
     if (!$this->context->cart->checkQuantities()) {
         $this->step = 0;
         $this->errors[] = Tools::displayError('An item in your cart is no longer available in this quantity, you cannot proceed with your order.');
     }
     // Check minimal amount
     $currency = Currency::getCurrency((int) $this->context->cart->id_currency);
     $orderTotal = $this->context->cart->getOrderTotal();
     $minimal_purchase = Tools::convertPrice((double) Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
     if ($this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS) < $minimal_purchase && $this->step != -1) {
         $this->step = 0;
         $this->errors[] = sprintf(Tools::displayError('A minimum purchase total of %d is required in order to validate your order.'), Tools::displayPrice($minimal_purchase, $currency));
     }
     if (!$this->context->customer->isLogged(true) && in_array($this->step, array(1, 2, 3))) {
         Tools::redirect($this->context->link->getPageLink('authentication', true, (int) $this->context->language->id, 'back=' . $this->context->link->getPageLink('order', true, (int) $this->context->language->id, 'step=' . $this->step . '&multi-shipping=' . (int) Tools::getValue('multi-shipping')) . '&multi-shipping=' . (int) Tools::getValue('multi-shipping')));
     }
     if (Tools::getValue('multi-shipping') == 1) {
         $this->context->smarty->assign('multi_shipping', true);
     } else {
         $this->context->smarty->assign('multi_shipping', false);
     }
     if ($this->context->customer->id) {
         $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id));
     } else {
         $this->context->smarty->assign('address_list', array());
     }
 }
 public function postProcess()
 {
     $sid = Configuration::get('TWOCHECKOUTPP_SID');
     $secret_word = Configuration::get('TWOCHECKOUTPP_SECRET');
     $credit_card_processed = $_REQUEST['credit_card_processed'];
     $order_number = $_REQUEST['order_number'];
     $cart_id = $_REQUEST['merchant_order_id'];
     $cart = new Cart($cart_id);
     $checkout = new twocheckoutpp();
     if (Configuration::get('TWOCHECKOUTPP_CURRENCY') > 0) {
         $amount = number_format($cart->getOrderTotal(true, 3), 2, '.', '');
         $currency_from = Currency::getCurrency($cart->id_currency);
         $currency_to = Currency::getCurrency(Configuration::get('TWOCHECKOUTPP_CURRENCY'));
         $amount = Tools::ps_round($amount / $currency_from['conversion_rate'], 2);
         $total = number_format(Tools::ps_round($amount *= $currency_to['conversion_rate'], 2), 2, '.', '');
     } else {
         $total = number_format($cart->getOrderTotal(true, 3), 2, '.', '');
     }
     //Check the hash
     $compare_string = $secret_word . $sid . $order_number . $total;
     $compare_hash1 = strtoupper(md5($compare_string));
     $compare_hash2 = $_REQUEST['key'];
     if ($compare_hash1 == $compare_hash2) {
         $customer = new Customer($cart->id_customer);
         $total = (double) $cart->getOrderTotal(true, Cart::BOTH);
         $checkout->validateOrder($cart_id, _PS_OS_PAYMENT_, $total, $checkout->displayName, '', array(), NULL, false, $customer->secure_key);
         $order = new Order($checkout->currentOrder);
         Tools::redirect('index.php?controller=order-confirmation&id_cart=' . (int) $cart->id . '&id_module=' . (int) $this->module->id . '&id_order=' . $checkout->currentOrder);
     } else {
         echo 'Hash Mismatch! Please contact the seller directly for assistance.</br>';
         echo 'Total: ' . $total . '</br>';
         echo '2CO Total: ' . $_REQUEST['total'];
     }
 }
 public function preProcess()
 {
     global $isVirtualCart, $orderTotal;
     parent::preProcess();
     /* If some products have disappear */
     if (!self::$cart->checkQuantities()) {
         $this->step = 0;
         $this->errors[] = Tools::displayError('An item in your cart is no longer available for this quantity, you cannot proceed with your order.');
     }
     /* Check minimal amount */
     $currency = Currency::getCurrency((int) self::$cart->id_currency);
     $orderTotal = self::$cart->getOrderTotal();
     $minimalPurchase = Tools::convertPrice((double) Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
     if (self::$cart->getOrderTotal(false, Cart::ONLY_PRODUCTS) < $minimalPurchase && $this->step != -1) {
         $this->step = 0;
         $this->errors[] = Tools::displayError('A minimum purchase total of') . ' ' . Tools::displayPrice($minimalPurchase, $currency) . ' ' . Tools::displayError('is required in order to validate your order.');
     }
     if (!self::$cookie->isLogged(true) and in_array($this->step, array(1, 2, 3))) {
         Tools::redirect('authentication.php?back=' . urlencode('order.php?step=' . $this->step));
     }
     if ($this->nbProducts) {
         self::$smarty->assign('virtual_cart', $isVirtualCart);
     }
     // Update carrier selected on preProccess in order to fix a bug of
     // block cart when it's hooked on leftcolumn
     if ($this->step == 3 && Tools::isSubmit('processCarrier')) {
         $this->processCarrier();
     }
 }
Esempio n. 4
0
 public static function validCurrency($id_currency)
 {
     $ret_valid_currency = null;
     if ($id_currency <= 0 || (!($res_currency = Currency::getCurrency($id_currency)) || empty($res_currency))) {
         $ret_valid_currency['error'] = 'The selected currency is not valid';
     } else {
         $ret_valid_currency['currency_code'] = $res_currency['iso_code'];
     }
     return $ret_valid_currency;
 }
Esempio n. 5
0
 /**
  * Initialize order controller
  * @see FrontController::init()
  */
 public function init()
 {
     global $orderTotal;
     parent::init();
     $this->step = (int) Tools::getValue('step');
     if (!$this->nbProducts) {
         $this->step = -1;
     }
     $product = $this->context->cart->checkQuantities(true);
     if ((int) ($id_product = $this->context->cart->checkProductsAccess())) {
         $this->step = 0;
         $this->errors[] = sprintf(Tools::displayError('An item in your cart is no longer available (%1s). You cannot proceed with your order.'), Product::getProductName((int) $id_product));
     }
     // If some products have disappear
     if (is_array($product)) {
         $this->step = 0;
         $this->errors[] = sprintf(Tools::displayError('An item (%1s) in your cart is no longer available in this quantity. You cannot proceed with your order until the quantity is adjusted.'), $product['name']);
     }
     // Check minimal amount
     $currency = Currency::getCurrency((int) $this->context->cart->id_currency);
     $orderTotal = $this->context->cart->getOrderTotal();
     $minimal_purchase = Tools::convertPrice((double) Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
     if ($this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS) < $minimal_purchase && $this->step > 0) {
         $this->step = 0;
         $this->errors[] = sprintf(Tools::displayError('A minimum purchase total of %1s (tax excl.) is required to validate your order, current purchase total is %2s (tax excl.).'), Tools::displayPrice($minimal_purchase, $currency), Tools::displayPrice($this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS), $currency));
     }
     if (!$this->context->customer->isLogged(true) && in_array($this->step, array(1, 2, 3))) {
         $params = array();
         if ($this->step) {
             $params['step'] = (int) $this->step;
         }
         if ($multi = (int) Tools::getValue('multi-shipping')) {
             $params['multi-shipping'] = $multi;
         }
         $back_url = $this->context->link->getPageLink('order', true, (int) $this->context->language->id, $params);
         $params = array('back' => $back_url);
         if ($multi) {
             $params['multi-shipping'] = $multi;
         }
         if ($guest = (int) Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
             $params['display_guest_checkout'] = $guest;
         }
         Tools::redirect($this->context->link->getPageLink('authentication', true, (int) $this->context->language->id, $params));
     }
     if (Tools::getValue('multi-shipping') == 1) {
         $this->context->smarty->assign('multi_shipping', true);
     } else {
         $this->context->smarty->assign('multi_shipping', false);
     }
     if ($this->context->customer->id) {
         $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id));
     } else {
         $this->context->smarty->assign('address_list', array());
     }
 }
 public function initContent()
 {
     if (Tools::isSubmit('module') && Tools::getValue('controller') == 'payment') {
         $currency = Currency::getCurrency((int) $this->context->cart->id_currency);
         $orderTotal = $this->context->cart->getOrderTotal();
         $minimal_purchase = Tools::convertPrice((double) Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
         if ($this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS) < $minimal_purchase) {
             Tools::redirect('index.php?controller=order&step=1');
         }
     }
     parent::initContent();
 }
Esempio n. 7
0
 /**
  * Initialize order controller
  * @see FrontController::init()
  */
 public function init()
 {
     global $orderTotal;
     parent::init();
     $this->step = (int) Tools::getValue('step');
     if (!$this->nbProducts) {
         $this->step = -1;
     }
     // If some products have disappear
     if (!$this->context->cart->checkQuantities()) {
         $this->step = 0;
         $this->errors[] = Tools::displayError('An item in your cart is no longer available in this quantity. You cannot proceed with your order until the quantity is adjusted.');
     }
     // Check minimal amount
     $currency = Currency::getCurrency((int) $this->context->cart->id_currency);
     //Gelikon Стоимость товаров без доставки BEGIN
     $cart_products = $this->context->cart->getProducts();
     $products_total_wt = 0;
     if ($cart_products) {
         foreach ($cart_products as $cart_product) {
             $products_total_wt += $cart_product["total_wt"];
         }
     }
     $this->context->smarty->assign('products_total_wt', $products_total_wt);
     //Gelikon Стоимость товаров без доставки END
     $orderTotal = $this->context->cart->getOrderTotal();
     $this->context->smarty->assign('global_order_total', $orderTotal);
     $minimal_purchase = Tools::convertPrice((double) Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
     if ($this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS) < $minimal_purchase && $this->step > 0) {
         $this->step = 0;
         $this->errors[] = sprintf(Tools::displayError('A minimum purchase total of %1s (tax excl.) is required in order to validate your order, current purchase total is %2s (tax excl.).'), Tools::displayPrice($minimal_purchase, $currency), Tools::displayPrice($this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS), $currency));
     }
     if (!$this->context->customer->isLogged(true) && in_array($this->step, array(1, 2, 3))) {
         $back_url = $this->context->link->getPageLink('order', true, (int) $this->context->language->id, array('step' => $this->step, 'multi-shipping' => (int) Tools::getValue('multi-shipping')));
         $params = array('multi-shipping' => (int) Tools::getValue('multi-shipping'), 'display_guest_checkout' => (int) Configuration::get('PS_GUEST_CHECKOUT_ENABLED'), 'back' => $back_url);
         Tools::redirect($this->context->link->getPageLink('authentication', true, (int) $this->context->language->id, $params));
     }
     if (Tools::getValue('multi-shipping') == 1) {
         $this->context->smarty->assign('multi_shipping', true);
     } else {
         $this->context->smarty->assign('multi_shipping', false);
     }
     if ($this->context->customer->id) {
         $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id));
     } else {
         $this->context->smarty->assign('address_list', array());
     }
 }
Esempio n. 8
0
 public function preProcess()
 {
     global $isVirtualCart, $orderTotal;
     parent::preProcess();
     /* If some products have disappear */
     if (!self::$cart->checkQuantities()) {
         $this->step = 0;
         $this->errors[] = Tools::displayError('An item in your shopping bag is no longer available for this quantity, please remove it to proceed.');
     }
     /* Check minimal amount */
     $currency = Currency::getCurrency((int) self::$cart->id_currency);
     $orderTotal = self::$cart->getOrderTotal();
     $minimalPurchase = Tools::convertPrice((double) Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
     if (self::$cart->getOrderTotal(false) < $minimalPurchase && $this->step != -1) {
         $this->step = 0;
         $this->errors[] = Tools::displayError('A minimum purchase total of') . ' ' . Tools::displayPrice($minimalPurchase, $currency) . ' ' . Tools::displayError('is required in order to validate your order.');
     }
     if (!self::$cookie->isLogged(true) and in_array($this->step, array(1, 2, 3))) {
         Tools::redirect('authentication.php?back=' . urlencode('order.php?step=' . $this->step));
     }
     if ($this->nbProducts) {
         self::$smarty->assign('virtual_cart', $isVirtualCart);
     }
     $this->_addAddress($this->step);
     if (self::$cookie->isLogged(true)) {
         $reward_points = VBRewards::getCustomerPoints(self::$cookie->id_customer);
         $redemption_status = VBRewards::checkPointsValidity(self::$cookie->id_customer, 0, self::$cart->getOrderTotal(true, Cart::ONLY_PRODUCTS));
         self::$smarty->assign('can_redeem_points', 1);
         self::$smarty->assign("redemption_status", $redemption_status);
         if ($redemption_status === CANNOT_REDEEM_COINS) {
             self::$smarty->assign('can_redeem_points', 0);
         } else {
             if ($redemption_status === INSUFFICIENT_VALID_ORDERS) {
                 self::$smarty->assign('redemption_status_message', 'Coins can be redeemed from second purchase onwards.');
             } else {
                 if ($redemption_status === MIN_CRITERIA_NOT_MET) {
                     self::$smarty->assign('redemption_status_message', 'Order value should be more than 100 USD to redeem coins');
                 }
             }
         }
         self::$smarty->assign('redeem_points', (int) self::$cart->getPoints());
         self::$smarty->assign('balance_points', $reward_points);
         if ($reward_points - (int) self::$cart->getPoints() > 0) {
             self::$smarty->assign('balance_cash', (int) self::$cart->getPointsDiscounts($reward_points - (int) self::$cart->getPoints()));
         }
     }
 }
Esempio n. 9
0
    public function hookBackOfficeHome($params)
    {
        global $cookie;
        $this->_postProcess();
        $currency = Currency::getCurrency(intval(Configuration::get('PS_CURRENCY_DEFAULT')));
        $results = $this->getResults();
        $employee = new Employee(intval($cookie->id_employee));
        $id_tab_stats = Tab::getIdFromClassName('AdminStats');
        $access = Profile::getProfileAccess($employee->id_profile, $id_tab_stats);
        if (!$access['view']) {
            return '';
        }
        $this->_html = '
		<fieldset style="width:520px;">
			<legend><img src="../modules/' . $this->name . '/logo.gif" /> ' . $this->l('Statistics') . '</legend>
			<div style="float:left;width:240px;text-align:center">
				<div style="float:left;width:120px;text-align:center">
					<center><p style="font-weight:bold;height:80px;width:100px;text-align:center;background-image:url(\'' . __PS_BASE_URI__ . 'modules/statshome/square1.gif\')">
						<br /><br />' . Tools::displayPrice($results['total_sales'], $currency) . '
					</p></center>
					<p>' . $this->l('of sales') . '</p>
					<center><p style="font-weight:bold;height:80px;width:100px;text-align:center;background-image:url(\'' . __PS_BASE_URI__ . 'modules/statshome/square3.gif\')">
						<br /><br />' . intval($results['total_registrations']) . '
					</p></center>
					<p>' . ($results['total_registrations'] != 1 ? $this->l('registrations') : $this->l('registration')) . '</p>
				</div>
				<div style="float:left;width:120px;text-align:center">
					<center><p style="font-weight:bold;height:80px;width:100px;text-align:center;background-image:url(\'' . __PS_BASE_URI__ . 'modules/statshome/square2.gif\')">
						<br /><br />' . intval($results['total_orders']) . '
					</p></center>
					<p>' . ($results['total_orders'] != 1 ? $this->l('orders placed') : $this->l('order placed')) . '</p>
					<center><p style="font-weight:bold;height:80px;width:100px;text-align:center;background-image:url(\'' . __PS_BASE_URI__ . 'modules/statshome/square4.gif\')">
						<br /><br />' . intval($results['total_viewed']) . '
					</p></center>
					<p>' . ($results['total_viewed'] != 1 ? $this->l('product pages viewed') : $this->l('product page viewed')) . '</p>
				</div>
			</div>
			<div style="float:right;text-align:right;width:240px">';
        include_once dirname(__FILE__) . '/../..' . $this->_adminPath . '/tabs/AdminStats.php';
        $this->_html .= AdminStatsTab::displayCalendarStatic(array('Calendar' => $this->l('Calendar'), 'Day' => $this->l('Day'), 'Month' => $this->l('Month'), 'Year' => $this->l('Year')));
        $this->_html .= '<div class="space"></div>
				<p style=" font-weight: bold ">' . $this->l('Visitors online now:') . ' ' . intval($this->getVisitorsNow()) . '</p>
			</div>
		</fieldset>
		<div class="clear space"><br /><br /></div>';
        return $this->_html;
    }
Esempio n. 10
0
 public function getTableRecentOrders()
 {
     $header = array(array('title' => $this->l('Customer Name'), 'class' => 'text-left'), array('title' => $this->l('Products'), 'class' => 'text-center'), array('title' => $this->l('Total'), 'class' => 'text-center'), array('title' => $this->l('Date'), 'class' => 'text-center'), array('title' => $this->l('Action'), 'class' => 'text-center'));
     $orders = Order::getOrdersWithInformations((int) Configuration::get('DASHPRODUCT_NBR_SHOW_LAST_ORDER', 10));
     $body = array();
     foreach ($orders as $order) {
         $currency = Currency::getCurrency((int) $order['id_currency']);
         $tr = array();
         $tr[] = array('id' => 'firstname_lastname', 'value' => Tools::htmlentitiesUTF8($order['firstname']) . ' ' . Tools::htmlentitiesUTF8($order['lastname']), 'class' => 'text-left');
         $tr[] = array('id' => 'state_name', 'value' => count(OrderDetail::getList((int) $order['id_order'])), 'class' => 'text-center');
         $tr[] = array('id' => 'total_paid', 'value' => Tools::displayPrice((double) $order['total_paid'], $currency), 'class' => 'text-center', 'wrapper_start' => '<span class="badge">', 'wrapper_end' => '<span>');
         $tr[] = array('id' => 'date_add', 'value' => Tools::displayDate($order['date_add']), 'class' => 'text-center');
         $tr[] = array('id' => 'details', 'value' => $this->l('Details'), 'class' => 'text-right', 'wrapper_start' => '<a class="btn btn-default" href="index.php?tab=AdminOrders&id_order=' . (int) $order['id_order'] . '&vieworder&token=' . Tools::getAdminTokenLite('AdminOrders') . '" title="' . $this->l('Details') . '"><i class="icon-search"></i>', 'wrapper_end' => '</a>');
         $body[] = $tr;
     }
     return array('header' => $header, 'body' => $body);
 }
 public function preProcess()
 {
     global $isVirtualCart, $orderTotal;
     parent::preProcess();
     /* If some products have disappear */
     if (!self::$cart->checkQuantities()) {
         $this->step = 0;
         $this->errors[] = Tools::displayError('An item in your cart is no longer available for this quantity, you cannot proceed with your order.');
     }
     /* Check minimal amount */
     $currency = Currency::getCurrency((int) self::$cart->id_currency);
     $orderTotal = self::$cart->getOrderTotal();
     $minimalPurchase = Tools::convertPrice((double) Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
     if ($orderTotal < $minimalPurchase) {
         $this->step = 0;
         $this->errors[] = Tools::displayError('A minimum purchase total of') . ' ' . Tools::displayPrice($minimalPurchase, $currency) . ' ' . Tools::displayError('is required in order to validate your order.');
     }
     if (!self::$cookie->isLogged(true) and in_array($this->step, array(1, 2, 3))) {
         Tools::redirect('authentication.php?back=order.php?step=' . $this->step);
     }
     if ($this->nbProducts) {
         self::$smarty->assign('virtual_cart', $isVirtualCart);
     }
 }
 function execPayment($cart)
 {
     $delivery = new Address(intval($cart->id_address_delivery));
     $invoice = new Address(intval($cart->id_address_invoice));
     $customer = new Customer(intval($cart->id_customer));
     global $cookie, $smarty;
     //Verify currencies and display payment form
     $cart_details = $cart->getSummaryDetails(null, true);
     $currencies = Currency::getCurrencies();
     $authorized_currencies = array_flip(explode(',', $this->currencies));
     $currencies_used = array();
     foreach ($currencies as $key => $currency) {
         if (isset($authorized_currencies[$currency['id_currency']])) {
             $currencies_used[] = $currencies[$key];
         }
     }
     $order_currency = '';
     foreach ($currencies_used as $key => $currency) {
         if ($currency['id_currency'] == $cart->id_currency) {
             $order_currency = $currency['iso_code'];
         }
     }
     $products = $cart->getProducts();
     foreach ($products as $key => $product) {
         $products[$key]['name'] = str_replace('"', '\'', $product['name']);
         $products[$key]['name'] = htmlentities(utf8_decode($product['name']));
     }
     $discounts = $cart_details['discounts'];
     $carrier = $cart_details['carrier'];
     if (_PS_VERSION_ < '1.5') {
         $shipping_cost = $cart_details['total_shipping_tax_exc'];
     } else {
         $shipping_cost = $this->context->cart->getTotalShippingCost();
     }
     $CheckoutUrl = 'https://www.2checkout.com/checkout/purchase';
     $sid = Configuration::get('TWOCHECKOUTPP_SID');
     $amount = number_format($cart->getOrderTotal(true, 3), 2, '.', '');
     $cart_order_id = $cart->id;
     $email = $customer->email;
     $secure_key = $customer->secure_key;
     $demo = "N";
     // Change to "Y" for demo mode
     $outside_state = "XX";
     // This will pre-select Outside USA and Canada, if state does not exist
     // Invoice Parameters
     $card_holder_name = $invoice->firstname . ' ' . $invoice->lastname;
     $street_address = $invoice->address1;
     $street_address2 = $invoice->address2;
     $phone = $invoice->phone;
     $city = $invoice->city;
     $state = (Validate::isLoadedObject($invoice) and $invoice->id_state) ? new State(intval($invoice->id_state)) : false;
     $zip = $invoice->postcode;
     $country = $invoice->country;
     // Shipping Parameters
     $ship_name = $delivery->firstname . ' ' . $invoice->lastname;
     $ship_street_address = $delivery->address1;
     $ship_street_address2 = $delivery->address2;
     $ship_city = $delivery->city;
     $ship_state = (Validate::isLoadedObject($delivery) and $delivery->id_state) ? new State(intval($delivery->id_state)) : false;
     $ship_zip = $delivery->postcode;
     $ship_country = $delivery->country;
     $check_total = $this->checkTotal($cart);
     if (Configuration::get('TWOCHECKOUTPP_CURRENCY') > 0) {
         $currency_from = Currency::getCurrency($cart->id_currency);
         $currency_to = Currency::getCurrency(Configuration::get('TWOCHECKOUTPP_CURRENCY'));
         $amount = Tools::ps_round($amount / $currency_from['conversion_rate'], 2);
         $total = Tools::ps_round($amount *= $currency_to['conversion_rate'], 2);
         $order_currency = $currency_to['iso_code'];
         $override_currency = $currency_to;
     } else {
         $total = number_format($cart->getOrderTotal(true, 3), 2, '.', '');
         $override_currency = 0;
     }
     $cart = new Cart($cookie->id_cart);
     $address = new Address($cart->id_address_delivery, intval($cookie->id_lang));
     $state = State::getNameById($address->id_state);
     $state = $state ? '(' . $state . ')' : '';
     $str_address = ($address->company ? $address->company . '<br>' : '') . $address->firstname . ' ' . $address->lastname . '<br>' . $address->address1 . '<br>' . ($address->address2 ? $address->address2 . '<br>' : '') . $address->postcode . ' ' . $address->city . '<br>' . $address->country . $state;
     $carrier = Carrier::getCarriers(intval($cookie->id_lang));
     if ($carrier) {
         foreach ($carrier as $c) {
             if ($cart->id_carrier == $c['id_carrier']) {
                 $carrier_name = $c['name'];
                 break;
             }
         }
     }
     $params = array();
     $params['sid'] = $sid;
     $params['paypal_direct'] = 'Y';
     $params['currency_code'] = $order_currency;
     $params['return_url'] = $this->context->link->getPageLink('order', true, NULL, "step=3");
     $params['merchant_order_id'] = $cart_order_id;
     $params['email'] = $email;
     $params['phone'] = $phone;
     $params['card_holder_name'] = $card_holder_name;
     $params['street_address'] = $street_address;
     $params['street_address2'] = $street_address2;
     $params['city'] = $city;
     $params['state'] = $state;
     $params['zip'] = $zip;
     $params['country'] = $country;
     $params['ship_name'] = $ship_name;
     $params['ship_street_address'] = $ship_street_address;
     $params['ship_street_address2'] = $ship_street_address2;
     $params['ship_city'] = $ship_city;
     $params['ship_state'] = $ship_state ? $ship_state->name : $outside_state;
     $params['ship_zip'] = $ship_zip;
     $params['ship_country'] = $ship_country;
     if (sprintf("%01.2f", $check_total) == sprintf("%01.2f", $total)) {
         $params['mode'] = '2CO';
         $i = 0;
         foreach ($products as $product) {
             $params['li_' . $i . '_type'] = 'product';
             $params['li_' . $i . '_id'] = $product['id_product'];
             $params['li_' . $i . '_name'] = $product['name'];
             $params['li_' . $i . '_description'] = $product['description_short'];
             $params['li_' . $i . '_quantity'] = $product['quantity'];
             $params['li_' . $i . '_price'] = $product['price'];
             $i++;
         }
         if ($shipping_cost > 0) {
             $params['li_' . $i . '_type'] = 'shipping';
             $params['li_' . $i . '_name'] = $carrier_name;
             $params['li_' . $i . '_price'] = $shipping_cost;
             $i++;
         }
         if ($cart_details['total_tax'] > 0) {
             $params['li_' . $i . '_type'] = 'tax';
             $params['li_' . $i . '_name'] = 'Tax';
             $params['li_' . $i . '_price'] = $cart_details['total_tax'];
             $i++;
         }
         if ($cart_details['total_discounts_tax_exc'] > 0) {
             $params['li_' . $i . '_type'] = 'coupon';
             $params['li_' . $i . '_name'] = 'Discounts';
             $params['li_' . $i . '_price'] = $cart_details['total_discounts_tax_exc'];
             $i++;
         }
     } else {
         $params['cart_order_id'] = $cart_order_id;
         $params['total'] = sprintf("%01.2f", $total);
     }
     $redirect_url = $CheckoutUrl . '?' . http_build_query($params);
     header('Location: ' . $redirect_url);
 }
Esempio n. 13
0
 /**
  * Calculate a forex order
  * @param $currencyCode
  * @param null $currencyAmount
  * @param null $payableAmount
  * @param bool $applyDiscount
  * @return bool|Order
  */
 public static function calculateOrder($currencyCode, $currencyAmount = null, $payableAmount = null, $applyDiscount = false)
 {
     if (!isset($currencyAmount) && !isset($payableAmount)) {
         return false;
     }
     $currency = Currency::getCurrency($currencyCode);
     if (!$currency) {
         return false;
     }
     $order = new self();
     $order->currency_code = $currencyCode;
     $order->exchange_rate = $currency->exchange_rate;
     $order->surcharge_percentage = $currency->currency_surcharge;
     $order->discount_amount = 0;
     $order->discount_percentage = 0;
     if (!empty($currencyAmount)) {
         $order->currency_amount = $currencyAmount;
         // Calculate the initial currency conversion before surcharges and discounts
         $order->payable_amount = $currencyAmount * (1 / $currency->exchange_rate);
         // Calculate the surcharge
         $order->surcharge_amount = $order->payable_amount / 100 * $order->surcharge_percentage;
         // Add the surcharge to the amount payable
         $order->payable_amount += $order->surcharge_amount;
         $order->payable_amount = round($order->payable_amount, 2, PHP_ROUND_HALF_UP);
     } else {
         $order->payable_amount = $payableAmount;
         $order->surcharge_amount = $payableAmount / (100 + $order->surcharge_percentage) * $order->surcharge_percentage;
         $order->currency_amount = $payableAmount - $order->surcharge_amount;
         $order->currency_amount = $order->currency_amount * $currency->exchange_rate;
     }
     // Apply the discount if one is available
     if ($applyDiscount && $currency->currency_discount > 0) {
         $order->discount_percentage = $currency->currency_discount;
         $order->discount_amount = $order->payable_amount / 100 * $currency->currency_discount;
         $order->payable_amount -= $order->discount_amount;
         $order->payable_amount = round($order->payable_amount, 2, PHP_ROUND_HALF_UP);
     }
     $order->zar_amount = self::calculateRandValue($order->payable_amount);
     $order->currency_amount = self::formatValue($order->currency_amount);
     $order->surcharge_amount = self::formatValue($order->surcharge_amount);
     $order->payable_amount = self::formatValue($order->payable_amount);
     $order->zar_amount = self::formatValue($order->zar_amount);
     return $order;
 }
 /**
  * AdminController::postProcess() override
  * @see AdminController::postProcess()
  */
 public function postProcess()
 {
     $this->is_editing_order = false;
     // Checks access
     if (Tools::isSubmit('submitAddsupply_order') && !($this->tabAccess['add'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have permission to add a supply order.');
     }
     if (Tools::isSubmit('submitBulkUpdatesupply_order_detail') && !($this->tabAccess['edit'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have permission to edit an order.');
     }
     // Trick to use both Supply Order as template and actual orders
     if (Tools::isSubmit('is_template')) {
         $_GET['mod'] = 'template';
     }
     // checks if supply order reference is unique
     if (Tools::isSubmit('reference')) {
         // gets the reference
         $ref = pSQL(Tools::getValue('reference'));
         if (Tools::getValue('id_supply_order') != 0 && SupplyOrder::getReferenceById((int) Tools::getValue('id_supply_order')) != $ref) {
             if ((int) SupplyOrder::exists($ref) != 0) {
                 $this->errors[] = Tools::displayError('The reference has to be unique.');
             }
         } elseif (Tools::getValue('id_supply_order') == 0 && (int) SupplyOrder::exists($ref) != 0) {
             $this->errors[] = Tools::displayError('The reference has to be unique.');
         }
     }
     if ($this->errors) {
         return;
     }
     // Global checks when add / update a supply order
     if (Tools::isSubmit('submitAddsupply_order') || Tools::isSubmit('submitAddsupply_orderAndStay')) {
         $this->action = 'save';
         $this->is_editing_order = true;
         // get supplier ID
         $id_supplier = (int) Tools::getValue('id_supplier', 0);
         if ($id_supplier <= 0 || !Supplier::supplierExists($id_supplier)) {
             $this->errors[] = Tools::displayError('The selected supplier is not valid.');
         }
         // get warehouse id
         $id_warehouse = (int) Tools::getValue('id_warehouse', 0);
         if ($id_warehouse <= 0 || !Warehouse::exists($id_warehouse)) {
             $this->errors[] = Tools::displayError('The selected warehouse is not valid.');
         }
         // get currency id
         $id_currency = (int) Tools::getValue('id_currency', 0);
         if ($id_currency <= 0 || (!($result = Currency::getCurrency($id_currency)) || empty($result))) {
             $this->errors[] = Tools::displayError('The selected currency is not valid.');
         }
         // get delivery date
         if (Tools::getValue('mod') != 'template' && strtotime(Tools::getValue('date_delivery_expected')) <= strtotime('-1 day')) {
             $this->errors[] = Tools::displayError('The specified date cannot be in the past.');
         }
         // gets threshold
         $quantity_threshold = Tools::getValue('load_products');
         if (is_numeric($quantity_threshold)) {
             $quantity_threshold = (int) $quantity_threshold;
         } else {
             $quantity_threshold = null;
         }
         if (!count($this->errors)) {
             // forces date for templates
             if (Tools::isSubmit('is_template') && !Tools::getValue('date_delivery_expected')) {
                 $_POST['date_delivery_expected'] = date('Y-m-d h:i:s');
             }
             // specify initial state
             $_POST['id_supply_order_state'] = 1;
             //defaut creation state
             // specify global reference currency
             $_POST['id_ref_currency'] = Currency::getDefaultCurrency()->id;
             // specify supplier name
             $_POST['supplier_name'] = Supplier::getNameById($id_supplier);
             //specific discount check
             $_POST['discount_rate'] = (double) str_replace(array(' ', ','), array('', '.'), Tools::getValue('discount_rate', 0));
         }
         // manage each associated product
         $this->manageOrderProducts();
         // if the threshold is defined and we are saving the order
         if (Tools::isSubmit('submitAddsupply_order') && Validate::isInt($quantity_threshold)) {
             $this->loadProducts((int) $quantity_threshold);
         }
     }
     // Manage state change
     if (Tools::isSubmit('submitChangestate') && Tools::isSubmit('id_supply_order') && Tools::isSubmit('id_supply_order_state')) {
         if ($this->tabAccess['edit'] != '1') {
             $this->errors[] = Tools::displayError('You do not have permission to change the order status.');
         }
         // get state ID
         $id_state = (int) Tools::getValue('id_supply_order_state', 0);
         if ($id_state <= 0) {
             $this->errors[] = Tools::displayError('The selected supply order status is not valid.');
         }
         // get supply order ID
         $id_supply_order = (int) Tools::getValue('id_supply_order', 0);
         if ($id_supply_order <= 0) {
             $this->errors[] = Tools::displayError('The supply order ID is not valid.');
         }
         if (!count($this->errors)) {
             // try to load supply order
             $supply_order = new SupplyOrder($id_supply_order);
             if (Validate::isLoadedObject($supply_order)) {
                 // get valid available possible states for this order
                 $states = SupplyOrderState::getSupplyOrderStates($supply_order->id_supply_order_state);
                 foreach ($states as $state) {
                     // if state is valid, change it in the order
                     if ($id_state == $state['id_supply_order_state']) {
                         $new_state = new SupplyOrderState($id_state);
                         $old_state = new SupplyOrderState($supply_order->id_supply_order_state);
                         // special case of validate state - check if there are products in the order and the required state is not an enclosed state
                         if ($supply_order->isEditable() && !$supply_order->hasEntries() && !$new_state->enclosed) {
                             $this->errors[] = Tools::displayError('It is not possible to change the status of this order because you did not order any products.');
                         }
                         if (!count($this->errors)) {
                             $supply_order->id_supply_order_state = $state['id_supply_order_state'];
                             if ($supply_order->save()) {
                                 if ($new_state->pending_receipt) {
                                     $supply_order_details = $supply_order->getEntries();
                                     foreach ($supply_order_details as $supply_order_detail) {
                                         $is_present = Stock::productIsPresentInStock($supply_order_detail['id_product'], $supply_order_detail['id_product_attribute'], $supply_order->id_warehouse);
                                         if (!$is_present) {
                                             $stock = new Stock();
                                             $stock_params = array('id_product_attribute' => $supply_order_detail['id_product_attribute'], 'id_product' => $supply_order_detail['id_product'], 'physical_quantity' => 0, 'price_te' => $supply_order_detail['price_te'], 'usable_quantity' => 0, 'id_warehouse' => $supply_order->id_warehouse);
                                             // saves stock in warehouse
                                             $stock->hydrate($stock_params);
                                             $stock->add();
                                         }
                                     }
                                 }
                                 // if pending_receipt,
                                 // or if the order is being canceled,
                                 // or if the order is received completely
                                 // synchronizes StockAvailable
                                 if ($new_state->pending_receipt && !$new_state->receipt_state || ($old_state->receipt_state || $old_state->pending_receipt) && $new_state->enclosed && !$new_state->receipt_state || $new_state->receipt_state && $new_state->enclosed) {
                                     $supply_order_details = $supply_order->getEntries();
                                     $products_done = array();
                                     foreach ($supply_order_details as $supply_order_detail) {
                                         if (!in_array($supply_order_detail['id_product'], $products_done)) {
                                             StockAvailable::synchronize($supply_order_detail['id_product']);
                                             $products_done[] = $supply_order_detail['id_product'];
                                         }
                                     }
                                 }
                                 $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
                                 $redirect = self::$currentIndex . '&token=' . $token;
                                 $this->redirect_after = $redirect . '&conf=5';
                             }
                         }
                     }
                 }
             } else {
                 $this->errors[] = Tools::displayError('The selected supplier is not valid.');
             }
         }
     }
     // updates receipt
     if (Tools::isSubmit('submitBulkUpdatesupply_order_detail') && Tools::isSubmit('id_supply_order')) {
         $this->postProcessUpdateReceipt();
     }
     // use template to create a supply order
     if (Tools::isSubmit('create_supply_order') && Tools::isSubmit('id_supply_order')) {
         $this->postProcessCopyFromTemplate();
     }
     if (!count($this->errors) && $this->is_editing_order || !$this->is_editing_order) {
         parent::postProcess();
     }
 }
Esempio n. 15
0
 protected function _getPaymentMethods()
 {
     if (!$this->isOpcModuleActive()) {
         return parent::_getPaymentMethods();
     }
     if ($this->context->cart->OrderExists()) {
         $ret = '<p class="warning">' . Tools::displayError('Error: this order has already been validated') . '</p>';
         return array("orig_hook" => $ret, "parsed_content" => $ret);
     }
     $ret = "";
     $address_delivery = new Address($this->context->cart->id_address_delivery);
     $address_invoice = $this->context->cart->id_address_delivery == $this->context->cart->id_address_invoice ? $address_delivery : new Address($this->context->cart->id_address_invoice);
     if (!$this->context->cart->id_address_delivery || !$this->context->cart->id_address_invoice || !Validate::isLoadedObject($address_delivery) || !Validate::isLoadedObject($address_invoice) || $address_invoice->deleted || $address_delivery->deleted) {
         $ret = '<p class="warning">' . Tools::displayError('Error: please choose an address') . '</p>';
     }
     if (count($this->context->cart->getDeliveryOptionList()) == 0 && !$this->context->cart->isVirtualCart()) {
         if ($this->context->cart->isMultiAddressDelivery()) {
             $ret .= '<p class="warning">' . Tools::displayError('Error: There are no carriers available that deliver to some of your addresses') . '</p>';
         } else {
             $ret .= '<p class="warning">' . Tools::displayError('Error: There are no carriers available that deliver to this address') . '</p>';
         }
     }
     if (!$this->context->cart->getDeliveryOption(null, false) && !$this->context->cart->isVirtualCart()) {
         $ret = '<p class="warning">' . Tools::displayError('Error: please choose a carrier') . '</p>';
     }
     if (!$this->context->cart->id_currency) {
         $ret .= '<p class="warning">' . Tools::displayError('Error: no currency has been selected') . '</p>';
     }
     if (!$this->context->cart->checkQuantities()) {
         $ret .= '<p class="warning">' . Tools::displayError('An item in your cart is no longer available, you cannot proceed with your order.') . '</p>';
     }
     $currency = Currency::getCurrency((int) $this->context->cart->id_currency);
     $minimalPurchase = Tools::convertPrice((double) Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
     if ($this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS) < $minimalPurchase) {
         $ret .= '<p class="warning">' . sprintf(Tools::displayError('A minimum purchase total of %s is required in order to validate your order.'), Tools::displayPrice($minimalPurchase, $currency)) . '</p>';
     }
     if (trim($ret) != "") {
         return array("orig_hook" => $ret, "parsed_content" => $ret);
     }
     $opc_config = $this->context->smarty->tpl_vars["opc_config"]->value;
     $tmp_customer_id_1 = isset($opc_config) && isset($opc_config["payment_customer_id"]) ? intval($opc_config["payment_customer_id"]) : 0;
     $reset_id_customer = false;
     if (!$this->context->cookie->id_customer) {
         $simulated_customer_id = $tmp_customer_id_1 > 0 ? $tmp_customer_id_1 : Customer::getFirstCustomerId();
         $this->context->cookie->id_customer = $simulated_customer_id;
         $reset_id_customer = true;
         if (!$this->context->customer->id) {
             $this->context->customer->id = $simulated_customer_id;
         }
     }
     $orig_context_country = $this->context->country;
     if (isset($address_invoice) && $address_invoice != null) {
         $this->context->country = new Country($address_invoice->id_country);
     }
     if ($this->context->cart->getOrderTotal() <= 0) {
         $return = $this->context->smarty->fetch($this->opc_templates_path . '/free-order-payment.tpl');
     } else {
         $ship2pay_support = isset($opc_config) && isset($opc_config["ship2pay"]) && $opc_config["ship2pay"] == "1" ? true : false;
         if ($ship2pay_support) {
             $orig_id_carrier = $this->context->cart->id_carrier;
             $selected_carrier = Cart::desintifier($this->context->cart->simulateCarrierSelectedOutput());
             $selected_carrier = explode(",", $selected_carrier);
             $selected_carrier = $selected_carrier[0];
             $this->context->cart->id_carrier = $selected_carrier;
             $this->context->cart->update();
             $return = Hook::exec('displayPayment');
         } else {
             $return = Hook::exec('displayPayment');
         }
     }
     $this->context->country = $orig_context_country;
     # restore cookie's id_customer
     if ($reset_id_customer) {
         unset($this->context->cookie->id_customer);
         $this->context->customer->id = null;
     }
     # fix Moneybookers relative path to images
     $return = preg_replace('/src="modules\\//', 'src="' . __PS_BASE_URI__ . 'modules/', $return);
     # OPCKT fix Paypal relative path to redirect script
     $return = preg_replace('/href="modules\\//', 'href="' . __PS_BASE_URI__ . 'modules/', $return);
     if (!$return) {
         $ret = '<p class="warning">' . Tools::displayError('No payment method is available') . '</p>';
         return array("orig_hook" => $ret, "parsed_content" => $ret);
     }
     $parsed_content = "";
     $parse_payment_methods = isset($opc_config) && isset($opc_config["payment_radio_buttons"]) && $opc_config["payment_radio_buttons"] == "1" ? true : false;
     if ($parse_payment_methods) {
         $content = $return;
         $payment_methods = array();
         $i = 0;
         preg_match_all('/<a.*?>[^>]*?<img[^>]*?src="(.*?)".*?\\/?>(.*?)<\\/a>/ms', $content, $matches1, PREG_SET_ORDER);
         $tmp_return = preg_replace_callback('/(<(a))([^>]*?>[^>]*?<img.*?src)/ms', array($this, "_genPaymentModId"), $return);
         if ($tmp_return == NULL) {
             echo "ERRoR!";
         }
         if ($tmp_return != null) {
             // NULL can be returned on backtrace limit exhaustion
             $return = $tmp_return;
         }
         preg_match_all('/<input [^>]*?type="image".*?src="(.*?)".*?>.*?<span.*?>(.*?)<\\/span>/ms', $content, $matches2, PREG_SET_ORDER);
         $tmp_return = preg_replace_callback('/(<(input)[^>]*?type="image")(.*?<span.)/ms', array($this, "_genPaymentModId"), $return);
         if ($tmp_return != null) {
             $return = $tmp_return;
         }
         preg_match_all('/<a[^>]*?class="(.*?)".*?>(.*?)<\\/a>/ms', $content, $matches3, PREG_SET_ORDER);
         $tmp_return = preg_replace_callback('/(<a[^>]*?class="(.*?)")([^>]*?>)/ms', array($this, "_genPaymentModId"), $return);
         if ($tmp_return != null) {
             $return = $tmp_return;
         }
         for ($k = 0; $k < count($matches3); $k++) {
             $matches3[$k][3] = $matches3[$k][1];
             // IMG class of original module
             $matches3[$k][1] = preg_replace('/.*?themes\\//', 'themes/', _THEME_IMG_DIR_) . $matches3[$k][1] . ".png";
         }
         $matches = array_merge($matches1, $matches2, $matches3);
         foreach ($matches as $match) {
             $payment_methods[$i]['img'] = preg_replace('/(\\r)?\\n/m', " ", trim($match[1]));
             $payment_methods[$i]['desc'] = preg_replace('/\\s/m', " ", trim($match[2]));
             // fixed for Auriga payment
             $payment_methods[$i]['link'] = "opc_pid_{$i}";
             if (isset($match[3])) {
                 $payment_methods[$i]['class'] = trim($match[3]);
             }
             $i++;
         }
         $this->context->smarty->assign("payment_methods", $payment_methods);
         $parsed_content = $this->context->smarty->fetch($this->opc_templates_path . "/payment-methods.tpl");
         $parsed_content = str_replace("&amp;", "&", $parsed_content);
     }
     return array("orig_hook" => $return, "parsed_content" => $parsed_content);
 }
Esempio n. 16
0
 public function hookPayment($params)
 {
     global $smarty, $cart;
     global $cart;
     $invoice_address = new Address((int) $cart->id_address_invoice);
     if ($invoice_address->id_country == 110) {
         return;
     }
     $id_currency = (int) $cart->id_currency;
     $currency = Currency::getCurrency($id_currency);
     if ((int) $currency["paypal_support"] !== 1) {
         return;
         /*$total = Tools::convertPrice((float)$cart->getOrderTotal(), $cart->id_currency, false);
           $curr_conversion_msg = "<p>Unfortunately we are unable to accept payments in <b>{$currency['name']}</b>.</p> <p>An equivalent order value of USD <b>". Tools::displayPrice($total,2)."</b> will be processed.</p>";
           $smarty->assign("curr_conversion_msg",$curr_conversion_msg);*/
     }
     if (!$this->active) {
         return;
     }
     /*
      * PAYMENT METHOD:
      * 0: Integral
      * 1: Option +
      * 2: Integral Evolution
      */
     if (Configuration::get('PAYPAL_PAYMENT_METHOD') == _PAYPAL_INTEGRAL_EVOLUTION_) {
         return $this->display(__FILE__, 'integral_evolution/paypal.tpl');
     } elseif (Configuration::get('PAYPAL_PAYMENT_METHOD') == _PAYPAL_INTEGRAL_ or Configuration::get('PAYPAL_PAYMENT_METHOD') == _PAYPAL_OPTION_PLUS_) {
         if ($this->_isPayPalAPIAvailable()) {
             $smarty->assign('integral', Configuration::get('PAYPAL_PAYMENT_METHOD') == 0 ? 1 : 0);
             $smarty->assign('logo', _MODULE_DIR_ . $this->name . '/paypal.gif');
             $smarty->assign('currency', $currency);
             return $this->display(__FILE__, 'payment/payment.tpl');
         } else {
             return $this->display(__FILE__, 'standard/paypal.tpl');
         }
     } else {
         die($this->l('No valid payment method selected'));
     }
 }
Esempio n. 17
0
 /**
  * Check if COD carrier can be visible in checkout pages
  * depending on customer delivery address country and selected currency
  *
  * @param Cart $cart
  * @param DpdGroupConfiguration $configuration
  * @param $id_customer_country
  * @return bool
  */
 private function isCODCarrierAvailable(Cart $cart, DpdGroupConfiguration $configuration, $id_customer_country)
 {
     if ($configuration->dpd_country_select == DpdGroupConfiguration::OTHER_COUNTRY) {
         return true;
     }
     $customer_country_iso_code = Country::getIsoById((int) $id_customer_country);
     if ($configuration->dpd_country_select != $customer_country_iso_code) {
         return false;
     }
     require_once _DPDGROUP_CONTROLLERS_DIR_ . 'Configuration.controller.php';
     $configuration_controller = new DpdGroupConfigurationController();
     $configuration_controller->setAvailableCountries();
     $sender_currency = '';
     if (isset($configuration_controller->countries[$configuration->dpd_country_select]['currency'])) {
         $sender_currency = $configuration_controller->countries[$configuration->dpd_country_select]['currency'];
     }
     if (!$sender_currency) {
         return false;
     }
     $id_cart_currency = (int) $cart->id_currency;
     $cart_currency = Currency::getCurrency((int) $id_cart_currency);
     if ($sender_currency != $cart_currency['iso_code']) {
         return false;
     }
     return true;
 }
Esempio n. 18
0
    public function hookAdminStatsModules($params)
    {
        global $cookie;
        $categories = Category::getCategories(intval($cookie->id_lang), true, false);
        $productToken = Tools::getAdminToken('AdminCatalog' . intval(Tab::getIdFromClassName('AdminCatalog')) . intval($cookie->id_employee));
        $currency = Currency::getCurrency(Configuration::get('PS_CURRENCY_DEFAULT'));
        $link = new Link();
        $irow = 0;
        if ($id_category = intval(Tools::getValue('id_category'))) {
            $this->_join = 'LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_product` = p.`id_product`)';
            $this->_where = 'AND cp.`id_category` = ' . $id_category;
        }
        $result1 = $this->getQuery1(true);
        $total = $result1['total'];
        $averagePrice = $result1['average_price'];
        $totalPictures = $result1['images'];
        $averagePictures = $total ? $totalPictures / $total : 0;
        $neverBought = $this->getProductsNB(intval($cookie->id_lang));
        $totalNB = $neverBought['total'];
        $productsNB = $neverBought['result'];
        $totalBought = $this->getTotalBought();
        $averagePurchase = $total ? $totalBought / $total : 0;
        $totalPageViewed = $this->getTotalPageViewed();
        $averageViewed = $total ? $totalPageViewed / $total : 0;
        $conversion = number_format(floatval($totalPageViewed ? $totalBought / $totalPageViewed : 0), 2, '.', '');
        if ($conversionReverse = number_format(floatval($totalBought ? $totalPageViewed / $totalBought : 0), 2, '.', '')) {
            $conversion .= ' (1 ' . $this->l('purchase') . ' / ' . $conversionReverse . ' ' . $this->l('visits') . ')';
        }
        $totalNV = $total - $this->getTotalProductViewed();
        $html = '
		<script type="text/javascript" language="javascript">openCloseLayer(\'calendar\');</script>
		<fieldset class="width3"><legend><img src="../modules/' . $this->name . '/logo.gif" /> ' . $this->displayName . '</legend>
			<label>
				' . $this->l('Choose a category') . '
			</label>
			<div class="margin-form">
				<form action="" method="post" id="categoriesForm">
					<select name="id_category" onchange="$(\'#categoriesForm\').submit();">
						<option value="0">' . $this->l('All') . '</option>';
        foreach ($categories as $category) {
            $html .= '<option value="' . $category['id_category'] . '"' . ($id_category == $category['id_category'] ? ' selected="selected"' : '') . '>' . $category['name'] . '</option>';
        }
        $html .= '
					</select>
				</form>
			</div>
			<div class="clear space"></div>
			<table>
				' . $this->returnLine($this->l('Products available:'), intval($total)) . '
				' . $this->returnLine($this->l('Average price (base price):'), Tools::displayPrice($averagePrice, $currency)) . '
				' . $this->returnLine($this->l('Product pages viewed:'), intval($totalPageViewed)) . '
				' . $this->returnLine($this->l('Products bought:'), intval($totalBought)) . '
				' . $this->returnLine($this->l('Average number of page visits:'), number_format(floatval($averageViewed), 2, '.', '')) . '
				' . $this->returnLine($this->l('Average number of purchases:'), number_format(floatval($averagePurchase), 2, '.', '')) . '
				' . $this->returnLine($this->l('Images available:'), intval($totalPictures)) . '
				' . $this->returnLine($this->l('Average number of images:'), number_format(floatval($averagePictures), 2, '.', '')) . '
				' . $this->returnLine($this->l('Products never viewed:'), intval($totalNV) . ' / ' . intval($total)) . '
				' . $this->returnLine('<a style="cursor : pointer" onclick="openCloseLayer(\'pnb\')">' . $this->l('Products never bought:') . '</a>', intval($totalNB) . ' / ' . intval($total)) . '
				' . $this->returnLine($this->l('Conversion rate*:'), $conversion) . '
			</table>
			<div style="margin-top: 20px;">
				<span style="color:red;font-weight:bold">*</span> 
				' . $this->l('Average conversion rate for the product page. It is possible to purchase a product without viewing the product page, so this rate can be greater than 1.') . '
			</div>
		</fieldset>';
        if (sizeof($productsNB) and sizeof($productsNB) < 50) {
            $html .= '
			<fieldset class="width3 space"><legend><img src="../modules/' . $this->name . '/basket_delete.png" /> ' . $this->l('Products never bought') . '</legend>
				<table cellpadding="0" cellspacing="0" class="table">
					<tr><th>' . $this->l('ID') . '</th><th>' . $this->l('Name') . '</th><th>' . $this->l('Edit / View') . '</th></tr>';
            foreach ($productsNB as $product) {
                $html .= '
					<tr' . ($irow++ % 2 ? ' class="alt_row"' : '') . '>
						<td>' . $product['id_product'] . '</td>
						<td style="width: 400px;">' . $product['name'] . '</td>
						<td style="text-align: right">
							<a href="index.php?tab=AdminCatalog&id_product=' . $product['id_product'] . '&addproduct&token=' . $productToken . '" target="_blank"><img src="../modules/' . $this->name . '/page_edit.png" /></a>
							<a href="' . $link->getProductLink($product['id_product'], $product['link_rewrite']) . '" target="_blank"><img src="../modules/' . $this->name . '/application_home.png" /></a>
						</td>
					</tr>';
            }
            $html .= '
				</table>
			</fieldset>';
        }
        return $html;
    }
 public function initContent($cart, $user, $shopname)
 {
     session_start();
     unset($_SESSION['log_id']);
     $_SESSION['log_id'] = time();
     $db = Db::getInstance();
     $token = Tools::getValue('paymillToken');
     $payment = Tools::getValue('payment');
     $validPayments = array();
     if (Configuration::get('PIGMBH_PAYMILL_DEBIT')) {
         $validPayments[] = 'debit';
     }
     if (Configuration::get('PIGMBH_PAYMILL_CREDITCARD')) {
         $validPayments[] = 'creditcard';
     }
     if (empty($token)) {
         $this->log('No paymill token was provided. Redirect to payments page.', null);
         Tools::redirect('order.php?step=1&paymillerror=1&paymillpayment=' . $payment);
     } elseif (!in_array($payment, $validPayments)) {
         $this->log('The selected Paymentmethod is not valid.', $payment);
         Tools::redirect('order.php?step=1&paymillerror=1&paymillpayment=' . $payment);
     }
     $this->log('Start processing payment with token', $token);
     $paymentProcessor = new Services_Paymill_PaymentProcessor(Configuration::get('PIGMBH_PAYMILL_PRIVATEKEY'), "https://api.paymill.com/v2/");
     $currency = Currency::getCurrency((int) $cart->id_currency);
     $iso_currency = $currency['iso_code'];
     $paymentProcessor->setAmount($_SESSION['pigmbhPaymill']['authorizedAmount']);
     $paymentProcessor->setPreAuthAmount($_SESSION['pigmbhPaymill']['authorizedAmount']);
     $paymentProcessor->setToken($token);
     $paymentProcessor->setCurrency(strtolower($iso_currency));
     $paymentProcessor->setName($user["lastname"] . ', ' . $user["firstname"]);
     $paymentProcessor->setEmail($user["email"]);
     $paymentProcessor->setDescription(" ");
     $paymentProcessor->setLogger($this);
     $paymentProcessor->setSource(Configuration::get('PIGMBH_PAYMILL_VERSION') . "_prestashop_" . _PS_VERSION_);
     if ($payment == 'creditcard') {
         $userData = $db->getRow('SELECT `clientId`,`paymentId` FROM `pigmbh_paymill_creditcard_userdata` WHERE `userId`=' . $user["id_customer"]);
     } elseif ($payment == 'debit') {
         $userData = $db->getRow('SELECT `clientId`,`paymentId` FROM `pigmbh_paymill_directdebit_userdata` WHERE `userId`=' . $user["id_customer"]);
     }
     $paymentProcessor->setClientId(!empty($userData['clientId']) ? $userData['clientId'] : null);
     if ($token === "dummyToken") {
         $paymentProcessor->setPaymentId(!empty($userData['paymentId']) ? $userData['paymentId'] : null);
     }
     $result = $paymentProcessor->processPayment();
     $this->log('Payment processing resulted in', $result ? 'Success' : 'Fail');
     $paymill = new PigmbhPaymill();
     // finish the order if payment was sucessfully processed
     if ($result === true) {
         $customer = new Customer((int) $cart->id_customer);
         if ($payment === 'debit') {
             $days = Configuration::get('PIGMBH_PAYMILL_DEBIT_DAYS');
             if (!is_numeric($days)) {
                 $days = '7';
             }
             $paymentText = $paymill->l('ELV /SEPA Debit Date: ') . date('Y-m-d', strtotime("+{$days} day"));
         } else {
             $paymentText = $paymill->l('Credit Card');
         }
         $_SESSION['piPaymentText'] = $paymentText;
         $this->saveUserData($paymentProcessor->getClientId(), $paymentProcessor->getPaymentId(), (int) $cart->id_customer);
         $orderID = $paymill->validateOrder((int) $cart->id, Configuration::get('PIGMBH_PAYMILL_ORDERSTATE'), $cart->getOrderTotal(true, Cart::BOTH), $paymentText, null, array(), null, false, $customer->secure_key);
         $_SESSION['piOrderId'] = $orderID;
         $this->updatePaymillTransaction($paymentProcessor->getTransactionId(), 'OrderID: ' . $orderID . ' - Name:' . $user["lastname"] . ', ' . $user["firstname"]);
         Tools::redirect('order-confirmation.php?key=' . $customer->secure_key . '&id_cart=' . (int) $cart->id . '&id_module=' . (int) $paymill->id . '&id_order=' . (int) $paymill->currentOrder);
     } else {
         $errorMessage = $paymill->errorCodeMapping($paymentProcessor->getErrorCode());
         $this->log('ErrorCode', $errorMessage);
         Tools::redirect('order.php?paymillpayment=' . $payment . '&step=3&paymillerror=1&errorCode=' . $paymentProcessor->getErrorCode());
     }
 }
 /**
  * @since 1.5.0
  */
 public function supplyOrdersImport()
 {
     // opens CSV & sets locale
     $this->receiveTab();
     $handle = $this->openCsvFile();
     AdminImportController::setLocale();
     // main loop, for each supply orders to import
     for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); ++$current_line) {
         // if convert requested
         if (Tools::getValue('convert')) {
             $line = $this->utf8EncodeArray($line);
         }
         $info = AdminImportController::getMaskedRow($line);
         // sets default values if needed
         AdminImportController::setDefaultValues($info);
         // if an id is set, instanciates a supply order with this id if possible
         if (array_key_exists('id', $info) && (int) $info['id'] && SupplyOrder::exists((int) $info['id'])) {
             $supply_order = new SupplyOrder((int) $info['id']);
         } elseif (array_key_exists('reference', $info) && $info['reference'] && SupplyOrder::exists(pSQL($info['reference']))) {
             $supply_order = SupplyOrder::getSupplyOrderByReference(pSQL($info['reference']));
         } else {
             // new supply order
             $supply_order = new SupplyOrder();
         }
         // gets parameters
         $id_supplier = (int) $info['id_supplier'];
         $id_lang = (int) $info['id_lang'];
         $id_warehouse = (int) $info['id_warehouse'];
         $id_currency = (int) $info['id_currency'];
         $reference = pSQL($info['reference']);
         $date_delivery_expected = pSQL($info['date_delivery_expected']);
         $discount_rate = (double) $info['discount_rate'];
         $is_template = (bool) $info['is_template'];
         $error = '';
         // checks parameters
         if (!Supplier::supplierExists($id_supplier)) {
             $error = sprintf($this->l('Supplier ID (%d) is not valid (at line %d).'), $id_supplier, $current_line + 1);
         }
         if (!Language::getLanguage($id_lang)) {
             $error = sprintf($this->l('Lang ID (%d) is not valid (at line %d).'), $id_lang, $current_line + 1);
         }
         if (!Warehouse::exists($id_warehouse)) {
             $error = sprintf($this->l('Warehouse ID (%d) is not valid (at line %d).'), $id_warehouse, $current_line + 1);
         }
         if (!Currency::getCurrency($id_currency)) {
             $error = sprintf($this->l('Currency ID (%d) is not valid (at line %d).'), $id_currency, $current_line + 1);
         }
         if (empty($supply_order->reference) && SupplyOrder::exists($reference)) {
             $error = sprintf($this->l('Reference (%s) already exists (at line %d).'), $reference, $current_line + 1);
         }
         if (!empty($supply_order->reference) && ($supply_order->reference != $reference && SupplyOrder::exists($reference))) {
             $error = sprintf($this->l('Reference (%s) already exists (at line %d).'), $reference, $current_line + 1);
         }
         if (!Validate::isDateFormat($date_delivery_expected)) {
             $error = sprintf($this->l('Date (%s) is not valid (at line %d). Format: %s.'), $date_delivery_expected, $current_line + 1, $this->l('YYYY-MM-DD'));
         } elseif (new DateTime($date_delivery_expected) <= new DateTime('yesterday')) {
             $error = sprintf($this->l('Date (%s) cannot be in the past (at line %d). Format: %s.'), $date_delivery_expected, $current_line + 1, $this->l('YYYY-MM-DD'));
         }
         if ($discount_rate < 0 || $discount_rate > 100) {
             $error = sprintf($this->l('Discount rate (%d) is not valid (at line %d). %s.'), $discount_rate, $current_line + 1, $this->l('Format: Between 0 and 100'));
         }
         if ($supply_order->id > 0 && !$supply_order->isEditable()) {
             $error = sprintf($this->l('Supply Order (%d) is not editable (at line %d).'), $supply_order->id, $current_line + 1);
         }
         // if no errors, sets supply order
         if (empty($error)) {
             // adds parameters
             $info['id_ref_currency'] = (int) Currency::getDefaultCurrency()->id;
             $info['supplier_name'] = pSQL(Supplier::getNameById($id_supplier));
             if ($supply_order->id > 0) {
                 $info['id_supply_order_state'] = (int) $supply_order->id_supply_order_state;
                 $info['id'] = (int) $supply_order->id;
             } else {
                 $info['id_supply_order_state'] = 1;
             }
             // sets parameters
             AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $supply_order);
             // updatesd($supply_order);
             $res = true;
             if ((int) $supply_order->id && ($supply_order->exists((int) $supply_order->id) || $supply_order->exists($supply_order->reference))) {
                 $res &= $supply_order->update();
             } else {
                 $supply_order->force_id = (bool) Tools::getValue('forceIDs');
                 $res &= $supply_order->add();
             }
             // errors
             if (!$res) {
                 $this->errors[] = sprintf($this->l('Supply Order could not be saved (at line %d).'), $current_line + 1);
             }
         } else {
             $this->errors[] = $error;
         }
     }
     // closes
     $this->closeCsvFile($handle);
 }
Esempio n. 21
0
    /**
     * Post treatment for suppliers
     */
    public function processSuppliers()
    {
        if ((int) Tools::getValue('supplier_loaded') === 1 && Validate::isLoadedObject($product = new Product((int) Tools::getValue('id_product')))) {
            // Get all id_product_attribute
            $attributes = $product->getAttributesResume($this->context->language->id);
            if (empty($attributes)) {
                $attributes[] = array('id_product_attribute' => 0, 'attribute_designation' => '');
            }
            // Get all available suppliers
            $suppliers = Supplier::getSuppliers();
            // Get already associated suppliers
            $associated_suppliers = ProductSupplier::getSupplierCollection($product->id);
            $suppliers_to_associate = array();
            $new_default_supplier = 0;
            if (Tools::isSubmit('default_supplier')) {
                $new_default_supplier = (int) Tools::getValue('default_supplier');
            }
            // Get new associations
            foreach ($suppliers as $supplier) {
                if (Tools::isSubmit('check_supplier_' . $supplier['id_supplier'])) {
                    $suppliers_to_associate[] = $supplier['id_supplier'];
                }
            }
            // Delete already associated suppliers if needed
            foreach ($associated_suppliers as $key => $associated_supplier) {
                if (!in_array($associated_supplier->id_supplier, $suppliers_to_associate)) {
                    $associated_supplier->delete();
                    unset($associated_suppliers[$key]);
                }
            }
            // Associate suppliers
            foreach ($suppliers_to_associate as $id) {
                $to_add = true;
                foreach ($associated_suppliers as $as) {
                    if ($id == $as->id_supplier) {
                        $to_add = false;
                    }
                }
                if ($to_add) {
                    $product_supplier = new ProductSupplier();
                    $product_supplier->id_product = $product->id;
                    $product_supplier->id_product_attribute = 0;
                    $product_supplier->id_supplier = $id;
                    if ($this->context->currency->id) {
                        $product_supplier->id_currency = (int) $this->context->currency->id;
                    } else {
                        $product_supplier->id_currency = (int) Configuration::get('PS_CURRENCY_DEFAULT');
                    }
                    $product_supplier->save();
                    $associated_suppliers[] = $product_supplier;
                }
            }
            // Manage references and prices
            foreach ($attributes as $attribute) {
                foreach ($associated_suppliers as $supplier) {
                    if (Tools::isSubmit('supplier_reference_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier) || Tools::isSubmit('product_price_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier) && Tools::isSubmit('product_price_currency_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier)) {
                        $reference = pSQL(Tools::getValue('supplier_reference_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier, ''));
                        $price = (double) str_replace(array(' ', ','), array('', '.'), Tools::getValue('product_price_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier, 0));
                        $price = Tools::ps_round($price, 6);
                        $id_currency = (int) Tools::getValue('product_price_currency_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier, 0);
                        if ($id_currency <= 0 || (!($result = Currency::getCurrency($id_currency)) || empty($result))) {
                            $this->errors[] = Tools::displayError('The selected currency is not valid');
                        }
                        // Save product-supplier data
                        $product_supplier_id = (int) ProductSupplier::getIdByProductAndSupplier($product->id, $attribute['id_product_attribute'], $supplier->id_supplier);
                        if (!$product_supplier_id) {
                            $product->addSupplierReference($supplier->id_supplier, (int) $attribute['id_product_attribute'], $reference, (double) $price, (int) $id_currency);
                            if ($product->id_supplier == $supplier->id_supplier) {
                                if ((int) $attribute['id_product_attribute'] > 0) {
                                    $data = array('supplier_reference' => pSQL($reference), 'wholesale_price' => (double) Tools::convertPrice($price, $id_currency));
                                    $where = '
										a.id_product = ' . (int) $product->id . '
										AND a.id_product_attribute = ' . (int) $attribute['id_product_attribute'];
                                    ObjectModel::updateMultishopTable('Combination', $data, $where);
                                } else {
                                    $product->wholesale_price = (double) Tools::convertPrice($price, $id_currency);
                                    //converted in the default currency
                                    $product->supplier_reference = pSQL($reference);
                                    $product->update();
                                }
                            }
                        } else {
                            $product_supplier = new ProductSupplier($product_supplier_id);
                            $product_supplier->id_currency = (int) $id_currency;
                            $product_supplier->product_supplier_price_te = (double) $price;
                            $product_supplier->product_supplier_reference = pSQL($reference);
                            $product_supplier->update();
                        }
                    } elseif (Tools::isSubmit('supplier_reference_' . $product->id . '_' . $attribute['id_product_attribute'] . '_' . $supplier->id_supplier)) {
                        //int attribute with default values if possible
                        if ((int) $attribute['id_product_attribute'] > 0) {
                            $product_supplier = new ProductSupplier();
                            $product_supplier->id_product = $product->id;
                            $product_supplier->id_product_attribute = (int) $attribute['id_product_attribute'];
                            $product_supplier->id_supplier = $supplier->id_supplier;
                            $product_supplier->save();
                        }
                    }
                }
            }
            // Manage defaut supplier for product
            if ($new_default_supplier != $product->id_supplier) {
                $this->object->id_supplier = $new_default_supplier;
                $this->object->update();
            }
        }
    }
Esempio n. 22
0
 /**
  * Returns id of order currency
  * @return int
  */
 public function getDotCurrencyId()
 {
     $currency = Currency::getCurrency($this->context->cart->id_currency);
     return $currency["id_currency"];
 }
Esempio n. 23
0
    public function display()
    {
        global $cookie;
        $this->warnDomainName();
        $tab = get_class();
        $protocol = Tools::usingSecureMode() ? 'https' : 'http';
        $isoDefault = Language::getIsoById(intval(Configuration::get('PS_LANG_DEFAULT')));
        $isoUser = Language::getIsoById(intval($cookie->id_lang));
        $isoCountry = Country::getIsoById(Configuration::get('PS_COUNTRY_DEFAULT'));
        $currency = new Currency((int) Configuration::get('PS_CURRENCY_DEFAULT'));
        $employee = new Employee($cookie->id_employee);
        echo '<div>
		<h1>' . $this->l('Dashboard') . '</h1>
		<hr style="background-color: #812143;color: #812143;" />
		<br />';
        if (@ini_get('allow_url_fopen')) {
            $upgrade = new Upgrader();
            if ($update = $upgrade->checkPSVersion()) {
                echo '<div class="warning warn" style="margin-bottom:30px;"><h3>' . $this->l('New PrestaShop version available') . ' : <a style="text-decoration: underline;" href="' . $update['link'] . '" target="_blank">' . $this->l('Download') . '&nbsp;' . $update['name'] . '</a> !</h3></div>';
            }
        } else {
            echo '<p>' . $this->l('Update notification unavailable') . '</p>';
            echo '<p>&nbsp;</p>';
            echo '<p>' . $this->l('To receive PrestaShop update warnings, you need to activate the <b>allow_url_fopen</b> command in your <b>php.ini</b> config file.') . ' [<a href="http://www.php.net/manual/' . $isoUser . '/ref.filesystem.php">' . $this->l('more info') . '</a>]</p>';
            echo '<p>' . $this->l('If you don\'t know how to do that, please contact your host administrator !') . '</p><br>';
        }
        echo '</div>';
        if ($employee->bo_show_screencast) {
            echo '
			<div id="adminpresentation">
				<iframe src="' . $protocol . '://screencasts.prestashop.com/screencast.php?iso_lang=' . Tools::strtolower($isoUser) . '" style="border:none;width:100%;height:420px;" scrolling="no"></iframe>
				<div id="footer_iframe_home">
					<!--<a href="#">' . $this->l('View more video tutorials') . '</a>-->
					<input type="checkbox" id="screencast_dont_show_again"><label for="screencast_dont_show_again">' . $this->l('don\'t show again') . '</label>
				</div>
			</div>
			<script type="text/javascript">
			$(document).ready(function() {
				$(\'#screencast_dont_show_again\').click(function() {
					if ($(this).is(\':checked\'))
					{
						$.ajax({
							type: \'POST\',
							async: true,
							url: \'ajax.php?toggleScreencast\',
							success: function(data) {
								$(\'#adminpresentation\').slideUp(\'slow\');
							}
						});
					}
				});
			});
			</script>
			<div class="clear"></div><br />';
        }
        echo '
		<div id="column_left">
			<ul class="F_list clearfix">
				<li id="first_block">
					<h4><a href="index.php?tab=AdminCatalog&addcategory&token=' . Tools::getAdminTokenLite('AdminCatalog') . '">' . $this->l('New category') . '</a></h4>
					<p>' . $this->l('Create a new category and organize your products.') . '</p>
				</li>
				<li id="second_block">
					<h4><a href="index.php?tab=AdminCatalog&id_category=1&addproduct&token=' . Tools::getAdminTokenLite('AdminCatalog') . '">' . $this->l('New product') . '</a></h4>
					<p>' . $this->l('Fill up your catalog with new articles and attributes.') . '</p>
				</li>
				<li id="third_block">
					<h4><a href="index.php?tab=AdminStats&token=' . Tools::getAdminTokenLite('AdminStats') . '">' . $this->l('Statistics') . '</a></h4>
					<p>' . $this->l('Manage your activity with a thorough analysis of your e-shop.') . '</p>
				</li>
				<li id="fourth_block">
					<h4><a href="index.php?tab=AdminEmployees&addemployee&token=' . Tools::getAdminTokenLite('AdminEmployees') . '">' . $this->l('New employee') . '</a></h4>
					<p>' . $this->l('Add a new employee account and discharge a part of your duties of shop owner.') . '</p>
				</li>
			</ul>
			';
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
			SELECT SUM(o.`total_paid_real` / o.conversion_rate) as total_sales, COUNT(*) as total_orders
			FROM `' . _DB_PREFIX_ . 'orders` o
			WHERE o.valid = 1
			AND o.`invoice_date` BETWEEN \'' . date('Y-m') . '-01 00:00:00\' AND \'' . date('Y-m') . '-31 23:59:59\' ');
        $result2 = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
			SELECT COUNT(`id_customer`) AS total_registrations
			FROM `' . _DB_PREFIX_ . 'customer` c
			WHERE c.`date_add` BETWEEN \'' . date('Y-m') . '-01 00:00:00\' AND \'' . date('Y-m') . '-31 23:59:59\'');
        $result3 = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
			SELECT SUM(pv.`counter`) AS total_viewed
			FROM `' . _DB_PREFIX_ . 'page_viewed` pv
			LEFT JOIN `' . _DB_PREFIX_ . 'date_range` dr ON pv.`id_date_range` = dr.`id_date_range`
			LEFT JOIN `' . _DB_PREFIX_ . 'page` p ON pv.`id_page` = p.`id_page`
			LEFT JOIN `' . _DB_PREFIX_ . 'page_type` pt ON pt.`id_page_type` = p.`id_page_type`
			WHERE pt.`name` = \'product.php\'
			AND dr.`time_start` BETWEEN \'' . date('Y-m') . '-01 00:00:00\' AND \'' . date('Y-m') . '-31 23:59:59\'
			AND dr.`time_end` BETWEEN \'' . date('Y-m') . '-01 00:00:00\' AND \'' . date('Y-m') . '-31 23:59:59\'');
        $results = array_merge($result, array_merge($result2, $result3));
        echo '
			<div class="table_info">
				<h5><a href="index.php?tab=AdminStats&token=' . Tools::getAdminTokenLite('AdminStats') . '">' . $this->l('View more') . '</a> ' . $this->l('Monthly Statistics') . ' </h5>
				<table class="table_info_details">
					<tr class="tr_odd">
						<td class="td_align_left">
						' . $this->l('Sales') . '
						</td>
						<td>
							' . Tools::displayPrice($results['total_sales'], $currency) . '
						</td>
					</tr>
					<tr>
						<td class="td_align_left">
							' . $this->l('Total registrations') . '
						</td>
						<td>
							' . (int) $results['total_registrations'] . '
						</td>
					</tr>
					<tr class="tr_odd">
						<td class="td_align_left">
							' . $this->l('Total orders') . '
						</td>
						<td>
							' . (int) $results['total_orders'] . '
						</td>
					</tr>
					<tr>
						<td class="td_align_left">
							' . $this->l('Product pages viewed') . '
						</td>
						<td>
							' . (int) $results['total_viewed'] . '
						</td>
					</tr>
				</table>
			</div>
			';
        $all = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT COUNT(*) FROM ' . _DB_PREFIX_ . 'customer_thread');
        $unread = (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT COUNT(*) FROM `' . _DB_PREFIX_ . 'customer_thread` WHERE `status` = "open"');
        $pending = (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT COUNT(*) FROM `' . _DB_PREFIX_ . 'customer_thread` WHERE `status` LIKE "%pending%"');
        $close = $all - ($unread + $pending);
        echo '
			<div class="table_info" id="table_info_last">
				<h5><a href="index.php?tab=AdminCustomerThreads&token=' . Tools::getAdminTokenLite('AdminCustomerThreads') . '">' . $this->l('View more') . '</a> ' . $this->l('Customers service') . '</h5>
				<table class="table_info_details">
					<tr class="tr_odd">
						<td class="td_align_left">
						' . $this->l('Thread unread') . '
						</td>
						<td>
							' . $unread . '
						</td>
					</tr>
					<tr>
						<td class="td_align_left">
							' . $this->l('Thread pending') . '
						</td>
						<td>
							' . $pending . '
						</td>
					</tr>
					<tr class="tr_odd">
						<td class="td_align_left">
							' . $this->l('Thread closed') . '
						</td>
						<td>
							' . $close . '
						</td>
					</tr>
					<tr>
						<td class="td_align_left">
							' . $this->l('Total thread') . '
						</td>
						<td>
							' . $all . '
						</td>
					</tr>
				</table>
			</div>

			<div id="table_info_large">
				<h5><a href="index.php?tab=AdminStats&token=' . Tools::getAdminTokenLite('AdminStats') . '">' . $this->l('View more') . '</a> <strong>' . $this->l('Statistics') . '</strong> / ' . $this->l('Sales of the week') . '</h5>
				<div id="stat_google">';
        define('PS_BASE_URI', __PS_BASE_URI__);
        $chart = new Chart();
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
			SELECT total_paid / conversion_rate as total_converted, invoice_date
			FROM ' . _DB_PREFIX_ . 'orders o
			WHERE valid = 1
			AND invoice_date BETWEEN \'' . date('Y-m-d', strtotime('-7 DAYS', time())) . ' 00:00:00\' AND \'' . date('Y-m-d H:i:s') . '\'');
        foreach ($result as $row) {
            $chart->getCurve(1)->setPoint(strtotime($row['invoice_date']), $row['total_converted']);
        }
        $chart->setSize(580, 170);
        $chart->setTimeMode(strtotime('-7 DAYS', time()), time(), 'd');
        $chart->getCurve(1)->setLabel($this->l('Sales +Tx') . ' (' . strtoupper($currency->iso_code) . ')');
        $chart->display();
        echo '	</div>
			</div>
			<table cellpadding="0" cellspacing="0" id="table_customer">
				<thead>
					<tr>
						<th class="order_id"><span class="first">' . $this->l('ID') . '</span></th>
						<th class="order_customer"><span>' . $this->l('Customer Name') . '</span></th>
						<th class="order_status"><span>' . $this->l('Status') . '</span></th>
						<th class="order_total"><span>' . $this->l('Total') . '</span></th>
						<th class="order_action"><span class="last">' . $this->l('Action') . '</span></th>
					<tr>
				</thead>
				<tbody>';
        $orders = Order::getOrdersWithInformations(10);
        $i = 0;
        foreach ($orders as $order) {
            $currency = Currency::getCurrency((int) $order['id_currency']);
            echo '
					<tr' . ($i % 2 ? ' id="order_line1"' : '') . '>
						<td class="order_td_first order_id">' . (int) $order['id_order'] . '</td>
						<td class="order_customer">' . Tools::htmlentitiesUTF8($order['firstname']) . ' ' . Tools::htmlentitiesUTF8($order['lastname']) . '</td>
						<td class="order_status">' . Tools::htmlentitiesUTF8($order['state_name']) . '</td>
						<td class="order_total">' . Tools::displayPrice((double) $order['total_paid'], $currency) . '</td>
						<td class="order_action">
							<a href="index.php?tab=AdminOrders&id_order=' . (int) $order['id_order'] . '&vieworder&token=' . Tools::getAdminTokenLite('AdminOrders') . '" title="' . $this->l('Details') . '"><img src="../img/admin/details.gif" alt="' . $this->l('See') . '" /></a>
						</td>
					</tr>
				';
            $i++;
        }
        echo '
				</tbody>
			</table>
		</div>
		<div id="column_right">
			<script type="text/javascript">
				$(document).ready(function() {
					$.ajax({
						url: "ajax.php",
						dataType: "json",
						data: "getAdminHomeElement",
						success: function(json) {
							if (json.screencast != \'NOK\')
								$(\'#adminpresentation\').fadeIn(\'slow\');
							else
								$(\'#adminpresentation\').fadeOut(\'slow\');

							$(\'#partner_preactivation\').fadeOut(\'slow\', function() {
								if (json.partner_preactivation != \'NOK\')
									$(\'#partner_preactivation\').html(json.partner_preactivation);
								else
									$(\'#partner_preactivation\').html(\'\');
								$(\'#partner_preactivation\').fadeIn(\'slow\');
							});

							$(\'#discover_prestashop\').fadeOut(\'slow\', function() {
								if (json.discover_prestashop != \'NOK\')
									$(\'#discover_prestashop\').html(json.discover_prestashop);
								else
									$(\'#discover_prestashop\').html(\'\');
								$(\'#discover_prestashop\').fadeIn(\'slow\');
							});
						},
						error: function(XMLHttpRequest, textStatus, errorThrown)
						{
							$(\'#adminpresentation\').fadeOut(\'slow\');
							$(\'#partner_preactivation\').fadeOut(\'slow\');
							$(\'#discover_prestashop\').fadeOut(\'slow\');
						}
					});
				});
			</script>
			<div id="partner_preactivation">
				<p class="center"><img src="../img/loader.gif" alt="" /> ' . translate('Loading...') . '</p>
			</div>
		';
        if (Tools::isSubmit('hideOptimizationTips')) {
            Configuration::updateValue('PS_HIDE_OPTIMIZATION_TIPS', 1);
        }
        $this->_displayOptimizationTips();
        echo '
			<div id="discover_prestashop">
				<p class="center"><img src="../img/loader.gif" alt="" /> ' . translate('Loading...') . '</p>
			</div>
		</div>
		<div class="clear"></div>';
        echo Module::hookExec('backOfficeHome');
    }
Esempio n. 24
0
 /**
  * @param OrderCore $order
  *
  * @return array
  */
 protected function _getOrderItems($order)
 {
     $result = array();
     if (method_exists($order, 'getOrderDetailList')) {
         $orderItems = $order->getOrderDetailList();
     } else {
         $orderItems = $order->getProducts();
     }
     foreach ($orderItems as $item) {
         /** @var OrderDetailCore $orderItemCore */
         $orderItemCore = new OrderDetail($item['id_order_detail']);
         $orderItem = new ShopgateExternalOrderItem();
         $orderItem->setItemNumber($orderItemCore->product_id);
         //$orderItem->setItemNumberPublic()
         $orderItem->setQuantity($orderItemCore->product_quantity);
         $orderItem->setName($orderItemCore->product_name);
         $orderItem->setUnitAmount($orderItemCore->unit_price_tax_excl);
         $orderItem->setUnitAmountWithTax($orderItemCore->unit_price_tax_incl);
         $orderItem->setTaxPercent($orderItemCore->tax_rate);
         /** @var CurrencyCore $currency */
         $currency = Currency::getCurrency($order->id_currency);
         $orderItem->setCurrency($currency['iso_code']);
         if (!array_key_exists($orderItemCore->tax_rate, $this->_orderTaxes)) {
             $this->_orderTaxes[$orderItemCore->tax_rate] = array('tax_name' => $orderItemCore->tax_name, 'price_tax_excl' => $orderItemCore->unit_price_tax_excl * $orderItemCore->product_quantity);
         } else {
             $taxInfoItem = $this->_orderTaxes[$orderItemCore->tax_rate];
             $taxInfoItem['price_tax_excl'] = $taxInfoItem['price_tax_excl'] + $orderItemCore->unit_price_tax_excl * $orderItemCore->product_quantity;
             $this->_orderTaxes[$orderItemCore->tax_rate] = $taxInfoItem;
         }
         $result[] = $orderItem;
     }
     return $result;
 }
Esempio n. 25
0
    public function display()
    {
        global $cookie;
        $currency = Currency::getCurrency(Configuration::get('PS_CURRENCY_DEFAULT'));
        $language = Language::getLanguage(intval($cookie->id_lang));
        $iso = $language['iso_code'];
        $dateBetween = ModuleGraph::getDateBetween();
        $sales = self::getSales($dateBetween);
        $carts = self::getCarts($dateBetween);
        $records = self::getRecords($dateBetween);
        echo '
		<div style="float: left">';
        $this->displayCalendar();
        $this->displayMenu(false);
        $this->displayEngines();
        $this->displaySearch();
        echo '
		</div>
		<div style="float: left; margin-left: 40px;">
			<fieldset class="width3"><legend><img src="../img/admin/tab-stats.gif" /> ' . $this->l('Help') . '</legend>
				<p>' . $this->l('Use the calendar on the left to select the time period.') . '</p>
				<p>' . $this->l('All available statistic modules are displayed in the Navigation list beneath the calendar.') . '</p>
				<p>' . $this->l('In the Settings sub-tab, you can also customize the Stats tab to fit your needs and resources, change the graph rendering engine, and adjust the database settings.') . '</p>
			</fieldset>
			<br /><br />
			<fieldset class="width3"><legend><img src="../img/admin/___info-ca.gif" style="vertical-align: middle" /> ' . $this->l('Sales') . '</legend>
				<table>
					<tr><td style="font-weight: bold">' . $this->l('Total placed orders') . '</td><td style="padding-left: 20px">' . $sales['orders'] . '</td></tr>
					<tr><td style="font-weight: bold">' . $this->l('Total products sold') . '</td><td style="padding-left: 20px">' . $sales['products'] . '</td></tr>
				</table>
				<table cellspacing="0" cellpadding="0" class="table space">
					<tr>
						<th style="width: 150px"></th>
						<th style="width: 180px; text-align: center; font-weight: bold">' . $this->l('total paid with tax') . '</th>
						<th style="width: 220px; text-align: center; font-weight: bold">' . $this->l('total products not incl. tax') . '</th>
					</tr>
					<tr>
						<th style="font-weight: bold">' . $this->l('Sales turnover') . '</th>
						<td align="right">' . Tools::displayPrice($sales['ttc'], $currency) . '</td>
						<td align="right">' . Tools::displayPrice($sales['ht'], $currency) . '</td>
					</tr>
					<tr>
						<th style="font-weight: bold">' . $this->l('Largest order') . '</th>
						<td align="right">' . Tools::displayPrice($sales['maxttc'], $currency) . '</td>
						<td align="right">' . Tools::displayPrice($sales['maxht'], $currency) . '</td>
					</tr>
					<tr>
						<th style="font-weight: bold">' . $this->l('Smallest order') . '</th>
						<td align="right">' . Tools::displayPrice($sales['minttc'], $currency) . '</td>
						<td align="right">' . Tools::displayPrice($sales['minht'], $currency) . '</td>
					</tr>
				</table>
			</fieldset>
			<br /><br />
			<fieldset class="width3"><legend><img src="../img/admin/products.gif" style="vertical-align: middle" /> ' . $this->l('Carts') . '</legend>
				<table cellspacing="0" cellpadding="0" class="table">
					<tr>
						<th style="width: 150px"></th>
						<th style="width: 180px; text-align: center; font-weight: bold">' . $this->l('Products total all tax inc.') . '</th>
					</tr>
					<tr>
						<th style="font-weight: bold">' . $this->l('Average cart') . '</th>
						<td align="right">' . Tools::displayPrice($carts['average'], $currency) . '</td>
					</tr>
					<tr>
						<th style="font-weight: bold">' . $this->l('Largest cart') . '</th>
						<td align="right">' . Tools::displayPrice($carts['highest'], $currency) . '</td>
					</tr>
					<tr>
						<th style="font-weight: bold">' . $this->l('Smallest cart') . '</th>
						<td align="right">' . Tools::displayPrice($carts['lowest'], $currency) . '</td>
					</tr>
				</table>
			</fieldset>';
        if (strtolower($cookie->stats_granularity) != 'd' and $records and is_array($records)) {
            echo '
			<br /><br />
			<fieldset class="width3"><legend><img src="../img/admin/medal.png" style="vertical-align: middle" />' . $this->l('Records') . '</legend>
				<table cellspacing="0" cellpadding="0" class="table">
					<tr>
						<th style="width: 150px"></th>
						<th style="width: 100px; text-align: center; font-weight: bold">' . $this->l('date') . '</th>
						<th style="width: 120px; text-align: center; font-weight: bold">' . $this->l('with tax') . '</th>
						<th style="width: 180px; text-align: center; font-weight: bold">' . $this->l('only products not incl. tax') . '</th>
					</tr>';
            if (strtolower($cookie->stats_granularity) == 'y') {
                echo '
					<tr>
						<th style="font-weight: bold">' . $this->l('Best month') . '</th>
						<td align="right">' . $this->displayDate($records['bestmonth']['date'], $iso) . '</td>
						<td align="right">' . Tools::displayPrice($records['bestmonth']['totalttc'], $currency) . '</td>
						<td align="right">' . Tools::displayPrice($records['bestmonth']['totalht'], $currency) . '</td>
					</tr>
					<tr>
						<th style="font-weight: bold">' . $this->l('Worst month') . '</th>
						<td align="right">' . $this->displayDate($records['worstmonth']['date'], $iso) . '</td>
						<td align="right">' . Tools::displayPrice($records['worstmonth']['totalttc'], $currency) . '</td>
						<td align="right">' . Tools::displayPrice($records['worstmonth']['totalht'], $currency) . '</td>
					</tr>';
            }
            echo '
					<tr>
						<th style="font-weight: bold">' . $this->l('Best day') . '</th>
						<td align="right">' . $this->displayDate($records['bestday']['date'], $iso) . '</td>
						<td align="right">' . Tools::displayPrice($records['bestday']['totalttc'], $currency) . '</td>
						<td align="right">' . Tools::displayPrice($records['bestday']['totalht'], $currency) . '</td>
					</tr>
					<tr>
						<th style="font-weight: bold">' . $this->l('Worst day') . '</th>
						<td align="right">' . $this->displayDate($records['worstday']['date'], $iso) . '</td>
						<td align="right">' . Tools::displayPrice($records['worstday']['totalttc'], $currency) . '</td>
						<td align="right">' . Tools::displayPrice($records['worstday']['totalht'], $currency) . '</td>
					</tr>
				</table>
			</fieldset>';
        }
        echo '
		</div>
		<div class="clear"></div>';
    }
Esempio n. 26
0
 protected function _getPaymentMethods()
 {
     if (!$this->isLogged) {
         return '<p class="warning">' . Tools::displayError('Please sign in to see payment methods.') . '</p>';
     }
     if ($this->context->cart->OrderExists()) {
         return '<p class="warning">' . Tools::displayError('Error: This order has already been validated.') . '</p>';
     }
     if (!$this->context->cart->id_customer || !Customer::customerIdExistsStatic($this->context->cart->id_customer) || Customer::isBanned($this->context->cart->id_customer)) {
         return '<p class="warning">' . Tools::displayError('Error: No customer.') . '</p>';
     }
     $address_delivery = new Address($this->context->cart->id_address_delivery);
     $address_invoice = $this->context->cart->id_address_delivery == $this->context->cart->id_address_invoice ? $address_delivery : new Address($this->context->cart->id_address_invoice);
     if (!$this->context->cart->id_address_delivery || !$this->context->cart->id_address_invoice || !Validate::isLoadedObject($address_delivery) || !Validate::isLoadedObject($address_invoice) || $address_invoice->deleted || $address_delivery->deleted) {
         return '<p class="warning">' . Tools::displayError('Error: Please select an address.') . '</p>';
     }
     if (count($this->context->cart->getDeliveryOptionList()) == 0 && !$this->context->cart->isVirtualCart()) {
         if ($this->context->cart->isMultiAddressDelivery()) {
             return '<p class="warning">' . Tools::displayError('Error: None of your chosen carriers deliver to some of  the addresses you\'ve selected.') . '</p>';
         } else {
             return '<p class="warning">' . Tools::displayError('Error: None of your chosen carriers deliver to the address you\'ve selected.') . '</p>';
         }
     }
     if (!$this->context->cart->getDeliveryOption(null, false) && !$this->context->cart->isVirtualCart()) {
         return '<p class="warning">' . Tools::displayError('Error: Please choose a carrier.') . '</p>';
     }
     if (!$this->context->cart->id_currency) {
         return '<p class="warning">' . Tools::displayError('Error: No currency has been selected.') . '</p>';
     }
     if (!$this->context->cookie->checkedTOS && Configuration::get('PS_CONDITIONS')) {
         return '<p class="warning">' . Tools::displayError('Please accept the Terms of Service.') . '</p>';
     }
     /* If some products have disappear */
     if (!$this->context->cart->checkQuantities()) {
         return '<p class="warning">' . Tools::displayError('An item in your cart is no longer available. You cannot proceed with your order.') . '</p>';
     }
     /* Check minimal amount */
     $currency = Currency::getCurrency((int) $this->context->cart->id_currency);
     $minimal_purchase = Tools::convertPrice((double) Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
     if ($this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS) < $minimal_purchase) {
         return '<p class="warning">' . sprintf(Tools::displayError('A minimum purchase total of %1s (tax excl.) is required in order to validate your order, current purchase total is %2s (tax excl.).'), Tools::displayPrice($minimal_purchase, $currency), Tools::displayPrice($this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS), $currency)) . '</p>';
     }
     /* Bypass payment step if total is 0 */
     if ($this->context->cart->getOrderTotal() <= 0) {
         return '<p class="center"><button class="button btn btn-default button-medium" name="confirmOrder" id="confirmOrder" onclick="confirmFreeOrder();" type="submit"> <span>' . Tools::displayError('I confirm my order.') . '</span></button></p>';
     }
     $return = Hook::exec('displayPayment');
     if (!$return) {
         return '<p class="warning">' . Tools::displayError('No payment method is available for use at this time. ') . '</p>';
     }
     return $return;
 }
Esempio n. 27
0
 protected function supplyOrdersImportOne($info, $force_ids, $current_line, $validateOnly = false)
 {
     // sets default values if needed
     AdminImportController::setDefaultValues($info);
     // if an id is set, instanciates a supply order with this id if possible
     if (array_key_exists('id', $info) && (int) $info['id'] && SupplyOrder::exists((int) $info['id'])) {
         $supply_order = new SupplyOrder((int) $info['id']);
     } elseif (array_key_exists('reference', $info) && $info['reference'] && SupplyOrder::exists(pSQL($info['reference']))) {
         $supply_order = SupplyOrder::getSupplyOrderByReference(pSQL($info['reference']));
     } else {
         // new supply order
         $supply_order = new SupplyOrder();
     }
     // gets parameters
     $id_supplier = (int) $info['id_supplier'];
     $id_lang = (int) $info['id_lang'];
     $id_warehouse = (int) $info['id_warehouse'];
     $id_currency = (int) $info['id_currency'];
     $reference = pSQL($info['reference']);
     $date_delivery_expected = pSQL($info['date_delivery_expected']);
     $discount_rate = (double) $info['discount_rate'];
     $is_template = (bool) $info['is_template'];
     $error = '';
     // checks parameters
     if (!Supplier::supplierExists($id_supplier)) {
         $error = sprintf($this->l('Supplier ID (%d) is not valid (at line %d).'), $id_supplier, $current_line + 1);
     }
     if (!Language::getLanguage($id_lang)) {
         $error = sprintf($this->l('Lang ID (%d) is not valid (at line %d).'), $id_lang, $current_line + 1);
     }
     if (!Warehouse::exists($id_warehouse)) {
         $error = sprintf($this->l('Warehouse ID (%d) is not valid (at line %d).'), $id_warehouse, $current_line + 1);
     }
     if (!Currency::getCurrency($id_currency)) {
         $error = sprintf($this->l('Currency ID (%d) is not valid (at line %d).'), $id_currency, $current_line + 1);
     }
     if (empty($supply_order->reference) && SupplyOrder::exists($reference)) {
         $error = sprintf($this->l('Reference (%s) already exists (at line %d).'), $reference, $current_line + 1);
     }
     if (!empty($supply_order->reference) && ($supply_order->reference != $reference && SupplyOrder::exists($reference))) {
         $error = sprintf($this->l('Reference (%s) already exists (at line %d).'), $reference, $current_line + 1);
     }
     if (!Validate::isDateFormat($date_delivery_expected)) {
         $error = sprintf($this->l('Date format (%s) is not valid (at line %d). It should be: %s.'), $date_delivery_expected, $current_line + 1, $this->l('YYYY-MM-DD'));
     } elseif (new DateTime($date_delivery_expected) <= new DateTime('yesterday')) {
         $error = sprintf($this->l('Date (%s) cannot be in the past (at line %d). Format: %s.'), $date_delivery_expected, $current_line + 1, $this->l('YYYY-MM-DD'));
     }
     if ($discount_rate < 0 || $discount_rate > 100) {
         $error = sprintf($this->l('Discount rate (%d) is not valid (at line %d). %s.'), $discount_rate, $current_line + 1, $this->l('Format: Between 0 and 100'));
     }
     if ($supply_order->id > 0 && !$supply_order->isEditable()) {
         $error = sprintf($this->l('Supply Order (%d) is not editable (at line %d).'), $supply_order->id, $current_line + 1);
     }
     // if no errors, sets supply order
     if (empty($error)) {
         // adds parameters
         $info['id_ref_currency'] = (int) Currency::getDefaultCurrency()->id;
         $info['supplier_name'] = pSQL(Supplier::getNameById($id_supplier));
         if ($supply_order->id > 0) {
             $info['id_supply_order_state'] = (int) $supply_order->id_supply_order_state;
             $info['id'] = (int) $supply_order->id;
         } else {
             $info['id_supply_order_state'] = 1;
         }
         // sets parameters
         AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $supply_order);
         // updatesd($supply_order);
         $res = false;
         if ((int) $supply_order->id && ($supply_order->exists((int) $supply_order->id) || $supply_order->exists($supply_order->reference))) {
             $res = $validateOnly || $supply_order->update();
         } else {
             $supply_order->force_id = (bool) $force_ids;
             $res = $validateOnly || $supply_order->add();
         }
         // errors
         if (!$res) {
             $this->errors[] = sprintf($this->l('Supply Order could not be saved (at line %d).'), $current_line + 1);
         }
     } else {
         $this->errors[] = $error;
     }
 }
    public function getLastOrders()
    {
        $content = '
			<table cellpadding="0" cellspacing="0" id="table_customer" style="width:100%;">
				<thead>
					<tr>
						<th class="order_id"><span class="first">' . $this->l('ID') . '</span></th>
						<th class="order_customer"><span>' . $this->l('Customer Name') . '</span></th>
						<th class="order_status"><span>' . $this->l('Status') . '</span></th>
						<th class="order_total"><span>' . $this->l('Total') . '</span></th>
						<th class="order_action"><span class="last">' . $this->l('Action') . '</span></th>
					<tr>
				</thead>
				<tbody>';
        $orders = Order::getOrdersWithInformations(10);
        $i = 0;
        foreach ($orders as $order) {
            $currency = Currency::getCurrency((int) $order['id_currency']);
            $content .= '
					<tr' . ($i % 2 ? ' id="order_line1"' : '') . '>
						<td class="order_td_first order_id">' . (int) $order['id_order'] . '</td>
						<td class="order_customer">' . Tools::htmlentitiesUTF8($order['firstname']) . ' ' . Tools::htmlentitiesUTF8($order['lastname']) . '</td>
						<td class="order_status">' . Tools::htmlentitiesUTF8($order['state_name']) . '</td>
						<td class="order_total">' . Tools::displayPrice((double) $order['total_paid'], $currency) . '</td>
						<td class="order_action">
							<a href="index.php?tab=AdminOrders&id_order=' . (int) $order['id_order'] . '&vieworder&token=' . Tools::getAdminTokenLite('AdminOrders') . '" title="' . $this->l('Details') . '"><img src="../img/admin/details.gif" alt="' . $this->l('See') . '" /></a>
						</td>
					</tr>
				';
            $i++;
        }
        $content .= '
				</tbody>
			</table>
	';
        return $content;
    }
 /**
  * AdminController::postProcess() override
  * @see AdminController::postProcess()
  */
 public function postProcess()
 {
     parent::postProcess();
     // Checks access
     if (Tools::isSubmit('addStock') && !($this->tabAccess['add'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have the required permission to add stock.');
     }
     if (Tools::isSubmit('removeStock') && !($this->tabAccess['delete'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have the required permission to delete stock');
     }
     if (Tools::isSubmit('transferStock') && !($this->tabAccess['edit'] === '1')) {
         $this->errors[] = Tools::displayError('You do not have the required permission to transfer stock.');
     }
     if (count($this->errors)) {
         return;
     }
     // Global checks when add / remove / transfer product
     if ((Tools::isSubmit('addstock') || Tools::isSubmit('removestock') || Tools::isSubmit('transferstock')) && Tools::isSubmit('is_post')) {
         // get product ID
         $id_product = (int) Tools::getValue('id_product', 0);
         if ($id_product <= 0) {
             $this->errors[] = Tools::displayError('The selected product is not valid.');
         }
         // get product_attribute ID
         $id_product_attribute = (int) Tools::getValue('id_product_attribute', 0);
         // check the product hash
         $check = Tools::getValue('check', '');
         $check_valid = md5(_COOKIE_KEY_ . $id_product . $id_product_attribute);
         if ($check != $check_valid) {
             $this->errors[] = Tools::displayError('The selected product is not valid.');
         }
         // get quantity and check that the post value is really an integer
         // If it's not, we have nothing to do
         $quantity = Tools::getValue('quantity', 0);
         if (!is_numeric($quantity) || (int) $quantity <= 0) {
             $this->errors[] = Tools::displayError('The quantity value is not valid.');
         }
         $quantity = (int) $quantity;
         $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
         $redirect = self::$currentIndex . '&token=' . $token;
     }
     // Global checks when add / remove product
     if ((Tools::isSubmit('addstock') || Tools::isSubmit('removestock')) && Tools::isSubmit('is_post')) {
         // get warehouse id
         $id_warehouse = (int) Tools::getValue('id_warehouse', 0);
         if ($id_warehouse <= 0 || !Warehouse::exists($id_warehouse)) {
             $this->errors[] = Tools::displayError('The selected warehouse is not valid.');
         }
         // get stock movement reason id
         $id_stock_mvt_reason = (int) Tools::getValue('id_stock_mvt_reason', 0);
         if ($id_stock_mvt_reason <= 0 || !StockMvtReason::exists($id_stock_mvt_reason)) {
             $this->errors[] = Tools::displayError('The reason is not valid.');
         }
         // get usable flag
         $usable = Tools::getValue('usable', null);
         if (is_null($usable)) {
             $this->errors[] = Tools::displayError('You have to specify whether the product quantity is usable for sale on shops or not.');
         }
         $usable = (bool) $usable;
     }
     if (Tools::isSubmit('addstock') && Tools::isSubmit('is_post')) {
         // get product unit price
         $price = str_replace(',', '.', Tools::getValue('price', 0));
         if (!is_numeric($price)) {
             $this->errors[] = Tools::displayError('The product price is not valid.');
         }
         $price = round(floatval($price), 6);
         // get product unit price currency id
         $id_currency = (int) Tools::getValue('id_currency', 0);
         if ($id_currency <= 0 || (!($result = Currency::getCurrency($id_currency)) || empty($result))) {
             $this->errors[] = Tools::displayError('The selected currency is not valid.');
         }
         // if all is ok, add stock
         if (count($this->errors) == 0) {
             $warehouse = new Warehouse($id_warehouse);
             // convert price to warehouse currency if needed
             if ($id_currency != $warehouse->id_currency) {
                 // First convert price to the default currency
                 $price_converted_to_default_currency = Tools::convertPrice($price, $id_currency, false);
                 // Convert the new price from default currency to needed currency
                 $price = Tools::convertPrice($price_converted_to_default_currency, $warehouse->id_currency, true);
             }
             // add stock
             $stock_manager = StockManagerFactory::getManager();
             if ($stock_manager->addProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $price, $usable)) {
                 // Create warehouse_product_location entry if we add stock to a new warehouse
                 $id_wpl = (int) WarehouseProductLocation::getIdByProductAndWarehouse($id_product, $id_product_attribute, $id_warehouse);
                 if (!$id_wpl) {
                     $wpl = new WarehouseProductLocation();
                     $wpl->id_product = (int) $id_product;
                     $wpl->id_product_attribute = (int) $id_product_attribute;
                     $wpl->id_warehouse = (int) $id_warehouse;
                     $wpl->save();
                 }
                 StockAvailable::synchronize($id_product);
                 if (Tools::isSubmit('addstockAndStay')) {
                     $redirect = self::$currentIndex . '&id_product=' . (int) $id_product;
                     if ($id_product_attribute) {
                         $redirect .= '&id_product_attribute=' . (int) $id_product_attribute;
                     }
                     $redirect .= '&addstock&token=' . $token;
                 }
                 Tools::redirectAdmin($redirect . '&conf=1');
             } else {
                 $this->errors[] = Tools::displayError('An error occurred. No stock was added.');
             }
         }
     }
     if (Tools::isSubmit('removestock') && Tools::isSubmit('is_post')) {
         // if all is ok, remove stock
         if (count($this->errors) == 0) {
             $warehouse = new Warehouse($id_warehouse);
             // remove stock
             $stock_manager = StockManagerFactory::getManager();
             $removed_products = $stock_manager->removeProduct($id_product, $id_product_attribute, $warehouse, $quantity, $id_stock_mvt_reason, $usable);
             if (count($removed_products) > 0) {
                 StockAvailable::synchronize($id_product);
                 Tools::redirectAdmin($redirect . '&conf=2');
             } else {
                 $physical_quantity_in_stock = (int) $stock_manager->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), false);
                 $usable_quantity_in_stock = (int) $stock_manager->getProductPhysicalQuantities($id_product, $id_product_attribute, array($warehouse->id), true);
                 $not_usable_quantity = $physical_quantity_in_stock - $usable_quantity_in_stock;
                 if ($usable_quantity_in_stock < $quantity) {
                     $this->errors[] = sprintf(Tools::displayError('You don\'t have enough usable quantity. Cannot remove %d items out of %d.'), (int) $quantity, (int) $usable_quantity_in_stock);
                 } elseif ($not_usable_quantity < $quantity) {
                     $this->errors[] = sprintf(Tools::displayError('You don\'t have enough usable quantity. Cannot remove %d items out of %d.'), (int) $quantity, (int) $not_usable_quantity);
                 } else {
                     $this->errors[] = Tools::displayError('It is not possible to remove the specified quantity. Therefore no stock was removed.');
                 }
             }
         }
     }
     if (Tools::isSubmit('transferstock') && Tools::isSubmit('is_post')) {
         // get source warehouse id
         $id_warehouse_from = (int) Tools::getValue('id_warehouse_from', 0);
         if ($id_warehouse_from <= 0 || !Warehouse::exists($id_warehouse_from)) {
             $this->errors[] = Tools::displayError('The source warehouse is not valid.');
         }
         // get destination warehouse id
         $id_warehouse_to = (int) Tools::getValue('id_warehouse_to', 0);
         if ($id_warehouse_to <= 0 || !Warehouse::exists($id_warehouse_to)) {
             $this->errors[] = Tools::displayError('The destination warehouse is not valid.');
         }
         // get usable flag for source warehouse
         $usable_from = Tools::getValue('usable_from', null);
         if (is_null($usable_from)) {
             $this->errors[] = Tools::displayError('You have to specify whether the product quantity in your source warehouse(s) is ready for sale or not.');
         }
         $usable_from = (bool) $usable_from;
         // get usable flag for destination warehouse
         $usable_to = Tools::getValue('usable_to', null);
         if (is_null($usable_to)) {
             $this->errors[] = Tools::displayError('You have to specify whether the product quantity in your destination warehouse(s) is ready for sale or not.');
         }
         $usable_to = (bool) $usable_to;
         // if we can process stock transfers
         if (count($this->errors) == 0) {
             // transfer stock
             $stock_manager = StockManagerFactory::getManager();
             $is_transfer = $stock_manager->transferBetweenWarehouses($id_product, $id_product_attribute, $quantity, $id_warehouse_from, $id_warehouse_to, $usable_from, $usable_to);
             StockAvailable::synchronize($id_product);
             if ($is_transfer) {
                 Tools::redirectAdmin($redirect . '&conf=3');
             } else {
                 $this->errors[] = Tools::displayError('It is not possible to transfer the specified quantity. No stock was transferred.');
             }
         }
     }
 }
 protected function _getPaymentMethods()
 {
     if (!$this->isLogged) {
         return '<p class="warning">' . Tools::displayError('Please sign in to see payment methods') . '</p>';
     }
     if (self::$cart->OrderExists()) {
         return '<p class="warning">' . Tools::displayError('Error: this order is already validated') . '</p>';
     }
     if (!self::$cart->id_customer or !Customer::customerIdExistsStatic(self::$cart->id_customer) or Customer::isBanned(self::$cart->id_customer)) {
         return '<p class="warning">' . Tools::displayError('Error: no customer') . '</p>';
     }
     $address_delivery = new Address(self::$cart->id_address_delivery);
     $address_invoice = self::$cart->id_address_delivery == self::$cart->id_address_invoice ? $address_delivery : new Address(self::$cart->id_address_invoice);
     if (!self::$cart->id_address_delivery or !self::$cart->id_address_invoice or !Validate::isLoadedObject($address_delivery) or !Validate::isLoadedObject($address_invoice) or $address_invoice->deleted or $address_delivery->deleted) {
         return '<p class="warning">' . Tools::displayError('Error: please choose an address') . '</p>';
     }
     if (!self::$cart->id_carrier and !self::$cart->isVirtualCart()) {
         return '<p class="warning">' . Tools::displayError('Error: please choose a carrier') . '</p>';
     } elseif (self::$cart->id_carrier != 0) {
         $carrier = new Carrier((int) self::$cart->id_carrier);
         if (!Validate::isLoadedObject($carrier) or $carrier->deleted or !$carrier->active) {
             return '<p class="warning">' . Tools::displayError('Error: the carrier is invalid') . '</p>';
         }
     }
     if (!self::$cart->id_currency) {
         return '<p class="warning">' . Tools::displayError('Error: no currency has been selected') . '</p>';
     }
     if (!self::$cookie->checkedTOS and Configuration::get('PS_CONDITIONS')) {
         return '<p class="warning">' . Tools::displayError('Please accept Terms of Service') . '</p>';
     }
     /* If some products have disappear */
     if (!self::$cart->checkQuantities()) {
         return '<p class="warning">' . Tools::displayError('An item in your cart is no longer available, you cannot proceed with your order.') . '</p>';
     }
     /* Check minimal amount */
     $currency = Currency::getCurrency((int) self::$cart->id_currency);
     $minimalPurchase = Tools::convertPrice((double) Configuration::get('PS_PURCHASE_MINIMUM'), $currency);
     if (self::$cart->getOrderTotal(false, Cart::ONLY_PRODUCTS) < $minimalPurchase) {
         return '<p class="warning">' . Tools::displayError('A minimum purchase total of') . ' ' . Tools::displayPrice($minimalPurchase, $currency) . ' ' . Tools::displayError('is required in order to validate your order.') . '</p>';
     }
     /* Bypass payment step if total is 0 */
     if (self::$cart->getOrderTotal() <= 0) {
         return '<p class="center"><input type="button" class="exclusive_large" name="confirmOrder" id="confirmOrder" value="' . Tools::displayError('I confirm my order') . '" onclick="confirmFreeOrder();" /></p>';
     }
     $return = Module::hookExecPayment();
     if (!$return) {
         return '<p class="warning">' . Tools::displayError('No payment method is available') . '</p>';
     }
     return $return;
 }