From 21514d413483f36e6027b0814d637d95fab23e31 Mon Sep 17 00:00:00 2001 From: Shreesh Arora Date: Thu, 2 Jun 2022 14:27:52 +0530 Subject: [PATCH 01/56] resolve same order status issue when booking room from multiple hotels --- .../controllers/orders/helpers/view/view.tpl | 30 +++---- classes/PaymentModule.php | 12 ++- classes/order/Order.php | 84 +++++++++++++------ classes/order/OrderHistory.php | 15 ++-- classes/order/OrderInvoice.php | 5 ++ classes/order/OrderPaymentDetail.php | 79 +++++++++++++++++ controllers/admin/AdminOrdersController.php | 17 +++- install/data/db_structure.sql | 10 +++ pdf/invoice.payment-tab.tpl | 6 +- 9 files changed, 200 insertions(+), 58 deletions(-) create mode 100644 classes/order/OrderPaymentDetail.php diff --git a/admin/themes/default/template/controllers/orders/helpers/view/view.tpl b/admin/themes/default/template/controllers/orders/helpers/view/view.tpl index 6922cff6d..f5a30ca46 100644 --- a/admin/themes/default/template/controllers/orders/helpers/view/view.tpl +++ b/admin/themes/default/template/controllers/orders/helpers/view/view.tpl @@ -505,15 +505,15 @@ - {foreach from=$order->getOrderPaymentCollection() item=payment} + {foreach from=$order_payment_detail item=payment} - {dateFormat date=$payment->date_add full=true} - {$payment->payment_method|escape:'html':'UTF-8'} - {$payment->transaction_id|escape:'html':'UTF-8'} - {displayPrice price=$payment->amount currency=$payment->id_currency} + {dateFormat date=$payment['date_add'] full=true} + {$payment['payment_method']|escape:'html':'UTF-8'} + {$payment['transaction_id']|escape:'html':'UTF-8'} + {displayPrice price=$payment['real_paid_amount'] currency=$payment['id_currency']} - {if $invoice = $payment->getOrderInvoice($order->id)} - {$invoice->getInvoiceNumberFormatted($current_id_lang, $order->id_shop)} + {if $payment['invoice_number']} + {$payment['invoice_number']} {else} {/if} @@ -528,32 +528,32 @@

{l s='Card Number'}  - {if $payment->card_number} - {$payment->card_number} + {if $payment['card_number']} + {$payment['card_number']} {else} {l s='Not defined'} {/if}

{l s='Card Brand'}  - {if $payment->card_brand} - {$payment->card_brand} + {if $payment['card_brand']} + {$payment['card_brand']} {else} {l s='Not defined'} {/if}

{l s='Card Expiration'}  - {if $payment->card_expiration} - {$payment->card_expiration} + {if $payment['card_expiration']} + {$payment['card_expiration']} {else} {l s='Not defined'} {/if}

{l s='Card Holder'}  - {if $payment->card_holder} - {$payment->card_holder} + {if $payment['card_holder']} + {$payment['card_holder']} {else} {l s='Not defined'} {/if} diff --git a/classes/PaymentModule.php b/classes/PaymentModule.php index 010dcf4a8..88dfe8a9d 100644 --- a/classes/PaymentModule.php +++ b/classes/PaymentModule.php @@ -431,10 +431,14 @@ abstract class PaymentModuleCore extends Module $transaction_id = null; } - if (!isset($order) || !Validate::isLoadedObject($order) || !$order->addOrderPayment($amount_paid, null, $transaction_id)) { + if (!isset($order) || !Validate::isLoadedObject($order) || !$order->addOrderPayment($amount_paid, null, $transaction_id, null, null, null, false)) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Order Payment', 3, null, 'Cart', (int)$id_cart, true); throw new PrestaShopException('Can\'t save Order Payment'); } + + foreach($order_list as $order) { + $order->addOrderPaymentDetail($order->advance_paid_amount); + } } // Next ! @@ -713,7 +717,11 @@ abstract class PaymentModuleCore extends Module // Set the order status $new_history = new OrderHistory(); $new_history->id_order = (int)$order->id; - $new_history->changeIdOrderState((int)$id_order_state, $order, true); + if ($order->is_advance_payment && $order->advance_paid_amount < $order->total_paid_tax_incl) { + $new_history->changeIdOrderState((int)Configuration::get('PS_OS_PARTIAL_PAYMENT'), $order, true); + } else { + $new_history->changeIdOrderState((int)$id_order_state, $order, true); + } $new_history->addWithemail(true, $extra_vars); // Switch to back order if needed diff --git a/classes/order/Order.php b/classes/order/Order.php index fbc292b4a..9d0f54cda 100644 --- a/classes/order/Order.php +++ b/classes/order/Order.php @@ -1267,8 +1267,6 @@ class OrderCore extends ObjectModel $this->setLastInvoiceNumber($order_invoice->id, $this->id_shop); } - - // Update order_carrier $id_order_carrier = Db::getInstance()->getValue(' SELECT `id_order_carrier` @@ -1292,11 +1290,13 @@ class OrderCore extends ObjectModel // Update order payment if ($use_existing_payment) { $id_order_payments = Db::getInstance()->executeS(' - SELECT DISTINCT op.id_order_payment + SELECT DISTINCT op.id_order_payment, opd.id_order_payment_detail FROM `'._DB_PREFIX_.'order_payment` op INNER JOIN `'._DB_PREFIX_.'orders` o ON (o.reference = op.order_reference) + LEFT JOIN `'._DB_PREFIX_.'order_payment_detail` opd ON (op.id_order_payment = opd.id_order_payment) LEFT JOIN `'._DB_PREFIX_.'order_invoice_payment` oip ON (oip.id_order_payment = op.id_order_payment) - WHERE (oip.id_order != '.(int)$order_invoice->id_order.' OR oip.id_order IS NULL) AND o.id_order = '.(int)$order_invoice->id_order); + WHERE (oip.id_order != '.(int)$order_invoice->id_order.' OR oip.id_order IS NULL) AND o.id_order = '.(int)$order_invoice->id_order.' + AND opd.`id_order` = '.$order_invoice->id_order); if (count($id_order_payments)) { foreach ($id_order_payments as $order_payment) { @@ -1304,6 +1304,7 @@ class OrderCore extends ObjectModel INSERT INTO `'._DB_PREFIX_.'order_invoice_payment` SET `id_order_invoice` = '.(int)$order_invoice->id.', + `id_order_payment_detail` = '.(int)$order_payment['id_order_payment_detail'].', `id_order_payment` = '.(int)$order_payment['id_order_payment'].', `id_order` = '.(int)$order_invoice->id_order); } @@ -1311,7 +1312,6 @@ class OrderCore extends ObjectModel Cache::clean('order_invoice_paid_*'); } } - // Update order cart rule Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'order_cart_rule` @@ -1705,6 +1705,16 @@ class OrderCore extends ObjectModel return $order_payments; } + public function getOrderPaymentDetailCollection() + { + $order_payments = new DbQuery(); + $order_payments->select('opd.`amount` as `real_paid_amount`, opd.*, op.*'); + $order_payments->from('order_payment_detail', 'opd'); + $order_payments->innerJoin('order_payment', 'op', 'opd.`id_order_payment` = op.`id_order_payment`'); + $order_payments->where('id_order = '.$this->id); + return Db::getInstance()->executeS($order_payments); + } + /** * * This method allows to add a payment to the current order @@ -1717,7 +1727,7 @@ class OrderCore extends ObjectModel * @param OrderInvoice $order_invoice * @return bool */ - public function addOrderPayment($amount_paid, $payment_method = null, $payment_transaction_id = null, $currency = null, $date = null, $order_invoice = null) + public function addOrderPayment($amount_paid, $payment_method = null, $payment_transaction_id = null, $currency = null, $date = null, $order_invoice = null, $update_payment_detail = true) { $order_payment = new OrderPayment(); $order_payment->order_reference = $this->reference; @@ -1735,32 +1745,50 @@ class OrderCore extends ObjectModel $order_payment->date_add .= ' '.date('H:i:s'); } - // Update total_paid_real value for backward compatibility reasons - if ($order_payment->id_currency == $this->id_currency) { - $this->total_paid_real += $order_payment->amount; - } else { - $this->total_paid_real += Tools::ps_round(Tools::convertPrice($order_payment->amount, $order_payment->id_currency, false), 2); - } - // We put autodate parameter of add method to true if date_add field is null - $res = $order_payment->add(is_null($order_payment->date_add)) && $this->update(); + $res = $order_payment->add(is_null($order_payment->date_add)); if (!$res) { return false; } - if (!is_null($order_invoice)) { - $res = Db::getInstance()->execute(' - INSERT INTO `'._DB_PREFIX_.'order_invoice_payment` (`id_order_invoice`, `id_order_payment`, `id_order`) - VALUES('.(int)$order_invoice->id.', '.(int)$order_payment->id.', '.(int)$this->id.')'); - - // Clear cache - Cache::clean('order_invoice_paid_*'); + if ($update_payment_detail) { + $this->addOrderPaymentDetail($amount_paid, $order_invoice); } return $res; } + public function addOrderPaymentDetail($amount, $order_invoice = null) + { + if ($orderPayments = OrderPayment::getByOrderReference($this->reference)) { + $lastOrderPayment = array_pop($orderPayments); + $order_payment_detail = new OrderPaymentDetail(); + $order_payment_detail->id_order = $this->id; + $order_payment_detail->id_order_payment = (int)$lastOrderPayment->id; + $order_payment_detail->amount = $amount; + + if ($lastOrderPayment->id_currency == $this->id_currency) { + $this->total_paid_real += $order_payment_detail->amount; + } else { + $this->total_paid_real += Tools::ps_round(Tools::convertPrice($order_payment_detail->amount, $lastOrderPayment->id_currency, false), 2); + } + if ($order_payment_detail->add() && $this->update()) { + if (!is_null($order_invoice)) { + $res = Db::getInstance()->execute(' + INSERT INTO `'._DB_PREFIX_.'order_invoice_payment` (`id_order_invoice`, `id_order_payment`, `id_order_payment_detail`, `id_order`) + VALUES('.(int)$order_invoice->id.', '.(int)(int)$lastOrderPayment->id.', '.(int)$order_payment_detail->id.', '.(int)$this->id.')'); + + // Clear cache + Cache::clean('order_invoice_paid_*'); + } + + return $order_payment_detail->id; + } + } + return false; + } + /** * Returns the correct product taxes breakdown. * @@ -1893,14 +1921,15 @@ class OrderCore extends ObjectModel } $total = 0; + // Retrieve all payments - $payments = $this->getOrderPaymentCollection(); + $payments = $this->getOrderPaymentDetailCollection(); foreach ($payments as $payment) { /** @var OrderPayment $payment */ - if ($payment->id_currency == $currency->id) { - $total += $payment->amount; + if ($payment['id_currency'] == $currency->id) { + $total += $payment['real_paid_amount']; } else { - $amount = Tools::convertPrice($payment->amount, $payment->id_currency, false); + $amount = Tools::convertPrice($payment['real_paid_amount'], $payment['id_currency'], false); if ($currency->id == Configuration::get('PS_CURRENCY_DEFAULT', null, null, $this->id_shop)) { $total += $amount; } else { @@ -2166,6 +2195,11 @@ class OrderCore extends ObjectModel return OrderPayment::getByOrderReference($this->reference); } + public function getOrderPaymentsDetail() + { + return OrderPaymentDetail::getByOrderId($this->id); + } + /** * Return a unique reference like : GWJTHMZUN#2 * diff --git a/classes/order/OrderHistory.php b/classes/order/OrderHistory.php index 2da4bf501..851365312 100644 --- a/classes/order/OrderHistory.php +++ b/classes/order/OrderHistory.php @@ -333,19 +333,14 @@ class OrderHistoryCore extends ObjectModel $payment->payment_method = null; } - // Update total_paid_real value for backward compatibility reasons - if ($payment->id_currency == $order->id_currency) { - $order->total_paid_real += $payment->amount; - } else { - $order->total_paid_real += Tools::ps_round(Tools::convertPrice($payment->amount, $payment->id_currency, false), 2); - } - $order->save(); - $payment->conversion_rate = ($order ? $order->conversion_rate : 1); $payment->save(); + + $id_order_payment_detail = $order->addOrderPaymentDetail($rest_paid); + Db::getInstance()->execute(' - INSERT INTO `'._DB_PREFIX_.'order_invoice_payment` (`id_order_invoice`, `id_order_payment`, `id_order`) - VALUES('.(int)$invoice->id.', '.(int)$payment->id.', '.(int)$order->id.')'); + INSERT INTO `'._DB_PREFIX_.'order_invoice_payment` (`id_order_invoice`, `id_order_payment`, `id_order_payment_detail`, `id_order`) + VALUES('.(int)$invoice->id.', '.(int)$payment->id.', '.(int)$id_order_payment_detail.', '.(int)$order->id.')'); } } } diff --git a/classes/order/OrderInvoice.php b/classes/order/OrderInvoice.php index 2e4e6ceab..91f07ea83 100644 --- a/classes/order/OrderInvoice.php +++ b/classes/order/OrderInvoice.php @@ -880,6 +880,11 @@ class OrderInvoiceCore extends ObjectModel return OrderPayment::getByInvoiceId($this->id); } + public function getOrderPaymentDetailCollection() + { + return OrderPaymentDetail::getByInvoiceId($this->id); + } + /** * Get the formatted number of invoice * @since 1.5.0.2 diff --git a/classes/order/OrderPaymentDetail.php b/classes/order/OrderPaymentDetail.php new file mode 100644 index 000000000..b231efb4d --- /dev/null +++ b/classes/order/OrderPaymentDetail.php @@ -0,0 +1,79 @@ + 'order_payment_detail', + 'primary' => 'id_order_payment_detail', + 'fields' => array( + 'id_order_payment' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'), + 'id_order' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'), + 'amount' => array('type' => self::TYPE_FLOAT, 'validate' => 'isNegativePrice', 'required' => true), + 'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDate'), + ), + 'associations' => array( + 'order_payment' => array('type' => self::HAS_ONE, 'table' => 'order_payment') + ) + ); + + public static function getByOrderId($id_order) + { + return Db::getInstance()->executeS(' + SELECT opd.*, op.`id_currency`, op.`payment_method`, op.`conversion_rate`, op.`transaction_id`, op.`card_number`, op.`card_brand`, op.`card_expiration`, op.`card_holder` + FROM `'._DB_PREFIX_.'order_payment_detail` opd + INNER JOIN `'._DB_PREFIX_.'order_payment`op ON (op.`id_order_payment` = opd.`id_order_payment`) + WHERE `id_order` = '.(int)$id_order); + } + + /** + * Get Order Payments By Invoice ID + * + * @param int $id_invoice Invoice ID + * @return PrestaShopCollection Collection of OrderPayment + */ + public static function getByInvoiceId($id_invoice) + { + $payments = Db::getInstance()->executeS('SELECT id_order_payment_detail FROM `'._DB_PREFIX_.'order_invoice_payment` WHERE id_order_invoice = '.(int)$id_invoice); + if (!$payments) { + return array(); + } + + $payment_list = array(); + foreach ($payments as $payment) { + $payment_list[] = $payment['id_order_payment_detail']; + } + $order_payments = new DbQuery(); + $order_payments->select('opd.*, op.*, opd.`amount` as `amount`'); + $order_payments->from('order_payment_detail', 'opd'); + $order_payments->innerJoin('order_payment', 'op', 'opd.`id_order_payment` = op.`id_order_payment`'); + $order_payments->where('id_order_payment_detail IN ('.pSQL(implode(', ', $payment_list)).')'); + return Db::getInstance()->executeS($order_payments); + // $payments = new PrestaShopCollection('OrderPaymentDetail'); + // $payments->join('order_payment', 'id_order_payment'); + // $payments->where('id_order_payment_detail', 'IN', $payment_list); + // ddd($payments->getAll()); + } +} diff --git a/controllers/admin/AdminOrdersController.php b/controllers/admin/AdminOrdersController.php index b67bb86d9..43ab91edc 100644 --- a/controllers/admin/AdminOrdersController.php +++ b/controllers/admin/AdminOrdersController.php @@ -159,7 +159,7 @@ class AdminOrdersControllerCore extends AdminController 'remove_onclick' => true ) )); - + $this->shopLinkType = 'shop'; $this->shopShareDatas = Shop::SHARE_ORDER; @@ -321,7 +321,7 @@ class AdminOrdersControllerCore extends AdminController $this->addJqueryUI('ui.datepicker'); $this->addJS(_PS_JS_DIR_.'vendor/d3.v3.min.js'); - + if ($this->tabAccess['edit'] == 1 && $this->display == 'view') { $this->addJS(_PS_JS_DIR_.'admin/orders.js'); $this->addJS(_PS_JS_DIR_.'tools.js'); @@ -1432,6 +1432,16 @@ class AdminOrdersControllerCore extends AdminController foreach ($history as &$order_state) { $order_state['text-color'] = Tools::getBrightness($order_state['color']) < 128 ? 'white' : 'black'; } + + $order_payment_detail = $order->getOrderPaymentDetailCollection(); + foreach ($order_payment_detail as &$payment_detail) { + $payment = new OrderPayment($payment_detail['id_order_payment']); + if ($invoice = $payment->getOrderInvoice($order->id)) { + $payment_detail['invoice_number'] = $invoice->getInvoiceNumberFormatted($this->context->language->id, $order->id_shop); + } + } + + //by webkul to get data to show hotel rooms order data on order detail page $cart_id = Cart::getCartIdByOrderId(Tools::getValue('id_order')); @@ -1544,13 +1554,14 @@ class AdminOrdersControllerCore extends AdminController 'customerStats' => $customer->getStats(), 'products' => $products, 'discounts' => $order->getCartRules(), - 'orders_total_paid_tax_incl' => $order->getOrdersTotalPaid(), // Get the sum of total_paid_tax_incl of the order with similar reference + 'orders_total_paid_tax_incl' => $order->total_paid_tax_incl, // Get the sum of total_paid_tax_incl of the order with similar reference 'total_paid' => $order->getTotalPaid(), 'customer_thread_message' => CustomerThread::getCustomerMessages($order->id_customer, null, $order->id), 'orderMessages' => OrderMessage::getOrderMessages($order->id_lang), 'messages' => Message::getMessagesByOrderId($order->id, true), 'carrier' => new Carrier($order->id_carrier), 'history' => $history, + 'order_payment_detail' => $order_payment_detail, 'states' => OrderState::getOrderStates($this->context->language->id), 'warehouse_list' => $warehouse_list, 'sources' => ConnectionsSource::getOrderSources($order->id), diff --git a/install/data/db_structure.sql b/install/data/db_structure.sql index 60fc52813..0c969ff1b 100644 --- a/install/data/db_structure.sql +++ b/install/data/db_structure.sql @@ -1455,6 +1455,15 @@ CREATE TABLE `PREFIX_order_payment` ( KEY `order_reference`(`order_reference`) ) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION; +CREATE TABLE `PREFIX_order_payment_detail` ( + `id_order_payment_detail` INT(10) unsigned NOT NULL auto_increment, + `id_order_payment` INT(10) unsigned NOT NULL, + `id_order` INT(10) unsigned NOT NULL, + `amount` DECIMAL(10,2) NOT NULL, + `date_add` DATETIME NOT NULL, + PRIMARY KEY (`id_order_payment_detail`), +) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION; + CREATE TABLE `PREFIX_product` ( `id_product` int(10) unsigned NOT NULL auto_increment, `id_supplier` int(10) unsigned DEFAULT NULL, @@ -2605,6 +2614,7 @@ CREATE TABLE `PREFIX_tab_module_preference` ( CREATE TABLE `PREFIX_order_invoice_payment` ( `id_order_invoice` int(11) unsigned NOT NULL, `id_order_payment` int(11) unsigned NOT NULL, + `id_order_payment_detail` int(11) unsigned NOT NULL, `id_order` int(11) unsigned NOT NULL, PRIMARY KEY (`id_order_invoice`,`id_order_payment`), KEY `order_payment` (`id_order_payment`), diff --git a/pdf/invoice.payment-tab.tpl b/pdf/invoice.payment-tab.tpl index 5c303aaf5..a80c0e91e 100644 --- a/pdf/invoice.payment-tab.tpl +++ b/pdf/invoice.payment-tab.tpl @@ -27,10 +27,10 @@ {l s='Payment Method' pdf='true'} - {foreach from=$order_invoice->getOrderPaymentCollection() item=payment} + {foreach from=$order_invoice->getOrderPaymentDetailCollection() item=payment} - - + + {/foreach}
{$payment->payment_method}{displayPrice currency=$payment->id_currency price=$payment->amount}{$payment['payment_method']}{displayPrice currency=$payment['id_currency'] price=$payment['amount']}
From a8c844d2dd3b9913f73d199dd2fecd8a3e541c29 Mon Sep 17 00:00:00 2001 From: Shreesh Arora Date: Thu, 9 Jun 2022 18:39:08 +0530 Subject: [PATCH 02/56] resolved Db issue --- install/data/db_structure.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/install/data/db_structure.sql b/install/data/db_structure.sql index 0c969ff1b..eaeac96c8 100644 --- a/install/data/db_structure.sql +++ b/install/data/db_structure.sql @@ -1461,7 +1461,7 @@ CREATE TABLE `PREFIX_order_payment_detail` ( `id_order` INT(10) unsigned NOT NULL, `amount` DECIMAL(10,2) NOT NULL, `date_add` DATETIME NOT NULL, - PRIMARY KEY (`id_order_payment_detail`), + PRIMARY KEY (`id_order_payment_detail`) ) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION; CREATE TABLE `PREFIX_product` ( @@ -2604,7 +2604,7 @@ CREATE TABLE `PREFIX_tab_module_preference` ( UNIQUE KEY `employee_module` (`id_employee`, `id_tab`, `module`) ) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8 COLLATION; - CREATE TABLE `PREFIX_carrier_tax_rules_group_shop` ( +CREATE TABLE `PREFIX_carrier_tax_rules_group_shop` ( `id_carrier` int( 11 ) unsigned NOT NULL, `id_tax_rules_group` int(11) unsigned NOT NULL, `id_shop` int(11) unsigned NOT NULL, From 867701c49851cdf87d6b3c255073bda2fe60e3b7 Mon Sep 17 00:00:00 2001 From: Shreesh Arora Date: Sat, 11 Jun 2022 13:20:00 +0530 Subject: [PATCH 03/56] update invoce total price --- classes/order/OrderInvoice.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/classes/order/OrderInvoice.php b/classes/order/OrderInvoice.php index 91f07ea83..9f79fd793 100644 --- a/classes/order/OrderInvoice.php +++ b/classes/order/OrderInvoice.php @@ -738,10 +738,10 @@ class OrderInvoiceCore extends ObjectModel $cache_id = 'order_invoice_paid_'.(int)$this->id; if (!Cache::isStored($cache_id)) { $amount = 0; - $payments = OrderPayment::getByInvoiceId($this->id); + $payments = OrderPaymentDetail::getByInvoiceId($this->id); foreach ($payments as $payment) { /** @var OrderPayment $payment */ - $amount += $payment->amount; + $amount += $payment['amount']; } Cache::store($cache_id, $amount); return $amount; From 5eed6a0b1abedf9d4c566ea79085e4f9f5c4ea6d Mon Sep 17 00:00:00 2001 From: Shreesh Arora Date: Tue, 14 Jun 2022 13:19:46 +0530 Subject: [PATCH 04/56] resolve issue when paying from nonreal payment gateway --- classes/PaymentModule.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classes/PaymentModule.php b/classes/PaymentModule.php index 88dfe8a9d..86f9e02ce 100644 --- a/classes/PaymentModule.php +++ b/classes/PaymentModule.php @@ -717,7 +717,7 @@ abstract class PaymentModuleCore extends Module // Set the order status $new_history = new OrderHistory(); $new_history->id_order = (int)$order->id; - if ($order->is_advance_payment && $order->advance_paid_amount < $order->total_paid_tax_incl) { + if ($order_status->logable && $order->is_advance_payment && $order->advance_paid_amount < $order->total_paid_tax_incl) { $new_history->changeIdOrderState((int)Configuration::get('PS_OS_PARTIAL_PAYMENT'), $order, true); } else { $new_history->changeIdOrderState((int)$id_order_state, $order, true); From e84768cf58c24ab1eb5a89dfcff7d87936f95989 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Fri, 22 Jul 2022 20:37:04 +0530 Subject: [PATCH 05/56] Fix guest can not edit personal info on checkout page issue --- controllers/front/OrderOpcController.php | 44 +++ .../hotel-reservation-theme/css/order-opc.css | 59 +++- .../hotel-reservation-theme/js/order-opc.js | 53 ++- .../order-opc-edit-guest-info.tpl | 323 ++++++++++++++++++ .../order-opc-new-account.tpl | 58 +--- themes/hotel-reservation-theme/order-opc.tpl | 84 +++-- 6 files changed, 530 insertions(+), 91 deletions(-) create mode 100644 themes/hotel-reservation-theme/order-opc-edit-guest-info.tpl diff --git a/controllers/front/OrderOpcController.php b/controllers/front/OrderOpcController.php index 1c0227326..6af7666c0 100644 --- a/controllers/front/OrderOpcController.php +++ b/controllers/front/OrderOpcController.php @@ -135,6 +135,34 @@ class OrderOpcControllerCore extends ParentOrderController $this->ajaxDie(json_encode($return)); break; + case 'transformGuestAccount': + $passwd = Tools::getValue('passwd'); + + if (!$passwd) { + $this->errors[] = Tools::displayError('Please enter a password.'); + } + + if ($passwd && !Validate::isPasswd($passwd)) { + $this->errors[] = Tools::displayError('Please enter a valid password.'); + } + + if (!count($this->errors)) { + $customer = new Customer($this->context->customer->id); + if ($customer->transformToCustomer($this->context->language->id, $passwd)) { + $this->updateContext($customer); + } else { + $this->errors[] = Tools::displayError('An error occurred while transforming your account into a registered customer.'); + } + } + + $return = array( + 'hasError' => !empty($this->errors), + 'errors' => $this->errors, + ); + + $this->ajaxDie(json_encode($return)); + break; + case 'getAddressBlockAndCarriersAndPayments': if ($this->context->customer->isLogged() || $this->context->customer->isGuest()) { // check if customer have addresses @@ -968,4 +996,20 @@ class OrderOpcControllerCore extends ParentOrderController } die('0'); } + + public function updateContext(Customer $customer) + { + $this->context->cookie->id_customer = (int)$customer->id; + $this->context->cookie->customer_lastname = $customer->lastname; + $this->context->cookie->customer_firstname = $customer->firstname; + $this->context->cookie->passwd = $customer->passwd; + $this->context->cookie->logged = 1; + $this->context->cookie->email = $customer->email; + $this->context->cookie->is_guest = 0; + + $this->context->cart->secure_key = $customer->secure_key; + + $customer->logged = 1; + $this->context->customer = $customer; + } } diff --git a/themes/hotel-reservation-theme/css/order-opc.css b/themes/hotel-reservation-theme/css/order-opc.css index 5124ad9a2..68d7fa248 100644 --- a/themes/hotel-reservation-theme/css/order-opc.css +++ b/themes/hotel-reservation-theme/css/order-opc.css @@ -91,6 +91,20 @@ /* By Webkul */ +.strikethrough { + width: 100%; + text-align: center; + border-bottom: 1px solid #777; + line-height: 0.1em; + margin: 10px 0 25px; +} + +.strikethrough span { + background: #fff; + color: #333; + padding:0 10px; +} + #title { font-size: 13px; color: #3C3C3C; @@ -264,6 +278,9 @@ .order-detail-content .room_remove_block i { font-size: 18px; } +#order-opc #guest-info-block { + position: relative; +} #order-opc #guest-info-block div.info-head { font-size: 14px; color: #555555; @@ -312,6 +329,16 @@ font-weight: 600; } +#order-opc #login_form_content .text-secondary { + color: #333; + font-size: 14px; +} + +#order-opc #login_form_content #idAccountChoice { + color: #003AEF; + font-weight: 600; +} + #new_account_form #opc_guestCheckout { padding: 14px 25px; } @@ -552,6 +579,10 @@ padding-top: 0px; } +#order-opc #opc_account_errors { + margin-top: 10px +} + /* buttons css */ #order-opc .opc-button-small { border: none; @@ -570,7 +601,7 @@ color: #1292FF; } #order-opc .opc-button { - padding: 11px 0 0 0; + padding: 2px 0 0 0; } #order-opc .button-medium { background-color: #1292FF; @@ -641,3 +672,29 @@ content: "";} #order-opc .fancybox-skin .fancybox-close { background-image: url(../img/icon/icon-close.svg);} + +.btn-edit-guest-info { + padding: 0px 50px; + font-size: 17px; + line-height: 23px; + border-radius: 2px; + background-color: #D9D9D9; + border: 1px solid #D9D9D9; + margin-right: 10px; } + +.btn-edit-guest-info span { + display: block; + font-size: 14px; + padding: 11px; + font-weight: 600; + text-transform: uppercase; + text-align: center; } + +.transform-to-customer-block { + margin-top: 25px; } + +.transform-to-customer-block .text-secondary { + font-size: 14px; + line-height: 19px; + color: #333; + margin-bottom: 15px; } diff --git a/themes/hotel-reservation-theme/js/order-opc.js b/themes/hotel-reservation-theme/js/order-opc.js index 7ef710bf4..52fcc374d 100644 --- a/themes/hotel-reservation-theme/js/order-opc.js +++ b/themes/hotel-reservation-theme/js/order-opc.js @@ -63,7 +63,6 @@ $(document).ready(function() $('.is_customer_param').show(); $('#opc_account_form').slideDown('slow'); $('#is_new_customer').val('1'); - $('#opc_account_choice, #opc_invoice_address').hide(); if (typeof bindUniform !=='undefined') bindUniform(); }); @@ -72,7 +71,6 @@ $(document).ready(function() $('.is_customer_param').hide(); $('#opc_account_form').slideDown('slow'); $('#is_new_customer').val('0'); - $('#opc_account_choice, #opc_invoice_address').hide(); $('#new_account_title').html(txtInstantCheckout); $('#submitAccount').attr({id : 'submitGuestAccount', name : 'submitGuestAccount'}); if (typeof bindUniform !=='undefined') @@ -98,11 +96,19 @@ $(document).ready(function() // LOGIN FORM $(document).on('click', '#openLoginFormBlock', function(e){ e.preventDefault(); - $('#openNewAccountBlock').show(); - $('.already_registered_block').hide(); - $('#login_form_content').slideDown('slow'); - $('#new_account_form').slideUp('slow'); + $('#openNewAccountBlock').show(200); + $('.already_registered_block').hide(200); + $('#login_form_content').slideDown(200); + $('#new_account_form').slideUp(200); }); + + $(document).on('click', '#idAccountChoice', function(e) { + e.preventDefault(); + $('#login_form_content').slideUp(200); + $('#new_account_form').slideDown(200); + $('.already_registered_block').show(200); + }); + // LOGIN FORM SENDING $(document).on('click', '#SubmitLogin', function(e) { @@ -165,6 +171,7 @@ $(document).ready(function() var callingFile = ''; var advApiParam = ''; var params = ''; + var isTransforming = false; if ($(this).attr('data-adv-api')) { advApiParam = '&isAdvApi=1'; @@ -177,8 +184,12 @@ $(document).ready(function() } else { - callingFile = orderOpcUrl; - params = 'method=editCustomer&'; + if ($('#opc_account_form #passwd').val().length > 0) { + params = 'method=transformGuestAccount&'; + isTransforming = true; + } else { + params = 'method=editCustomer&'; + } } $('#opc_account_form input:visible, #opc_account_form input[type=hidden]').each(function() { @@ -199,8 +210,6 @@ $(document).ready(function() $('#opc_account_form select:visible').each(function() { params += encodeURIComponent($(this).attr('name'))+'='+encodeURIComponent($(this).val())+'&'; }); - params += 'customer_lastname='+encodeURIComponent($('#customer_lastname').val())+'&'; - params += 'customer_firstname='+encodeURIComponent($('#customer_firstname').val())+'&'; params += 'alias='+encodeURIComponent($('#alias').val())+'&'; params += 'other='+encodeURIComponent($('#other').val())+'&'; params += 'is_new_customer='+encodeURIComponent($('#is_new_customer').val())+'&'; @@ -214,7 +223,7 @@ $(document).ready(function() async: false, cache: false, dataType : "json", - data: 'ajax=true&'+params+'&token=' + static_token , + data: 'ajax=true&'+params+'&token=' + static_token, success: function(jsonData) { if (jsonData.hasError) @@ -241,6 +250,10 @@ $(document).ready(function() $('#opc_account_errors').slideUp('slow', function(){ $(this).html(''); }); + + if (isTransforming) { + location.reload(); + } } isGuest = parseInt($('#is_new_customer').val()) == 1 ? 0 : 1; @@ -256,18 +269,18 @@ $(document).ready(function() static_token = jsonData.token; // It's not a new customer - if ($('#opc_id_customer').val() !== '0') + if (PS_CUSTOMER_ADDRESS_CREATION && $('#opc_id_customer').val() !== '0') if (!saveAddress('delivery')) return false; // update id_customer $('#opc_id_customer').val(jsonData.id_customer); - if ($('#invoice_address:checked').length !== 0) - { - if (!saveAddress('invoice')) - return false; - } + // if ($('#invoice_address:checked').length !== 0) + // { + // if (!saveAddress('invoice')) + // return false; + // } // update id_customer $('#opc_id_customer').val(jsonData.id_customer); @@ -1202,3 +1215,9 @@ function multishippingMode(it) bindUniform(); } } + +$(document).on('click', '.btn-edit-guest-info', function(e) { + e.preventDefault(); + $('#collapse-guest-info .card-body:nth-child(1)').hide(); + $('#collapse-guest-info .card-body:nth-child(2)').toggleClass('hidden'); +}); diff --git a/themes/hotel-reservation-theme/order-opc-edit-guest-info.tpl b/themes/hotel-reservation-theme/order-opc-edit-guest-info.tpl new file mode 100644 index 000000000..ad1aacaf9 --- /dev/null +++ b/themes/hotel-reservation-theme/order-opc-edit-guest-info.tpl @@ -0,0 +1,323 @@ +{** +* 2010-2022 Webkul. +* +* NOTICE OF LICENSE +* +* All right is reserved, +* Please go through LICENSE.txt file inside our module +* +* DISCLAIMER +* +* Do not edit or add to this file if you wish to upgrade this module to newer +* versions in the future. If you wish to customize this module for your +* needs please refer to CustomizationPolicy.txt file inside our module for more information. +* +* @author Webkul IN +* @copyright 2010-2022 Webkul IN +* @license LICENSE.txt +*} + +

+ +
+
+ +
+
+
+
+ {$HOOK_CREATE_ACCOUNT_TOP} + + + + + + + + + +

*{l s='Required field'}

+ +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ +
+
+ + +
+
+ +
+
+
+

{l s='OR'}

+

{l s='Create a customer account using above details.'}

+
+
+ + + {l s='(five characters min.)'} +
+
+
+
+
+ {if $PS_CUSTOMER_ADDRESS_CREATION} +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+
+ + {if isset($newsletter) && $newsletter} +
+ + {if array_key_exists('newsletter', $field_required)} + * + {/if} +
+ {/if} + {if isset($optin) && $optin} +
+ + {if array_key_exists('optin', $field_required)} + * + {/if} +
+ {/if} + +

{l s='RESIDENTIAL ADDRESS'}

+ {$stateExist = false} + {$postCodeExist = false} + {$dniExist = false} +
+ {foreach from=$dlv_all_fields item=field_name} + {if $field_name eq "firstname"} +
+ + +
+ {elseif $field_name eq "lastname"} +
+ + +
+ {elseif $field_name eq "address1"} +
+ + +
+ {elseif $field_name eq "address2"} +
+ + +
+ {elseif $field_name eq "city"} +
+ + +
+ {elseif $field_name eq "postcode"} + {$postCodeExist = true} +
+ + +
+ {elseif $field_name eq "company"} +
+ + +
+ {elseif $field_name eq "vat_number"} + + {elseif $field_name eq "dni"} + {assign var='dniExist' value=true} +
+ + + {l s='DNI / NIF / NIE'} +
+ {elseif $field_name eq "country" || $field_name eq "Country:name"} +
+ + +
+ {elseif $field_name eq "state" || $field_name eq 'State:name'} + {$stateExist = true} + + {/if} + {/foreach} + {if !$postCodeExist} +
+ + +
+ {/if} + {if !$stateExist} +
+ + +
+ {/if} + {if !$dniExist} +
+ + + {l s='DNI / NIF / NIE'} +
+ {/if} +
+ + +
+
+ + +
+
+ + +
+
+
+
+ {if isset($one_phone_at_least) && $one_phone_at_least} + {assign var="atLeastOneExists" value=true} +

** {l s='You must register at least one phone number.'}

+ {/if} + + +

+ *{l s='Required field'} +

+
+
+ {/if} + {$HOOK_CREATE_ACCOUNT_FORM} +
+ +
+ +
+
+
+ +{strip} + {if isset($guestInformations) && isset($guestInformations.id_state) && $guestInformations.id_state} + {addJsDef idSelectedState=$guestInformations.id_state|intval} + {else} + {addJsDef idSelectedState=false} + {/if} + {if isset($guestInformations) && isset($guestInformations.id_state_invoice) && $guestInformations.id_state_invoice} + {addJsDef idSelectedStateInvoice=$guestInformations.id_state_invoice|intval} + {else} + {addJsDef idSelectedStateInvoice=false} + {/if} + {if isset($guestInformations) && isset($guestInformations.id_country) && $guestInformations.id_country} + {addJsDef idSelectedCountry=$guestInformations.id_country|intval} + {else} + {addJsDef idSelectedCountry=false} + {/if} + {if isset($guestInformations) && isset($guestInformations.id_country_invoice) && $guestInformations.id_country_invoice} + {addJsDef idSelectedCountryInvoice=$guestInformations.id_country_invoice|intval} + {else} + {addJsDef idSelectedCountryInvoice=false} + {/if} + {if isset($countries)} + {addJsDef countries=$countries} + {/if} + {if isset($vatnumber_ajax_call) && $vatnumber_ajax_call} + {addJsDef vatnumber_ajax_call=$vatnumber_ajax_call} + {/if} + {addJsDef PS_CUSTOMER_ADDRESS_CREATION=$PS_CUSTOMER_ADDRESS_CREATION|intval} +{/strip} diff --git a/themes/hotel-reservation-theme/order-opc-new-account.tpl b/themes/hotel-reservation-theme/order-opc-new-account.tpl index 72b596a85..cfbd7a515 100644 --- a/themes/hotel-reservation-theme/order-opc-new-account.tpl +++ b/themes/hotel-reservation-theme/order-opc-new-account.tpl @@ -4,28 +4,32 @@

- {l s='Already have an account? '} {l s='Login Now'} {l s='to make check process faster and time saving.'} + {l s='Already have an account?'} {l s='Login now'} {l s='to make checkout process faster and time saving.'}

{l s='Or'}

-

@@ -51,6 +55,9 @@ + @@ -395,37 +402,8 @@ {$HOOK_CREATE_ACCOUNT_FORM}
-
-{strip} -{if isset($guestInformations) && isset($guestInformations.id_state) && $guestInformations.id_state} - {addJsDef idSelectedState=$guestInformations.id_state|intval} -{else} - {addJsDef idSelectedState=false} -{/if} -{if isset($guestInformations) && isset($guestInformations.id_state_invoice) && $guestInformations.id_state_invoice} - {addJsDef idSelectedStateInvoice=$guestInformations.id_state_invoice|intval} -{else} - {addJsDef idSelectedStateInvoice=false} -{/if} -{if isset($guestInformations) && isset($guestInformations.id_country) && $guestInformations.id_country} - {addJsDef idSelectedCountry=$guestInformations.id_country|intval} -{else} - {addJsDef idSelectedCountry=false} -{/if} -{if isset($guestInformations) && isset($guestInformations.id_country_invoice) && $guestInformations.id_country_invoice} - {addJsDef idSelectedCountryInvoice=$guestInformations.id_country_invoice|intval} -{else} - {addJsDef idSelectedCountryInvoice=false} -{/if} -{if isset($countries)} - {addJsDef countries=$countries} -{/if} -{if isset($vatnumber_ajax_call) && $vatnumber_ajax_call} - {addJsDef vatnumber_ajax_call=$vatnumber_ajax_call} -{/if} -{/strip} diff --git a/themes/hotel-reservation-theme/order-opc.tpl b/themes/hotel-reservation-theme/order-opc.tpl index 3a5677863..9a90bc071 100644 --- a/themes/hotel-reservation-theme/order-opc.tpl +++ b/themes/hotel-reservation-theme/order-opc.tpl @@ -78,51 +78,69 @@
{if $is_logged || $isGuest} -
-
{l s='Name'}
-
{$guestInformations['firstname']} {$guestInformations['lastname']}
-
-
-
{l s='Email'}
-
{$guestInformations['email']}
-
- {if (isset($delivery->phone_mobile) && $delivery->phone_mobile) || (isset($delivery->phone) && $delivery->phone)} +
-
- {if isset($delivery->phone_mobile) && $delivery->phone_mobile} - {l s='Mobile Number'} - {else} - {l s='Phone Number'} - {/if} -
+
{l s='Name'}
- {if isset($delivery->phone_mobile) && $delivery->phone_mobile} - {$delivery->phone_mobile|escape:'html':'UTF-8'} + {if $isGuest} + {$guestInformations['customer_firstname']} {$guestInformations['customer_lastname']} {else} - {$delivery->phone|escape:'html':'UTF-8'} + {$guestInformations['firstname']} {$guestInformations['lastname']} {/if}
- {/if} - - {* proceed only if no order restrict errors are there *} - {if !$orderRestrictErr} -
-
- +
+
{l s='Email'}
+
{$guestInformations['email']}
- {/if} + {if (isset($delivery->phone_mobile) && $delivery->phone_mobile) || (isset($delivery->phone) && $delivery->phone)} +
+
+ {if isset($delivery->phone_mobile) && $delivery->phone_mobile} + {l s='Mobile Number'} + {else} + {l s='Phone Number'} + {/if} +
+
+ {if isset($delivery->phone_mobile) && $delivery->phone_mobile} + {$delivery->phone_mobile|escape:'html':'UTF-8'} + {else} + {$delivery->phone|escape:'html':'UTF-8'} + {/if} +
+
+ {/if} + + {* proceed only if no order restrict errors are there *} + {if !$orderRestrictErr} +
+
+ +
+ {/if} +
{else} {include file="$tpl_dir./order-opc-new-account.tpl"} {/if}
+
{/if}
From e3d62e1fc1c52a25917b4baf43332b43a7354789 Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Tue, 23 Aug 2022 17:25:17 +0530 Subject: [PATCH 06/56] Improve statistics calculation and display at back office --- .../admin/AdminCustomerThreadsController.php | 1 - controllers/admin/AdminModulesController.php | 2 +- controllers/admin/AdminProductsController.php | 2 +- controllers/admin/AdminStatsController.php | 428 +++++++++++++----- controllers/admin/AdminStatsTabController.php | 8 + .../admin/AdminTranslationsController.php | 49 +- js/admin/dashboard.js | 9 - modules/dashactivity/dashactivity.php | 35 +- modules/dashactivity/views/js/dashactivity.js | 6 +- modules/dashavailability/dashavailability.php | 5 +- .../views/js/dashavailability.js | 2 +- .../templates/hook/dashboard_zone_two.tpl | 2 +- modules/dashoccupancy/dashoccupancy.php | 38 +- .../dashoccupancy/views/js/dashoccupancy.js | 20 +- .../templates/hook/dashboard_zone_one.tpl | 8 +- .../views/css/dashperformance.css | 4 + modules/dashproducts/dashproducts.php | 23 +- modules/dashtrends/dashtrends.php | 33 +- .../templates/hook/dashboard_zone_two.tpl | 6 +- .../classes/HotelBookingDetail.php | 4 +- .../hotelreservationsystem.php | 40 +- modules/pagesnotfound/pagesnotfound.php | 2 +- modules/sekeywords/sekeywords.php | 8 +- .../statsbestcategories.php | 194 ++++---- .../statsbestcustomers/statsbestcustomers.php | 26 +- .../statsbestproducts/statsbestproducts.php | 76 +++- .../statsbestvouchers/statsbestvouchers.php | 8 +- modules/statscatalog/statscatalog.php | 32 +- modules/statscheckup/statscheckup.php | 19 +- modules/statsequipment/statsequipment.php | 6 +- modules/statsforecast/statsforecast.php | 139 +++--- modules/statslive/statslive.php | 8 +- modules/statsnewsletter/statsnewsletter.php | 4 +- modules/statsorigin/statsorigin.php | 10 +- .../statspersonalinfos/statspersonalinfos.php | 14 +- modules/statsproduct/statsproduct.php | 30 +- .../statsregistrations/statsregistrations.php | 8 +- modules/statssales/statssales.php | 10 +- modules/statssearch/statssearch.php | 2 +- modules/statsvisits/statsvisits.php | 10 +- 40 files changed, 809 insertions(+), 522 deletions(-) diff --git a/controllers/admin/AdminCustomerThreadsController.php b/controllers/admin/AdminCustomerThreadsController.php index 3f2c52268..0deca4f1a 100644 --- a/controllers/admin/AdminCustomerThreadsController.php +++ b/controllers/admin/AdminCustomerThreadsController.php @@ -515,7 +515,6 @@ class AdminCustomerThreadsControllerCore extends AdminController $helper->id = 'box-pending-messages'; $helper->icon = 'icon-envelope'; $helper->color = 'color1'; - $helper->href = $this->context->link->getAdminLink('AdminCustomerThreads'); $helper->title = $this->l('Pending Discussion Threads', null, null, false); if (ConfigurationKPI::get('PENDING_MESSAGES') !== false) { $helper->value = ConfigurationKPI::get('PENDING_MESSAGES'); diff --git a/controllers/admin/AdminModulesController.php b/controllers/admin/AdminModulesController.php index 2e9a2e165..80048335a 100644 --- a/controllers/admin/AdminModulesController.php +++ b/controllers/admin/AdminModulesController.php @@ -1331,7 +1331,7 @@ class AdminModulesControllerCore extends AdminController $helper->id = 'box-update-modules'; $helper->icon = 'icon-refresh'; $helper->color = 'color3'; - $helper->title = $this->l('Modules to update', null, null, false); + $helper->title = $this->l('Modules to Update', null, null, false); if (ConfigurationKPI::get('UPDATE_MODULES') !== false && ConfigurationKPI::get('UPDATE_MODULES') != '') { $helper->value = ConfigurationKPI::get('UPDATE_MODULES'); } diff --git a/controllers/admin/AdminProductsController.php b/controllers/admin/AdminProductsController.php index 8a558d516..9b38ed5c7 100644 --- a/controllers/admin/AdminProductsController.php +++ b/controllers/admin/AdminProductsController.php @@ -2741,7 +2741,7 @@ class AdminProductsControllerCore extends AdminController $helper->id = 'box-8020-sales-catalog'; $helper->icon = 'icon-beaker'; $helper->color = 'color3'; - $helper->title = $this->l('Purchased references', null, null, false); + $helper->title = $this->l('Purchased References', null, null, false); $helper->subtitle = $this->l('30 days', null, null, false); if (ConfigurationKPI::get('8020_SALES_CATALOG') !== false) { $helper->value = ConfigurationKPI::get('8020_SALES_CATALOG'); diff --git a/controllers/admin/AdminStatsController.php b/controllers/admin/AdminStatsController.php index 5e69b81d3..60a066d4d 100644 --- a/controllers/admin/AdminStatsController.php +++ b/controllers/admin/AdminStatsController.php @@ -29,11 +29,10 @@ class AdminStatsControllerCore extends AdminStatsTabController public static function getVisits($unique = false, $date_from, $date_to, $granularity = false) { $visits = ($granularity == false) ? 0 : array(); - /** @var Gapi $gapi */ - $gapi = Module::isInstalled('gapi') ? Module::getInstanceByName('gapi') : false; - if (Validate::isLoadedObject($gapi) && $gapi->isConfigured()) { + $objQGA = Module::isEnabled('qlogoogleanalytics') ? Module::getInstanceByName('qlogoogleanalytics') : false; + if (Validate::isLoadedObject($objQGA) && $objQGA->isConfigured()) { $metric = $unique ? 'visitors' : 'visits'; - if ($result = $gapi->requestReportData($granularity ? 'ga:date' : '', 'ga:'.$metric, $date_from, $date_to, null, null, 1, 5000)) { + if ($result = $objQGA->requestReportData($granularity ? 'ga:date' : '', 'ga:'.$metric, $date_from, $date_to, null, null, 1, 5000)) { foreach ($result as $row) { if ($granularity == 'day') { $visits[strtotime(preg_replace('/^([0-9]{4})([0-9]{2})([0-9]{2})$/', '$1-$2-$3', $row['dimensions']['date']))] = $row['metrics'][$metric]; @@ -199,43 +198,59 @@ class AdminStatsControllerCore extends AdminStatsTabController { if ($granularity == 'day') { $sales = array(); - $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(' - SELECT LEFT(`invoice_date`, 10) as date, SUM(total_paid_tax_excl / o.conversion_rate) as sales - FROM `'._DB_PREFIX_.'orders` o - LEFT JOIN `'._DB_PREFIX_.'order_state` os ON o.current_state = os.id_order_state - LEFT JOIN `'._DB_PREFIX_.'htl_booking_detail` hbd ON (hbd.`id_order` = o.`id_order`) - WHERE `invoice_date` BETWEEN "'.pSQL($date_from).' 00:00:00" AND "'.pSQL($date_to).' 23:59:59" AND os.logable = 1 - '.Shop::addSqlRestriction(false, 'o') - .HotelBranchInformation::addHotelRestriction($id_hotel, 'hbd').' - GROUP BY LEFT(`invoice_date`, 10)'); + $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS( + 'SELECT LEFT(`invoice_date`, 10) AS date, SUM(total_paid_tax_excl / o.conversion_rate) AS sales, + ( + SELECT hbd.`id_hotel` + FROM`'._DB_PREFIX_.'htl_booking_detail` hbd + WHERE hbd.`id_order` = o.`id_order` LIMIT 1 + ) AS id_hotel + FROM `'._DB_PREFIX_.'orders` o + LEFT JOIN `'._DB_PREFIX_.'order_state` os ON o.current_state = os.id_order_state + WHERE `invoice_date` BETWEEN "'.pSQL($date_from).' 00:00:00" AND "'.pSQL($date_to).' 23:59:59" AND os.logable = 1 + GROUP BY LEFT(`invoice_date`, 10) + HAVING 1 '.HotelBranchInformation::addHotelRestriction($id_hotel) + ); + foreach ($result as $row) { $sales[strtotime($row['date'])] = $row['sales']; } + return $sales; } elseif ($granularity == 'month') { $sales = array(); - $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(' - SELECT LEFT(`invoice_date`, 7) as date, SUM(total_paid_tax_excl / o.conversion_rate) as sales - FROM `'._DB_PREFIX_.'orders` o - LEFT JOIN `'._DB_PREFIX_.'order_state` os ON o.current_state = os.id_order_state - LEFT JOIN `'._DB_PREFIX_.'htl_booking_detail` hbd ON (hbd.`id_order` = o.`id_order`) - WHERE `invoice_date` BETWEEN "'.pSQL($date_from).' 00:00:00" AND "'.pSQL($date_to).' 23:59:59" AND os.logable = 1 - '.Shop::addSqlRestriction(false, 'o') - .HotelBranchInformation::addHotelRestriction($id_hotel, 'hbd').' - GROUP BY LEFT(`invoice_date`, 7)'); + $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS( + 'SELECT LEFT(`invoice_date`, 7) AS date, SUM(total_paid_tax_excl / o.conversion_rate) AS sales, + ( + SELECT hbd.`id_hotel` + FROM`'._DB_PREFIX_.'htl_booking_detail` hbd + WHERE hbd.`id_order` = o.`id_order` LIMIT 1 + ) AS id_hotel + FROM `'._DB_PREFIX_.'orders` o + LEFT JOIN `'._DB_PREFIX_.'order_state` os ON o.current_state = os.id_order_state + WHERE `invoice_date` BETWEEN "'.pSQL($date_from).' 00:00:00" AND "'.pSQL($date_to).' 23:59:59" AND os.logable = 1 + GROUP BY LEFT(`invoice_date`, 7) + HAVING 1 '.HotelBranchInformation::addHotelRestriction($id_hotel) + ); + foreach ($result as $row) { $sales[strtotime($row['date'].'-01')] = $row['sales']; } + return $sales; } else { - return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(' - SELECT SUM(total_paid_tax_excl / o.conversion_rate) - FROM `'._DB_PREFIX_.'orders` o - LEFT JOIN `'._DB_PREFIX_.'order_state` os ON o.current_state = os.id_order_state - LEFT JOIN `'._DB_PREFIX_.'htl_booking_detail` hbd ON (hbd.`id_order` = o.`id_order`) - WHERE `invoice_date` BETWEEN "'.pSQL($date_from).' 00:00:00" AND "'.pSQL($date_to).' 23:59:59" AND os.logable = 1 - '.Shop::addSqlRestriction(false, 'o') - .HotelBranchInformation::addHotelRestriction($id_hotel, 'hbd')); + return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue( + 'SELECT SUM(total_paid_tax_excl / o.conversion_rate), + ( + SELECT hbd.`id_hotel` + FROM`'._DB_PREFIX_.'htl_booking_detail` hbd + WHERE hbd.`id_order` = o.`id_order` LIMIT 1 + ) AS id_hotel + FROM `'._DB_PREFIX_.'orders` o + LEFT JOIN `'._DB_PREFIX_.'order_state` os ON o.current_state = os.id_order_state + WHERE `invoice_date` BETWEEN "'.pSQL($date_from).' 00:00:00" AND "'.pSQL($date_to).' 23:59:59" AND os.logable = 1 + HAVING 1 '.HotelBranchInformation::addHotelRestriction($id_hotel) + ); } } @@ -258,7 +273,7 @@ class AdminStatsControllerCore extends AdminStatsTabController if ($granularity == 'day') { $orders = array(); $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(' - SELECT LEFT(`invoice_date`, 10) as date, COUNT(*) as orders + SELECT LEFT(`invoice_date`, 10) as date, COUNT(DISTINCT o.`id_order`) as orders FROM `'._DB_PREFIX_.'orders` o LEFT JOIN `'._DB_PREFIX_.'order_state` os ON o.current_state = os.id_order_state LEFT JOIN `'._DB_PREFIX_.'htl_booking_detail` hbd ON (hbd.`id_order` = o.`id_order`) @@ -273,7 +288,7 @@ class AdminStatsControllerCore extends AdminStatsTabController } elseif ($granularity == 'month') { $orders = array(); $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(' - SELECT LEFT(`invoice_date`, 7) as date, COUNT(*) as orders + SELECT LEFT(`invoice_date`, 7) as date, COUNT(DISTINCT o.`id_order`) as orders FROM `'._DB_PREFIX_.'orders` o LEFT JOIN `'._DB_PREFIX_.'order_state` os ON o.current_state = os.id_order_state LEFT JOIN `'._DB_PREFIX_.'htl_booking_detail` hbd ON (hbd.`id_order` = o.`id_order`) @@ -287,7 +302,7 @@ class AdminStatsControllerCore extends AdminStatsTabController return $orders; } else { $orders = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(' - SELECT COUNT(*) as orders + SELECT COUNT(DISTINCT o.`id_order`) as orders FROM `'._DB_PREFIX_.'orders` o LEFT JOIN `'._DB_PREFIX_.'order_state` os ON o.current_state = os.id_order_state LEFT JOIN `'._DB_PREFIX_.'htl_booking_detail` hbd ON (hbd.`id_order` = o.`id_order`) @@ -391,7 +406,7 @@ class AdminStatsControllerCore extends AdminStatsTabController return CustomerThread::getTotalCustomerThreads('status LIKE "%pending%" OR status = "open"'.Shop::addSqlRestriction()); } - public static function getAverageMessageResponseTime($date_from, $date_to) + public static function getAverageMessageResponseTime($date_from, $date_to, $return_seconds = false) { $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT MIN(cm1.date_add) as question, MIN(cm2.date_add) as reply @@ -411,7 +426,10 @@ class AdminStatsControllerCore extends AdminStatsTabController if (!$threads) { return 0; } - return round(($total_replies - $total_questions) / $threads / 3600, 1); + + $seconds = ($total_replies - $total_questions) / $threads; + + return $return_seconds ? $seconds : Tools::ps_round($seconds / 3600, 1); } public static function getMessagesPerThread($date_from, $date_to) @@ -546,7 +564,7 @@ class AdminStatsControllerCore extends AdminStatsTabController $visits_sum = $visitors; //array_sum($visitors); $orders_sum = $orders; //array_sum($orders); if ($visits_sum) { - $value = round(100 * $orders_sum / $visits_sum, 2); + $value = sprintf('%0.2f', 100 * $orders_sum / $visits_sum); } elseif ($orders_sum) { $value = '∞'; } else { @@ -615,7 +633,7 @@ class AdminStatsControllerCore extends AdminStatsTabController case '8020_sales_catalog': $value = AdminStatsController::get8020SalesCatalog(date('Y-m-d', strtotime('-30 days')), date('Y-m-d')); - $value = sprintf($this->l('%d%% of your Catalog'), $value); + $value = sprintf($this->l('%d%% of your catalog'), $value); ConfigurationKPI::updateValue('8020_SALES_CATALOG', $value); ConfigurationKPI::updateValue('8020_SALES_CATALOG_EXPIRE', strtotime('+12 hour')); break; @@ -632,11 +650,11 @@ class AdminStatsControllerCore extends AdminStatsTabController if ($value === false) { $value = $this->l('No customers', null, null, false); } elseif ($value['type'] == 'female') { - $value = sprintf($this->l('%d%% Female Customers', null, null, false), $value['value']); + $value = sprintf($this->l('%d%% Female customers', null, null, false), $value['value']); } elseif ($value['type'] == 'male') { - $value = sprintf($this->l('%d%% Male Customers', null, null, false), $value['value']); + $value = sprintf($this->l('%d%% Male customers', null, null, false), $value['value']); } else { - $value = sprintf($this->l('%d%% Neutral Customers', null, null, false), $value['value']); + $value = sprintf($this->l('%d%% Neutral customers', null, null, false), $value['value']); } ConfigurationKPI::updateValue('CUSTOMER_MAIN_GENDER', array($this->context->language->id => $value)); @@ -656,7 +674,18 @@ class AdminStatsControllerCore extends AdminStatsTabController break; case 'avg_msg_response_time': - $value = sprintf($this->l('%.1f hours', null, null, false), AdminStatsController::getAverageMessageResponseTime(date('Y-m-d', strtotime('-31 day')), date('Y-m-d', strtotime('-1 day')))); + $value = AdminStatsController::getAverageMessageResponseTime(date('Y-m-d', strtotime('-31 day')), date('Y-m-d', strtotime('-1 day')), true); + + if ($value <= 0) { + $value = '--'; + } elseif ($value < 60) { + $value = sprintf($this->l('%d seconds', null, null, false), $value); + } elseif ($value < 3600) { + $value = sprintf($this->l('%d minutes', null, null, false), (int) $value / 60); + } else { + $value = sprintf($this->l('%.1f hours', null, null, false), $value / 3600); + } + ConfigurationKPI::updateValue('AVG_MSG_RESPONSE_TIME', $value); ConfigurationKPI::updateValue('AVG_MSG_RESPONSE_TIME_EXPIRE', strtotime('+4 hour')); break; @@ -699,8 +728,8 @@ class AdminStatsControllerCore extends AdminStatsTabController /** @var Theme $theme */ foreach ($languages as $language) { $kpi_key = substr(strtoupper($theme->name.'_'.$language['iso_code']), 0, 16); - $total += ConfigurationKPI::get('TRANSLATE_TOTAL_'.$kpi_key); - $translated += ConfigurationKPI::get('TRANSLATE_DONE_'.$kpi_key); + $total += ConfigurationKPI::get('FRONTOFFICE_TRANSLATE_TOTAL_'.$kpi_key); + $translated += ConfigurationKPI::get('FRONTOFFICE_TRANSLATE_DONE_'.$kpi_key); } } $value = 0; @@ -712,6 +741,23 @@ class AdminStatsControllerCore extends AdminStatsTabController ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATIONS_EXPIRE', strtotime('+2 min')); break; + case 'backoffice_translations': + $languages = Language::getLanguages(); + $total = $translated = 0; + foreach ($languages as $language) { + $kpi_key = substr(strtoupper($language['iso_code']), 0, 16); + $total += ConfigurationKPI::get('BACKOFFICE_TRANSLATE_TOTAL_'.$kpi_key); + $translated += ConfigurationKPI::get('BACKOFFICE_TRANSLATE_DONE_'.$kpi_key); + } + $value = 0; + if ($translated) { + $value = round(100 * $translated / $total, 1); + } + $value .= '%'; + ConfigurationKPI::updateValue('BACKOFFICE_TRANSLATIONS', $value); + ConfigurationKPI::updateValue('BACKOFFICE_TRANSLATIONS_EXPIRE', strtotime('+2 min')); + break; + case 'main_country': if (!($row = AdminStatsController::getMainCountry(date('Y-m-d', strtotime('-30 day')), date('Y-m-d')))) { $value = $this->l('No orders', null, null, false); @@ -746,10 +792,11 @@ class AdminStatsControllerCore extends AdminStatsTabController case 'average_order_value': $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(' SELECT - COUNT(`id_order`) as orders, - SUM(`total_paid_tax_excl` / `conversion_rate`) as total_paid_tax_excl - FROM `'._DB_PREFIX_.'orders` - WHERE `invoice_date` BETWEEN "'.pSQL(date('Y-m-d', strtotime('-31 day'))).' 00:00:00" AND "'.pSQL(date('Y-m-d', strtotime('-1 day'))).' 23:59:59" + COUNT(o.`id_order`) as orders, + SUM(o.`total_paid_tax_excl` / o.`conversion_rate`) as total_paid_tax_excl + FROM `'._DB_PREFIX_.'orders` o + LEFT JOIN `'._DB_PREFIX_.'order_state` os ON os.`id_order_state` = o.`current_state` + WHERE o.`invoice_date` BETWEEN "'.pSQL(date('Y-m-d', strtotime('-31 day'))).' 00:00:00" AND "'.pSQL(date('Y-m-d', strtotime('-1 day'))).' 23:59:59" AND os.`logable` = 1 '.Shop::addSqlRestriction()); $value = Tools::displayPrice($row['orders'] ? $row['total_paid_tax_excl'] / $row['orders'] : 0, $currency); ConfigurationKPI::updateValue('AVG_ORDER_VALUE', $value); @@ -879,12 +926,15 @@ class AdminStatsControllerCore extends AdminStatsTabController public static function getCancelledBookingsByDate($date, $idHotel = false) { return Db::getInstance()->getValue( - 'SELECT COUNT(o.`id_order`) + 'SELECT COUNT(DISTINCT o.`id_order`) FROM `'._DB_PREFIX_.'orders` o LEFT JOIN `'._DB_PREFIX_.'order_state` os ON (os.`id_order_state` = o.`current_state`) LEFT JOIN `'._DB_PREFIX_.'htl_booking_detail` hbd ON (hbd.`id_order` = o.`id_order`) WHERE o.`date_upd` BETWEEN "'.pSQL($date).' 00:00:00" AND "'.pSQL($date).' 23:59:59" - AND o.`current_state` = '.(int) Configuration::get('PS_OS_CANCELED'). + AND o.`current_state` IN ('.implode(',', array( + (int) Configuration::get('PS_OS_CANCELED'), + (int) Configuration::get('PS_OS_REFUND')) + ).')'. HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') ); } @@ -970,80 +1020,79 @@ class AdminStatsControllerCore extends AdminStatsTabController return $occupancyData; } - public static function getAvailBarChartData($days, $dateFrom, $idHotel = null) + public static function getAvailabilityLineChartData($days, $dateFrom, $idHotel = null) // $dateFrom is inclusive { - - $availability_data = array(); - $from = date('Y-m-d' ,strtotime($dateFrom." 00:00:00")); - $to = date('Y-m-d' ,strtotime($dateFrom."+".$days." day 23:59:59")); - - for ($date = $from; $date < $to; $date = date('Y-m-d', strtotime('+1 day', strtotime($date)))) { - $bookedRoomSql = 'SELECT hri.`id` FROM `'._DB_PREFIX_.'htl_booking_detail` hbd - LEFT JOIN `'._DB_PREFIX_.'htl_room_information` hri ON hbd.`id_room` = hri.`id` - WHERE hbd.`date_from` <= "'.pSQL($date).' 00:00:00" - AND hbd.`date_to` >= "'.pSQL(date('Y-m-d ', strtotime('+1 day', strtotime($date)))).' 00:00:00" - AND hbd.`is_refunded` = 0 AND hbd.`is_back_order` = 0'. - (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') : ''); - - $tempBookedRoomIds = Db::getInstance()->ExecuteS($bookedRoomSql); - $bookedRoomIds = array(); - if (count($tempBookedRoomIds)) { - foreach ($tempBookedRoomIds as $value) { - if ($value['id']) { - $bookedRoomIds[] = $value['id']; - } - } - } else { - $bookedRoomIds[] = "0"; - } - - $availRoomSql = 'SELECT COUNT("id") FROM `'._DB_PREFIX_.'htl_room_information` hri - WHERE hri.`id` NOT IN ('.implode(',', $bookedRoomIds).') - AND hri.`id_status` != '.(int) HotelRoomInformation::STATUS_INACTIVE.' - AND hri.`id_status` != '.(int) HotelRoomInformation::STATUS_TEMPORARY_INACTIVE. - (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hri') : ''); - $availRoomIds = Db::getInstance()->getValue($availRoomSql); - - $availability_data["values"][] = array(strtotime($date), sprintf("%02d", $availRoomIds)); + if ($days == 0) { + return array(); } - return $availability_data; + $dateTo = date('Y-m-d', strtotime($dateFrom.'+'.$days.' days')); + $availableRoomsDiscrete = self::getAvailableRoomsForDiscreteDates($dateFrom, $dateTo, $idHotel); + $availabilityData = array(); + if ($availableRoomsDiscrete) { + foreach ($availableRoomsDiscrete as $timestamp => $availableRoom) { + $availabilityData['values'][] = array( + $timestamp, + sprintf('%02d', $availableRoom) + ); + } + } + + return $availabilityData; } - public static function getAverageDailyRate($dateFrom, $dateTo, $idHotel = false) + public static function getAverageDailyRate($dateFrom, $dateTo, $idHotel = null) { - $result = Db::getInstance()->getRow( - 'SELECT - SUM(hbd.`total_price_tax_excl`) AS `rooms_revenue`, - COUNT(hbd.`id_room`) AS `room_sold` - FROM `'._DB_PREFIX_.'htl_booking_detail` hbd - WHERE hbd.`is_refunded` = 0 AND hbd.`is_back_order` = 0 - AND hbd.`date_add` BETWEEN "'.pSQL($dateFrom).' 00:00:00" AND "'.pSQL($dateTo).' 23:59:59"'. - HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') - ); - return Tools::displayPrice($result['rooms_revenue'] ? $result['rooms_revenue'] / $result['room_sold'] : 0); + if ($dateFrom == $dateTo) { + $dateTo = date('Y-m-d', strtotime('+1 day', strtotime($dateTo))); + } + + $occupiedRooms = self::getOccupiedRoomsForDiscreteDates($dateFrom, $dateTo, $idHotel); + $roomsRevenues = self::getRoomsRevenuesForDiscreteDates($dateFrom, $dateTo, $idHotel); + + if (count($occupiedRooms) != count($roomsRevenues)) { + return false; + } + + $divisor = 0; + $sumADRs = 0; + foreach ($occupiedRooms as $key => $occupiedRoom) { + if ($occupiedRoom == 0) { + unset($occupiedRooms[$key]); + unset($roomsRevenues[$key]); + continue; + } + + $sumADRs += ($occupiedRoom ? ($roomsRevenues[$key] / $occupiedRoom) : 0); + $divisor++; + } + + return Tools::displayPrice($divisor ? ($sumADRs / $divisor) : 0); } public static function getCancellationRate($dateFrom, $dateTo, $idHotel = false) { $numAllOrders = Db::getInstance()->getValue( - 'SELECT COUNT(o.`id_order`) FROM `'._DB_PREFIX_.'orders` o + 'SELECT COUNT(DISTINCT o.`id_order`) FROM `'._DB_PREFIX_.'orders` o LEFT JOIN `'._DB_PREFIX_.'htl_booking_detail` hbd ON (hbd.`id_order` = o.`id_order`) WHERE o.`date_add` BETWEEN "'.pSQL($dateFrom).' 00:00:00" AND "'.pSQL($dateTo).' 23:59:59"'. HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') ); $numCancelledOrders = Db::getInstance()->getValue( - 'SELECT COUNT(o.`id_order`) FROM `'._DB_PREFIX_.'orders` o + 'SELECT COUNT(DISTINCT o.`id_order`) FROM `'._DB_PREFIX_.'orders` o LEFT JOIN `'._DB_PREFIX_.'order_state` os ON (os.`id_order_state` = o.`current_state`) LEFT JOIN `'._DB_PREFIX_.'htl_booking_detail` hbd ON (hbd.`id_order` = o.`id_order`) WHERE o.`date_add` BETWEEN "'.pSQL($dateFrom).' 00:00:00" AND "'.pSQL($dateTo).' 23:59:59" - AND o.`current_state` = '.(int)Configuration::get('PS_OS_CANCELED'). + AND o.`current_state` IN ('.implode(',', array( + (int) Configuration::get('PS_OS_CANCELED'), + (int) Configuration::get('PS_OS_REFUND')) + ).')'. HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') ); - if ($numCancelledOrders != 0) { - return round(($numCancelledOrders / $numAllOrders) * 100, 2).'%'; + if ($numAllOrders != 0) { + return Tools::ps_round(($numCancelledOrders / $numAllOrders) * 100, 2).'%'; } else { return '0.00%'; } @@ -1052,12 +1101,20 @@ class AdminStatsControllerCore extends AdminStatsTabController public static function getRevenue($dateFrom, $dateTo, $idHotel = false) { $result = Db::getInstance()->getValue( - 'SELECT (SUM(o.`total_paid_tax_excl` / o.`conversion_rate`) - SUM(orr.`refunded_amount`)) - FROM `'._DB_PREFIX_.'orders` o - LEFT JOIN `' ._DB_PREFIX_.'order_return` orr ON orr.`id_order` = o.`id_order` - LEFT JOIN `'._DB_PREFIX_.'htl_booking_detail` hbd ON (hbd.`id_order` = o.`id_order`) - WHERE o.`invoice_date` BETWEEN "'.pSQL($dateFrom).' 00:00:00" AND "'.pSQL($dateTo).' 23:59:59"'. - HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') + 'SELECT SUM(total_paid_tax_excl - refunded_amount) + FROM ( + SELECT o.`total_paid_tax_excl` / o.`conversion_rate` AS total_paid_tax_excl, + IFNULL(orr.`refunded_amount`, 0) AS refunded_amount, + ( + SELECT hbd.`id_hotel` + FROM`'._DB_PREFIX_.'htl_booking_detail` hbd + WHERE hbd.`id_order` = o.`id_order` LIMIT 1 + ) AS id_hotel + FROM `'._DB_PREFIX_.'orders` o + LEFT JOIN `' ._DB_PREFIX_.'order_return` orr ON orr.`id_order` = o.`id_order` + WHERE o.`invoice_date` BETWEEN "'.pSQL($dateFrom).' 00:00:00" AND "'.pSQL($dateTo).' 23:59:59" + HAVING 1 '.HotelBranchInformation::addHotelRestriction($idHotel).' + ) AS t' ); return Tools::displayPrice($result ? $result : 0); @@ -1101,4 +1158,163 @@ class AdminStatsControllerCore extends AdminStatsTabController ((int) $limit ? ' LIMIT 0, '.(int) $limit : '') ); } + + public static function getOccupiedRoomsForDiscreteDates($dateFrom, $dateTo = null, $idHotel = null, $useCache = true) + { + $dateTo = !$dateTo ? date('Y-m-d', strtotime('+1 day', strtotime($dateFrom))) : $dateTo; + + $discreteDates = array(); + $date = $dateFrom; + while ($date < $dateTo) { + $dateNext = date('Y-m-d', strtotime('+1 day', strtotime($date))); + $discreteDates[] = array( + 'date_from' => $date, + 'date_to' => $dateNext, + 'timestamp_from' => strtotime($date), + ); + $date = $dateNext; + }; + + $result = array(); + foreach ($discreteDates as $discreteDate) { + $cacheKey = 'AdminStats::getOccupiedRoomsForDiscreteDates_'.(int) $discreteDate['timestamp_from'].'_'. + (!is_array($idHotel) ? (int) $idHotel : implode('_', $idHotel)); + if (!Cache::isStored($cacheKey) || !$useCache) { + $sql = 'SELECT COUNT(DISTINCT hbd.`id_room`) + FROM `'._DB_PREFIX_.'htl_booking_detail` hbd + LEFT JOIN `'._DB_PREFIX_.'htl_room_information` hri + ON (hri.`id` = hbd.`id_room`) + LEFT JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hri.`id_product`) + WHERE p.`active` = 1 + AND hbd.`is_refunded` = 0 + AND hbd.`date_from` < "'.pSQL($discreteDate['date_to']).' 00:00:00" AND hbd.`date_to` > "'.pSQL($discreteDate['date_from']).' 00:00:00"'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') : ''); + + $value = Db::getInstance()->getValue($sql); + Cache::store($cacheKey, $value); + } + + $result[$discreteDate['timestamp_from']] = Cache::retrieve($cacheKey); + } + + return $result; + } + + public static function getRoomsRevenuesForDiscreteDates($dateFrom, $dateTo = null, $idHotel = null, $useCache = true) + { + $dateTo = !$dateTo ? date('Y-m-d', strtotime('+1 day', strtotime($dateFrom))) : $dateTo; + + $discreteDates = array(); + $date = $dateFrom; + while ($date < $dateTo) { + $dateNext = date('Y-m-d', strtotime('+1 day', strtotime($date))); + $discreteDates[] = array( + 'date_from' => $date, + 'date_to' => $dateNext, + 'timestamp_from' => strtotime($date), + ); + $date = $dateNext; + }; + + $result = array(); + foreach ($discreteDates as $discreteDate) { + $cacheKey = 'AdminStats::getRoomsRevenuesForDiscreteDates'.(int) $discreteDate['timestamp_from'].'_'. + (!is_array($idHotel) ? (int) $idHotel : implode('_', $idHotel)); + if (!Cache::isStored($cacheKey) || !$useCache) { + $sql = 'SELECT IFNULL(SUM(hbd.`total_price_tax_excl` / DATEDIFF(hbd.`date_to`, hbd.`date_from`)), 0) + FROM `'._DB_PREFIX_.'htl_booking_detail` hbd + LEFT JOIN `'._DB_PREFIX_.'htl_room_information` hri + ON (hri.`id` = hbd.`id_room`) + LEFT JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hri.`id_product`) + WHERE p.`active` = 1 + AND hbd.`is_refunded` = 0 + AND hbd.`date_from` < "'.pSQL($discreteDate['date_to']).' 00:00:00" AND hbd.`date_to` > "'.pSQL($discreteDate['date_from']).' 00:00:00"'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') : ''); + + $value = Db::getInstance()->getValue($sql); + Cache::store($cacheKey, $value); + } + + $result[$discreteDate['timestamp_from']] = Cache::retrieve($cacheKey); + } + + return $result; + } + + public static function getAvailableRoomsForDiscreteDates($dateFrom, $dateTo = null, $idHotel = null, $useCache = true) + { + $dateTo = !$dateTo ? date('Y-m-d', strtotime('+1 day', strtotime($dateFrom))) : $dateTo; + $discreteDates = array(); + $date = $dateFrom; + while ($date < $dateTo) { + $dateNext = date('Y-m-d', strtotime('+1 day', strtotime($date))); + $discreteDates[] = array( + 'date_from' => $date, + 'date_to' => $dateNext, + 'timestamp_from' => strtotime($date), + ); + $date = $dateNext; + }; + + $result = array(); + foreach ($discreteDates as $discreteDate) { + $cacheKey = 'AdminStats::getAvailableRoomsForDiscreteDates'.(int) $discreteDate['timestamp_from'].'_'. + (!is_array($idHotel) ? (int) $idHotel : implode('_', $idHotel)); + if (!Cache::isStored($cacheKey) || !$useCache) { + $sql = 'SELECT (num_total - num_booked - num_inactive - num_temporarily_inactive) AS num_available + FROM ( + SELECT ( + SELECT IFNULL(COUNT(hri.`id`), 0) + FROM `'._DB_PREFIX_.'htl_room_information` hri + LEFT JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hri.`id_product`) + WHERE p.`active` = 1'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hri') : '').' + ) AS num_total, + ( + SELECT COUNT(DISTINCT hbd.`id_room`) + FROM `'._DB_PREFIX_.'htl_booking_detail` hbd + LEFT JOIN `'._DB_PREFIX_.'htl_room_information` hri + ON (hri.`id` = hbd.`id_room`) + LEFT JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hri.`id_product`) + WHERE p.`active` = 1 + AND hbd.`is_refunded` = 0 + AND hbd.`date_from` < "'.pSQL($discreteDate['date_to']).' 00:00:00" AND hbd.`date_to` > "'.pSQL($discreteDate['date_from']).' 00:00:00"'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') : '').' + ) AS num_booked, + ( + SELECT IFNULL(COUNT(hri.`id`), 0) + FROM `'._DB_PREFIX_.'htl_room_information` hri + LEFT JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hri.`id_product`) + WHERE hri.`id_status` = '.(int) HotelRoomInformation::STATUS_INACTIVE.' + AND p.`active` = 1'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hri') : '').' + ) AS num_inactive, + ( + SELECT IFNULL(COUNT(hri.`id`), 0) + FROM `'._DB_PREFIX_.'htl_room_information` hri + LEFT JOIN `'._DB_PREFIX_.'htl_room_disable_dates` hrdd + ON (hrdd.`id_room` = hri.`id`) + LEFT JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hri.`id_product`) + WHERE hri.`id_status` = '.(int) HotelRoomInformation::STATUS_TEMPORARY_INACTIVE.' + AND ("'.pSQL($discreteDate['date_from']).'" >= hrdd.`date_from` AND "'.pSQL($discreteDate['date_from']).'" < hrdd.`date_to`) + AND p.`active` = 1'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hri') : '').' + ) AS num_temporarily_inactive + ) AS t'; + + $value = Db::getInstance()->getValue($sql); + Cache::store($cacheKey, $value); + } + + $result[$discreteDate['timestamp_from']] = Cache::retrieve($cacheKey); + } + + return $result; + } } diff --git a/controllers/admin/AdminStatsTabController.php b/controllers/admin/AdminStatsTabController.php index 54b1682fb..72c2b2e85 100644 --- a/controllers/admin/AdminStatsTabController.php +++ b/controllers/admin/AdminStatsTabController.php @@ -150,8 +150,13 @@ abstract class AdminStatsTabControllerCore extends AdminPreferencesControllerCor $tpl = $this->createTemplate('menu.tpl'); $modules = $this->getModules(); + $key_statsforecast = null; $module_instance = array(); foreach ($modules as $m => $module) { + if ($module['name'] == 'statsforecast') { + $key_statsforecast = $m; + } + if ($module_instance[$module['name']] = Module::getInstanceByName($module['name'])) { $modules[$m]['displayName'] = $module_instance[$module['name']]->displayName; } else { @@ -161,6 +166,9 @@ abstract class AdminStatsTabControllerCore extends AdminPreferencesControllerCor } uasort($modules, array($this, 'checkModulesNames')); + if (!is_null($key_statsforecast)) { + $modules = array($key_statsforecast => $modules[$key_statsforecast]) + $modules; + } $tpl->assign(array( 'current' => self::$currentIndex, diff --git a/controllers/admin/AdminTranslationsController.php b/controllers/admin/AdminTranslationsController.php index d2024c057..87f8e3f5e 100644 --- a/controllers/admin/AdminTranslationsController.php +++ b/controllers/admin/AdminTranslationsController.php @@ -295,9 +295,6 @@ class AdminTranslationsControllerCore extends AdminController } } - $thm_name = str_replace('.', '', Tools::getValue('theme')); - $kpi_key = substr(strtoupper($thm_name.'_'.Tools::getValue('lang')), 0, 16); - if ($fd = fopen($file_path, 'w')) { // Get value of button save and stay $save_and_stay = Tools::isSubmit('submitTranslations'.$type.'AndStay'); @@ -323,9 +320,22 @@ class AdminTranslationsControllerCore extends AdminController } } - ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATIONS_EXPIRE', time()); - ConfigurationKPI::updateValue('TRANSLATE_TOTAL_'.$kpi_key, count($_POST)); - ConfigurationKPI::updateValue('TRANSLATE_DONE_'.$kpi_key, count($to_insert)); + if (in_array($this->type_selected, array('front', 'back'))) { + if ($this->type_selected == 'front') { + $thm_name = str_replace('.', '', Tools::getValue('theme')); + $kpi_key = substr(strtoupper($thm_name.'_'.Tools::getValue('lang')), 0, 16); + + ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATIONS_EXPIRE', time()); + ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATE_TOTAL_'.$kpi_key, count($_POST)); + ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATE_DONE_'.$kpi_key, count($to_insert)); + } else { + $kpi_key = substr(strtoupper(Tools::getValue('lang')), 0, 16); + + ConfigurationKPI::updateValue('BACKOFFICE_TRANSLATIONS_EXPIRE', time()); + ConfigurationKPI::updateValue('BACKOFFICE_TRANSLATE_TOTAL_'.$kpi_key, count($_POST)); + ConfigurationKPI::updateValue('BACKOFFICE_TRANSLATE_DONE_'.$kpi_key, count($to_insert)); + } + } // translations array is ordered by key (easy merge) ksort($to_insert); @@ -1426,20 +1436,7 @@ class AdminTranslationsControllerCore extends AdminController $kpis[] = $helper->generate(); $helper = new HelperKpi(); - $helper->id = 'box-country'; - $helper->icon = 'icon-home'; - $helper->color = 'color2'; - $helper->title = $this->l('Main Country', null, null, false); - $helper->subtitle = $this->l('30 Days', null, null, false); - if (ConfigurationKPI::get('MAIN_COUNTRY', $this->context->language->id) !== false) { - $helper->value = ConfigurationKPI::get('MAIN_COUNTRY', $this->context->language->id); - } - $helper->source = $this->context->link->getAdminLink('AdminStats').'&ajax=1&action=getKpi&kpi=main_country'; - $helper->refresh = (bool)(ConfigurationKPI::get('MAIN_COUNTRY_EXPIRE', $this->context->language->id) < $time); - $kpis[] = $helper->generate(); - - $helper = new HelperKpi(); - $helper->id = 'box-translations'; + $helper->id = 'box-fo-translations'; $helper->icon = 'icon-list'; $helper->color = 'color3'; $helper->title = $this->l('Front office Translations', null, null, false); @@ -1450,6 +1447,18 @@ class AdminTranslationsControllerCore extends AdminController $helper->refresh = (bool)(ConfigurationKPI::get('FRONTOFFICE_TRANSLATIONS_EXPIRE') < $time); $kpis[] = $helper->generate(); + $helper = new HelperKpi(); + $helper->id = 'box-bo-translations'; + $helper->icon = 'icon-list'; + $helper->color = 'color4'; + $helper->title = $this->l('Back office Translations', null, null, false); + if (ConfigurationKPI::get('BACKOFFICE_TRANSLATIONS') !== false) { + $helper->value = ConfigurationKPI::get('BACKOFFICE_TRANSLATIONS'); + } + $helper->source = $this->context->link->getAdminLink('AdminStats').'&ajax=1&action=getKpi&kpi=backoffice_translations'; + $helper->refresh = (bool)(ConfigurationKPI::get('BACKOFFICE_TRANSLATIONS_EXPIRE') < $time); + $kpis[] = $helper->generate(); + $helper = new HelperKpiRow(); $helper->kpis = $kpis; return $helper->generate(); diff --git a/js/admin/dashboard.js b/js/admin/dashboard.js index 8757970b7..8bba6525b 100644 --- a/js/admin/dashboard.js +++ b/js/admin/dashboard.js @@ -109,15 +109,6 @@ function data_value(widget_name, data) { } } -function data_avail_pie_chart(widget_name, data) { - if (data) { - $("#pie_occupied_text").text(data.count_occupied + '/' + data.count_total); - $("#pie_avail_text").text(data.count_available); - $("#pie_inactive_text").text(data.count_unavailable); - generateAvailablityPieChart(data.chart_data); - } -} - function data_trends(widget_name, data) { for (var data_id in data) { this.el = $('#' + data_id); diff --git a/modules/dashactivity/dashactivity.php b/modules/dashactivity/dashactivity.php index 284b75071..9530d987b 100644 --- a/modules/dashactivity/dashactivity.php +++ b/modules/dashactivity/dashactivity.php @@ -86,17 +86,9 @@ class Dashactivity extends Module public function hookDashboardZoneOne($params) { - $gapi_mode = 'configure'; - if (!Module::isInstalled('gapi')) { - $gapi_mode = 'install'; - } elseif (($gapi = Module::getInstanceByName('gapi')) && Validate::isLoadedObject($gapi) && $gapi->isConfigured()) { - $gapi_mode = false; - } - $this->context->smarty->assign($this->getConfigFieldsValues()); $this->context->smarty->assign( array( - 'gapi_mode' => $gapi_mode, 'dashactivity_config_form' => $this->renderConfigForm(), 'date_subtitle' => $this->l('(from %s to %s)'), 'date_format' => $this->context->language->date_format_lite, @@ -160,26 +152,23 @@ class Dashactivity extends Module ); } - $gapi = Module::isInstalled('gapi') ? Module::getInstanceByName('gapi') : false; - if (Validate::isLoadedObject($gapi) && $gapi->isConfigured()) { + $objQGA = Module::isEnabled('qlogoogleanalytics') ? Module::getInstanceByName('qlogoogleanalytics') : false; + if (Validate::isLoadedObject($objQGA) && $objQGA->isConfigured()) { $visits = $unique_visitors = $online_visitor = 0; - if ($result = $gapi->requestReportData('', 'ga:visits,ga:visitors', Tools::substr($params['date_from'], 0, 10), Tools::substr($params['date_to'], 0, 10), null, null, 1, 1)) { + if ($result = $objQGA->requestReportData('', 'ga:visits,ga:visitors', Tools::substr($params['date_from'], 0, 10), Tools::substr($params['date_to'], 0, 10), null, null, 1, 1)) { $visits = $result[0]['metrics']['visits']; $unique_visitors = $result[0]['metrics']['visitors']; } } else { - $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(' - SELECT COUNT(*) as visits, COUNT(DISTINCT `id_guest`) as unique_visitors - FROM `'._DB_PREFIX_.'connections` - WHERE `date_add` BETWEEN "'.pSQL($params['date_from']).'" AND "'.pSQL($params['date_to']).'" - '.Shop::addSqlRestriction(false) - ); + $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow( + 'SELECT COUNT(*) AS visits, COUNT(DISTINCT `id_guest`) AS unique_visitors + FROM `'._DB_PREFIX_.'connections` + WHERE `date_add` BETWEEN "'.pSQL($params['date_from']).'" AND "'.pSQL($params['date_to']).'" + '.Shop::addSqlRestriction(false) + ); extract($row); } - // Online visitors is only available with Analytics Real Time still in private beta at this time (October 18th, 2013). - // if ($result = $gapi->requestReportData('', 'ga:activeVisitors', null, null, null, null, 1, 1)) - // $online_visitor = $result[0]['metrics']['activeVisitors']; if ($maintenance_ips = Configuration::get('PS_MAINTENANCE_IP')) { $maintenance_ips = implode(',', array_map('ip2long', array_map('trim', explode(',', $maintenance_ips)))); } @@ -358,10 +347,10 @@ class Dashactivity extends Module protected function getReferer($date_from, $date_to, $limit = 3) { - $gapi = Module::isInstalled('gapi') ? Module::getInstanceByName('gapi') : false; - if (Validate::isLoadedObject($gapi) && $gapi->isConfigured()) { + $objQGA = Module::isEnabled('qlogoogleanalytics') ? Module::getInstanceByName('qlogoogleanalytics') : false; + if (Validate::isLoadedObject($objQGA) && $objQGA->isConfigured()) { $websites = array(); - if ($result = $gapi->requestReportData( + if ($result = $objQGA->requestReportData( 'ga:source', 'ga:visitors', Tools::substr($date_from, 0, 10), diff --git a/modules/dashactivity/views/js/dashactivity.js b/modules/dashactivity/views/js/dashactivity.js index 49bffb2ad..96ee7ad9f 100644 --- a/modules/dashactivity/views/js/dashactivity.js +++ b/modules/dashactivity/views/js/dashactivity.js @@ -40,11 +40,11 @@ function pie_chart_trends(widget_name, chart_details) .datum(chart_details.data) .transition().duration(1200) .call(chart); - + nv.utils.windowResize(chart.update); return chart; - }); + }); } //TODO unify this with other function in calenda.js and replace date.js functions @@ -151,7 +151,7 @@ $(document).ready(function() { $('#date-end').change(function() { start = Date.parseDate($('#date-start').val(), 'Y-m-d'); end = Date.parseDate($('#date-end').val(), 'Y-m-d'); - + $('#customers-newsletters-subtitle').html(sprintf(date_subtitle, start.format(date_format), end.format(date_format))); $('#traffic-subtitle').html(sprintf(date_subtitle, start.format(date_format), end.format(date_format))); }); diff --git a/modules/dashavailability/dashavailability.php b/modules/dashavailability/dashavailability.php index 65f2a8614..092646a15 100644 --- a/modules/dashavailability/dashavailability.php +++ b/modules/dashavailability/dashavailability.php @@ -92,7 +92,7 @@ class DashAvailability extends Module $availability_data['values'][] = array($date, round(rand(0, 20))); } } else { - $availability_data = AdminStatsController::getAvailBarChartData($days, $dateFrom, $params['id_hotel']); + $availability_data = AdminStatsController::getAvailabilityLineChartData($days, $dateFrom, $params['id_hotel']); } $availability_data = array_merge( @@ -111,8 +111,9 @@ class DashAvailability extends Module 'date_format' => $this->context->language->date_format_lite, 'data' => $data ); + return array( - 'data_chart' => array('availableBarChart' => $data), + 'data_chart' => array('availability_line_chart1' => $data), ); } } diff --git a/modules/dashavailability/views/js/dashavailability.js b/modules/dashavailability/views/js/dashavailability.js index 001a40cc8..44b6a0f30 100644 --- a/modules/dashavailability/views/js/dashavailability.js +++ b/modules/dashavailability/views/js/dashavailability.js @@ -44,7 +44,7 @@ function line_chart_availability(widget_name, chart_details) { dashavailability_data = chart_details.data; dashavailability_chart = chart; - d3.select('#availableBarChart svg') + d3.select('#availability_line_chart1 svg') .datum(dashavailability_data) .call(chart); nv.utils.windowResize(chart.update); diff --git a/modules/dashavailability/views/templates/hook/dashboard_zone_two.tpl b/modules/dashavailability/views/templates/hook/dashboard_zone_two.tpl index ef9c0bbe1..6385a4eaf 100644 --- a/modules/dashavailability/views/templates/hook/dashboard_zone_two.tpl +++ b/modules/dashavailability/views/templates/hook/dashboard_zone_two.tpl @@ -59,7 +59,7 @@ -
+
diff --git a/modules/dashoccupancy/dashoccupancy.php b/modules/dashoccupancy/dashoccupancy.php index 472f7b446..e7aadc99f 100644 --- a/modules/dashoccupancy/dashoccupancy.php +++ b/modules/dashoccupancy/dashoccupancy.php @@ -57,19 +57,9 @@ class DashOccupancy extends Module } } - public function hookDashboardZoneOne($params) + public function hookDashboardZoneOne() { - $occupancyData = AdminStatsController::getOccupancyData( - $params['date_from'], - $params['date_to'], - $params['id_hotel'] - ); - $this->context->smarty->assign(array( - 'count_total' => sprintf('%02d', $occupancyData['count_total']), - 'count_occupied' => sprintf('%02d', $occupancyData['count_occupied']), - 'count_available' => sprintf('%02d', $occupancyData['count_available']), - 'count_unavailable' => sprintf('%02d', $occupancyData['count_unavailable']), 'date_occupancy_range' => $this->l('(from %s to %s)'), 'date_occupancy_avail_format' => $this->context->language->date_format_lite, )); @@ -79,7 +69,6 @@ class DashOccupancy extends Module public function hookDashboardData($params) { - $data = array(); if (Configuration::get('PS_DASHBOARD_SIMULATION')) { $occupancyData = array(); $occupancyData['count_total'] = sprintf('%02d', rand(0, 1000)); @@ -97,7 +86,14 @@ class DashOccupancy extends Module ); } - $chartData = array( + $dataValue = array( + 'do_count_total' => sprintf('%02d', $occupancyData['count_total']), + 'do_count_occupied' => sprintf('%02d', $occupancyData['count_occupied']), + 'do_count_available' => sprintf('%02d', $occupancyData['count_available']), + 'do_count_unavailable' => sprintf('%02d', $occupancyData['count_unavailable']), + ); + + $dataPieChartBig = array( array( 'label' => $this->l('Occupied'), 'value' => $occupancyData['count_total'] @@ -118,12 +114,14 @@ class DashOccupancy extends Module ), ); - $data['count_total'] = sprintf('%02d', $occupancyData['count_total']); - $data['count_occupied'] = sprintf('%02d', $occupancyData['count_occupied']); - $data['count_available'] = sprintf('%02d', $occupancyData['count_available']); - $data['count_unavailable'] = sprintf('%02d', $occupancyData['count_unavailable']); - $data['chart_data'] = $chartData; - - return array('data_avail_pie_chart' => $data); + return array( + 'data_value' => $dataValue, + 'data_chart' => array( + 'dash_occupancy_chart1' => array( + 'chart_type' => 'pie_chart_occupancy', + 'data' => $dataPieChartBig, + ), + ), + ); } } diff --git a/modules/dashoccupancy/views/js/dashoccupancy.js b/modules/dashoccupancy/views/js/dashoccupancy.js index 516502741..22f1d3919 100644 --- a/modules/dashoccupancy/views/js/dashoccupancy.js +++ b/modules/dashoccupancy/views/js/dashoccupancy.js @@ -17,8 +17,7 @@ * @license LICENSE.txt */ -// PIE CHART CODE -function generateAvailablityPieChart(chartData) { +function pie_chart_occupancy(widget_name, chart_details) { nv.addGraph(function() { var chart = nv.models.pieChart() .x(function(d) { return d.label }) @@ -26,26 +25,29 @@ function generateAvailablityPieChart(chartData) { .showLabels(true) .showLegend(false) .labelThreshold(.01) - .labelType("percent") + .labelType('percent') .donut(true) .donutRatio(0.35) - .color(["#A569DF", "#56CE56", "#FF655C"]); + .color(['#A569DF', '#56CE56', '#FF655C']); - d3.select("#availablePieChart svg") - .datum(chartData) + d3.select('#availablePieChart svg') + .datum(chart_details.data) .transition().duration(350) .call(chart); nv.utils.windowResize(chart.update); + return chart; }); } $(document).ready(function() { - if (typeof date_occupancy_range === "undefined") + if (typeof date_occupancy_range === 'undefined') { var date_occupancy_range = '(from %s to %s)'; + } - if (typeof date_occupancy_avail_format === "undefined") + if (typeof date_occupancy_avail_format === 'undefined') { var date_occupancy_avail_format = 'Y-mm-dd'; + } $('#date-start').change(function() { start = Date.parseDate($('#date-start').val(), 'Y-m-d'); @@ -59,4 +61,4 @@ $(document).ready(function() { $('#dashoccupancy_date_range').html(sprintf(date_occupancy_range, start.format(date_occupancy_avail_format), end.format(date_occupancy_avail_format))); }); -}); \ No newline at end of file +}); diff --git a/modules/dashoccupancy/views/templates/hook/dashboard_zone_one.tpl b/modules/dashoccupancy/views/templates/hook/dashboard_zone_one.tpl index 9d289a61f..480eba249 100644 --- a/modules/dashoccupancy/views/templates/hook/dashboard_zone_one.tpl +++ b/modules/dashoccupancy/views/templates/hook/dashboard_zone_one.tpl @@ -39,8 +39,8 @@ {l s='Occupied' mod='dashoccupancy'}

-

- {$count_occupied|escape:'htmlall':'UTF-8'}/{$count_total|escape:'htmlall':'UTF-8'} +

+ /

@@ -56,7 +56,7 @@

- {$count_available|escape:'htmlall':'UTF-8'} +

@@ -72,7 +72,7 @@

- {$count_unavailable|escape:'htmlall':'UTF-8'} +

diff --git a/modules/dashperformance/views/css/dashperformance.css b/modules/dashperformance/views/css/dashperformance.css index c52b803a6..5d8873915 100644 --- a/modules/dashperformance/views/css/dashperformance.css +++ b/modules/dashperformance/views/css/dashperformance.css @@ -24,6 +24,10 @@ font-weight: 500; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); margin-bottom: 25px; + transition: 0.25s; +} +.preformance-index-wrapper:hover { + transform: translate(0, -3px); } .preformance-index-wrapper .value-wrapper { font-size: 18px; diff --git a/modules/dashproducts/dashproducts.php b/modules/dashproducts/dashproducts.php index f40a124ef..a87379cae 100644 --- a/modules/dashproducts/dashproducts.php +++ b/modules/dashproducts/dashproducts.php @@ -398,7 +398,7 @@ class DashProducts extends Module } } else { $link = $this->context->link->getAdminLink('AdminModules').'&configure=statsdata'; - $body = '
'.$this->l('You must enable the "Save global page views" option from ').'Data mining for statistics'.$this->l(' module in order to display the most viewed room types, or use the Google Analytics module.').'
'; + $body = '
'.$this->l('You must enable the "Save global page views" option from ').'Data mining for statistics'.$this->l(' module in order to display the most viewed room types, or use the QloApps Google Analytics module.').'
'; } return array('header' => $header, 'body' => $body); } @@ -444,6 +444,7 @@ class DashProducts extends Module if (is_array($hotels) && count($hotels)) foreach ($hotels as $hotel) { $objHBI = new HotelBranchInformation($hotel['id_hotel'], $this->context->language->id); + $addressInfo = $objHBI->getAddress($hotel['id_hotel']); $tr = array(); $tr[] = array( 'id' => 'reference', @@ -459,7 +460,7 @@ class DashProducts extends Module ); $tr[] = array( 'id' => 'location', - 'value' => $objHBI->address, + 'value' => $addressInfo['address1'], 'class' => 'text-center', ); $tr[] = array( @@ -471,7 +472,7 @@ class DashProducts extends Module } } else { $link = $this->context->link->getAdminLink('AdminModules').'&configure=statsdata'; - $body = '
'.$this->l('You must enable the "Save global page views" option from ').'Data mining for statistics'.$this->l(' module in order to display the most viewed room types, or use the Google Analytics module.').'
'; + $body = '
'.$this->l('You must enable the "Save global page views" option from ').'Data mining for statistics'.$this->l(' module in order to display the most viewed room types, or use the QloApps Google Analytics module.').'
'; } return array('header' => $header, 'body' => $body); @@ -542,16 +543,17 @@ class DashProducts extends Module public function getTotalViewed($date_from, $date_to, $limit = 10) { - $gapi = Module::isInstalled('gapi') ? Module::getInstanceByName('gapi') : false; - if (Validate::isLoadedObject($gapi) && $gapi->isConfigured()) { + $objQGA = Module::isEnabled('qlogoogleanalytics') ? Module::getInstanceByName('qlogoogleanalytics') : false; + if (Validate::isLoadedObject($objQGA) && $objQGA->isConfigured()) { $products = array(); // Only works with the default product URL pattern at this time - if ($result = $gapi->requestReportData('ga:pagePath', 'ga:visits', $date_from, $date_to, '-ga:visits', 'ga:pagePath=~/([a-z]{2}/)?([a-z]+/)?[0-9][0-9]*\-.*\.html$', 1, 10)) - foreach ($result as $row) - { - if (preg_match('@/([a-z]{2}/)?([a-z]+/)?([0-9]+)\-.*\.html$@', $row['dimensions']['pagePath'], $matches)) + if ($result = $objQGA->requestReportData('ga:pagePath', 'ga:visits', $date_from, $date_to, '-ga:visits', 'ga:pagePath=~/([a-z]{2}/)?([a-z]+/)?[0-9][0-9]*\-.*\.html$', 1, $limit)) { + foreach ($result as $row) { + if (preg_match('@/([a-z]{2}/)?([a-z]+/)?([0-9]+)\-.*\.html@', $row['dimensions']['pagePath'], $matches)) { $products[] = array('id_object' => (int)$matches[3], 'counter' => $row['metrics']['visits']); + } } + } return $products; } else { @@ -579,14 +581,13 @@ class DashProducts extends Module return array(); } - $pageType = Page::getPageTypeByName('category'); return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS( 'SELECT hbi.`id` AS `id_hotel`, cl.`name` AS `hotel_name`, pv.`counter` AS `views` FROM `'._DB_PREFIX_.'page_viewed` pv LEFT JOIN `'._DB_PREFIX_.'page` p ON (p.`id_page` = pv.`id_page`) LEFT JOIN `'._DB_PREFIX_.'page_type` pt ON (pt.`id_page_type` = p.`id_page_type`) LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (cl.`id_category` = p.`id_object`) - LEFT JOIN `'._DB_PREFIX_.'htl_branch_info` hbi ON (hbi.`id_category` = hbi.`id_category`) + LEFT JOIN `'._DB_PREFIX_.'htl_branch_info` hbi ON (hbi.`id_category` = cl.`id_category`) LEFT JOIN `'._DB_PREFIX_.'date_range` dr ON (pv.`id_date_range` = dr.`id_date_range`) WHERE pt.`name` = "'.pSQL('category').'" AND dr.`time_start` BETWEEN "'.pSQL($date_from).' 00:00:00" AND "'.pSQL($date_to).' 23:59:59" diff --git a/modules/dashtrends/dashtrends.php b/modules/dashtrends/dashtrends.php index c529b6058..9c512c3aa 100644 --- a/modules/dashtrends/dashtrends.php +++ b/modules/dashtrends/dashtrends.php @@ -79,6 +79,7 @@ class Dashtrends extends Module return $this->display(__FILE__, 'dashboard_zone_two.tpl'); } + // get available data from database for each day within date range protected function getData($date_from, $date_to, $id_hotel) { // We need the following figures to calculate our stats @@ -113,6 +114,7 @@ class Dashtrends extends Module return $tmp_data; } + // interpolate data for missing days within date range protected function refineData($date_from, $date_to, $gross_data) { $refined_data = array( @@ -127,31 +129,30 @@ class Dashtrends extends Module $from = strtotime($date_from.' 00:00:00'); $to = min(time(), strtotime($date_to.' 23:59:59')); for ($date = $from; $date <= $to; $date = strtotime('+1 day', $date)) { + // initialize values for current date first $refined_data['sales'][$date] = 0; - if (isset($gross_data['total_paid_tax_excl'][$date])) { - $refined_data['sales'][$date] += $gross_data['total_paid_tax_excl'][$date]; - } + $refined_data['orders'][$date] = 0; + $refined_data['average_cart_value'][$date] = 0; + $refined_data['visits'][$date] = 0; + $refined_data['conversion_rate'][$date] = 0; + $refined_data['net_profits'][$date] = 0; + // calculate actual values now for current date from available $gross_data to be used to display in line chart + $refined_data['sales'][$date] = isset($gross_data['total_paid_tax_excl'][$date]) ? $gross_data['total_paid_tax_excl'][$date] : 0; $refined_data['orders'][$date] = isset($gross_data['orders'][$date]) ? $gross_data['orders'][$date] : 0; $refined_data['average_cart_value'][$date] = $refined_data['orders'][$date] ? $refined_data['sales'][$date] / $refined_data['orders'][$date] : 0; $refined_data['visits'][$date] = isset($gross_data['visits'][$date]) ? $gross_data['visits'][$date] : 0; $refined_data['conversion_rate'][$date] = $refined_data['visits'][$date] ? $refined_data['orders'][$date] / $refined_data['visits'][$date] : 0; - $refined_data['net_profits'][$date] = 0; - if (isset($gross_data['total_paid_tax_excl'][$date])) { - $refined_data['net_profits'][$date] += $gross_data['total_paid_tax_excl'][$date]; - } - if (isset($gross_data['total_purchases'][$date])) { - $refined_data['net_profits'][$date] -= $gross_data['total_purchases'][$date]; - } - if (isset($gross_data['total_expenses'][$date])) { - $refined_data['net_profits'][$date] -= $gross_data['total_expenses'][$date]; - } + $refined_data['net_profits'][$date] += (isset($gross_data['total_paid_tax_excl'][$date]) ? $gross_data['total_paid_tax_excl'][$date] : 0); + $refined_data['net_profits'][$date] -= (isset($gross_data['total_purchases'][$date]) ? $gross_data['total_purchases'][$date] : 0); + $refined_data['net_profits'][$date] -= (isset($gross_data['total_expenses'][$date]) ? $gross_data['total_expenses'][$date] : 0); } return $refined_data; } + // calculate sum of individual values protected function addupData($data) { $summing = array( @@ -232,7 +233,7 @@ class Dashtrends extends Module 'orders_score' => Tools::displayNumber($this->dashboard_data_sum['orders'], $this->currency), 'cart_value_score' => $cart_value_score, 'visits_score' => Tools::displayNumber($this->dashboard_data_sum['visits'], $this->currency), - 'conversion_rate_score' => round(100 * $this->dashboard_data_sum['conversion_rate'], 2).'%', + 'conversion_rate_score' => sprintf('%0.2f', 100 * $this->dashboard_data_sum['conversion_rate']).'%', 'net_profits_score' => $net_profit_score, ), 'data_trends' => $this->data_trends, @@ -309,7 +310,7 @@ class Dashtrends extends Module $charts = array( 'sales' => $this->l('Sales'), - 'orders' => $this->l('Orders'), + 'orders' => $this->l('Bookings'), 'average_cart_value' => $this->l('Average Cart Value'), 'visits' => $this->l('Visits'), 'conversion_rate' => $this->l('Conversion Rate'), @@ -317,7 +318,7 @@ class Dashtrends extends Module ); $gfx_color = array('#72C3F0','#56CE56','#FF4036','#FF7F0E','#A569DF','#AF8A42'); - $gfx_color_border = array('#11f0fc','#118c11','#9e1010','#af5c13','#681daf','#845c0d'); + $gfx_color_border = $gfx_color; $gfx_color_compare = array('#1777B6','#19900d','#b9140c','#bf6307','#6B399C','#B3591F'); $i = 0; diff --git a/modules/dashtrends/views/templates/hook/dashboard_zone_two.tpl b/modules/dashtrends/views/templates/hook/dashboard_zone_two.tpl index aad61f1db..3eff771d5 100644 --- a/modules/dashtrends/views/templates/hook/dashboard_zone_two.tpl +++ b/modules/dashtrends/views/templates/hook/dashboard_zone_two.tpl @@ -64,7 +64,7 @@
-
{l s='Cart Value' mod='dashtrends'}
+
{l s='Average Cart Value' mod='dashtrends'}
@@ -77,14 +77,14 @@
+ data-toggle="tooltip" data-placement="top" data-original-title="{l s='Conversion Rate is the percentage of visits that resulted in a validated booking.' mod='dashtrends'}" data-placement="bottom" style="background-color: #A569DF;">
{l s='Conversion Rate' mod='dashtrends'}
{l s='Net Profit' mod='dashtrends'}
diff --git a/modules/hotelreservationsystem/classes/HotelBookingDetail.php b/modules/hotelreservationsystem/classes/HotelBookingDetail.php index 0eb8610cd..f8da3c535 100644 --- a/modules/hotelreservationsystem/classes/HotelBookingDetail.php +++ b/modules/hotelreservationsystem/classes/HotelBookingDetail.php @@ -1124,10 +1124,10 @@ class HotelBookingDetail extends ObjectModel * * @return [boolean] [true if updated otherwise false] */ - public function updateOrderRefundStatus($id_order, $date_from = false, $date_to = false, $id_rooms = array()) + public function updateOrderRefundStatus($id_order, $date_from = false, $date_to = false, $id_rooms = array(), $is_refunded = 1) { $table = 'htl_booking_detail'; - $data = array('is_refunded' => 1); + $data = array('is_refunded' => (int) $is_refunded); if ($id_rooms) { foreach ($id_rooms as $key_rm => $val_rm) { $where = 'id_order='.(int)$id_order.' AND id_room = '.(int)$val_rm['id_room'].' AND `date_from`= \''. diff --git a/modules/hotelreservationsystem/hotelreservationsystem.php b/modules/hotelreservationsystem/hotelreservationsystem.php index 0d18ff40f..e686d2804 100644 --- a/modules/hotelreservationsystem/hotelreservationsystem.php +++ b/modules/hotelreservationsystem/hotelreservationsystem.php @@ -346,14 +346,40 @@ class hotelreservationsystem extends Module } } - public function hookActionOrderStatusPostUpdate($params) + public function hookActionOrderStatusUpdate($params) { - $objHtlBkDtl = new HotelBookingDetail(); + $objHotelBookingDetail = new HotelBookingDetail(); + $statusesAvailable = $objHotelBookingDetail->getOrderStatusToFreeBookedRoom(); - // Make rooms available for booking if order status is cancelled, refunded or error - if (in_array($params['newOrderStatus']->id, $objHtlBkDtl->getOrderStatusToFreeBookedRoom())) { - if (!$objHtlBkDtl->updateOrderRefundStatus($params['id_order'])) { - $this->context->controller->errors[] = $this->l('Error while making booked rooms available, attached with this order. Please try again !!'); + if (in_array($params['newOrderStatus']->id, $statusesAvailable)) { + // make rooms available for booking if order status is changing to cancelled, refunded or error + if (!$objHotelBookingDetail->updateOrderRefundStatus( + $params['id_order'], + false, + false, + array(), + 1 + )) { + $this->context->controller->errors[] = $this->l('Error while making rooms available attached with this order. Please try again.'); + } + } else { + $objOrder = new Order($params['id_order']); + if (!Validate::isLoadedObject($objOrder)) { + return; + } + + $objOrderStatusCurrent = $objOrder->getCurrentOrderState(); + if (in_array($objOrderStatusCurrent->id, $statusesAvailable)) { + // make rooms unavailable for booking if previous order status was any of cancelled, refunded or error + if (!$objHotelBookingDetail->updateOrderRefundStatus( + $params['id_order'], + false, + false, + array(), + 0 + )) { + $this->context->controller->errors[] = $this->l('Error while making rooms unavailable attached with this order. Please try again.'); + } } } } @@ -514,7 +540,7 @@ class hotelreservationsystem extends Module 'actionObjectProfileAddAfter', 'actionObjectProfileDeleteBefore', 'actionObjectGroupDeleteBefore', - 'actionOrderStatusPostUpdate' + 'actionOrderStatusUpdate', ) ); } diff --git a/modules/pagesnotfound/pagesnotfound.php b/modules/pagesnotfound/pagesnotfound.php index 2c40e5be4..187e07198 100644 --- a/modules/pagesnotfound/pagesnotfound.php +++ b/modules/pagesnotfound/pagesnotfound.php @@ -164,7 +164,7 @@ class PagesNotFound extends Module '; } else { - $this->html .= '
'.$this->l('No "page not found" issue registered for now.').'
'; + $this->html .= '
'.$this->l('No "Page not found" issue registered or database has been cleared for this time period.').'
'; } if (count($pages)) { diff --git a/modules/sekeywords/sekeywords.php b/modules/sekeywords/sekeywords.php index 8843ff70f..8f57b1398 100644 --- a/modules/sekeywords/sekeywords.php +++ b/modules/sekeywords/sekeywords.php @@ -126,9 +126,9 @@ class SEKeywords extends ModuleGraph

 

'.$this->l('How does it work?').'

' - .$this->l('When a visitor comes to your website, the web server notes the URL of the site he/she comes from. This module then parses the URL, and if it finds a reference to a known search engine, it finds the keywords in it.').'
'. - $this->l('This module can recognize all the search engines listed in QloApps\'s Stats/Search Engine page -- and you can add more!').'
'. - $this->l('IMPORTANT NOTE: in September 2013, Google chose to encrypt its searches queries using SSL. This means all the referer-based tools in the World (including this one) cannot identify Google keywords anymore.').' + .$this->l('When a visitor comes to your website, the web server notes the URL of the site he/she came from. This module then parses the URL, and if it finds a reference to a known search engine, it finds the keywords in it.').'
'. + $this->l('This module can recognize all the search engines listed on Stats > Search Engines page -- and you can add more!').'
'. + $this->l('IMPORTANT: In September 2013, Google chose to encrypt its searche queries using SSL. This means all HTTP referer-based tools in the world (including this one) cannot identify Google keywords anymore.').'

'.($total == 1 ? sprintf($this->l('%d keyword matches your query.'), $total) : sprintf($this->l('%d keywords match your query.'), $total)).'

'; @@ -173,7 +173,7 @@ class SEKeywords extends ModuleGraph } $table .= ''; $this->html .= '
'.$this->engine(array('type' => 'pie')).'
- < '.$this->l('CSV Export').' + < '.$this->l('CSV Export').' '.$form.'
'.$table; } else { $this->html .= $form.'

'.$this->l('No keywords').'

'; diff --git a/modules/statsbestcategories/statsbestcategories.php b/modules/statsbestcategories/statsbestcategories.php index fef2b8079..6c2cd75cf 100644 --- a/modules/statsbestcategories/statsbestcategories.php +++ b/modules/statsbestcategories/statsbestcategories.php @@ -56,34 +56,46 @@ class StatsBestCategories extends ModuleGrid $this->columns = array( array( 'id' => 'name', - 'header' => $this->l('Name'), - 'dataIndex' => 'name', + 'header' => $this->l('Hotel name'), + 'dataIndex' => 'hotel_name', 'align' => 'left' ), array( 'id' => 'totalRoomsBooked', - 'header' => $this->l('Total Rooms Booked'), + 'header' => $this->l('Rooms booked'), 'dataIndex' => 'totalRoomsBooked', 'align' => 'center' ), array( 'id' => 'totalPriceSold', - 'header' => $this->l('Total Price'), + 'header' => $this->l('Sales'), 'dataIndex' => 'totalPriceSold', 'align' => 'center' ), array( 'id' => 'totalWholeSalePriceSold', - 'header' => $this->l('Total Margin'), + 'header' => $this->l('Margin'), 'dataIndex' => 'totalWholeSalePriceSold', 'align' => 'center' ), array( 'id' => 'totalPageViewed', - 'header' => $this->l('Total Viewed'), + 'header' => $this->l('Views'), 'dataIndex' => 'totalPageViewed', 'align' => 'center' - ) + ), + array( + 'id' => 'percentageViews', + 'header' => $this->l('Precentage of views'), + 'dataIndex' => 'percentageViews', + 'align' => 'center' + ), + array( + 'id' => 'percentageRoomsBooked', + 'header' => $this->l('Precentage of rooms booked'), + 'dataIndex' => 'percentageRoomsBooked', + 'align' => 'center' + ), ); $this->displayName = $this->l('Best hotels'); @@ -120,16 +132,20 @@ class StatsBestCategories extends ModuleGrid $this->html = '
'.$this->displayName.' -
- '.$this->engine($engine_params).' + '; + if (!(Module::isEnabled('statsdata') && Configuration::get('PS_STATSDATA_PAGESVIEWS'))) { + $link = $this->context->link->getAdminLink('AdminModules').'&configure=statsdata'; + $this->html .= '
'.$this->l('You must enable the "Save global page views" option from ').'Data mining for statistics'.$this->l(' module in order to display the most viewed hotels, or use the QloApps Google Analytics module.').'
'; + } + + $this->html .= $this->engine($engine_params).' '; - return $this->html; } @@ -177,113 +193,54 @@ class StatsBestCategories extends ModuleGrid $onlyChildren = 'AND NOT EXISTS (SELECT NULL FROM '._DB_PREFIX_.'category WHERE id_parent = ca.id_category)'; } - // Get best categories - if (version_compare(_PS_VERSION_, '1.6.1.1', '>=')) { - $this->query = ' - SELECT SQL_CALC_FOUND_ROWS ca.`id_category`, CONCAT(parent.name, \' > \', calang.`name`) as name, - IFNULL(SUM(t.`totalQuantitySold`), 0) AS totalQuantitySold, - ROUND(IFNULL(SUM(t.`totalPriceSold`), 0), 2) AS totalPriceSold, - ROUND(IFNULL(SUM(t.`totalWholeSalePriceSold`), 0), 2) AS totalWholeSalePriceSold, - ( - SELECT IFNULL(SUM(pv.`counter`), 0) - FROM `'._DB_PREFIX_.'page` p - LEFT JOIN `'._DB_PREFIX_.'page_viewed` pv ON p.`id_page` = pv.`id_page` - LEFT JOIN `'._DB_PREFIX_.'date_range` dr ON pv.`id_date_range` = dr.`id_date_range` - LEFT JOIN `'._DB_PREFIX_.'product` pr ON CAST(p.`id_object` AS UNSIGNED INTEGER) = pr.`id_product` - LEFT JOIN `'._DB_PREFIX_.'category_product` capr2 ON capr2.`id_product` = pr.`id_product` - WHERE capr.`id_category` = capr2.`id_category` - AND p.`id_page_type` = 1 - AND dr.`time_start` BETWEEN '.$date_between.' - AND dr.`time_end` BETWEEN '.$date_between.' - ) AS totalPageViewed, - ( - SELECT COUNT(id_category) FROM '._DB_PREFIX_.'category WHERE `id_parent` = ca.`id_category` - ) AS hasChildren, + // Get best hotels + $this->query = ' + SELECT hbi.`id`, hbil.`hotel_name` AS hotel_name, ( - SELECT COUNT(`id_room`) FROM `'._DB_PREFIX_.'htl_booking_detail` hbd - LEFT JOIN `'._DB_PREFIX_.'orders` o ON (o.`id_order` = hbd.`id_order`) - WHERE `id_hotel` IN (SELECT `id` FROM `'._DB_PREFIX_.'htl_branch_info` hbi WHERE hbi.`id_category` = ca.`id_category`) AND o.`valid` = 1 AND o.`invoice_date` BETWEEN '.$date_between.' - ) AS totalRoomsBooked - FROM `'._DB_PREFIX_.'category` ca - LEFT JOIN `'._DB_PREFIX_.'category_lang` calang ON (ca.`id_category` = calang.`id_category` AND calang.`id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('calang').') - LEFT JOIN `'._DB_PREFIX_.'category_lang` parent ON (ca.`id_parent` = parent.`id_category` AND parent.`id_lang` = '.(int)$id_lang.Shop::addSqlRestrictionOnLang('parent').') - LEFT JOIN `'._DB_PREFIX_.'category_product` capr ON ca.`id_category` = capr.`id_category` - LEFT JOIN ( - SELECT pr.`id_product`, t.`totalQuantitySold`, t.`totalPriceSold`, t.`totalWholeSalePriceSold` - FROM `'._DB_PREFIX_.'product` pr + SELECT IFNULL(SUM(pv.`counter`), 0) + FROM `' . _DB_PREFIX_ . 'page_viewed` pv + 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` + LEFT JOIN `' . _DB_PREFIX_ . 'date_range` dr ON pv.`id_date_range` = dr.`id_date_range` + WHERE pt.`name` = "category" + AND p.`id_object` = hbi.`id_category` + AND dr.`time_start` BETWEEN '.$date_between.' + AND dr.`time_end` BETWEEN '.$date_between.' + ) AS totalPageViewed, + ( + SELECT COUNT(`id_room`) FROM `' . _DB_PREFIX_ . 'htl_booking_detail` hbd + LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON (o.`id_order` = hbd.`id_order`) + WHERE hbd.`id_hotel` = hbi.`id` AND o.`valid` = 1 AND o.`invoice_date` BETWEEN '.$date_between.' + ) AS totalRoomsBooked, + IFNULL(SUM(t.`totalQuantitySold`), 0) AS totalQuantitySold, + IFNULL(SUM(t.`totalPriceSold`), 0) AS totalPriceSold, + IFNULL(SUM(t.`totalWholeSalePriceSold`), 0) AS totalWholeSalePriceSold + FROM `' . _DB_PREFIX_ . 'htl_branch_info` hbi + LEFT JOIN `' . _DB_PREFIX_ . 'htl_room_type` hrt ON hrt.`id_hotel` = hbi.`id` + LEFT JOIN `' . _DB_PREFIX_ . 'product` pr ON pr.`id_product` = hrt.`id_product` + LEFT JOIN `' . _DB_PREFIX_ . 'htl_branch_info_lang` hbil ON hbil.`id` = hbi.`id` AND hbil.`id_lang` = '.(int)$id_lang .' LEFT JOIN ( SELECT pr.`id_product`, pa.`wholesale_price`, IFNULL(SUM(cp.`product_quantity`), 0) AS totalQuantitySold, IFNULL(SUM(cp.`product_price` * cp.`product_quantity`), 0) / o.conversion_rate AS totalPriceSold, IFNULL(SUM( - CASE + CASE WHEN cp.`original_wholesale_price` <> "0.000000" THEN cp.`original_wholesale_price` * cp.`product_quantity` - WHEN pa.`wholesale_price` <> "0.000000" - THEN pa.`wholesale_price` * cp.`product_quantity` WHEN pr.`wholesale_price` <> "0.000000" THEN pr.`wholesale_price` * cp.`product_quantity` END - ), 0) / o.conversion_rate AS totalWholeSalePriceSold - FROM `'._DB_PREFIX_.'product` pr - LEFT OUTER JOIN `'._DB_PREFIX_.'order_detail` cp ON pr.`id_product` = cp.`product_id` - LEFT JOIN `'._DB_PREFIX_.'orders` o ON o.`id_order` = cp.`id_order` - LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON pa.`id_product_attribute` = cp.`product_attribute_id` - '.Shop::addSqlRestriction(Shop::SHARE_ORDER, 'o').' - WHERE o.valid = 1 - AND o.invoice_date BETWEEN '.$date_between.' - GROUP BY pr.`id_product` - ) t ON t.`id_product` = pr.`id_product` - ) t ON t.`id_product` = capr.`id_product` - '.(($categories) ? 'WHERE ca.id_category IN ('.implode(', ', $categories).')' : '').' - '.$onlyChildren.' - GROUP BY ca.`id_category` - HAVING ca.`id_category` != 1'; - } else { - $this->query = ' - SELECT SQL_CALC_FOUND_ROWS ca.`id_category`, CONCAT(parent.name, \' > \', calang.`name`) as name, - IFNULL(SUM(t.`totalQuantitySold`), 0) AS totalQuantitySold, - ROUND(IFNULL(SUM(t.`totalPriceSold`), 0), 2) AS totalPriceSold, - ( - SELECT IFNULL(SUM(pv.`counter`), 0) - FROM `' . _DB_PREFIX_ . 'page` p - LEFT JOIN `' . _DB_PREFIX_ . 'page_viewed` pv ON p.`id_page` = pv.`id_page` - LEFT JOIN `' . _DB_PREFIX_ . 'date_range` dr ON pv.`id_date_range` = dr.`id_date_range` - LEFT JOIN `' . _DB_PREFIX_ . 'product` pr ON CAST(p.`id_object` AS UNSIGNED INTEGER) = pr.`id_product` - LEFT JOIN `' . _DB_PREFIX_ . 'category_product` capr2 ON capr2.`id_product` = pr.`id_product` - WHERE capr.`id_category` = capr2.`id_category` - AND p.`id_page_type` = 1 - AND dr.`time_start` BETWEEN ' . $date_between . ' - AND dr.`time_end` BETWEEN ' . $date_between . ' - ) AS totalPageViewed, - ( - SELECT COUNT(id_category) FROM '._DB_PREFIX_.'category WHERE `id_parent` = ca.`id_category` - ) AS hasChildren - FROM `' . _DB_PREFIX_ . 'category` ca - LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` calang ON (ca.`id_category` = calang.`id_category` AND calang.`id_lang` = ' . (int)$id_lang . Shop::addSqlRestrictionOnLang('calang') . ') - LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` parent ON (ca.`id_parent` = parent.`id_category` AND parent.`id_lang` = ' . (int)$id_lang . Shop::addSqlRestrictionOnLang('parent') . ') - LEFT JOIN `' . _DB_PREFIX_ . 'category_product` capr ON ca.`id_category` = capr.`id_category` - LEFT JOIN ( - SELECT pr.`id_product`, t.`totalQuantitySold`, t.`totalPriceSold` - FROM `' . _DB_PREFIX_ . 'product` pr - LEFT JOIN ( - SELECT pr.`id_product`, - IFNULL(SUM(cp.`product_quantity`), 0) AS totalQuantitySold, - IFNULL(SUM(cp.`product_price` * cp.`product_quantity`), 0) / o.conversion_rate AS totalPriceSold + ), 0) / o.conversion_rate AS totalWholeSalePriceSold FROM `' . _DB_PREFIX_ . 'product` pr LEFT OUTER JOIN `' . _DB_PREFIX_ . 'order_detail` cp ON pr.`id_product` = cp.`product_id` LEFT JOIN `' . _DB_PREFIX_ . 'orders` o ON o.`id_order` = cp.`id_order` - ' . Shop::addSqlRestriction(Shop::SHARE_ORDER, 'o') . ' + LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON pa.`id_product_attribute` = cp.`product_attribute_id` + AND o.id_shop IN (1) WHERE o.valid = 1 - AND o.invoice_date BETWEEN ' . $date_between . ' + AND o.invoice_date BETWEEN '.$date_between.' GROUP BY pr.`id_product` - ) t ON t.`id_product` = pr.`id_product` - ) t ON t.`id_product` = capr.`id_product` - ' . (($categories) ? 'WHERE ca.id_category IN (' . implode(', ', $categories) . ')' : '') . ' - '.$onlyChildren.' - GROUP BY ca.`id_category` - HAVING ca.`id_category` != 1'; - } + ) t ON t.`id_product` = hrt.`id_product` + GROUP BY (hbi.`id`)'; if (Validate::IsName($this->_sort)) { $this->query .= ' ORDER BY `'.bqSQL($this->_sort).'`'; @@ -297,19 +254,40 @@ class StatsBestCategories extends ModuleGrid } $values = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($this->query); - foreach ($values as &$value) { - if ((int)Tools::getIsset('export') == false) { - $parts = explode('>', $value['name']); - $value['name'] = trim($parts[1]); - } + $this->_totalCount = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT FOUND_ROWS()'); + // get stats total + $sql = 'SELECT IFNULL(SUM(pv.`counter`), 0) + FROM `'._DB_PREFIX_.'page_viewed` pv + 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` + LEFT JOIN `'._DB_PREFIX_.'date_range` dr ON pv.`id_date_range` = dr.`id_date_range` + WHERE pt.`name` = "category" + AND dr.`time_start` BETWEEN '.$date_between.' + AND dr.`time_end` BETWEEN '.$date_between; + $total_views = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); + + $sql = 'SELECT COUNT(hbd.`id_room`) + FROM `'._DB_PREFIX_.'htl_booking_detail` hbd + LEFT JOIN `'._DB_PREFIX_.'orders` o ON (o.`id_order` = hbd.`id_order`) + WHERE o.`valid` = 1 AND o.`invoice_date` BETWEEN '.$date_between; + $total_rooms_booked = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql); + + $stats_total = array( + 'views' => $total_views, + 'rooms_booked' => $total_rooms_booked, + ); + + foreach ($values as &$value) { if (isset($value['totalWholeSalePriceSold'])) { $value['totalWholeSalePriceSold'] = Tools::displayPrice($value['totalPriceSold'] - $value['totalWholeSalePriceSold'], $currency); } $value['totalPriceSold'] = Tools::displayPrice($value['totalPriceSold'], $currency); + + $value['percentageViews'] = sprintf('%0.2f', $stats_total['views'] ? ($value['totalPageViewed'] / $stats_total['views']) * 100 : 0).'%'; + $value['percentageRoomsBooked'] = sprintf('%0.2f', $stats_total['rooms_booked'] ? ($value['totalRoomsBooked'] / $stats_total['rooms_booked']) * 100 : 0).'%'; } $this->_values = $values; - $this->_totalCount = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT FOUND_ROWS()'); } } diff --git a/modules/statsbestcustomers/statsbestcustomers.php b/modules/statsbestcustomers/statsbestcustomers.php index 97217a806..34a161599 100644 --- a/modules/statsbestcustomers/statsbestcustomers.php +++ b/modules/statsbestcustomers/statsbestcustomers.php @@ -57,15 +57,15 @@ class StatsBestCustomers extends ModuleGrid $this->columns = array( array( - 'id' => 'lastname', - 'header' => $this->l('Last Name'), - 'dataIndex' => 'lastname', + 'id' => 'firstname', + 'header' => $this->l('First name'), + 'dataIndex' => 'firstname', 'align' => 'center' ), array( - 'id' => 'firstname', - 'header' => $this->l('First Name'), - 'dataIndex' => 'firstname', + 'id' => 'lastname', + 'header' => $this->l('Last name'), + 'dataIndex' => 'lastname', 'align' => 'center' ), array( @@ -140,7 +140,7 @@ class StatsBestCustomers extends ModuleGrid '.$this->engine($engine_params).' - '.$this->l('CSV Export').' + '.$this->l('CSV Export').' '; return $this->html; @@ -148,8 +148,9 @@ class StatsBestCustomers extends ModuleGrid public function getData() { - $this->query = ' - SELECT SQL_CALC_FOUND_ROWS c.`id_customer`, c.`lastname`, c.`firstname`, c.`email`, + $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT')); + + $this->query = 'SELECT SQL_CALC_FOUND_ROWS c.`id_customer`, c.`lastname`, c.`firstname`, c.`email`, COUNT(co.`id_connections`) as totalVisits, IFNULL(( SELECT ROUND(SUM(IFNULL(op.`amount`, 0) / cu.conversion_rate), 2) @@ -185,7 +186,12 @@ class StatsBestCustomers extends ModuleGrid $this->query .= ' LIMIT '.(int)$this->_start.', '.(int)$this->_limit; } - $this->_values = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($this->query); + $values = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($this->query); + foreach ($values as &$value) { + $value['totalMoneySpent'] = Tools::displayPrice($value['totalMoneySpent'], $currency); + } + + $this->_values = $values; $this->_totalCount = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT FOUND_ROWS()'); } } diff --git a/modules/statsbestproducts/statsbestproducts.php b/modules/statsbestproducts/statsbestproducts.php index e2e6d1179..39d8c4e35 100644 --- a/modules/statsbestproducts/statsbestproducts.php +++ b/modules/statsbestproducts/statsbestproducts.php @@ -58,19 +58,19 @@ class StatsBestProducts extends ModuleGrid $this->columns = array( array( 'id' => 'name', - 'header' => $this->l('Room Type Name'), + 'header' => $this->l('Room type name'), 'dataIndex' => 'name', - 'align' => 'left' + 'align' => 'center' ), array( 'id' => 'hotel_name', - 'header' => $this->l('Hotel Name'), + 'header' => $this->l('Hotel name'), 'dataIndex' => 'hotel_name', - 'align' => 'left' + 'align' => 'center' ), array( 'id' => 'totalRoomsSold', - 'header' => $this->l('Rooms sold'), + 'header' => $this->l('Rooms booked'), 'dataIndex' => 'totalRoomsSold', 'align' => 'center' ), @@ -138,11 +138,17 @@ class StatsBestProducts extends ModuleGrid $this->csvExport($engine_params); } - return '
'.$this->displayName.'
- '.$this->engine($engine_params).' + $html = '
'.$this->displayName.'
'; + if (!(Module::isEnabled('statsdata') && Configuration::get('PS_STATSDATA_PAGESVIEWS'))) { + $link = $this->context->link->getAdminLink('AdminModules').'&configure=statsdata'; + $html .= '
'.$this->l('You must enable the "Save global page views" option from ').'Data mining for statistics'.$this->l(' module in order to display the most viewed room types, or use the QloApps Google Analytics module.').'
'; + } + $html .= $this->engine($engine_params).' - '.$this->l('CSV Export').' + '.$this->l('CSV Export').' '; + + return $html; } public function getData() @@ -161,24 +167,43 @@ class StatsBestProducts extends ModuleGrid WHERE pa.id_object = p.id_product AND pa.id_page_type = '.(int)Page::getPageTypeByName('product').' AND dr.time_start BETWEEN '.$date_between.' AND dr.time_end BETWEEN '.$date_between.' - ) AS totalPageViewed, - (SELECT COUNT(hbd.`id_room`) FROM '._DB_PREFIX_.'htl_booking_detail hbd WHERE hbd.`id_product` = p.id_product) AS totalRoomsSold, - ROUND(IFNULL(IFNULL((SELECT COUNT(hbd.`id_room`) FROM '._DB_PREFIX_.'htl_booking_detail hbd WHERE hbd.`id_product` = p.id_product), 0) / (1 + LEAST(TO_DAYS('.$array_date_between[1].'), TO_DAYS(NOW())) - GREATEST(TO_DAYS('.$array_date_between[0].'), TO_DAYS(product_shop.date_add))), 0), 2) as averageQuantitySold, - product_shop.active - FROM '._DB_PREFIX_.'product p - '.Shop::addSqlAssociation('product', 'p').' - LEFT JOIN '._DB_PREFIX_.'product_lang pl ON (p.id_product = pl.id_product AND pl.id_lang = '.(int)$this->getLang().' '.Shop::addSqlRestrictionOnLang('pl').') - LEFT JOIN '._DB_PREFIX_.'htl_room_type hrt ON hrt.id_product = p.id_product - LEFT JOIN '._DB_PREFIX_.'htl_branch_info_lang hbil ON (hbil.id = hrt.id_hotel AND hbil.id_lang = '.(int)$this->getLang().') - LEFT JOIN '._DB_PREFIX_.'order_detail od ON od.product_id = p.id_product - LEFT JOIN '._DB_PREFIX_.'orders o ON od.id_order = o.id_order - '.Shop::addSqlRestriction(Shop::SHARE_ORDER, 'o').' - '.Product::sqlStock('p', 0).' - WHERE o.valid = 1 - AND o.invoice_date BETWEEN '.$date_between.' - GROUP BY od.product_id'; + ) AS totalPageViewed,'; + if (explode(' ',trim($array_date_between[0]))[0] == explode(' ',trim($array_date_between[1]))[0]) { + $this->query .=' (SELECT + SUM(IFNULL(DATEDIFF( + IF ('.$array_date_between[1].' > hbd.`date_to`, hbd.`date_to`, '.$array_date_between[1].'), + IF ('.$array_date_between[0].' < hbd.`date_from`, hbd.`date_from`, '.$array_date_between[0].') + ), 0)) + FROM '._DB_PREFIX_.'htl_booking_detail hbd WHERE hbd.`id_product` = p.id_product AND hbd.date_from <= '.$array_date_between[0].' + AND hbd.date_to > '.$array_date_between[0].') AS totalRoomsSold, + ROUND(IFNULL(IFNULL((SELECT COUNT(hbd.`id_room`) FROM '._DB_PREFIX_.'htl_booking_detail hbd WHERE hbd.`id_product` = p.id_product AND hbd.date_from <= '.$array_date_between[0]. + ' AND hbd.date_to > '.$array_date_between[0].'), 0) / (1 + LEAST(TO_DAYS('.$array_date_between[1].'), TO_DAYS(NOW())) - GREATEST(TO_DAYS('.$array_date_between[0].'), TO_DAYS(product_shop.date_add))), 0), 2) as averageQuantitySold,'; + } else { + $this->query .= '(SELECT + SUM(IFNULL(DATEDIFF( + IF ('.$array_date_between[1].' > hbd.`date_to`, hbd.`date_to`, '.$array_date_between[1].'), + IF ('.$array_date_between[0].' < hbd.`date_from`, hbd.`date_from`, '.$array_date_between[0].') + ), 0)) + FROM '._DB_PREFIX_.'htl_booking_detail hbd WHERE hbd.`id_product` = p.id_product AND hbd.date_from BETWEEN '.$date_between.' + AND hbd.date_to BETWEEN '.$date_between.') AS totalRoomsSold, + ROUND(IFNULL(IFNULL((SELECT COUNT(hbd.`id_room`) FROM '._DB_PREFIX_.'htl_booking_detail hbd WHERE hbd.`id_product` = p.id_product AND hbd.date_from BETWEEN '.$date_between. + ' AND hbd.date_to BETWEEN '.$date_between.'), 0) / (1 + LEAST(TO_DAYS('.$array_date_between[1].'), TO_DAYS(NOW())) - GREATEST(TO_DAYS('.$array_date_between[0].'), TO_DAYS(product_shop.date_add))), 0), 2) as averageQuantitySold,'; + } + $this->query .= 'product_shop.active + FROM '._DB_PREFIX_.'product p + '.Shop::addSqlAssociation('product', 'p').' + LEFT JOIN '._DB_PREFIX_.'product_lang pl ON (p.id_product = pl.id_product AND pl.id_lang = '.(int)$this->getLang().' '.Shop::addSqlRestrictionOnLang('pl').') + LEFT JOIN '._DB_PREFIX_.'htl_room_type hrt ON hrt.id_product = p.id_product + LEFT JOIN '._DB_PREFIX_.'htl_branch_info_lang hbil ON (hbil.id = hrt.id_hotel AND hbil.id_lang = '.(int)$this->getLang().') + LEFT JOIN '._DB_PREFIX_.'order_detail od ON od.product_id = p.id_product + LEFT JOIN '._DB_PREFIX_.'orders o ON od.id_order = o.id_order + '.Shop::addSqlRestriction(Shop::SHARE_ORDER, 'o').' + '.Product::sqlStock('p', 0).' + WHERE o.valid = 1 + GROUP BY od.product_id'; if (Validate::IsName($this->_sort)) { + $this->query .= ' ORDER BY `'.bqSQL($this->_sort).'`'; if (isset($this->_direction) && Validate::isSortDirection($this->_direction)) { $this->query .= ' '.$this->_direction; @@ -190,6 +215,8 @@ class StatsBestProducts extends ModuleGrid } $values = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($this->query); + $this->_totalCount = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT FOUND_ROWS()'); + $dateFrom = date("Y-m-d", strtotime($this->_employee->stats_date_from)); $dateTo = date("Y-m-d", strtotime($this->_employee->stats_date_to)); @@ -212,6 +239,5 @@ class StatsBestProducts extends ModuleGrid unset($value); $this->_values = $values; - $this->_totalCount = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT FOUND_ROWS()'); } } diff --git a/modules/statsbestvouchers/statsbestvouchers.php b/modules/statsbestvouchers/statsbestvouchers.php index c748d1287..891b3ecfb 100644 --- a/modules/statsbestvouchers/statsbestvouchers.php +++ b/modules/statsbestvouchers/statsbestvouchers.php @@ -58,19 +58,19 @@ class StatsBestVouchers extends ModuleGrid 'id' => 'code', 'header' => $this->l('Code'), 'dataIndex' => 'code', - 'align' => 'left' + 'align' => 'center' ), array( 'id' => 'name', 'header' => $this->l('Name'), 'dataIndex' => 'name', - 'align' => 'left' + 'align' => 'center' ), array( 'id' => 'ca', 'header' => $this->l('Sales'), 'dataIndex' => 'ca', - 'align' => 'right' + 'align' => 'center' ), array( 'id' => 'total', @@ -112,7 +112,7 @@ class StatsBestVouchers extends ModuleGrid '.$this->engine($engine_params).' - '.$this->l('CSV Export').' + '.$this->l('CSV Export').' '; return $this->html; diff --git a/modules/statscatalog/statscatalog.php b/modules/statscatalog/statscatalog.php index c683d4018..3c90654dc 100644 --- a/modules/statscatalog/statscatalog.php +++ b/modules/statscatalog/statscatalog.php @@ -192,13 +192,13 @@ class StatsCatalog extends Module $average_viewed = $total ? ($total_page_viewed / $total) : 0; $conversion = number_format((float)($total_page_viewed ? ($total_booked_rooms / $total_page_viewed) : 0), 2, '.', ''); if ($conversion_reverse = number_format((float)($total_booked_rooms ? ($total_page_viewed / $total_booked_rooms) : 0), 2, '.', '')) { - $conversion .= sprintf($this->l('(1 purchase / %d visits)'), $conversion_reverse); + $conversion .= sprintf($this->l(' (1 purchase / %d visits)'), $conversion_reverse); } $total_nv = $total - $this->getTotalProductViewed(); $html = ' - +
'.$this->displayName.'
@@ -221,17 +221,17 @@ class StatsCatalog extends Module

@@ -241,13 +241,13 @@ class StatsCatalog extends Module if (count($products_nb) && count($products_nb) < 50) { $html .= ' -

'.$this->l('Room type never booked').'
+
'.$this->l('Room types never booked').'
- + '; @@ -268,7 +268,7 @@ class StatsCatalog extends Module diff --git a/modules/statscheckup/statscheckup.php b/modules/statscheckup/statscheckup.php index 545d53d96..f73e4f120 100644 --- a/modules/statscheckup/statscheckup.php +++ b/modules/statscheckup/statscheckup.php @@ -71,6 +71,10 @@ class StatsCheckUp extends Module public function hookAdminStatsModules() { + $this->html = ' +
' + .$this->displayName.' +
'; if (Tools::isSubmit('submitCheckup')) { $confs = array( 'CHECKUP_DESCRIPTIONS_LT', @@ -85,12 +89,12 @@ class StatsCheckUp extends Module foreach ($confs as $confname) { Configuration::updateValue($confname, (int)Tools::getValue($confname)); } - echo '
'.$this->l('Configuration updated').'
'; + $this->html .= $this->displayConfirmation($this->l('Configuration updated.')); } if (Tools::isSubmit('submitCheckupOrder')) { $this->context->cookie->checkup_order = (int)Tools::getValue('submitCheckupOrder'); - echo '
'.$this->l('Configuration updated').'
'; + $this->html .= $this->displayConfirmation($this->l('Configuration updated.')); } if (!isset($this->context->cookie->checkup_order)) { @@ -108,9 +112,9 @@ class StatsCheckUp extends Module $languages = $db->executeS($sql); $array_colors = array( - 0 => ''.$this->l('Bad').'', - 1 => ''.$this->l('Average').'', - 2 => ''.$this->l('Good').'' + 0 => ''.$this->l('Bad').'', + 1 => ''.$this->l('Average').'', + 2 => ''.$this->l('Good').'' ); $token_products = Tools::getAdminToken('AdminProducts'.(int)Tab::getIdFromClassName('AdminProducts').(int)Context::getContext()->employee->id); $divisor = 4; @@ -167,10 +171,7 @@ class StatsCheckUp extends Module 'STOCK' => array('name' => $this->l('Available rooms'), 'text' => $this->l('items')) ); - $this->html = ' -
' - .$this->displayName.' -
+ $this->html .= '
'.$this->l('ID').' '.$this->l('Name').''.$this->l('Edit / View').''.$this->l('Edit / Preview').'
diff --git a/modules/statsequipment/statsequipment.php b/modules/statsequipment/statsequipment.php index a8e146e8d..5465e535a 100644 --- a/modules/statsequipment/statsequipment.php +++ b/modules/statsequipment/statsequipment.php @@ -132,7 +132,7 @@ class StatsEquipment extends ModuleGraph

'.$this->l('Making sure that your website is accessible to as many people as possible').'

- '.$this->l('When managing a website, it is important to keep track of the software used by visitors so as to be sure that the site displays the same way for everyone. Qloapps was built to be compatible with the most recent Web browsers and computer operating systems (OS). However, because you may end up adding advanced features to your website or even modifying the core Qloapps code, these additions may not be accessible to everyone. That is why it is a good idea to keep track of the percentage of users for each type of software before adding or changing something that only a limited number of users will be able to access.').' + '.$this->l('When managing a website, it is important to keep track of the software used by visitors so as to be sure that the site displays the same way for everyone. QloApps was built to be compatible with the most recent Web browsers and computer operating systems (OS). However, because you may end up adding advanced features to your website or even modifying the core QloApps code, these additions may not be accessible to everyone. That is why it is a good idea to keep track of the percentage of users for each type of software before adding or changing something that only a limited number of users will be able to access.').'

@@ -144,7 +144,7 @@ class StatsEquipment extends ModuleGraph

'.$this->l('Indicates the percentage of each web browser used by customers.').'


- '.$this->l('CSV Export').' + '.$this->l('CSV Export').'
@@ -158,7 +158,7 @@ class StatsEquipment extends ModuleGraph

'.$this->l('Indicates the percentage of each operating system used by customers.').'


- '.$this->l('CSV Export').' + '.$this->l('CSV Export').' diff --git a/modules/statsforecast/statsforecast.php b/modules/statsforecast/statsforecast.php index 0f5132af0..a7404f323 100644 --- a/modules/statsforecast/statsforecast.php +++ b/modules/statsforecast/statsforecast.php @@ -168,7 +168,7 @@ class StatsForecast extends Module - + @@ -205,8 +205,8 @@ class StatsForecast extends Module - - + + '; @@ -223,7 +223,7 @@ class StatsForecast extends Module - + @@ -240,12 +240,12 @@ class StatsForecast extends Module - - - - - - + + + + + + @@ -313,7 +313,7 @@ class StatsForecast extends Module @@ -397,7 +397,7 @@ class StatsForecast extends Module

'.$this->l('Payment distribution').'

' - .$this->l('The amounts include taxes, so you can get an estimation of the commission due to the payment method.').' + .$this->l('The amounts in this section include taxes, so you can get an estimation of the commission due to the payment method.').'
@@ -422,19 +422,30 @@ class StatsForecast extends Module
+ + '; - foreach ($ca['payment'] as $payment) { - $this->html .= ' + if (is_array($ca['payment']) && count($ca['payment'])) { + foreach ($ca['payment'] as $payment) { + $this->html .= ' + + '; - } + } + } else { + $this->html .= ' + + + '; + } $this->html .= '
'.$this->l('Visits').' '.$this->l('Registrations').' '.$this->l('Placed orders').''.$this->l('Booked Rooms').''.$this->l('Booked rooms').' '.$this->l('Percentage of registrations').' '.$this->l('Percentage of orders').' '.$this->l('Revenue').''.(int)$row['registrations'].' '.(int)$row['countOrders'].' '.(int)$row['roomBooked'].''.($visits_today ? round(100 * (int)$row['registrations'] / $visits_today, 2).' %' : '-').''.($visits_today ? round(100 * (int)$row['countOrders'] / $visits_today, 2).' %' : '-').''.($visits_today ? sprintf('%0.2f', ($row['registrations'] / $visits_today) * 100).' %' : '--').''.($visits_today ? sprintf('%0.2f', ($row['countOrders'] / $visits_today) * 100).' %' : '--').' '.Tools::displayPrice($row['totalSales'], $currency).'
'.$this->l('Visits').' '.$this->l('Registrations').' '.$this->l('Placed orders').''.$this->l('Booked Rooms').''.$this->l('Booked rooms').' '.$this->l('Percentage of registrations').' '.$this->l('Percentage of orders').' '.$this->l('Revenue').'
'.$this->l('Average').''.(int)($this->t1 / $interval_avg).''.(int)($this->t2 / $interval_avg).''.(int)($this->t3 / $interval_avg).''.(int)($this->t4 / $interval_avg).''.($this->t1 ? round(100 * $this->t2 / $this->t1, 2).' %' : '-').''.($this->t1 ? round(100 * $this->t3 / $this->t1, 2).' %' : '-').''.sprintf('%0.2f', $this->t1 / $interval_avg).''.sprintf('%0.2f', $this->t2 / $interval_avg).''.sprintf('%0.2f', $this->t3 / $interval_avg).''.sprintf('%0.2f', $this->t4 / $interval_avg).''.($this->t1 ? sprintf('%0.2f', ($this->t2 / $this->t1) * 100).' %' : '--').''.($this->t1 ? sprintf('%0.2f', ($this->t3 / $this->t1) * 100).' %' : '--').' '.Tools::displayPrice($this->t8 / $interval_avg, $currency).'

-

'.round(100 * $customers / max(1, $visitors), 2).' %

+

'.sprintf('%0.2f', ($customers / max(1, $visitors)) * 100).' %

'.$this->l('Accounts').'

@@ -321,7 +321,7 @@ class StatsForecast extends Module

-

'.round(100 * $fullcarts / max(1, $customers), 2).' %

+

'.sprintf('%0.2f', ($fullcarts / max(1, $customers)) * 100).' %

'.$this->l('Full carts').'

@@ -329,7 +329,7 @@ class StatsForecast extends Module

-

'.round(100 * $orders / max(1, $fullcarts), 2).' %

+

'.sprintf('%0.2f', ($orders / max(1, $fullcarts)) * 100).' %

'.$this->l('Orders').'

@@ -342,7 +342,7 @@ class StatsForecast extends Module
-

'.round(100 * $orders / max(1, $customers), 2).' %

+

'.sprintf('%0.2f', ($orders / max(1, $customers)) * 100).' %

@@ -357,7 +357,7 @@ class StatsForecast extends Module -

'.round(100 * $orders / max(1, $visitors), 2).' %

+

'.sprintf('%0.2f', ($orders / max(1, $visitors)) * 100).' %

@@ -369,7 +369,7 @@ class StatsForecast extends Module

-

'.round(100 * $carts / max(1, $visitors)).' %

+

'.sprintf('%0.2f', ($carts / max(1, $visitors)) * 100).' %

'.$this->l('Carts').'

@@ -377,7 +377,7 @@ class StatsForecast extends Module

-

'.round(100 * $fullcarts / max(1, $carts)).' %

+

'.sprintf('%0.2f', ($fullcarts / max(1, $carts)) * 100).' %

'.$this->l('Module').' '.$this->l('Orders').' '.$this->l('Sales').''.$this->l('Percentage of orders').''.$this->l('Percentage of sales').' '.$this->l('Average cart value').'
'.$payment['payment_method'].' '.(int)$payment['nb'].' '.Tools::displayPrice($payment['total'], $currency).''.sprintf('%0.2f', ($ca['ventil']['nb'] ? ($payment['nb'] / $ca['ventil']['nb']) * 100 : 0)).'%'.sprintf('%0.2f', ($ca['ventil']['nb'] ? ($payment['total'] / $ca['ventil']['total_incl']) * 100 : 0)).'% '.Tools::displayPrice($payment['total'] / (int)$payment['nb'], $currency).'
'.$this->l('No data available.').'
@@ -451,17 +462,24 @@ class StatsForecast extends Module '; - foreach ($ca['lang'] as $ophone => $amount) { - $percent = (int)($ca['langprev'][$ophone]) ? number_format((100 * $amount / $ca['langprev'][$ophone]) - 100, 1, '.', ' ') : '∞'; - $this->html .= ' - - '.$ophone.' - '.Tools::displayPrice($amount, $currency).' - '.((int)$ca['ventil']['total'] ? number_format((100 * $amount / $ca['ventil']['total']), 1, '.', ' ').'%' : '-').' - '.(($percent > 0 || $percent == '∞') ? '' : ' ').' - '.(($percent > 0 || $percent == '∞') ? '+' : '').$percent.'% - '; - } + if (is_array($ca['lang']) && count($ca['lang'])) { + foreach ($ca['lang'] as $ophone => $amount) { + $percent = (int)($ca['langprev'][$ophone]) ? number_format((100 * $amount / $ca['langprev'][$ophone]) - 100, 1, '.', ' ') : '∞'; + $this->html .= ' + + '.$ophone.' + '.Tools::displayPrice($amount, $currency).' + '.sprintf('%0.2f', ($ca['ventil']['total'] ? ($amount / $ca['ventil']['total']) * 100 : 0)).'% + '.(($percent > 0 || $percent == '∞') ? '' : ' ').' + '.(($percent > 0 || $percent == '∞') ? '+' : '').$percent.'% + '; + } + } else { + $this->html .= ' + + '.$this->l('No data available.').' + '; + } $this->html .= ' @@ -479,16 +497,23 @@ class StatsForecast extends Module '; - foreach ($ca['zones'] as $zone) { - $this->html .= ' - - '.(isset($zone['name']) ? $zone['name'] : $this->l('Undefined')).' - '.(int)($zone['nb']).' - '.Tools::displayPrice($zone['total'], $currency).' - '.($ca['ventil']['nb'] ? number_format((100 * $zone['nb'] / $ca['ventil']['nb']), 1, '.', ' ') : '0').'% - '.((int)$ca['ventil']['total'] ? number_format((100 * $zone['total'] / $ca['ventil']['total']), 1, '.', ' ') : '0').'% - '; - } + if (is_array($ca['zones']) && count($ca['zones'])) { + foreach ($ca['zones'] as $zone) { + $this->html .= ' + + '.(isset($zone['name']) ? $zone['name'] : $this->l('Undefined')).' + '.(int)($zone['nb']).' + '.Tools::displayPrice($zone['total'], $currency).' + '.sprintf('%0.2f', $ca['ventil']['nb'] ? ($zone['nb'] / $ca['ventil']['nb']) * 100 : 0).'% + '.sprintf('%0.2f', $ca['ventil']['total'] ? ($zone['total'] / $ca['ventil']['total']) * 100 : 0).'% + '; + } + } else { + $this->html .= ' + + '.$this->l('No data available.').' + '; + } $this->html .= ' @@ -523,16 +548,23 @@ class StatsForecast extends Module '; - foreach ($ca['currencies'] as $currency_row) { - $this->html .= ' - - '.$currency_row['name'].' - '.(int)($currency_row['nb']).' - '.Tools::displayPrice($currency_row['total'], $currency).' - '.($ca['ventil']['nb'] ? number_format((100 * $currency_row['nb'] / $ca['ventil']['nb']), 1, '.', ' ') : '0').'% - '.((int)$ca['ventil']['total'] ? number_format((100 * $currency_row['total'] / $ca['ventil']['total']), 1, '.', ' ') : '0').'% - '; - } + if (is_array($ca['currencies']) && count($ca['currencies'])) { + foreach ($ca['currencies'] as $currency_row) { + $this->html .= ' + + '.$currency_row['name'].' + '.(int)($currency_row['nb']).' + '.Tools::displayPrice($currency_row['total'], $currency).' + '.sprintf('%0.2f', $ca['ventil']['nb'] ? ($currency_row['nb'] / $ca['ventil']['nb']) * 100 : 0).'% + '.sprintf('%0.2f', $ca['ventil']['total'] ? ($currency_row['total'] / $ca['ventil']['total']) * 100 : 0).'% + '; + } + } else { + $this->html .= ' + + '.$this->l('No data available.').' + '; + } $this->html .= ' @@ -633,7 +665,8 @@ class StatsForecast extends Module ORDER BY total DESC'; $ca['currencies'] = Db::getInstance()->executeS($sql); - $sql = 'SELECT SUM(total_paid_tax_excl / o.conversion_rate) as total, COUNT(*) AS nb + $sql = 'SELECT SUM(total_paid_tax_excl / o.conversion_rate) as total, + SUM(total_paid_tax_incl / o.conversion_rate) as total_incl, COUNT(*) AS nb FROM `'._DB_PREFIX_.'orders` o WHERE o.valid = 1 AND o.`invoice_date` BETWEEN '.ModuleGraph::getDateBetween().' diff --git a/modules/statslive/statslive.php b/modules/statslive/statslive.php index 3fcdc5142..f4f4c54a2 100644 --- a/modules/statslive/statslive.php +++ b/modules/statslive/statslive.php @@ -144,10 +144,8 @@ class StatsLive extends Module $("#calendar").remove(); '; if (!Configuration::get('PS_STATSDATA_CUSTOMER_PAGESVIEWS')) { - $this->html .= ' -
'. - $this->l('You must activate the "Save page views for each customer" option in the "Data mining for statistics" (StatsData) module in order to see the pages that your visitors are currently viewing.').' -
'; + $link = $this->context->link->getAdminLink('AdminModules').'&configure=statsdata'; + $this->html .= '
'.$this->l('You must enable the "Save page views for each customer" option from ').'Data mining for statistics'.$this->l(' module in order to see the pages that your visitors are currently viewing.').'
'; } $this->html .= '

'.$this->l('Current online customers').'

'; @@ -195,7 +193,7 @@ class StatsLive extends Module '.$this->l('IP').' '.$this->l('Last activity').' '.$this->l('Current page').' - '.$this->l('Referrer').' + '.$this->l('Referer').' '; diff --git a/modules/statsnewsletter/statsnewsletter.php b/modules/statsnewsletter/statsnewsletter.php index 5875159d6..17105629b 100644 --- a/modules/statsnewsletter/statsnewsletter.php +++ b/modules/statsnewsletter/statsnewsletter.php @@ -93,7 +93,7 @@ class StatsNewsletter extends ModuleGraph
- '.$this->l('CSV Export').' + '.$this->l('CSV Export').'
@@ -125,7 +125,7 @@ class StatsNewsletter extends ModuleGraph protected function getData($layers) { - $this->_titles['main'][0] = $this->l('customers'); + $this->_titles['main'][0] = $this->l('Customers'); $this->_titles['main'][1] = $this->l('Visitors'); $this->_titles['main'][2] = $this->l('Newsletter statistics'); $this->_titles['main'][3] = $this->l('Both'); diff --git a/modules/statsorigin/statsorigin.php b/modules/statsorigin/statsorigin.php index c98158ad1..3d8c4a3b9 100644 --- a/modules/statsorigin/statsorigin.php +++ b/modules/statsorigin/statsorigin.php @@ -90,15 +90,15 @@ class StatsOrigin extends ModuleGraph if (count($websites)) { $this->_html .= '
- '.$this->l('In the tab, we break down the 10 most popular referral websites that bring customers to your online store.').' + '.$this->l('This page lists the 10 most popular referral websites that bring customers to your website.').'

'.$this->l('Guide').'

'.$this->l('What is a referral website?').'

- '.$this->l('The referrer is the URL of the previous webpage from which a link was followed by the visitor.').'
- '.$this->l('A referrer also enables you to know which keywords visitors use in search engines when browsing for your online store.').'

- '.$this->l('A referrer can be:').' + '.$this->l('A referer is the URL of the previous webpage from which a link was followed by a visitor.').'
+ '.$this->l('A referer also enables you to know which keywords visitors use in search engines when searching for your website.').'

+ '.$this->l('A referer can be:').'

  • '.$this->l('Someone who posts a link to your website.').'
  • @@ -112,7 +112,7 @@ class StatsOrigin extends ModuleGraph
diff --git a/modules/statspersonalinfos/statspersonalinfos.php b/modules/statspersonalinfos/statspersonalinfos.php index 4a3bcff23..1a7513894 100644 --- a/modules/statspersonalinfos/statspersonalinfos.php +++ b/modules/statspersonalinfos/statspersonalinfos.php @@ -120,10 +120,10 @@ class StatsPersonalInfos extends ModuleGraph )).'
-

'.$this->l('Gender distribution allows you to determine the percentage of men and women shoppers on your website.').'

+

'.$this->l('Gender distribution allows you to determine the percentage of men and women customers on your website.').'


- '.$this->l('CSV Export').' + '.$this->l('CSV Export').'
@@ -140,7 +140,7 @@ class StatsPersonalInfos extends ModuleGraph

'.$this->l('Age ranges allow you to better understand target demographics.').'


- '.$this->l('CSV Export').' + '.$this->l('CSV Export').' @@ -154,10 +154,10 @@ class StatsPersonalInfos extends ModuleGraph )).'
-

'.$this->l('Country distribution allows you to analyze which part of the World your customers are booking from.').'

+

'.$this->l('Country distribution allows you to analyze which part of the world your customers are booking from.').'


- '.$this->l('CSV Export').' + '.$this->l('CSV Export').'
@@ -174,7 +174,7 @@ class StatsPersonalInfos extends ModuleGraph

'.$this->l('Currency range allows you to determine which currency your customers are using.').'


- '.$this->l('CSV Export').' + '.$this->l('CSV Export').' @@ -191,7 +191,7 @@ class StatsPersonalInfos extends ModuleGraph

'.$this->l('Language distribution allows you to analyze the browsing language used by your customers.').'


- '.$this->l('CSV Export').' + '.$this->l('CSV Export').' diff --git a/modules/statsproduct/statsproduct.php b/modules/statsproduct/statsproduct.php index 5814d7c41..4b5eb3e4e 100644 --- a/modules/statsproduct/statsproduct.php +++ b/modules/statsproduct/statsproduct.php @@ -46,7 +46,7 @@ class StatsProduct extends ModuleGraph $this->need_instance = 0; parent::__construct(); - + $this->query = array(); $this->displayName = $this->l('Room type details'); $this->description = $this->l('Adds detailed statistics for each room type to the Stats dashboard.'); $this->ps_versions_compliancy = array('min' => '1.6', 'max' => '1.7.0.99'); @@ -180,7 +180,7 @@ class StatsProduct extends ModuleGraph

'.$this->l('Number of purchases compared to number of views').'

'.$this->l('After choosing a hotel and selecting a room type, informational graphs will appear.').' @@ -216,13 +216,13 @@ class StatsProduct extends ModuleGraph
    -
  • '.$this->l('Total booked').' '.$total_bought.'
  • -
  • '.$this->l('Sales (tax excluded)').' '.Tools::displayprice($total_sales, $currency).'
  • -
  • '.$this->l('Total viewed').' '.$total_viewed.'
  • -
  • '.$this->l('Conversion rate').' '.number_format($total_viewed ? $total_bought / $total_viewed : 0, 2).'
  • +
  • '.$this->l('Total booked:').' '.$total_bought.'
  • +
  • '.$this->l('Sales (tax excluded):').' '.Tools::displayprice($total_sales, $currency).'
  • +
  • '.$this->l('Total viewed:').' '.$total_viewed.'
  • +
  • '.$this->l('Conversion rate:').' '.number_format($total_viewed ? $total_bought / $total_viewed : 0, 2).'
- '.$this->l('CSV Export').' + '.$this->l('CSV Export').'
@@ -252,7 +252,7 @@ class StatsProduct extends ModuleGraph '.($has_attribute ? ''.$this->l('Attribute').'' : '').' - '.$this->l('Rooms Booked').' + '.$this->l('Rooms booked').' '.$this->l('Price').' @@ -266,8 +266,8 @@ class StatsProduct extends ModuleGraph $this->html .= ' '.Tools::displayDate($sale['date_add'], null, false).' - '.(int)$sale['id_order'].' - '.(int)$sale['id_customer'].' + #'.(int)$sale['id_order'].' + #'.(int)$sale['id_customer'].' '.($has_attribute ? ''.$sale['product_name'].'' : '').' '.(int)$sale['total_booked'].' '.Tools::displayprice($sale['total'], $currency).' @@ -287,10 +287,10 @@ class StatsProduct extends ModuleGraph - '.$this->l('Room Type name').' + '.$this->l('Room type name').' - '.$this->l('Rooms Booked').' + '.$this->l('Rooms booked').' '.$this->l('Average price').' @@ -321,7 +321,7 @@ class StatsProduct extends ModuleGraph
@@ -341,7 +341,7 @@ class StatsProduct extends ModuleGraph - '.$this->l('Room Type Name').' + '.$this->l('Room type name').' '.$this->l('Available rooms').' @@ -382,7 +382,7 @@ class StatsProduct extends ModuleGraph - '.$this->l('CSV Export').' + '.$this->l('CSV Export').' '; } diff --git a/modules/statsregistrations/statsregistrations.php b/modules/statsregistrations/statsregistrations.php index 494226e05..260330edc 100644 --- a/modules/statsregistrations/statsregistrations.php +++ b/modules/statsregistrations/statsregistrations.php @@ -123,7 +123,7 @@ class StatsRegistrations extends ModuleGraph
  • - '.$this->l('Number of visitors who stopped at the registering step:').' '.(int)$total_blocked.($total_registrations ? ' ('.number_format(100 * $total_blocked / ($total_registrations + $total_blocked), 2).'%)' : '').'
  • + '.$this->l('Number of visitors who stopped at registration step:').' '.(int)$total_blocked.($total_registrations ? ' ('.number_format(100 * $total_blocked / ($total_registrations + $total_blocked), 2).'%)' : '').'
  • '.$this->l('Number of visitors who placed an order directly after registration:').' '.(int)$total_buyers.($total_registrations ? ' ('.number_format(100 * $total_buyers / ($total_registrations), 2).'%)' : '').'
  • '.$this->l('Total customer accounts:').' '.$total_registrations.'
  • @@ -141,7 +141,7 @@ class StatsRegistrations extends ModuleGraph '.$this->l('Here is a summary of what may affect the creation of customer accounts:').'
    • '.$this->l('An advertising campaign can attract an increased number of visitors to your website. This will likely be followed by an increase in customer accounts and profit margins, which will depend on customer "quality." Well-targeted advertising is typically more effective than large-scale advertising... and it\'s cheaper too!').'
    • -
    • '.$this->l('Specials, sales, promotions and/or contests typically demand a customers\' attentions. Offering such things will not only keep your business lively, it will also increase traffic, build customer loyalty and genuinely change your current e-commerce philosophy.').'
    • +
    • '.$this->l('Specials, sales, promotions and/or contests typically demand a customers\' attentions. Offering such things will not only keep your business lively, it will also increase traffic, build customer loyalty and genuinely change your current business philosophy.').'
    • '.$this->l('Design and user-friendliness are more important than ever in the world of online sales. An ill-chosen or hard-to-follow graphical theme can keep customers at bay. This means that you should aspire to find the right balance between beauty and functionality for your website.').'
@@ -153,7 +153,7 @@ class StatsRegistrations extends ModuleGraph
@@ -170,7 +170,7 @@ class StatsRegistrations extends ModuleGraph WHERE 1 '.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER).' AND `date_add` BETWEEN'; - $this->_titles['main'] = $this->l('Number of customer accounts created'); + $this->_titles['main'] = $this->l('Number of customer registrations'); $this->setDateGraph($layers, true); } diff --git a/modules/statssales/statssales.php b/modules/statssales/statssales.php index f70f0c38c..5357537fb 100644 --- a/modules/statssales/statssales.php +++ b/modules/statssales/statssales.php @@ -87,8 +87,8 @@ class StatsSales extends ModuleGraph

'.$this->l('About order statuses').'

- '.$this->l('In your Back Office, you can modify the following order statuses: Awaiting Check Payment, Payment Accepted, Preparation in Progress, Canceled, Refund, Payment Error, Out of Stock, and Awaiting Bank Wire Payment.').'
- '.$this->l('These order statuses cannot be removed from the Back Office; however you have the option to add more.').' + '.$this->l('In your back office, you can modify the following order statuses: Awaiting check payment, Payment accepted, Processing in progress, Canceled, Refunded, Payment error and Awaiting bank wire payment.').'
+ '.$this->l('These order statuses cannot be removed from the back office; however you have the option to add more.').'

@@ -127,7 +127,7 @@ class StatsSales extends ModuleGraph
- '.$this->l('CSV Export').' + '.$this->l('CSV Export').'
@@ -146,7 +146,7 @@ class StatsSales extends ModuleGraph
- '.$this->l('CSV Export').' + '.$this->l('CSV Export').' @@ -164,7 +164,7 @@ class StatsSales extends ModuleGraph diff --git a/modules/statssearch/statssearch.php b/modules/statssearch/statssearch.php index 0ebfb1873..a98bb5131 100644 --- a/modules/statssearch/statssearch.php +++ b/modules/statssearch/statssearch.php @@ -130,7 +130,7 @@ class StatsSearch extends ModuleGraph if (count($result)) $this->html .= '
'.$this->engine(array('type' => 'pie')).'
- '.$this->l('CSV Export').' + '.$this->l('CSV Export').' '.$table; else $this->html .= '

'.$this->l('Cannot find any keywords that have been searched for more than once.').'

'; diff --git a/modules/statsvisits/statsvisits.php b/modules/statsvisits/statsvisits.php index ef9a13c59..3442ac1f9 100644 --- a/modules/statsvisits/statsvisits.php +++ b/modules/statsvisits/statsvisits.php @@ -31,7 +31,7 @@ if (!defined('_PS_VERSION_')) { class StatsVisits extends ModuleGraph { private $html = ''; - private $query = ''; + private $query = array(); public function __construct() { @@ -43,7 +43,7 @@ class StatsVisits extends ModuleGraph parent::__construct(); - $this->displayName = $this->l('Visits and Visitors'); + $this->displayName = $this->l('Visits and visitors'); $this->description = $this->l('Adds statistics about your visits and visitors to the Stats dashboard.'); $this->ps_versions_compliancy = array('min' => '1.6', 'max' => '1.7.0.99'); } @@ -102,7 +102,7 @@ class StatsVisits extends ModuleGraph

'.$this->l('This information is mostly qualitative. It is up to you to determine the interest of a disjointed visit.').' @@ -110,7 +110,7 @@ class StatsVisits extends ModuleGraph

'.$this->l('A visit corresponds to an internet user coming to your website, and until the end of their session, only one visit is counted.').' - '.$this->l('A visitor is an unknown person who has not registered or logged into your store. A visitor can also be considered a person who has visited your website multiple times.').' + '.$this->l('A visitor is an unknown person who has not registered or logged into your website. A visitor can also be considered a person who has visited your website multiple times.').'
@@ -124,7 +124,7 @@ class StatsVisits extends ModuleGraph
- '.$this->l('CSV Export').' + '.$this->l('CSV Export').' ' : '').'
From b8d15048683c83972ca0a0f1508edd4d9d32acad Mon Sep 17 00:00:00 2001 From: Abhishek Kumar Date: Thu, 3 Nov 2022 16:48:03 +0530 Subject: [PATCH 07/56] Add new stats on dashboard and improve stats presentations and calculations --- .../template/form_date_range_picker.tpl | 51 +- classes/Translate.php | 336 +++++++++++ controllers/admin/AdminCartsController.php | 8 +- .../admin/AdminDashboardController.php | 33 +- controllers/admin/AdminStatsController.php | 571 +++++++++++++++--- controllers/admin/AdminStatsTabController.php | 9 +- .../admin/AdminTranslationsController.php | 231 ++----- install/data/xml/configuration.xml | 40 +- install/models/install.php | 10 +- js/jquery/plugins/jquery.connections.js | 251 ++++++++ modules/blocknewsletter/blocknewsletter.php | 4 +- modules/dashactivity/dashactivity.php | 51 +- .../views/js/dashavailability.js | 2 +- modules/dashgoals/dashgoals.php | 2 +- modules/dashgoals/views/js/dashgoals.js | 16 +- .../dashgoals/views/templates/hook/config.tpl | 2 +- .../templates/hook/dashboard_zone_two.tpl | 7 +- modules/dashperformance/dashperformance.php | 48 +- .../views/css/dashperformance.css | 36 +- .../templates/hook/dashboard_zone_two.tpl | 88 ++- modules/dashproducts/dashproducts.php | 6 +- modules/dashtrends/dashtrends.php | 2 +- modules/dashtrends/views/css/dashtrends.css | 1 + .../templates/hook/dashboard_zone_two.tpl | 40 +- modules/graphnvd3/graphnvd3.php | 15 +- modules/gridhtml/gridhtml.php | 5 +- .../hotelreservationsystem.php | 32 +- .../views/js/plugindetect.js | 7 + .../statsbestcategories.php | 241 ++++---- .../statsbestcustomers/statsbestcustomers.php | 16 +- .../statsbestproducts/statsbestproducts.php | 189 +++--- .../statsbestvouchers/statsbestvouchers.php | 6 +- modules/statscatalog/statscatalog.php | 96 ++- modules/statscheckup/statscheckup.php | 514 ++++++++++------ modules/statsdata/statsdata.php | 68 +-- modules/statsforecast/statsforecast.php | 333 +++++----- .../views/css/conversion-graph.css | 64 ++ modules/statsforecast/views/css/index.php | 29 + modules/statsforecast/views/index.php | 29 + .../views/js/conversion-graph.js | 51 ++ modules/statsforecast/views/js/index.php | 29 + .../views/templates/conversion.tpl | 67 ++ .../statsforecast/views/templates/index.php | 29 + modules/statsproduct/statsproduct.php | 292 ++++----- modules/statssales/statssales.php | 171 ++++-- modules/statsvisits/statsvisits.php | 4 +- 46 files changed, 2721 insertions(+), 1411 deletions(-) create mode 100644 js/jquery/plugins/jquery.connections.js create mode 100644 modules/hotelreservationsystem/views/js/plugindetect.js create mode 100644 modules/statsforecast/views/css/conversion-graph.css create mode 100644 modules/statsforecast/views/css/index.php create mode 100644 modules/statsforecast/views/index.php create mode 100644 modules/statsforecast/views/js/conversion-graph.js create mode 100644 modules/statsforecast/views/js/index.php create mode 100644 modules/statsforecast/views/templates/conversion.tpl create mode 100644 modules/statsforecast/views/templates/index.php diff --git a/admin/themes/default/template/form_date_range_picker.tpl b/admin/themes/default/template/form_date_range_picker.tpl index f75864be5..7334aa52b 100644 --- a/admin/themes/default/template/form_date_range_picker.tpl +++ b/admin/themes/default/template/form_date_range_picker.tpl @@ -9,7 +9,7 @@ - +
@@ -18,13 +18,13 @@
- +
- +
@@ -41,11 +41,50 @@
\ No newline at end of file diff --git a/classes/Translate.php b/classes/Translate.php index a11d739a2..7bb036099 100644 --- a/classes/Translate.php +++ b/classes/Translate.php @@ -29,6 +29,8 @@ */ class TranslateCore { + public static $ignore_folder = array('.', '..', '.svn', '.git', '.htaccess', 'index.php'); + /** * Get a translation for an admin controller * @@ -315,4 +317,338 @@ class TranslateCore { return Translate::postProcessTranslation($string, array('tags' => $tags)); } + + /** + * This method parse a file by type of translation and type file + * + * @param $content + * @param $type_translation : front, back, errors, modules... + * @param string|bool $type_file : (tpl|php) + * @param string $module_name : name of the module + * @return array + */ + public static function userParseFile($content, $type_translation, $type_file = false, $module_name = '') + { + switch ($type_translation) { + case 'front': + // Parsing file in Front office + $regex = '/\{l\s*s=([\'\"])'._PS_TRANS_PATTERN_.'\1(\s*sprintf=.*)?(\s*js=1)?\s*\}/U'; + break; + + case 'back': + // Parsing file in Back office + if ($type_file == 'php') { + $regex = '/this->l\((\')'._PS_TRANS_PATTERN_.'\'[\)|\,]/U'; + } elseif ($type_file == 'specific') { + $regex = '/Translate::getAdminTranslation\((\')'._PS_TRANS_PATTERN_.'\'(?:,.*)*\)/U'; + } else { + $regex = '/\{l\s*s\s*=([\'\"])'._PS_TRANS_PATTERN_.'\1(\s*sprintf=.*)?(\s*js=1)?(\s*slashes=1)?.*\}/U'; + } + break; + + case 'errors': + // Parsing file for all errors syntax + $regex = '/Tools::displayError\((\')'._PS_TRANS_PATTERN_.'\'(,\s*(.+))?\)/U'; + break; + + case 'modules': + // Parsing modules file + if ($type_file == 'php') { + $regex = '/->l\((\')'._PS_TRANS_PATTERN_.'\'(, ?\'(.+)\')?(, ?(.+))?\)/U'; + } else { + // In tpl file look for something that should contain mod='module_name' according to the documentation + $regex = '/\{l\s*s=([\'\"])'._PS_TRANS_PATTERN_.'\1.*\s+mod=\''.$module_name.'\'.*\}/U'; + } + break; + + case 'pdf': + // Parsing PDF file + if ($type_file == 'php') { + $regex = array( + '/HTMLTemplate.*::l\((\')'._PS_TRANS_PATTERN_.'\'[\)|\,]/U', + '/->l\((\')'._PS_TRANS_PATTERN_.'\'(, ?\'(.+)\')?(, ?(.+))?\)/U' + ); + } else { + $regex = '/\{l\s*s=([\'\"])'._PS_TRANS_PATTERN_.'\1(\s*sprintf=.*)?(\s*js=1)?(\s*pdf=\'true\')?\s*\}/U'; + } + break; + } + + if (!is_array($regex)) { + $regex = array($regex); + } + + $strings = array(); + foreach ($regex as $regex_row) { + $matches = array(); + $n = preg_match_all($regex_row, $content, $matches); + for ($i = 0; $i < $n; $i += 1) { + $quote = $matches[1][$i]; + $string = $matches[2][$i]; + + if ($quote === '"') { + // Escape single quotes because the core will do it when looking for the translation of this string + $string = str_replace('\'', '\\\'', $string); + // Unescape double quotes + $string = preg_replace('/\\\\+"/', '"', $string); + } + + $strings[] = $string; + } + } + + return array_unique($strings); + } + + /** + * Recursively list files in directory $dir + * + * @param string $dir + * @param array $list + * @param string $file_ext + * + * @return array + */ + public static function listFiles($dir, $list = array(), $file_ext = 'tpl') + { + $dir = rtrim($dir, '/').DIRECTORY_SEPARATOR; + + $to_parse = scandir($dir); + // copied (and kind of) adapted from AdminImages.php + foreach ($to_parse as $file) { + if (!in_array($file, self::$ignore_folder)) { + if (preg_match('#'.preg_quote($file_ext, '#').'$#i', $file)) { + $list[$dir][] = $file; + } elseif (is_dir($dir.$file)) { + $list = self::listFiles($dir.$file, $list, $file_ext); + } + } + } + + return $list; + } + + /** + * Find sentence which use %d, %s, %%, %1$d, %1$s... + * + * @param $key : english sentence + * @return array|bool return list of matches + */ + public static function checkIfKeyUseSprintf($key) + { + if (preg_match_all('#(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])#', $key, $matches)) { + return implode(', ', $matches[0]); + } + + return false; + } + + public static function getTranslationsCountFrontOffice($theme, $isoCode) + { + $themeDir = _PS_ROOT_DIR_.'/themes/'.$theme.'/'; + $langFile = $themeDir.'lang/'.$isoCode.'.php'; + + // include global translation file + if (Tools::file_exists_cache($langFile)) { + include $langFile; + } else { + $_LANG = array(); + } + + // count translatable strings in theme tpl files + $directories = array(); + $directories['tpl'] = array(_PS_ALL_THEMES_DIR_ => scandir(_PS_ALL_THEMES_DIR_)); + self::$ignore_folder[] = 'modules'; + $directories['tpl'] = array_merge($directories['tpl'], self::listFiles($themeDir)); + if (isset($directories['tpl'][$themeDir.'pdf/'])) { + unset($directories['tpl'][$themeDir.'pdf/']); + } + + if (Tools::file_exists_cache(_PS_THEME_OVERRIDE_DIR_)) { + $directories['tpl'] = array_merge($directories['tpl'], self::listFiles(_PS_THEME_OVERRIDE_DIR_)); + } + + // process tpl files + $countTotal = 0; + $countTranslated = 0; + foreach ($directories['tpl'] as $dir => $files) { + $prefix = $dir == _PS_THEME_OVERRIDE_DIR_ ? 'override_' : ''; + + foreach ($files as $file) { + if (preg_match('/^(.*).tpl$/', $file) && (Tools::file_exists_cache($filePath = $dir.$file))) { + $prefixKey = $prefix.substr(basename($file), 0, -4); + $fileContent = Tools::file_get_contents($filePath); + $matches = self::userParseFile($fileContent, 'front'); + + foreach ($matches as $key) { + $countTotal++; + + if (!empty($key)) { + if (isset($_LANG[$prefixKey.'_'.md5($key)])) { + $countTranslated++; + } + } + } + } + } + } + + return array('total' => $countTotal, 'translated' => $countTranslated); + } + + public static function getTranslationsCountBackOffice($isoCode) + { + $translationsFile = _PS_TRANSLATIONS_DIR_.$isoCode.'/admin.php'; + + // include global translation file + if (Tools::file_exists_cache($translationsFile)) { + include $translationsFile; + } else { + $_LANGADM = array(); + } + + // list directories with translatable files + $directories = array( + 'php' => array( + _PS_ADMIN_CONTROLLER_DIR_ => scandir(_PS_ADMIN_CONTROLLER_DIR_), + _PS_OVERRIDE_DIR_.'controllers/admin/' => scandir(_PS_OVERRIDE_DIR_.'controllers/admin/'), + _PS_CLASS_DIR_.'helper/' => scandir(_PS_CLASS_DIR_.'helper/'), + _PS_CLASS_DIR_.'controller/' => array('AdminController.php'), + _PS_CLASS_DIR_ => array('PaymentModule.php'), + ), + 'tpl' => self::listFiles(_PS_ADMIN_DIR_.DIRECTORY_SEPARATOR.'themes/'), + 'specific' => array( + _PS_ADMIN_DIR_.DIRECTORY_SEPARATOR => array( + 'header.inc.php', + 'footer.inc.php', + 'index.php', + 'functions.php', + ), + ), + ); + + // list directories from override folders + if (Tools::file_exists_cache(_PS_OVERRIDE_DIR_.'controllers'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'templates')) { + $directories['tpl'] = array_merge($directories['tpl'], self::listFiles(_PS_OVERRIDE_DIR_.'controllers'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'templates')); + } + + // process files + $countTotal = 0; + $countTranslated = 0; + foreach ($directories['php'] as $dir => $files) { + foreach ($files as $file) { + // check if $file is a PHP file and corresponding override file exists + if (preg_match('/^(.*)\.php$/', $file) && Tools::file_exists_cache($filePath = $dir.$file) && !in_array($file, self::$ignore_folder)) { + $prefixKey = basename($file); + // -4 becomes -14 to remove the ending "Controller.php" from the filename + if (strpos($file, 'Controller.php') !== false) { + $prefixKey = basename(substr($file, 0, -14)); + } elseif (strpos($file, 'Helper') !== false) { + $prefixKey = 'Helper'; + } + + if ($prefixKey == 'Admin') { + $prefixKey = 'AdminController'; + } + + if ($prefixKey == 'PaymentModule.php') { + $prefixKey = 'PaymentModule'; + } + + $fileContent = Tools::file_get_contents($filePath); + $matches = self::userParseFile($fileContent, 'back', 'php'); + + foreach ($matches as $key) { + $countTotal++; + + if (!empty($key)) { + if (isset($_LANGADM[$prefixKey.md5($key)])) { + $countTranslated++; + } + } + } + } + } + } + + foreach ($directories['specific'] as $dir => $files) { + foreach ($files as $file) { + if (Tools::file_exists_cache($filePath = $dir.$file) && !in_array($file, self::$ignore_folder)) { + $prefixKey = 'index'; + + $fileContent = Tools::file_get_contents($filePath); + $matches = self::userParseFile($fileContent, 'back', 'specific'); + + foreach ($matches as $key) { + $countTotal++; + + if (!empty($key)) { + if (isset($_LANGADM[$prefixKey.md5($key)])) { + $countTranslated++; + } + } + } + } + } + } + + foreach ($directories['tpl'] as $dir => $files) { + foreach ($files as $file) { + if (preg_match('/^(.*).tpl$/', $file) && Tools::file_exists_cache($filePath = $dir.$file)) { + // get controller name instead of file name + $prefixKey = Tools::toCamelCase(str_replace(_PS_ADMIN_DIR_.DIRECTORY_SEPARATOR.'themes', '', $filePath), true); + $pos = strrpos($prefixKey, DIRECTORY_SEPARATOR); + $tmp = substr($prefixKey, 0, $pos); + + if (preg_match('#controllers#', $tmp)) { + $parentClass = explode(DIRECTORY_SEPARATOR, str_replace('/', DIRECTORY_SEPARATOR, $tmp)); + $override = array_search('override', $parentClass); + if ($override !== false) { + // case override/controllers/admin/templates/controller_name + $prefixKey = 'Admin'.ucfirst($parentClass[$override + 4]); + } else { + // case admin_name/themes/theme_name/template/controllers/controller_name + $key = array_search('controllers', $parentClass); + $prefixKey = 'Admin'.ucfirst($parentClass[$key + 1]); + } + } else { + $prefixKey = 'Admin'.ucfirst(substr($tmp, strrpos($tmp, DIRECTORY_SEPARATOR) + 1, $pos)); + } + + // Adding list, form, option in Helper Translations + $listPrefixKey = array('AdminHelpers', 'AdminList', 'AdminView', 'AdminOptions', 'AdminForm', + 'AdminCalendar', 'AdminTree', 'AdminUploader', 'AdminDataviz', 'AdminKpi', 'AdminModule_list', 'AdminModulesList'); + if (in_array($prefixKey, $listPrefixKey)) { + $prefixKey = 'Helper'; + } + + // Adding the folder backup/download/ in AdminBackup Translations + if ($prefixKey == 'AdminDownload') { + $prefixKey = 'AdminBackup'; + } + + // use the prefix 'AdminController' (like old php files 'header', 'footer.inc', 'index', 'login', 'password', 'functions' + if ($prefixKey == 'Admin' || $prefixKey == 'AdminTemplate') { + $prefixKey = 'AdminController'; + } + + $fileContent = Tools::file_get_contents($filePath); + $matches = self::userParseFile($fileContent, 'back', 'tpl'); + + // get string translation for each tpl file + foreach ($matches as $key) { + $countTotal++; + + if (!empty($key)) { + if (isset($_LANGADM[$prefixKey.md5($key)])) { + $countTranslated++; + } + } + } + } + } + } + + return array('total' => $countTotal, 'translated' => $countTranslated); + } } diff --git a/controllers/admin/AdminCartsController.php b/controllers/admin/AdminCartsController.php index ebd03b7a4..4de8b21d1 100644 --- a/controllers/admin/AdminCartsController.php +++ b/controllers/admin/AdminCartsController.php @@ -188,11 +188,11 @@ class AdminCartsControllerCore extends AdminController $helper->color = 'color4'; $helper->title = $this->l('Net Profit per Visitor', null, null, false); $helper->subtitle = $this->l('30 days', null, null, false); - if (ConfigurationKPI::get('NETPROFIT_VISITOR') !== false) { - $helper->value = ConfigurationKPI::get('NETPROFIT_VISITOR'); + if (ConfigurationKPI::get('NETPROFIT_VISIT') !== false) { + $helper->value = ConfigurationKPI::get('NETPROFIT_VISIT'); } - $helper->source = $this->context->link->getAdminLink('AdminStats').'&ajax=1&action=getKpi&kpi=netprofit_visitor'; - $helper->refresh = (bool)(ConfigurationKPI::get('NETPROFIT_VISITOR_EXPIRE') < $time); + $helper->source = $this->context->link->getAdminLink('AdminStats').'&ajax=1&action=getKpi&kpi=netprofit_visit'; + $helper->refresh = (bool)(ConfigurationKPI::get('NETPROFIT_VISIT_EXPIRE') < $time); $kpis[] = $helper->generate(); $helper = new HelperKpiRow(); diff --git a/controllers/admin/AdminDashboardController.php b/controllers/admin/AdminDashboardController.php index a7a01800c..8a694feaf 100644 --- a/controllers/admin/AdminDashboardController.php +++ b/controllers/admin/AdminDashboardController.php @@ -70,13 +70,11 @@ class AdminDashboardControllerCore extends AdminController { $forms = array(); $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT')); - $carriers = Carrier::getCarriers($this->context->language->id, true, false, false, null, 'ALL_CARRIERS'); $modules = Module::getModulesOnDisk(true); $forms = array( + 'net_profit' => array('title' => $this->l('Net Profit settings'), 'id' => 'net_profit'), 'payment' => array('title' => $this->l('Average bank fees per payment method'), 'id' => 'payment'), - 'carriers' => array('title' => $this->l('Average shipping fees per shipping method'), 'id' => 'carriers'), - 'other' => array('title' => $this->l('Other settings'), 'id' => 'other') ); foreach ($forms as &$form) { $form['icon'] = 'tab-preferences'; @@ -133,32 +131,9 @@ class AdminDashboardControllerCore extends AdminController } } - foreach ($carriers as $carrier) { - $forms['carriers']['fields']['CONF_'.strtoupper($carrier['id_reference']).'_SHIP'] = array( - 'title' => $carrier['name'], - 'desc' => sprintf($this->l('For the carrier named %s, indicate the domestic delivery costs in percentage of the price charged to customers.'), $carrier['name']), - 'validation' => 'isPercentage', - 'cast' => 'floatval', - 'type' => 'text', - 'defaultValue' => '0', - 'suffix' => '%' - ); - $forms['carriers']['fields']['CONF_'.strtoupper($carrier['id_reference']).'_SHIP_OVERSEAS'] = array( - 'title' => $carrier['name'], - 'desc' => sprintf($this->l('For the carrier named %s, indicate the overseas delivery costs in percentage of the price charged to customers.'), $carrier['name']), - 'validation' => 'isPercentage', - 'cast' => 'floatval', - 'type' => 'text', - 'defaultValue' => '0', - 'suffix' => '%' - ); - } - - $forms['carriers']['description'] = $this->l('Method: Indicate the percentage of your carrier margin. For example, if you charge $10 of shipping fees to your customer for each shipment, but you really pay $4 to this carrier, then you should indicate "40" in the percentage field.'); - - $forms['other']['fields']['CONF_AVERAGE_PRODUCT_MARGIN'] = array( + $forms['net_profit']['fields']['CONF_AVERAGE_PRODUCT_MARGIN'] = array( 'title' => $this->l('Average gross margin percentage'), - 'desc' => $this->l('You should calculate this percentage as follows: ((total sales revenue) - (cost of goods sold)) / (total sales revenue) * 100. This value is only used to calculate the Dashboard approximate gross margin, if you do not specify the wholesale price for each product.'), + 'desc' => $this->l('You should calculate this percentage as follows: ((total sales revenue) - (total operating cost)) / (total sales revenue) * 100. This value is only used to calculate Dashboard approximate gross margin, if you do not specify operating cost for each room type.'), 'validation' => 'isPercentage', 'cast' => 'intval', 'type' => 'text', @@ -166,7 +141,7 @@ class AdminDashboardControllerCore extends AdminController 'suffix' => '%' ); - $forms['other']['fields']['CONF_ORDER_FIXED'] = array( + $forms['net_profit']['fields']['CONF_ORDER_FIXED'] = array( 'title' => $this->l('Other fees per order'), 'desc' => $this->l('You should calculate this value by making the sum of all of your additional costs per order.'), 'validation' => 'isPrice', diff --git a/controllers/admin/AdminStatsController.php b/controllers/admin/AdminStatsController.php index 60a066d4d..d2df25f9c 100644 --- a/controllers/admin/AdminStatsController.php +++ b/controllers/admin/AdminStatsController.php @@ -29,10 +29,10 @@ class AdminStatsControllerCore extends AdminStatsTabController public static function getVisits($unique = false, $date_from, $date_to, $granularity = false) { $visits = ($granularity == false) ? 0 : array(); - $objQGA = Module::isEnabled('qlogoogleanalytics') ? Module::getInstanceByName('qlogoogleanalytics') : false; - if (Validate::isLoadedObject($objQGA) && $objQGA->isConfigured()) { + $objGoogleAnalytics = Module::isEnabled('qlogoogleanalytics') ? Module::getInstanceByName('qlogoogleanalytics') : false; + if (Validate::isLoadedObject($objGoogleAnalytics) && $objGoogleAnalytics->isConfigured()) { $metric = $unique ? 'visitors' : 'visits'; - if ($result = $objQGA->requestReportData($granularity ? 'ga:date' : '', 'ga:'.$metric, $date_from, $date_to, null, null, 1, 5000)) { + if ($result = $objGoogleAnalytics->requestReportData($granularity ? 'ga:date' : '', 'ga:'.$metric, $date_from, $date_to, null, null, 1, 5000)) { foreach ($result as $row) { if ($granularity == 'day') { $visits[strtotime(preg_replace('/^([0-9]{4})([0-9]{2})([0-9]{2})$/', '$1-$2-$3', $row['dimensions']['date']))] = $row['metrics'][$metric]; @@ -147,7 +147,6 @@ class AdminStatsControllerCore extends AdminStatsTabController return round($row['products'] ? 100 * $row['without_stock'] / $row['products'] : 0, 2).'%'; } - public static function getProductAverageGrossMargin() { $sql = 'SELECT AVG(1 - (IF(IFNULL(product_attribute_shop.wholesale_price, 0) = 0, product_shop.wholesale_price,product_attribute_shop.wholesale_price) / (IFNULL(product_attribute_shop.price, 0) + product_shop.price))) @@ -261,6 +260,7 @@ class AdminStatsControllerCore extends AdminStatsTabController FROM `'._DB_PREFIX_.'orders` o LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON o.id_order = od.id_order WHERE `invoice_date` BETWEEN "'.pSQL($date_from).' 00:00:00" AND "'.pSQL($date_to).' 23:59:59" + AND o.`valid` = 1 '.Shop::addSqlRestriction(false, 'o')); if (!$distinct_products) { return '0%'; @@ -524,21 +524,14 @@ class AdminStatsControllerCore extends AdminStatsTabController : Configuration::get('CONF_'.strtoupper($order['module']).'_VAR_FOREIGN') ) / 100; - // Add shipping fees for this order - $shipping_fees = $order['total_shipping_tax_excl'] * ( - $order['id_country'] == Configuration::get('PS_COUNTRY_DEFAULT') - ? Configuration::get('CONF_'.strtoupper($order['carrier_reference']).'_SHIP') - : Configuration::get('CONF_'.strtoupper($order['carrier_reference']).'_SHIP_OVERSEAS') - ) / 100; - // Tally up these fees if ($granularity == 'day') { if (!isset($expenses[strtotime($order['date'])])) { $expenses[strtotime($order['date'])] = 0; } - $expenses[strtotime($order['date'])] += $flat_fees + $var_fees + $shipping_fees; + $expenses[strtotime($order['date'])] += $flat_fees + $var_fees; } else { - $expenses += $flat_fees + $var_fees + $shipping_fees; + $expenses += $flat_fees + $var_fees; } } return $expenses; @@ -721,41 +714,11 @@ class AdminStatsControllerCore extends AdminStatsTabController break; case 'frontoffice_translations': - $themes = Theme::getThemes(); - $languages = Language::getLanguages(); - $total = $translated = 0; - foreach ($themes as $theme) { - /** @var Theme $theme */ - foreach ($languages as $language) { - $kpi_key = substr(strtoupper($theme->name.'_'.$language['iso_code']), 0, 16); - $total += ConfigurationKPI::get('FRONTOFFICE_TRANSLATE_TOTAL_'.$kpi_key); - $translated += ConfigurationKPI::get('FRONTOFFICE_TRANSLATE_DONE_'.$kpi_key); - } - } - $value = 0; - if ($translated) { - $value = round(100 * $translated / $total, 1); - } - $value .= '%'; - ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATIONS', $value); - ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATIONS_EXPIRE', strtotime('+2 min')); + $value = self::getFrontOfficeTranslations(); break; case 'backoffice_translations': - $languages = Language::getLanguages(); - $total = $translated = 0; - foreach ($languages as $language) { - $kpi_key = substr(strtoupper($language['iso_code']), 0, 16); - $total += ConfigurationKPI::get('BACKOFFICE_TRANSLATE_TOTAL_'.$kpi_key); - $translated += ConfigurationKPI::get('BACKOFFICE_TRANSLATE_DONE_'.$kpi_key); - } - $value = 0; - if ($translated) { - $value = round(100 * $translated / $total, 1); - } - $value .= '%'; - ConfigurationKPI::updateValue('BACKOFFICE_TRANSLATIONS', $value); - ConfigurationKPI::updateValue('BACKOFFICE_TRANSLATIONS_EXPIRE', strtotime('+2 min')); + $value = self::getBackOfficeTranslations(); break; case 'main_country': @@ -857,6 +820,35 @@ class AdminStatsControllerCore extends AdminStatsTabController die(json_encode(array('has_errors' => true))); } + public static function getFrontOfficeTranslations() + { + $themes = Theme::getThemes(); + $languages = Language::getLanguages(); + $total = $translated = 0; + foreach ($themes as $theme) { + foreach ($languages as $language) { + $result = Translate::getTranslationsCountFrontOffice($theme->name, $language['iso_code']); + $total += $result['total']; + $translated += $result['translated']; + } + } + + return sprintf('%0.2f', $total ? ($translated / $total) * 100 : 0).'%'; + } + + public static function getBackOfficeTranslations() + { + $languages = Language::getLanguages(); + $total = $translated = 0; + foreach ($languages as $language) { + $result = Translate::getTranslationsCountBackOffice($language['iso_code']); + $total += $result['total']; + $translated += $result['translated']; + } + + return sprintf('%0.2f', $total ? ($translated / $total) * 100 : 0).'%'; + } + public static function getArrivalsByDate($date, $idHotel = false) { $totalArrivals = Db::getInstance()->getValue( @@ -1020,7 +1012,10 @@ class AdminStatsControllerCore extends AdminStatsTabController return $occupancyData; } - public static function getAvailabilityLineChartData($days, $dateFrom, $idHotel = null) // $dateFrom is inclusive + /** + * $dateFrom is inclusive + */ + public static function getAvailabilityLineChartData($days, $dateFrom, $idHotel = null) { if ($days == 0) { return array(); @@ -1041,33 +1036,49 @@ class AdminStatsControllerCore extends AdminStatsTabController return $availabilityData; } - public static function getAverageDailyRate($dateFrom, $dateTo, $idHotel = null) + public static function getAverageDailyRateForDiscreteDates($dateFrom, $dateTo, $idHotel = null) { if ($dateFrom == $dateTo) { $dateTo = date('Y-m-d', strtotime('+1 day', strtotime($dateTo))); } $occupiedRooms = self::getOccupiedRoomsForDiscreteDates($dateFrom, $dateTo, $idHotel); - $roomsRevenues = self::getRoomsRevenuesForDiscreteDates($dateFrom, $dateTo, $idHotel); + $roomsRevenues = self::getRoomsRevenueForDiscreteDates($dateFrom, $dateTo, $idHotel); if (count($occupiedRooms) != count($roomsRevenues)) { return false; } - $divisor = 0; - $sumADRs = 0; + $averageDailyRates = array(); foreach ($occupiedRooms as $key => $occupiedRoom) { - if ($occupiedRoom == 0) { - unset($occupiedRooms[$key]); - unset($roomsRevenues[$key]); - continue; - } - - $sumADRs += ($occupiedRoom ? ($roomsRevenues[$key] / $occupiedRoom) : 0); - $divisor++; + $averageDailyRates[$key] = $occupiedRoom ? $roomsRevenues[$key] / $occupiedRoom : 0; } - return Tools::displayPrice($divisor ? ($sumADRs / $divisor) : 0); + return $averageDailyRates; + } + + public static function getAverageDailyRate($dateFrom, $dateTo, $idHotel = null) + { + if ($dateFrom == $dateTo) { + $dateTo = date('Y-m-d', strtotime('+1 day', strtotime($dateTo))); + } + + $averageDailyRates = self::getAverageDailyRateForDiscreteDates($dateFrom, $dateTo, $idHotel); + + if (!is_array($averageDailyRates)) { + return 0; + } + + $sumAverageDailyRates = 0; + $countAverageDailyRates = 0; + foreach ($averageDailyRates as $averageDailyRate) { + if ($averageDailyRate != 0) { + $sumAverageDailyRates += $averageDailyRate; + $countAverageDailyRates++; + } + } + + return $countAverageDailyRates ? $sumAverageDailyRates / $countAverageDailyRates : 0; } public static function getCancellationRate($dateFrom, $dateTo, $idHotel = false) @@ -1092,9 +1103,9 @@ class AdminStatsControllerCore extends AdminStatsTabController ); if ($numAllOrders != 0) { - return Tools::ps_round(($numCancelledOrders / $numAllOrders) * 100, 2).'%'; + return $numCancelledOrders / $numAllOrders * 100; } else { - return '0.00%'; + return 0; } } @@ -1112,18 +1123,19 @@ class AdminStatsControllerCore extends AdminStatsTabController ) AS id_hotel FROM `'._DB_PREFIX_.'orders` o LEFT JOIN `' ._DB_PREFIX_.'order_return` orr ON orr.`id_order` = o.`id_order` - WHERE o.`invoice_date` BETWEEN "'.pSQL($dateFrom).' 00:00:00" AND "'.pSQL($dateTo).' 23:59:59" + WHERE o.`valid` = 1 AND o.`invoice_date` BETWEEN "'.pSQL($dateFrom).' 00:00:00" AND "'.pSQL($dateTo).' 23:59:59" HAVING 1 '.HotelBranchInformation::addHotelRestriction($idHotel).' ) AS t' ); - return Tools::displayPrice($result ? $result : 0); + return $result ? $result : 0; } public static function getNightsStayed($dateFrom, $dateTo, $idHotel = false) { $dateFrom = date('Y-m-d H:i:s', strtotime($dateFrom)); $dateTo = date('Y-m-d H:i:s', strtotime($dateTo)); + return Db::getInstance()->getValue( 'SELECT IFNULL(SUM(DATEDIFF( IF (hbd.`id_status` = '.(int) HotelBookingDetail::STATUS_CHECKED_OUT.', IF ("'.$dateTo.'" > check_out, check_out, "'.$dateTo.'"), IF ("'.$dateTo.'" > date_to, date_to, "'.$dateTo.'")), @@ -1134,8 +1146,7 @@ class AdminStatsControllerCore extends AdminStatsTabController (IF (hbd.`id_status` = '.(int) HotelBookingDetail::STATUS_CHECKED_OUT.', (hbd.`check_in` < \''.pSQL($dateTo).'\' AND hbd.`check_out` >= \''.pSQL($dateFrom).'\'), (hbd.`date_from` < \''.pSQL($dateTo).'\' AND hbd.`date_to` >= \''.pSQL($dateFrom).'\') - ))'. - HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') + ))'.HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') ); } @@ -1164,20 +1175,20 @@ class AdminStatsControllerCore extends AdminStatsTabController $dateTo = !$dateTo ? date('Y-m-d', strtotime('+1 day', strtotime($dateFrom))) : $dateTo; $discreteDates = array(); - $date = $dateFrom; - while ($date < $dateTo) { - $dateNext = date('Y-m-d', strtotime('+1 day', strtotime($date))); + $dateTemp = $dateFrom; + while ($dateTemp <= $dateTo) { + $dateNext = date('Y-m-d', strtotime('+1 day', strtotime($dateTemp))); $discreteDates[] = array( - 'date_from' => $date, + 'date_from' => $dateTemp, 'date_to' => $dateNext, - 'timestamp_from' => strtotime($date), + 'timestamp_from' => strtotime($dateTemp), ); - $date = $dateNext; + $dateTemp = $dateNext; }; $result = array(); foreach ($discreteDates as $discreteDate) { - $cacheKey = 'AdminStats::getOccupiedRoomsForDiscreteDates_'.(int) $discreteDate['timestamp_from'].'_'. + $cacheKey = 'AdminStats::getOccupiedRoomsForDiscreteDates'.'_'.(int) $discreteDate['timestamp_from'].'_'. (!is_array($idHotel) ? (int) $idHotel : implode('_', $idHotel)); if (!Cache::isStored($cacheKey) || !$useCache) { $sql = 'SELECT COUNT(DISTINCT hbd.`id_room`) @@ -1201,33 +1212,31 @@ class AdminStatsControllerCore extends AdminStatsTabController return $result; } - public static function getRoomsRevenuesForDiscreteDates($dateFrom, $dateTo = null, $idHotel = null, $useCache = true) + public static function getRoomsRevenueForDiscreteDates($dateFrom, $dateTo = null, $idHotel = null, $useCache = true) { $dateTo = !$dateTo ? date('Y-m-d', strtotime('+1 day', strtotime($dateFrom))) : $dateTo; $discreteDates = array(); - $date = $dateFrom; - while ($date < $dateTo) { - $dateNext = date('Y-m-d', strtotime('+1 day', strtotime($date))); + $dateTemp = $dateFrom; + while ($dateTemp <= $dateTo) { + $dateNext = date('Y-m-d', strtotime('+1 day', strtotime($dateTemp))); $discreteDates[] = array( - 'date_from' => $date, + 'date_from' => $dateTemp, 'date_to' => $dateNext, - 'timestamp_from' => strtotime($date), + 'timestamp_from' => strtotime($dateTemp), ); - $date = $dateNext; + $dateTemp = $dateNext; }; $result = array(); foreach ($discreteDates as $discreteDate) { - $cacheKey = 'AdminStats::getRoomsRevenuesForDiscreteDates'.(int) $discreteDate['timestamp_from'].'_'. + $cacheKey = 'AdminStats::getRoomsRevenueForDiscreteDates'.'_'.(int) $discreteDate['timestamp_from'].'_'. (!is_array($idHotel) ? (int) $idHotel : implode('_', $idHotel)); if (!Cache::isStored($cacheKey) || !$useCache) { $sql = 'SELECT IFNULL(SUM(hbd.`total_price_tax_excl` / DATEDIFF(hbd.`date_to`, hbd.`date_from`)), 0) FROM `'._DB_PREFIX_.'htl_booking_detail` hbd - LEFT JOIN `'._DB_PREFIX_.'htl_room_information` hri - ON (hri.`id` = hbd.`id_room`) LEFT JOIN `'._DB_PREFIX_.'product` p - ON (p.`id_product` = hri.`id_product`) + ON (p.`id_product` = hbd.`id_product`) WHERE p.`active` = 1 AND hbd.`is_refunded` = 0 AND hbd.`date_from` < "'.pSQL($discreteDate['date_to']).' 00:00:00" AND hbd.`date_to` > "'.pSQL($discreteDate['date_from']).' 00:00:00"'. @@ -1243,24 +1252,166 @@ class AdminStatsControllerCore extends AdminStatsTabController return $result; } - public static function getAvailableRoomsForDiscreteDates($dateFrom, $dateTo = null, $idHotel = null, $useCache = true) + public static function getTotalRevenueForDiscreteDates($dateFrom, $dateTo = null, $idHotel = null, $useCache = true) { $dateTo = !$dateTo ? date('Y-m-d', strtotime('+1 day', strtotime($dateFrom))) : $dateTo; + $discreteDates = array(); - $date = $dateFrom; - while ($date < $dateTo) { - $dateNext = date('Y-m-d', strtotime('+1 day', strtotime($date))); + $dateTemp = $dateFrom; + while ($dateTemp <= $dateTo) { + $dateNext = date('Y-m-d', strtotime('+1 day', strtotime($dateTemp))); $discreteDates[] = array( - 'date_from' => $date, + 'date_from' => $dateTemp, 'date_to' => $dateNext, - 'timestamp_from' => strtotime($date), + 'timestamp_from' => strtotime($dateTemp), ); - $date = $dateNext; + $dateTemp = $dateNext; }; $result = array(); foreach ($discreteDates as $discreteDate) { - $cacheKey = 'AdminStats::getAvailableRoomsForDiscreteDates'.(int) $discreteDate['timestamp_from'].'_'. + $cacheKey = 'AdminStats::getTotalRevenueForDiscreteDates'.'_'.(int) $discreteDate['timestamp_from'].'_'. + (!is_array($idHotel) ? (int) $idHotel : implode('_', $idHotel)); + if (!Cache::isStored($cacheKey) || !$useCache) { + $sql = 'SELECT SUM((current_parts / total_parts) * total_paid_tax_excl) AS total_revenue + FROM ( + SELECT o.`id_order`, + o.`total_paid_tax_excl` / o.`conversion_rate` AS total_paid_tax_excl, + ( + SELECT SUM(DATEDIFF(hbd.`date_to`, hbd.`date_from`)) + FROM `'._DB_PREFIX_.'htl_booking_detail` hbd + INNER JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hbd.`id_product`) + WHERE hbd.`id_order` = o.`id_order` + AND p.`active` = 1 AND hbd.`is_refunded` = 0'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') : '').' + ) AS total_parts, + ( + SELECT COUNT(*) + FROM `'._DB_PREFIX_.'htl_booking_detail` hbd + INNER JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hbd.`id_product`) + WHERE hbd.`id_order` = o.`id_order` + AND hbd.`date_from` <= "'.pSQL($discreteDate['date_from']).' 00:00:00" AND hbd.`date_to` >= "'.pSQL($discreteDate['date_to']).' 00:00:00" + AND p.`active` = 1 AND hbd.`is_refunded` = 0'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') : '').' + ) AS current_parts + FROM `'._DB_PREFIX_.'orders` o + HAVING total_parts IS NOT NULL AND current_parts > 0 + ORDER BY o.`id_order` + ) AS t'; + + $value = Db::getInstance()->getValue($sql); + $value = !$value ? 0: (float) $value; + Cache::store($cacheKey, $value); + } + + $result[$discreteDate['timestamp_from']] = Cache::retrieve($cacheKey); + } + + return $result; + } + + /** + * total rooms (available for booking) for each date + */ + public static function getTotalRoomsForDiscreteDates($dateFrom, $dateTo = null, $idHotel = null, $useCache = true) + { + $dateTo = !$dateTo ? date('Y-m-d', strtotime('+1 day', strtotime($dateFrom))) : $dateTo; + + $discreteDates = array(); + $dateTemp = $dateFrom; + while ($dateTemp <= $dateTo) { + $dateNext = date('Y-m-d', strtotime('+1 day', strtotime($dateTemp))); + $discreteDates[] = array( + 'date_from' => $dateTemp, + 'date_to' => $dateNext, + 'timestamp_from' => strtotime($dateTemp), + ); + $dateTemp = $dateNext; + }; + + $result = array(); + foreach ($discreteDates as $discreteDate) { + $cacheKey = 'AdminStats::getTotalRoomsForDiscreteDates'.'_'.(int) $discreteDate['timestamp_from'].'_'. + (!is_array($idHotel) ? (int) $idHotel : implode('_', $idHotel)); + if (!Cache::isStored($cacheKey) || !$useCache) { + $sql = 'SELECT (num_total_added - num_inactive - num_temporarily_inactive) AS num_total + FROM ( + SELECT ( + SELECT IFNULL(COUNT(hri.`id`), 0) + FROM `'._DB_PREFIX_.'htl_room_information` hri + LEFT JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hri.`id_product`) + WHERE p.`active` = 1'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hri') : '').' + ) AS num_total_added, + ( + SELECT COUNT(DISTINCT hbd.`id_room`) + FROM `'._DB_PREFIX_.'htl_booking_detail` hbd + LEFT JOIN `'._DB_PREFIX_.'htl_room_information` hri + ON (hri.`id` = hbd.`id_room`) + LEFT JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hri.`id_product`) + WHERE p.`active` = 1 + AND hbd.`is_refunded` = 0 + AND hbd.`date_from` < "'.pSQL($discreteDate['date_to']).' 00:00:00" AND hbd.`date_to` > "'.pSQL($discreteDate['date_from']).' 00:00:00"'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') : '').' + ) AS num_booked, + ( + SELECT IFNULL(COUNT(hri.`id`), 0) + FROM `'._DB_PREFIX_.'htl_room_information` hri + LEFT JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hri.`id_product`) + WHERE hri.`id_status` = '.(int) HotelRoomInformation::STATUS_INACTIVE.' + AND p.`active` = 1'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hri') : '').' + ) AS num_inactive, + ( + SELECT IFNULL(COUNT(hri.`id`), 0) + FROM `'._DB_PREFIX_.'htl_room_information` hri + LEFT JOIN `'._DB_PREFIX_.'htl_room_disable_dates` hrdd + ON (hrdd.`id_room` = hri.`id`) + LEFT JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hri.`id_product`) + WHERE hri.`id_status` = '.(int) HotelRoomInformation::STATUS_TEMPORARY_INACTIVE.' + AND ("'.pSQL($discreteDate['date_from']).'" >= hrdd.`date_from` AND "'.pSQL($discreteDate['date_from']).'" < hrdd.`date_to`) + AND p.`active` = 1'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hri') : '').' + ) AS num_temporarily_inactive + ) AS t'; + + $value = Db::getInstance()->getValue($sql); + Cache::store($cacheKey, $value); + } + + $result[$discreteDate['timestamp_from']] = Cache::retrieve($cacheKey); + } + + return $result; + } + + /** + * total available (unoccupied) for each date + */ + public static function getAvailableRoomsForDiscreteDates($dateFrom, $dateTo = null, $idHotel = null, $useCache = true) + { + $dateTo = !$dateTo ? date('Y-m-d', strtotime('+1 day', strtotime($dateFrom))) : $dateTo; + $discreteDates = array(); + $dateTemp = $dateFrom; + while ($dateTemp <= $dateTo) { + $dateNext = date('Y-m-d', strtotime('+1 day', strtotime($dateTemp))); + $discreteDates[] = array( + 'date_from' => $dateTemp, + 'date_to' => $dateNext, + 'timestamp_from' => strtotime($dateTemp), + ); + $dateTemp = $dateNext; + }; + + $result = array(); + foreach ($discreteDates as $discreteDate) { + $cacheKey = 'AdminStats::getAvailableRoomsForDiscreteDates'.'_'.(int) $discreteDate['timestamp_from'].'_'. (!is_array($idHotel) ? (int) $idHotel : implode('_', $idHotel)); if (!Cache::isStored($cacheKey) || !$useCache) { $sql = 'SELECT (num_total - num_booked - num_inactive - num_temporarily_inactive) AS num_available @@ -1317,4 +1468,242 @@ class AdminStatsControllerCore extends AdminStatsTabController return $result; } + + public static function getOccupancyRateForDiscreteDates($dateFrom, $dateTo, $idHotel = null) + { + if ($dateFrom == $dateTo) { + $dateTo = date('Y-m-d', strtotime('+1 day', strtotime($dateTo))); + } + + $occupiedRooms = self::getOccupiedRoomsForDiscreteDates($dateFrom, $dateTo, $idHotel); + $totalRooms = self::getTotalRoomsForDiscreteDates($dateFrom, $dateTo, $idHotel); + + if (count($occupiedRooms) != count($totalRooms)) { + return false; + } + + $occupancyRates = array(); + foreach ($totalRooms as $key => $totalRoom) { + $occupancyRates[$key] = $totalRoom ? $occupiedRooms[$key] / $totalRoom : 0; + } + + return $occupancyRates; + } + + public static function getAverageOccupancyRate($dateFrom, $dateTo, $idHotel = null) + { + if ($dateFrom == $dateTo) { + $dateTo = date('Y-m-d', strtotime('+1 day', strtotime($dateTo))); + } + + $occupancyRates = self::getOccupancyRateForDiscreteDates($dateFrom, $dateTo, $idHotel); + + if (!is_array($occupancyRates)) { + return 0; + } + + return array_sum($occupancyRates) / count($occupancyRates); + } + + public static function getRevenuePerAvailableRoom($dateFrom, $dateTo, $idHotel = null) + { + if ($dateFrom == $dateTo) { + $dateTo = date('Y-m-d', strtotime('+1 day', strtotime($dateTo))); + } + + $averageDailyRates = self::getAverageDailyRateForDiscreteDates($dateFrom, $dateTo, $idHotel); + $occupancyRates = self::getOccupancyRateForDiscreteDates($dateFrom, $dateTo, $idHotel); + + if (count($averageDailyRates) != count($occupancyRates)) { + return false; + } + + $sumRevPars = 0; + $countRevPars = 0; + foreach ($averageDailyRates as $key => $averageDailyRate) { + if ($averageDailyRate != 0) { + $sumRevPars += ($averageDailyRate * $occupancyRates[$key]); + $countRevPars++; + } + } + + return $countRevPars ? $sumRevPars / $countRevPars : 0; + } + + public static function getTotalRevenuePerAvailableRoom($dateFrom, $dateTo, $idHotel = null) + { + if ($dateFrom == $dateTo) { + $dateTo = date('Y-m-d', strtotime('+1 day', strtotime($dateTo))); + } + + $totalRevenues = self::getTotalRevenueForDiscreteDates($dateFrom, $dateTo, $idHotel); + $totalRooms = self::getTotalRoomsForDiscreteDates($dateFrom, $dateTo, $idHotel); + + if (count($totalRevenues) != count($totalRooms)) { + return false; + } + + $sumTrevPars = 0; + $countTrevPars = 0; + foreach ($totalRevenues as $key => $totalRevenue) { + if ($totalRevenue != 0) { + $sumTrevPars += ($totalRevenue / $totalRooms[$key]); + $countTrevPars++; + } + } + + return $countTrevPars ? $sumTrevPars / $countTrevPars : 0; + } + + public static function getAverageLengthOfStay($dateFrom, $dateTo, $idHotel = null) + { + if ($dateFrom == $dateTo) { + $dateTo = date('Y-m-d', strtotime('+1 day', strtotime($dateTo))); + } + + $sql = 'SELECT AVG(DATEDIFF(hbd.`date_to`, hbd.`date_from`)) + FROM `'._DB_PREFIX_.'htl_booking_detail` hbd + LEFT JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hbd.`id_product`) + WHERE p.`active` = 1 + AND hbd.`is_refunded` = 0 + AND hbd.`date_from` < "'.pSQL($dateTo).' 00:00:00" AND hbd.`date_to` > "'.pSQL($dateFrom).' 00:00:00"'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') : ''); + $result = Db::getInstance()->getValue($sql); + + return $result ? $result : 0; + } + + public static function getDirectRevenueRatio($dateFrom, $dateTo, $idHotel = null) + { + if ($dateFrom == $dateTo) { + $dateTo = date('Y-m-d', strtotime('+1 day', strtotime($dateTo))); + } + + $sql = 'SELECT SUM(total_paid_tax_excl) + FROM ( + SELECT o.`id_order`, o.`total_paid_tax_excl` / o.`conversion_rate` AS total_paid_tax_excl, + (SELECT hbd.`id_hotel` + FROM `'._DB_PREFIX_.'htl_booking_detail` hbd + WHERE hbd.`id_order` = o.`id_order` LIMIT 1 + ) AS id_hotel + FROM `'._DB_PREFIX_.'orders` o + INNER JOIN `'._DB_PREFIX_.'htl_booking_detail` hbd + ON (hbd.`id_order` = o.`id_order`) + INNER JOIN `'._DB_PREFIX_.'htl_branch_info` hbi + ON (hbi.`id` = hbd.`id_hotel`) + WHERE o.`valid` = 1 AND hbi.`active` = 1 AND hbd.`is_refunded` = 0 + AND o.`invoice_date` BETWEEN "'.pSQL($dateFrom).' 00:00:00" AND "'.pSQL($dateTo).' 23:59:59" + AND o.`source` = "'.pSQL(Configuration::get('PS_SHOP_DOMAIN')).'"'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') : ''). + 'GROUP BY o.`id_order` + ) AS t'; + $directRevenue = (float) Db::getInstance()->getValue($sql); + + $totalRevenue = (float) self::getRevenue($dateFrom, $dateTo, $idHotel); + + return $totalRevenue ? ($directRevenue / $totalRevenue) * 100 : 0; + } + + public static function getOperatingExpensesForDiscreteDates($dateFrom, $dateTo = null, $idHotel = null, $useCache = true) + { + $dateTo = !$dateTo ? date('Y-m-d', strtotime('+1 day', strtotime($dateFrom))) : $dateTo; + + $discreteDates = array(); + $dateTemp = $dateFrom; + while ($dateTemp <= $dateTo) { + $dateNext = date('Y-m-d', strtotime('+1 day', strtotime($dateTemp))); + $discreteDates[] = array( + 'date_from' => $dateTemp, + 'date_to' => $dateNext, + 'timestamp_from' => strtotime($dateTemp), + ); + $dateTemp = $dateNext; + }; + + $result = array(); + foreach ($discreteDates as $discreteDate) { + $cacheKey = 'AdminStats::getOperatingExpensesForDiscreteDates'.'_'.(int) $discreteDate['timestamp_from'].'_'. + (!is_array($idHotel) ? (int) $idHotel : implode('_', $idHotel)); + if (!Cache::isStored($cacheKey) || !$useCache) { + $sql = 'SELECT + IFNULL(SUM( + CASE + WHEN od.`original_wholesale_price` <> "0.000000" + THEN od.`original_wholesale_price` + WHEN p.`wholesale_price` <> "0.000000" + THEN p.`wholesale_price` + END + ), 0) + FROM `'._DB_PREFIX_.'htl_booking_detail` hbd + LEFT JOIN `'._DB_PREFIX_.'product` p + ON (p.`id_product` = hbd.`id_product`) + LEFT JOIN `'._DB_PREFIX_.'order_detail` od + ON (od.`id_order_detail` = hbd.`id_order_detail`) + WHERE p.`active` = 1 + AND hbd.`is_refunded` = 0 + AND hbd.`date_from` < "'.pSQL($discreteDate['date_to']).' 00:00:00" AND hbd.`date_to` > "'.pSQL($discreteDate['date_from']).' 00:00:00"'. + (!is_null($idHotel) ? HotelBranchInformation::addHotelRestriction($idHotel, 'hbd') : ''); + + $value = Db::getInstance()->getValue($sql); + Cache::store($cacheKey, $value); + } + + $result[$discreteDate['timestamp_from']] = Cache::retrieve($cacheKey); + } + + return $result; + } + + public static function getGrossOperatingProfitPerAvailableRoomForDiscreteDates($dateFrom, $dateTo, $idHotel = null) + { + if ($dateFrom == $dateTo) { + $dateTo = date('Y-m-d', strtotime('+1 day', strtotime($dateTo))); + } + + $roomsRevenues = self::getRoomsRevenueForDiscreteDates($dateFrom, $dateTo, $idHotel); + $operatingExpenses = self::getOperatingExpensesForDiscreteDates($dateFrom, $dateTo, $idHotel); + $totalRooms = self::getTotalRoomsForDiscreteDates($dateFrom, $dateTo, $idHotel); + + if (!(count($roomsRevenues) == count($operatingExpenses) + && count($operatingExpenses) == count($totalRooms)) + ) { + return false; + } + + $operatingProfits = array(); + foreach ($roomsRevenues as $key => $roomsRevenue) { + if ($roomsRevenue != 0 && $totalRooms[$key] != 0) { + $operatingProfits[$key] = (($roomsRevenue - $operatingExpenses[$key]) / $totalRooms[$key]); + } else { + $operatingProfits[$key] = 0; + } + } + + return $operatingProfits; + } + + public static function getGrossOperatingProfitPerAvailableRoom($dateFrom, $dateTo, $idHotel = null) + { + if ($dateFrom == $dateTo) { + $dateTo = date('Y-m-d', strtotime('+1 day', strtotime($dateTo))); + } + + $grossOpProfitPars = self::getGrossOperatingProfitPerAvailableRoomForDiscreteDates($dateFrom, $dateTo, $idHotel); + + if (!count($grossOpProfitPars)) { + return false; + } + + $sumGrossOpProfitPars = 0; + $countGrossOpProfitPars = 0; + foreach ($grossOpProfitPars as $grossOpProfitPar) { + if ($grossOpProfitPar != 0) { + $sumGrossOpProfitPars += $grossOpProfitPar; + $countGrossOpProfitPars++; + } + } + + return $countGrossOpProfitPars ? $sumGrossOpProfitPars / $countGrossOpProfitPars : 0; + } } diff --git a/controllers/admin/AdminStatsTabController.php b/controllers/admin/AdminStatsTabController.php index 72c2b2e85..3a369c51c 100644 --- a/controllers/admin/AdminStatsTabController.php +++ b/controllers/admin/AdminStatsTabController.php @@ -104,6 +104,7 @@ abstract class AdminStatsTabControllerCore extends AdminPreferencesControllerCor $module = Tools::getValue('module'); $action .= ($module ? '&module='.Tools::safeOutput($module) : ''); $action .= (($id_product = Tools::getValue('id_product')) ? '&id_product='.Tools::safeOutput($id_product) : ''); + $action .= (($id_hotel = Tools::getValue('id_hotel')) ? '&id_hotel='.Tools::safeOutput($id_hotel) : ''); $tpl->assign(array( 'current' => self::$currentIndex, 'token' => $token, @@ -150,13 +151,8 @@ abstract class AdminStatsTabControllerCore extends AdminPreferencesControllerCor $tpl = $this->createTemplate('menu.tpl'); $modules = $this->getModules(); - $key_statsforecast = null; $module_instance = array(); foreach ($modules as $m => $module) { - if ($module['name'] == 'statsforecast') { - $key_statsforecast = $m; - } - if ($module_instance[$module['name']] = Module::getInstanceByName($module['name'])) { $modules[$m]['displayName'] = $module_instance[$module['name']]->displayName; } else { @@ -166,9 +162,6 @@ abstract class AdminStatsTabControllerCore extends AdminPreferencesControllerCor } uasort($modules, array($this, 'checkModulesNames')); - if (!is_null($key_statsforecast)) { - $modules = array($key_statsforecast => $modules[$key_statsforecast]) + $modules; - } $tpl->assign(array( 'current' => self::$currentIndex, diff --git a/controllers/admin/AdminTranslationsController.php b/controllers/admin/AdminTranslationsController.php index 87f8e3f5e..3ad0893ad 100644 --- a/controllers/admin/AdminTranslationsController.php +++ b/controllers/admin/AdminTranslationsController.php @@ -45,9 +45,6 @@ class AdminTranslationsControllerCore extends AdminController /** @var array */ protected $modules_translations = array(); - /** @var array : List of folder which must be ignored */ - protected static $ignore_folder = array('.', '..', '.svn', '.git', '.htaccess', 'index.php'); - /** @var array : List of theme by translation type : FRONT, BACK, ERRORS... */ protected $translations_informations = array(); @@ -320,23 +317,6 @@ class AdminTranslationsControllerCore extends AdminController } } - if (in_array($this->type_selected, array('front', 'back'))) { - if ($this->type_selected == 'front') { - $thm_name = str_replace('.', '', Tools::getValue('theme')); - $kpi_key = substr(strtoupper($thm_name.'_'.Tools::getValue('lang')), 0, 16); - - ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATIONS_EXPIRE', time()); - ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATE_TOTAL_'.$kpi_key, count($_POST)); - ConfigurationKPI::updateValue('FRONTOFFICE_TRANSLATE_DONE_'.$kpi_key, count($to_insert)); - } else { - $kpi_key = substr(strtoupper(Tools::getValue('lang')), 0, 16); - - ConfigurationKPI::updateValue('BACKOFFICE_TRANSLATIONS_EXPIRE', time()); - ConfigurationKPI::updateValue('BACKOFFICE_TRANSLATE_TOTAL_'.$kpi_key, count($_POST)); - ConfigurationKPI::updateValue('BACKOFFICE_TRANSLATE_DONE_'.$kpi_key, count($to_insert)); - } - } - // translations array is ordered by key (easy merge) ksort($to_insert); $tab = $translation_informations['var']; @@ -546,7 +526,7 @@ class AdminTranslationsControllerCore extends AdminController // Add mails files foreach ($arr_mails_needed as $mail_to_add) { - if (!in_array($mail_to_add, self::$ignore_folder)) { + if (!in_array($mail_to_add, Translate::$ignore_folder)) { @copy(_PS_MAIL_DIR_.$default_language.'/'.$mail_to_add, _PS_MAIL_DIR_.$iso_code.'/'.$mail_to_add); } } @@ -558,11 +538,11 @@ class AdminTranslationsControllerCore extends AdminController $module_mail_iso_code = array(); foreach ($modules as $module) { - if (!in_array($module, self::$ignore_folder) && Tools::file_exists_cache(_PS_MODULE_DIR_.$module.'/mails/'.$default_language.'/')) { + if (!in_array($module, Translate::$ignore_folder) && Tools::file_exists_cache(_PS_MODULE_DIR_.$module.'/mails/'.$default_language.'/')) { $arr_files = scandir(_PS_MODULE_DIR_.$module.'/mails/'.$default_language.'/'); foreach ($arr_files as $file) { - if (!in_array($file, self::$ignore_folder)) { + if (!in_array($file, Translate::$ignore_folder)) { if (Tools::file_exists_cache(_PS_MODULE_DIR_.$module.'/mails/'.$default_language.'/'.$file)) { $module_mail_en[] = _PS_MODULE_DIR_.$module.'/mails/ISO_CODE/'.$file; } @@ -973,7 +953,7 @@ class AdminTranslationsControllerCore extends AdminController } foreach ($files as $file) { - if (preg_match('/^(.*)\.(tpl|php)$/', $file) && Tools::file_exists_cache($dir.$file) && !in_array($file, self::$ignore_folder)) { + if (preg_match('/^(.*)\.(tpl|php)$/', $file) && Tools::file_exists_cache($dir.$file) && !in_array($file, Translate::$ignore_folder)) { // Get content for this file $content = file_get_contents($dir.$file); @@ -981,7 +961,7 @@ class AdminTranslationsControllerCore extends AdminController $type_file = substr($file, -4) == '.tpl' ? 'tpl' : 'php'; // Parse this content - $matches = $this->userParseFile($content, $this->type_selected, $type_file, $module_name); + $matches = Translate::userParseFile($content, $this->type_selected, $type_file, $module_name); // Write each translation on its module file $template_name = substr(basename($file), 0, -4); @@ -1076,7 +1056,7 @@ class AdminTranslationsControllerCore extends AdminController $type_file = substr($file, -4) == '.tpl' ? 'tpl' : 'php'; // Parse this content - $matches = $this->userParseFile($content, $this->type_selected, $type_file, $module_name); + $matches = Translate::userParseFile($content, $this->type_selected, $type_file, $module_name); // Write each translation on its module file $template_name = substr(basename($file), 0, -4); @@ -1099,7 +1079,7 @@ class AdminTranslationsControllerCore extends AdminController $this->modules_translations[$theme_name][$module_name][$template_name][$key]['trad'] = ''; $this->missing_translations++; } - $this->modules_translations[$theme_name][$module_name][$template_name][$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key); + $this->modules_translations[$theme_name][$module_name][$template_name][$key]['use_sprintf'] = Translate::checkIfKeyUseSprintf($key); } } } @@ -1118,14 +1098,14 @@ class AdminTranslationsControllerCore extends AdminController switch ($this->type_selected) { case 'front': $directories['tpl'] = array(_PS_ALL_THEMES_DIR_ => scandir(_PS_ALL_THEMES_DIR_)); - self::$ignore_folder[] = 'modules'; - $directories['tpl'] = array_merge($directories['tpl'], $this->listFiles(_PS_THEME_SELECTED_DIR_)); + Translate::$ignore_folder[] = 'modules'; + $directories['tpl'] = array_merge($directories['tpl'], Translate::listFiles(_PS_THEME_SELECTED_DIR_)); if (isset($directories['tpl'][_PS_THEME_SELECTED_DIR_.'pdf/'])) { unset($directories['tpl'][_PS_THEME_SELECTED_DIR_.'pdf/']); } if (Tools::file_exists_cache(_PS_THEME_OVERRIDE_DIR_)) { - $directories['tpl'] = array_merge($directories['tpl'], $this->listFiles(_PS_THEME_OVERRIDE_DIR_)); + $directories['tpl'] = array_merge($directories['tpl'], Translate::listFiles(_PS_THEME_OVERRIDE_DIR_)); } break; @@ -1139,7 +1119,7 @@ class AdminTranslationsControllerCore extends AdminController _PS_CLASS_DIR_.'controller/' => array('AdminController.php'), _PS_CLASS_DIR_ => array('PaymentModule.php') ), - 'tpl' => $this->listFiles(_PS_ADMIN_DIR_.DIRECTORY_SEPARATOR.'themes/'), + 'tpl' => Translate::listFiles(_PS_ADMIN_DIR_.DIRECTORY_SEPARATOR.'themes/'), 'specific' => array( _PS_ADMIN_DIR_.DIRECTORY_SEPARATOR => array( 'header.inc.php', @@ -1152,7 +1132,7 @@ class AdminTranslationsControllerCore extends AdminController // For translate the template which are overridden if (file_exists(_PS_OVERRIDE_DIR_.'controllers'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'templates')) { - $directories['tpl'] = array_merge($directories['tpl'], $this->listFiles(_PS_OVERRIDE_DIR_.'controllers'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'templates')); + $directories['tpl'] = array_merge($directories['tpl'], Translate::listFiles(_PS_OVERRIDE_DIR_.'controllers'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'templates')); } break; @@ -1168,12 +1148,12 @@ class AdminTranslationsControllerCore extends AdminController ); // Get all files for folders classes/ and override/classes/ recursively - $directories['php'] = array_merge($directories['php'], $this->listFiles(_PS_CLASS_DIR_, array(), 'php')); - $directories['php'] = array_merge($directories['php'], $this->listFiles(_PS_OVERRIDE_DIR_.'classes/', array(), 'php')); + $directories['php'] = array_merge($directories['php'], Translate::listFiles(_PS_CLASS_DIR_, array(), 'php')); + $directories['php'] = array_merge($directories['php'], Translate::listFiles(_PS_OVERRIDE_DIR_.'classes/', array(), 'php')); break; case 'fields': - $directories['php'] = $this->listFiles(_PS_CLASS_DIR_, array(), 'php'); + $directories['php'] = Translate::listFiles(_PS_CLASS_DIR_, array(), 'php'); break; case 'pdf': @@ -1203,8 +1183,8 @@ class AdminTranslationsControllerCore extends AdminController ); // Get all files for folders classes/ and override/classes/ recursively - $directories['php'] = array_merge($directories['php'], $this->listFiles(_PS_CLASS_DIR_, array(), 'php')); - $directories['php'] = array_merge($directories['php'], $this->listFiles(_PS_OVERRIDE_DIR_.'classes/', array(), 'php')); + $directories['php'] = array_merge($directories['php'], Translate::listFiles(_PS_CLASS_DIR_, array(), 'php')); + $directories['php'] = array_merge($directories['php'], Translate::listFiles(_PS_OVERRIDE_DIR_.'classes/', array(), 'php')); $directories['php'] = array_merge($directories['php'], $this->getModulesHasMails()); break; @@ -1213,88 +1193,6 @@ class AdminTranslationsControllerCore extends AdminController return $directories; } - /** - * This method parse a file by type of translation and type file - * - * @param $content - * @param $type_translation : front, back, errors, modules... - * @param string|bool $type_file : (tpl|php) - * @param string $module_name : name of the module - * @return array - */ - protected function userParseFile($content, $type_translation, $type_file = false, $module_name = '') - { - switch ($type_translation) { - case 'front': - // Parsing file in Front office - $regex = '/\{l\s*s=([\'\"])'._PS_TRANS_PATTERN_.'\1(\s*sprintf=.*)?(\s*js=1)?\s*\}/U'; - break; - - case 'back': - // Parsing file in Back office - if ($type_file == 'php') { - $regex = '/this->l\((\')'._PS_TRANS_PATTERN_.'\'[\)|\,]/U'; - } elseif ($type_file == 'specific') { - $regex = '/Translate::getAdminTranslation\((\')'._PS_TRANS_PATTERN_.'\'(?:,.*)*\)/U'; - } else { - $regex = '/\{l\s*s\s*=([\'\"])'._PS_TRANS_PATTERN_.'\1(\s*sprintf=.*)?(\s*js=1)?(\s*slashes=1)?.*\}/U'; - } - break; - - case 'errors': - // Parsing file for all errors syntax - $regex = '/Tools::displayError\((\')'._PS_TRANS_PATTERN_.'\'(,\s*(.+))?\)/U'; - break; - - case 'modules': - // Parsing modules file - if ($type_file == 'php') { - $regex = '/->l\((\')'._PS_TRANS_PATTERN_.'\'(, ?\'(.+)\')?(, ?(.+))?\)/U'; - } else { - // In tpl file look for something that should contain mod='module_name' according to the documentation - $regex = '/\{l\s*s=([\'\"])'._PS_TRANS_PATTERN_.'\1.*\s+mod=\''.$module_name.'\'.*\}/U'; - } - break; - - case 'pdf': - // Parsing PDF file - if ($type_file == 'php') { - $regex = array( - '/HTMLTemplate.*::l\((\')'._PS_TRANS_PATTERN_.'\'[\)|\,]/U', - '/->l\((\')'._PS_TRANS_PATTERN_.'\'(, ?\'(.+)\')?(, ?(.+))?\)/U' - ); - } else { - $regex = '/\{l\s*s=([\'\"])'._PS_TRANS_PATTERN_.'\1(\s*sprintf=.*)?(\s*js=1)?(\s*pdf=\'true\')?\s*\}/U'; - } - break; - } - - if (!is_array($regex)) { - $regex = array($regex); - } - - $strings = array(); - foreach ($regex as $regex_row) { - $matches = array(); - $n = preg_match_all($regex_row, $content, $matches); - for ($i = 0; $i < $n; $i += 1) { - $quote = $matches[1][$i]; - $string = $matches[2][$i]; - - if ($quote === '"') { - // Escape single quotes because the core will do it when looking for the translation of this string - $string = str_replace('\'', '\\\'', $string); - // Unescape double quotes - $string = preg_replace('/\\\\+"/', '"', $string); - } - - $strings[] = $string; - } - } - - return array_unique($strings); - } - /** * Get all translations informations for all type of translations * @@ -1760,20 +1658,6 @@ class AdminTranslationsControllerCore extends AdminController return $return; } - /** - * Find sentence which use %d, %s, %%, %1$d, %1$s... - * - * @param $key : english sentence - * @return array|bool return list of matches - */ - public function checkIfKeyUseSprintf($key) - { - if (preg_match_all('#(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])#', $key, $matches)) { - return implode(', ', $matches[0]); - } - return false; - } - /** * This method generate the form for front translations */ @@ -1807,7 +1691,7 @@ class AdminTranslationsControllerCore extends AdminController $content = file_get_contents($file_path); // Parse this content - $matches = $this->userParseFile($content, $this->type_selected); + $matches = Translate::userParseFile($content, $this->type_selected); /* Get string translation */ foreach ($matches as $key) { @@ -1828,7 +1712,7 @@ class AdminTranslationsControllerCore extends AdminController } } } - $new_lang[$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key); + $new_lang[$key]['use_sprintf'] = Translate::checkIfKeyUseSprintf($key); } } @@ -1874,7 +1758,7 @@ class AdminTranslationsControllerCore extends AdminController foreach ($files_per_directory['php'] as $dir => $files) { foreach ($files as $file) { // Check if is a PHP file and if the override file exists - if (preg_match('/^(.*)\.php$/', $file) && Tools::file_exists_cache($file_path = $dir.$file) && !in_array($file, self::$ignore_folder)) { + if (preg_match('/^(.*)\.php$/', $file) && Tools::file_exists_cache($file_path = $dir.$file) && !in_array($file, Translate::$ignore_folder)) { $prefix_key = basename($file); // -4 becomes -14 to remove the ending "Controller.php" from the filename if (strpos($file, 'Controller.php') !== false) { @@ -1895,7 +1779,7 @@ class AdminTranslationsControllerCore extends AdminController $content = file_get_contents($file_path); // Parse this content - $matches = $this->userParseFile($content, $this->type_selected, 'php'); + $matches = Translate::userParseFile($content, $this->type_selected, 'php'); foreach ($matches as $key) { // Caution ! front has underscore between prefix key and md5, back has not @@ -1914,7 +1798,7 @@ class AdminTranslationsControllerCore extends AdminController } } } - $tabs_array[$prefix_key][$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key); + $tabs_array[$prefix_key][$key]['use_sprintf'] = Translate::checkIfKeyUseSprintf($key); } } } @@ -1922,14 +1806,14 @@ class AdminTranslationsControllerCore extends AdminController foreach ($files_per_directory['specific'] as $dir => $files) { foreach ($files as $file) { - if (Tools::file_exists_cache($file_path = $dir.$file) && !in_array($file, self::$ignore_folder)) { + if (Tools::file_exists_cache($file_path = $dir.$file) && !in_array($file, Translate::$ignore_folder)) { $prefix_key = 'index'; // Get content for this file $content = file_get_contents($file_path); // Parse this content - $matches = $this->userParseFile($content, $this->type_selected, 'specific'); + $matches = Translate::userParseFile($content, $this->type_selected, 'specific'); foreach ($matches as $key) { // Caution ! front has underscore between prefix key and md5, back has not @@ -1948,7 +1832,7 @@ class AdminTranslationsControllerCore extends AdminController } } } - $tabs_array[$prefix_key][$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key); + $tabs_array[$prefix_key][$key]['use_sprintf'] = Translate::checkIfKeyUseSprintf($key); } } } @@ -2000,7 +1884,7 @@ class AdminTranslationsControllerCore extends AdminController $content = file_get_contents($file_path); // Parse this content - $matches = $this->userParseFile($content, $this->type_selected, 'tpl'); + $matches = Translate::userParseFile($content, $this->type_selected, 'tpl'); /* Get string translation for each tpl file */ foreach ($matches as $english_string) { @@ -2025,7 +1909,7 @@ class AdminTranslationsControllerCore extends AdminController } } } - $new_lang[$english_string]['use_sprintf'] = $this->checkIfKeyUseSprintf($english_string); + $new_lang[$english_string]['use_sprintf'] = Translate::checkIfKeyUseSprintf($english_string); } } if (isset($tabs_array[$prefix_key])) { @@ -2098,15 +1982,15 @@ class AdminTranslationsControllerCore extends AdminController if ($modules = $this->getListModules()) { foreach ($modules as $module) { - if (is_dir(_PS_MODULE_DIR_.$module) && !in_array($module, self::$ignore_folder)) { - $file_by_directory['php'] = array_merge($file_by_directory['php'], $this->listFiles(_PS_MODULE_DIR_.$module.'/', array(), 'php')); + if (is_dir(_PS_MODULE_DIR_.$module) && !in_array($module, Translate::$ignore_folder)) { + $file_by_directory['php'] = array_merge($file_by_directory['php'], Translate::listFiles(_PS_MODULE_DIR_.$module.'/', array(), 'php')); } } } foreach ($file_by_directory['php'] as $dir => $files) { foreach ($files as $file) { - if (preg_match('/\.php$/', $file) && Tools::file_exists_cache($file_path = $dir.$file) && !in_array($file, self::$ignore_folder)) { + if (preg_match('/\.php$/', $file) && Tools::file_exists_cache($file_path = $dir.$file) && !in_array($file, Translate::$ignore_folder)) { if (!filesize($file_path)) { continue; } @@ -2115,7 +1999,7 @@ class AdminTranslationsControllerCore extends AdminController $content = file_get_contents($file_path); // Parse this content - $matches = $this->userParseFile($content, $this->type_selected); + $matches = Translate::userParseFile($content, $this->type_selected); foreach ($matches as $key) { if (array_key_exists(md5($key), $GLOBALS[$name_var])) { @@ -2126,7 +2010,7 @@ class AdminTranslationsControllerCore extends AdminController $count_empty[$key] = 1; } } - $string_to_translate[$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key); + $string_to_translate[$key]['use_sprintf'] = Translate::checkIfKeyUseSprintf($key); } } } @@ -2522,7 +2406,7 @@ class AdminTranslationsControllerCore extends AdminController { $arr_modules = array(); foreach (scandir($this->translations_informations['modules']['dir']) as $module_dir) { - if (!in_array($module_dir, self::$ignore_folder)) { + if (!in_array($module_dir, Translate::$ignore_folder)) { $dir = false; if ($this->theme_selected && Tools::file_exists_cache($this->translations_informations['modules']['override']['dir'].$module_dir.'/mails/')) { $dir = $this->translations_informations['modules']['override']['dir'].$module_dir.'/'; @@ -2555,7 +2439,7 @@ class AdminTranslationsControllerCore extends AdminController { $arr_modules = array(); foreach (scandir($this->translations_informations['modules']['dir']) as $module_dir) { - if (!in_array($module_dir, self::$ignore_folder)) { + if (!in_array($module_dir, Translate::$ignore_folder)) { $dir = false; if ($classes) { if ($this->theme_selected && Tools::file_exists_cache($this->translations_informations['modules']['override']['dir'].$module_dir.'/classes/')) { @@ -2622,7 +2506,7 @@ class AdminTranslationsControllerCore extends AdminController foreach ($files_by_directiories['php'] as $dir => $files) { foreach ($files as $file) { // If file exist and is not in ignore_folder, in the next step we check if a folder or mail - if (Tools::file_exists_cache($dir.$file) && !in_array($file, self::$ignore_folder)) { + if (Tools::file_exists_cache($dir.$file) && !in_array($file, Translate::$ignore_folder)) { $subject_mail = $this->getSubjectMail($dir, $file, $subject_mail); } } @@ -2693,7 +2577,7 @@ class AdminTranslationsControllerCore extends AdminController foreach ($dir_to_copy_iso as $dir) { foreach (scandir($dir) as $file) { - if (!in_array($file, self::$ignore_folder)) { + if (!in_array($file, Translate::$ignore_folder)) { $files_to_copy_iso[] = array( "from" => $dir.$file, "to" => str_replace((strpos($dir, _PS_CORE_DIR_) !== false) ? _PS_CORE_DIR_ : _PS_ROOT_DIR_, _PS_ROOT_DIR_.'/themes/'.$current_theme, $dir).$file @@ -2739,7 +2623,7 @@ class AdminTranslationsControllerCore extends AdminController { $dir = rtrim($dir, '/'); // If is file and is not in ignore_folder - if (is_file($dir.'/'.$file) && !in_array($file, self::$ignore_folder) && preg_match('/\.php$/', $file)) { + if (is_file($dir.'/'.$file) && !in_array($file, Translate::$ignore_folder) && preg_match('/\.php$/', $file)) { $content = file_get_contents($dir.'/'.$file); $content = str_replace("\n", ' ', $content); @@ -2764,7 +2648,7 @@ class AdminTranslationsControllerCore extends AdminController } } // Or if is folder, we scan folder for check if found in folder and subfolder - elseif (!in_array($file, self::$ignore_folder) && is_dir($dir.'/'.$file)) { + elseif (!in_array($file, Translate::$ignore_folder) && is_dir($dir.'/'.$file)) { foreach (scandir($dir.'/'.$file) as $temp) { if ($temp[0] != '.') { $subject_mail = $this->getSubjectMail($dir.'/'.$file, $temp, $subject_mail); @@ -2792,7 +2676,7 @@ class AdminTranslationsControllerCore extends AdminController $subject = str_replace("\\'", "\'", $subject); $subject_mail_content[$key]['trad'] = htmlentities($subject, ENT_QUOTES, 'UTF-8'); - $subject_mail_content[$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key); + $subject_mail_content[$key]['use_sprintf'] = Translate::checkIfKeyUseSprintf($key); } } else { $this->errors[] = sprintf($this->l('Email subject translation file not found in "%s".'), $directory); @@ -2976,7 +2860,7 @@ class AdminTranslationsControllerCore extends AdminController $content = file_get_contents($file_path); // Parse this content - $matches = $this->userParseFile($content, $this->type_selected, $file_type); + $matches = Translate::userParseFile($content, $this->type_selected, $file_type); foreach ($matches as $key) { if (stripslashes(array_key_exists($tab.md5(addslashes($key)), $lang_array))) { @@ -2989,7 +2873,7 @@ class AdminTranslationsControllerCore extends AdminController $count_missing[$tab]++; } } - $tabs_array[$tab][$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key); + $tabs_array[$tab][$key]['use_sprintf'] = Translate::checkIfKeyUseSprintf($key); } return $tabs_array; @@ -3034,14 +2918,14 @@ class AdminTranslationsControllerCore extends AdminController foreach ($files_by_directory as $type => $directories) { foreach ($directories as $dir => $files) { foreach ($files as $file) { - if (!in_array($file, self::$ignore_folder) && Tools::file_exists_cache($file_path = $dir.$file)) { + if (!in_array($file, Translate::$ignore_folder) && Tools::file_exists_cache($file_path = $dir.$file)) { if ($type == 'tpl') { if (Tools::file_exists_cache($file_path) && is_file($file_path)) { // Get content for this file $content = file_get_contents($file_path); // Parse this content - $matches = $this->userParseFile($content, $this->type_selected, 'tpl'); + $matches = Translate::userParseFile($content, $this->type_selected, 'tpl'); foreach ($matches as $key) { if (isset($GLOBALS[$name_var][$prefix_key.md5($key)])) { @@ -3056,7 +2940,7 @@ class AdminTranslationsControllerCore extends AdminController } } } - $tabs_array[$prefix_key][$key]['use_sprintf'] = $this->checkIfKeyUseSprintf($key); + $tabs_array[$prefix_key][$key]['use_sprintf'] = Translate::checkIfKeyUseSprintf($key); } } } elseif (Tools::file_exists_cache($file_path)) { @@ -3081,33 +2965,6 @@ class AdminTranslationsControllerCore extends AdminController return parent::renderView(); } - /** - * Recursively list files in directory $dir - * - * @param string $dir - * @param array $list - * @param string $file_ext - * - * @return array - */ - public function listFiles($dir, $list = array(), $file_ext = 'tpl') - { - $dir = rtrim($dir, '/').DIRECTORY_SEPARATOR; - - $to_parse = scandir($dir); - // copied (and kind of) adapted from AdminImages.php - foreach ($to_parse as $file) { - if (!in_array($file, self::$ignore_folder)) { - if (preg_match('#'.preg_quote($file_ext, '#').'$#i', $file)) { - $list[$dir][] = $file; - } elseif (is_dir($dir.$file)) { - $list = $this->listFiles($dir.$file, $list, $file_ext); - } - } - } - return $list; - } - /** * Checks if theme exists * diff --git a/install/data/xml/configuration.xml b/install/data/xml/configuration.xml index eaa524deb..f5651018c 100644 --- a/install/data/xml/configuration.xml +++ b/install/data/xml/configuration.xml @@ -605,28 +605,52 @@ 10 - + 100 - + 400 - + 1 - + 2 - + 1 - + 2 - + 1 - + + 3 + + + 100 + + + 400 + + + 1 + + + 2 + + + 1 + + + 2 + + + 1 + + 3 diff --git a/install/models/install.php b/install/models/install.php index a9d9e0ae2..a58a792c1 100644 --- a/install/models/install.php +++ b/install/models/install.php @@ -665,12 +665,12 @@ class InstallModelInstall extends InstallAbstractModel 'blocknavigationmenu', 'dashguestcycle', 'dashoccupancy', - 'dashavailability', - 'dashproducts', - 'dashtrends', - 'dashperformance', - 'dashgoals', 'dashactivity', + 'dashtrends', + 'dashavailability', + 'dashperformance', + 'dashproducts', + 'dashgoals', 'graphnvd3', 'statsdata', 'statsvisits', diff --git a/js/jquery/plugins/jquery.connections.js b/js/jquery/plugins/jquery.connections.js new file mode 100644 index 000000000..5cdb7b10c --- /dev/null +++ b/js/jquery/plugins/jquery.connections.js @@ -0,0 +1,251 @@ +(function($) { + $.fn.connections = function(options) { + if (options === "update") { + return processConnections(update, this); + } else if (options === "remove") { + return processConnections(destroy, this); + } else { + options = $.extend( + true, + { + borderClasses: {}, + class: "connection", + css: {}, + from: this, + tag: "connection", + to: this, + within: ":root" + }, + options + ); + connect(options); + return this; + } + }; + + $.event.special.connections = { + teardown: function(namespaces) { + processConnections(destroy, $(this)); + } + }; + + var connect = function(options) { + var borderClasses = options.borderClasses; + var tag = options.tag; + var end1 = $(options.from); + var end2 = $(options.to); + var within = $(options.within); + delete options.borderClasses; + delete options.tag; + delete options.from; + delete options.to; + delete options.within; + within.each(function() { + var container = this; + var done = new Array(); + end1.each(function() { + var node = this; + done.push(this); + end2.not(done).each(function() { + createConnection( + container, + [node, this], + tag, + borderClasses, + options + ); + }); + }); + }); + }; + + var createConnection = function( + container, + nodes, + tag, + borderClasses, + options + ) { + var css = $.extend({ position: "absolute" }, options.css); + var connection = $("<" + tag + "/>", options).css(css); + connection.appendTo(container); + + var border_w = (connection.outerWidth() - connection.innerWidth()) / 2; + var border_h = (connection.outerHeight() - connection.innerHeight()) / 2; + + if (border_w <= 0 && border_h <= 0) { + border_w = border_h = 1; + } + + var data = { + borderClasses: borderClasses, + border_h: border_h, + border_w: border_w, + node_from: $(nodes[0]), + node_to: $(nodes[1]), + nodes_dom: nodes, + css: css + }; + + if ("none" === connection.css("border-top-style")) { + data.css.borderStyle = "solid"; + } + $.data(connection.get(0), "connection", data); + $.data(connection.get(0), "connections", [connection.get(0)]); + for (var i = 0; i < 2; i++) { + var connections = connection.add($.data(nodes[i], "connections")).get(); + $.data(nodes[i], "connections", connections); + if (connections.length == 1) { + $(nodes[i]).on("connections.connections", false); + } + } + update(connection.get(0)); + }; + + var destroy = function(connection) { + var nodes = $.data(connection, "connection").nodes_dom; + for (var i = 0; i < 2; i++) { + var connections = $($.data(nodes[i], "connections")) + .not(connection) + .get(); + $.data(nodes[i], "connections", connections); + } + $(connection).remove(); + }; + + var getState = function(data) { + data.rect_from = data.nodes_dom[0].getBoundingClientRect(); + data.rect_to = data.nodes_dom[1].getBoundingClientRect(); + var cached = data.cache; + data.cache = [ + data.rect_from.top, + data.rect_from.right, + data.rect_from.bottom, + data.rect_from.left, + data.rect_to.top, + data.rect_to.right, + data.rect_to.bottom, + data.rect_to.left + ]; + data.hidden = + 0 === (data.cache[0] | data.cache[1] | data.cache[2] | data.cache[3]) || + 0 === (data.cache[4] | data.cache[5] | data.cache[6] | data.cache[7]); + data.unmodified = true; + if (cached === undefined) { + return (data.unmodified = false); + } + for (var i = 0; i < 8; i++) { + if (cached[i] !== data.cache[i]) { + return (data.unmodified = false); + } + } + }; + + var update = function(connection) { + var data = $.data(connection, "connection"); + getState(data); + if (data.unmodified) { + return; + } + var border_h = data.border_h; + var border_w = data.border_w; + var from = data.rect_from; + var to = data.rect_to; + var b = (from.bottom + from.top) / 2; + var r = (to.left + to.right) / 2; + var t = (to.bottom + to.top) / 2; + var l = (from.left + from.right) / 2; + + var h = ["right", "left"]; + if (l > r) { + h = ["left", "right"]; + var x = Math.max(r - border_w / 2, Math.min(from.right, to.right)); + r = l + border_w / 2; + l = x; + } else { + l -= border_w / 2; + r = Math.min(r + border_w / 2, Math.max(from.left, to.left)); + } + var v = ["bottom", "top"]; + if (t > b) { + v = ["top", "bottom"]; + var x = Math.max(b - border_h / 2, Math.min(from.bottom, to.bottom)); + b = t + border_h / 2; + t = x; + } else { + b = Math.min(b, Math.max(from.top, to.top)); + t -= border_h / 2; + } + var width = r - l; + var height = b - t; + if (width < border_w) { + t = Math.max(t, Math.min(from.bottom, to.bottom)); + b = Math.min(b, Math.max(from.top, to.top)); + l = Math.max(from.left, to.left); + r = Math.min(from.right, to.right); + r = l = (l + r - border_w) / 2; + } + if (height < border_h) { + l = Math.max(l, Math.min(from.right, to.right)); + r = Math.min(r, Math.max(from.left, to.left)); + t = Math.max(from.top, to.top); + b = Math.min(from.bottom, to.bottom); + b = t = (t + b - border_h) / 2; + } + width = r - l; + height = b - t; + width <= 0 && (border_h = 0); + height <= 0 && (border_w = 0); + var style = + "border-" + + v[0] + + "-" + + h[0] + + "-radius: 0;" + + "border-" + + v[0] + + "-" + + h[1] + + "-radius: 0;" + + "border-" + + v[1] + + "-" + + h[0] + + "-radius: 0;"; + (border_h <= 0 || border_w <= 0) && + (style += "border-" + v[1] + "-" + h[1] + "-radius: 0;"); + if (data.hidden) { + style += "display: none;"; + } else { + data.css["border-" + v[0] + "-width"] = 0; + data.css["border-" + h[0] + "-width"] = 0; + data.css["border-" + v[1] + "-width"] = border_h; + data.css["border-" + h[1] + "-width"] = border_w; + var current_rect = connection.getBoundingClientRect(); + data.css.left = connection.offsetLeft + l - current_rect.left; + data.css.top = connection.offsetTop + t - current_rect.top; + data.css.width = width - border_w; + data.css.height = height - border_h; + } + var bc = data.borderClasses; + $(connection) + .removeClass(bc[v[0]]) + .removeClass(bc[h[0]]) + .addClass(bc[v[1]]) + .addClass(bc[h[1]]) + .attr("style", style) + .css(data.css); + }; + + var processConnections = function(method, elements) { + return elements.each(function() { + var connections = $.data(this, "connections"); + if (connections instanceof Array) { + for (var i = 0, len = connections.length; i < len; i++) { + method(connections[i]); + } + } + }); + }; + })(jQuery); + \ No newline at end of file diff --git a/modules/blocknewsletter/blocknewsletter.php b/modules/blocknewsletter/blocknewsletter.php index 99593bb09..2379124bf 100644 --- a/modules/blocknewsletter/blocknewsletter.php +++ b/modules/blocknewsletter/blocknewsletter.php @@ -908,9 +908,7 @@ class Blocknewsletter extends Module 'title' => $this->l('Export Newsletter Subscribers'), 'icon' => 'icon-envelope' ), - 'desc' => array( - array('text' => $this->l('Generate a .CSV file based on BlockNewsletter subscribers data. Only subscribers without an account on the shop will be exported.')) - ), + 'description' => $this->l('Generate a .CSV file based on Newsletter subscribers data. Only subscribers without an account on your website will be exported.'), 'submit' => array( 'title' => $this->l('Export .CSV file'), 'class' => 'btn btn-default pull-right', diff --git a/modules/dashactivity/dashactivity.php b/modules/dashactivity/dashactivity.php index 9530d987b..7bc469cc4 100644 --- a/modules/dashactivity/dashactivity.php +++ b/modules/dashactivity/dashactivity.php @@ -152,10 +152,10 @@ class Dashactivity extends Module ); } - $objQGA = Module::isEnabled('qlogoogleanalytics') ? Module::getInstanceByName('qlogoogleanalytics') : false; - if (Validate::isLoadedObject($objQGA) && $objQGA->isConfigured()) { + $objGoogleAnalytics = Module::isEnabled('qlogoogleanalytics') ? Module::getInstanceByName('qlogoogleanalytics') : false; + if (Validate::isLoadedObject($objGoogleAnalytics) && $objGoogleAnalytics->isConfigured()) { $visits = $unique_visitors = $online_visitor = 0; - if ($result = $objQGA->requestReportData('', 'ga:visits,ga:visitors', Tools::substr($params['date_from'], 0, 10), Tools::substr($params['date_to'], 0, 10), null, null, 1, 1)) { + if ($result = $objGoogleAnalytics->requestReportData('', 'ga:visits,ga:visitors', Tools::substr($params['date_from'], 0, 10), Tools::substr($params['date_to'], 0, 10), null, null, 1, 1)) { $visits = $result[0]['metrics']['visits']; $unique_visitors = $result[0]['metrics']['visitors']; } @@ -172,29 +172,28 @@ class Dashactivity extends Module if ($maintenance_ips = Configuration::get('PS_MAINTENANCE_IP')) { $maintenance_ips = implode(',', array_map('ip2long', array_map('trim', explode(',', $maintenance_ips)))); } + if (Configuration::get('PS_STATSDATA_CUSTOMER_PAGESVIEWS')) { - $sql = 'SELECT c.id_guest, c.ip_address, c.date_add, c.http_referer, pt.name as page - FROM `'._DB_PREFIX_.'connections` c - LEFT JOIN `'._DB_PREFIX_.'connections_page` cp ON c.id_connections = cp.id_connections - LEFT JOIN `'._DB_PREFIX_.'page` p ON p.id_page = cp.id_page - LEFT JOIN `'._DB_PREFIX_.'page_type` pt ON p.id_page_type = pt.id_page_type - INNER JOIN `'._DB_PREFIX_.'guest` g ON c.id_guest = g.id_guest - WHERE (g.id_customer IS NULL OR g.id_customer = 0) - '.Shop::addSqlRestriction(false, 'c').' - AND cp.`time_end` IS NULL - AND TIME_TO_SEC(TIMEDIFF(\''.pSQL(date('Y-m-d H:i:00', time())).'\', cp.`time_start`)) < 900 - '.($maintenance_ips ? 'AND c.ip_address NOT IN ('.preg_replace('/[^,0-9]/', '', $maintenance_ips).')' : '').' - GROUP BY c.id_connections - ORDER BY c.date_add DESC'; + $sql = 'SELECT c.id_guest, c.ip_address, c.date_add, c.http_referer + FROM `'._DB_PREFIX_.'connections` c + LEFT JOIN `'._DB_PREFIX_.'connections_page` cp ON c.id_connections = cp.id_connections + INNER JOIN `'._DB_PREFIX_.'guest` g ON c.id_guest = g.id_guest + WHERE (g.id_customer IS NULL OR g.id_customer = 0) + '.Shop::addSqlRestriction(false, 'c').' + AND cp.`time_end` IS NULL + AND TIME_TO_SEC(TIMEDIFF(\''.pSQL(date('Y-m-d H:i:00', time())).'\', cp.`time_start`)) < 900 + '.($maintenance_ips ? 'AND c.ip_address NOT IN ('.preg_replace('/[^,0-9]/', '', $maintenance_ips).')' : '').' + GROUP BY c.id_connections + ORDER BY c.date_add DESC'; } else { $sql = 'SELECT c.id_guest, c.ip_address, c.date_add, c.http_referer, "-" as page - FROM `'._DB_PREFIX_.'connections` c - INNER JOIN `'._DB_PREFIX_.'guest` g ON c.id_guest = g.id_guest - WHERE (g.id_customer IS NULL OR g.id_customer = 0) - '.Shop::addSqlRestriction(false, 'c').' - AND TIME_TO_SEC(TIMEDIFF(\''.pSQL(date('Y-m-d H:i:00', time())).'\', c.`date_add`)) < 900 - '.($maintenance_ips ? 'AND c.ip_address NOT IN ('.preg_replace('/[^,0-9]/', '', $maintenance_ips).')' : '').' - ORDER BY c.date_add DESC'; + FROM `'._DB_PREFIX_.'connections` c + INNER JOIN `'._DB_PREFIX_.'guest` g ON c.id_guest = g.id_guest + WHERE (g.id_customer IS NULL OR g.id_customer = 0) + '.Shop::addSqlRestriction(false, 'c').' + AND TIME_TO_SEC(TIMEDIFF(\''.pSQL(date('Y-m-d H:i:00', time())).'\', c.`date_add`)) < 900 + '.($maintenance_ips ? 'AND c.ip_address NOT IN ('.preg_replace('/[^,0-9]/', '', $maintenance_ips).')' : '').' + ORDER BY c.date_add DESC'; } Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql); $online_visitor = Db::getInstance()->NumRows(); @@ -347,10 +346,10 @@ class Dashactivity extends Module protected function getReferer($date_from, $date_to, $limit = 3) { - $objQGA = Module::isEnabled('qlogoogleanalytics') ? Module::getInstanceByName('qlogoogleanalytics') : false; - if (Validate::isLoadedObject($objQGA) && $objQGA->isConfigured()) { + $objGoogleAnalytics = Module::isEnabled('qlogoogleanalytics') ? Module::getInstanceByName('qlogoogleanalytics') : false; + if (Validate::isLoadedObject($objGoogleAnalytics) && $objGoogleAnalytics->isConfigured()) { $websites = array(); - if ($result = $objQGA->requestReportData( + if ($result = $objGoogleAnalytics->requestReportData( 'ga:source', 'ga:visitors', Tools::substr($date_from, 0, 10), diff --git a/modules/dashavailability/views/js/dashavailability.js b/modules/dashavailability/views/js/dashavailability.js index 44b6a0f30..73fdefb14 100644 --- a/modules/dashavailability/views/js/dashavailability.js +++ b/modules/dashavailability/views/js/dashavailability.js @@ -37,7 +37,7 @@ function line_chart_availability(widget_name, chart_details) { }); chart.yAxis.tickFormat(function(d) { - return parseInt(d); + return Number.isInteger(d) ? d : ''; }); chart.legend.updateState(false); diff --git a/modules/dashgoals/dashgoals.php b/modules/dashgoals/dashgoals.php index 3bd49fa93..401a0f456 100644 --- a/modules/dashgoals/dashgoals.php +++ b/modules/dashgoals/dashgoals.php @@ -193,7 +193,7 @@ class Dashgoals extends Module $stream_types = array( array('type' => 'traffic', 'title' => $this->l('Traffic'), 'unit_text' => $this->l('visits')), array('type' => 'conversion', 'title' => $this->l('Conversion'), 'unit_text' => ''), - array('type' => 'avg_cart_value', 'title' => $this->l('Average cart value'), 'unit_text' => ''), + array('type' => 'avg_cart_value', 'title' => $this->l('Average order value'), 'unit_text' => ''), array('type' => 'sales', 'title' => $this->l('Sales'), 'unit_text' => '') ); $stream_zones = array( diff --git a/modules/dashgoals/views/js/dashgoals.js b/modules/dashgoals/views/js/dashgoals.js index 4894db2e3..b2f29c357 100644 --- a/modules/dashgoals/views/js/dashgoals.js +++ b/modules/dashgoals/views/js/dashgoals.js @@ -76,7 +76,6 @@ function bar_chart_goals(widget_name, chart_details) }); - chart.yAxis.tickFormat(d3.format('.1f')); dashgoals_chart = chart; d3.select('#dash_goals_chart1 svg') @@ -103,6 +102,21 @@ function selectDashgoalsChart(type) value.disabled = true; }); } + + dashgoals_chart.yAxis.tickFormat(d3.format('.1f')); + + if (type == 'avg_cart_value' || type == 'sales') { + dashgoals_chart.yAxis.tickFormat(function(d) { + return formatCurrency(parseFloat(d), currency_format, currency_sign, currency_blank); + }); + } + + if (type == 'conversion') { + dashgoals_chart.yAxis.tickFormat(function(d) { + return d + ' %'; + }); + } + dashgoals_toggleDashConfig(); } diff --git a/modules/dashgoals/views/templates/hook/config.tpl b/modules/dashgoals/views/templates/hook/config.tpl index a404e7ff5..e856af643 100644 --- a/modules/dashgoals/views/templates/hook/config.tpl +++ b/modules/dashgoals/views/templates/hook/config.tpl @@ -31,7 +31,7 @@ {$goals_year} {l s='Traffic' mod='dashgoals'} {l s='Conversion Rate' mod='dashgoals'} - {l s='Average Cart Value' mod='dashgoals'} + {l s='Average Order Value' mod='dashgoals'} {l s='Sales' mod='dashgoals'} diff --git a/modules/dashgoals/views/templates/hook/dashboard_zone_two.tpl b/modules/dashgoals/views/templates/hook/dashboard_zone_two.tpl index fd231946c..d707a1d71 100644 --- a/modules/dashgoals/views/templates/hook/dashboard_zone_two.tpl +++ b/modules/dashgoals/views/templates/hook/dashboard_zone_two.tpl @@ -55,6 +55,9 @@ {include file='./config.tpl'}
+
+

{l s='Please use the configuration button right above here to set targets.' mod='dashgoals'}

+