Execute($sQuery)) { $sQuery = 'DELETE FROM ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_tpl_lang WHERE TPG_ID = ' . $iTplId; // delete lang associated if(!Db::getInstance()->Execute($sQuery)) { $bReturn = false; } else { // get last insert id $iInsertId = $iTplId; } } else { $bReturn = false; } } // use case - insert else { $sQuery = 'INSERT INTO ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_tpl (TPL_TYPE, TPL_DATA) ' . 'VALUES("' . pSQL($sType) . '", "' . pSQL(serialize($aData)) . '")'; // insert or update if (!Db::getInstance()->Execute($sQuery)) { $bReturn = false; } else { // get last insert id $iInsertId = Db::getInstance()->Insert_ID(); } } if ($bReturn) { // insert each translated title foreach ($aLang as $sIsoLang => $sTitle) { $sQuery = 'INSERT INTO ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_tpl_lang (TPG_ID, TPG_ISO_LANG, TPG_TITLE) ' . 'VALUES(' . $iInsertId . ', "' . pSQL($sIsoLang) . '", "' . pSQL($sTitle) .'")'; if(!Db::getInstance()->Execute($sQuery)) { $bReturn = false; } } } // destruct unset($sQuery); return $bReturn; } /** * getTemplates() method gets templates used for exporting action * * @param int $iTplId * @return array */ public static function getTemplates($iTplId = null) { // set $aTemplates = array(); $aTmpTemplates = array(); $sQuery = 'SELECT * FROM ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_tpl'; if (null !== $iTplId) { $sQuery .= ' WHERE TPL_ID = ' . pSQL($iTplId) . ''; } // order $sQuery .= ' ORDER BY TPL_ID ASC'; // get configured tabs $aTmpTemplates = Db::getInstance()->ExecuteS($sQuery); // destruct unset($sQuery); if (!empty($aTmpTemplates)) { foreach ($aTmpTemplates as $nKey => &$aTemplate) { // get unserialized data $aUnserialize = unserialize($aTemplate['TPL_DATA']); // ID $aTemplates[$aTemplate['TPL_TYPE']]['id'] = $aTemplate['TPL_ID']; // get cols $aTemplates[$aTemplate['TPL_TYPE']]['cols'] = $aUnserialize['cols']; // get group $aTemplates[$aTemplate['TPL_TYPE']]['group'] = $aUnserialize['group']; // destruct unset($aUnserialize); // get internationalization $aLanguages = Db::getInstance()->ExecuteS('SELECT * FROM ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_tpl_lang WHERE TPG_ID = ' . $aTemplate['TPL_ID']); foreach ($aLanguages as $nK => $aLang) { $aTemplates[$aTemplate['TPL_TYPE']]['lang'][$aLang['TPG_ISO_LANG']] = $aLang['TPG_TITLE']; } } } // destruct unset($aTmpTemplates); // return added templates in Back Office return $aTemplates; } /** * getStatusOrder() method returns list of status order * * @return array */ public static function getStatusOrder() { // set variable $aStatusTmp = array(); // set query $sQuery = 'SELECT * FROM ' . _DB_PREFIX_ . 'order_state_lang'; $aStatusOrder = Db::getInstance()->ExecuteS($sQuery); foreach ($aStatusOrder as $aStatus) { $aStatusTmp[$aStatus['id_order_state']][$aStatus['id_lang']] = $aStatus['name']; } // destruct unset($aStatusOrder); return $aStatusTmp; } /** * * isExistDiscountOrders() method returns if table is populated * * @return bool */ public static function isExistDiscountOrders() { // set query $sQuery = 'SELECT count(*) as nb FROM ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_order_discount'; $aCountDiscount = Db::getInstance()->ExecuteS($sQuery); return ( empty($aCountDiscount[0]['nb'])? false : true ); } /** * * isExistWrappingOrders() method returns if table is populated * * @return bool */ public static function isExistWrappingOrders() { // set query $sQuery = 'SELECT count(*) as nb FROM ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_order_wrapping'; $aCountDiscount = Db::getInstance()->ExecuteS($sQuery); return ( empty($aCountDiscount[0]['nb'])? false : true ); } /** * getOrdersDetail() method returns list of orders * * @return MySql resource */ public static function getOrdersDetail() { // set query if (version_compare(_PS_VERSION_, '1.5', '>')) { $sQuery = 'SELECT total_discounts, total_wrapping, total_wrapping_tax_incl, total_wrapping_tax_excl, total_products, ' . ' p.wholesale_price as product_wholesale_price, od.purchase_supplier_price, IF(pa.wholesale_price IS NOT NULL, pa.wholesale_price, 0) as attribute_wholesale_price, ' . ' od.id_order as id_order, od.id_order_detail as id_order_detail, ' . $GLOBALS[_OTPR_MODULE_NAME . '_COLS']['prod_unit_price']['install'] . ', ' . ' od.product_quantity, t.rate as tax_rate ' . ' FROM ' . _DB_PREFIX_ . 'order_detail as od' . ' LEFT JOIN ' . _DB_PREFIX_ . 'orders as o ON o.id_order = od.id_order' . ' LEFT JOIN ' . _DB_PREFIX_ . 'order_detail_tax as odt ON od.id_order_detail = odt.id_order_detail ' . ' LEFT JOIN ' . _DB_PREFIX_ . 'tax as t ON (odt.id_tax = t.id_tax AND t.active = 1)' . ' LEFT JOIN ' . _DB_PREFIX_ . 'product as p ON od.product_id = p.id_product' . ' LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute as pa ON (od.product_attribute_id = pa.id_product_attribute)' . ' ORDER BY o.id_order ASC'; } else { $sQuery = 'SELECT total_wrapping, total_discounts, total_products, od.id_order as id_order, od.id_order_detail as id_order_detail, ' . $GLOBALS[_OTPR_MODULE_NAME . '_COLS']['prod_unit_price']['install'] . ', od.product_quantity, tax_rate ' . ' FROM ' . _DB_PREFIX_ . 'order_detail as od' . ' LEFT JOIN ' . _DB_PREFIX_ . 'orders as o ON o.id_order = od.id_order' ; // hack for getting currency under 1.4.0.1 if (version_compare(_PS_VERSION_, '1.4.0.1', '<')) { $sQuery .= ' LEFT JOIN ' . _DB_PREFIX_ . 'currency as cu ON (o.id_currency = cu.id_currency)'; } $sQuery .= ' ORDER BY o.id_order ASC'; } return Db::getInstance()->ExecuteS($sQuery, false); } /** * getOrderDetailIds() method returns list of order detail ids from one order * * @param int $iOrderId * @return array */ public static function getOrderDetailIds($iOrderId) { // set query if (version_compare(_PS_VERSION_, '1.5', '>')) { $sQuery = 'SELECT od.id_order_detail as id_order_detail, ' . $GLOBALS[_OTPR_MODULE_NAME . '_COLS']['prod_unit_price']['install'] . ',' . ' od.product_quantity, t.rate as tax_rate, od.purchase_supplier_price as purchase_supplier_price, IF(pa.wholesale_price IS NOT NULL, pa.wholesale_price, 0) as attribute_wholesale_price, p.wholesale_price as product_wholesale_price' . ' FROM ' . _DB_PREFIX_ . 'order_detail as od ' . ' LEFT JOIN ' . _DB_PREFIX_ . 'orders as o ON o.id_order = od.id_order' . ' LEFT JOIN ' . _DB_PREFIX_ . 'order_detail_tax as odt ON od.id_order_detail = odt.id_order_detail ' . ' LEFT JOIN ' . _DB_PREFIX_ . 'tax as t ON (odt.id_tax = t.id_tax AND t.active = 1)' . ' LEFT JOIN ' . _DB_PREFIX_ . 'product as p ON od.product_id = p.id_product' . ' LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute as pa ON (od.product_attribute_id = pa.id_product_attribute)'; } else { $sQuery = 'SELECT id_order_detail, ' . $GLOBALS[_OTPR_MODULE_NAME . '_COLS']['prod_unit_price']['install'] . ', od.product_quantity, tax_rate ' . ' FROM ' . _DB_PREFIX_ . 'order_detail as od' . ' LEFT JOIN ' . _DB_PREFIX_ . 'orders as o ON o.id_order = od.id_order'; // hack for getting currency under 1.4.0.2 if (version_compare(_PS_VERSION_, '1.4.0.2', '<')) { $sQuery .= ' LEFT JOIN ' . _DB_PREFIX_ . 'currency as cu ON (o.id_currency = cu.id_currency)'; } } $sQuery .= ' WHERE od.id_order = ' . pSQL($iOrderId); $aOrderDetailIds = Db::getInstance()->ExecuteS($sQuery); return ( !empty($aOrderDetailIds)? $aOrderDetailIds : array() ); } /** * populateDiscountOrdersDetail() method insert discount order details * * @param int $iOrderId * @param int $iOrderDetailId * @param float $fTaxExcl * @param float $fTaxIncl * @param float $fTaxAmount * @return bool */ public static function populateDiscountOrdersDetail($iOrderId, $iOrderDetailId, $fTaxExcl, $fTaxIncl, $fTaxAmount) { // set query $sQuery = 'INSERT INTO ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_order_discount (SHOP_ID, DISC_ID_ORDER, DISC_ID_ORDER_DETAIL, DISC_TAX_EXCL, DISC_TAX_INCL, DISC_TAX_AMOUNT) ' . 'VALUES(' . pSQL(OrderTaxProfitReport::$iShopId) . ', ' . pSQL($iOrderId) . ',' . pSQL($iOrderDetailId) . ',' . floatval($fTaxExcl) . ',' . floatval($fTaxIncl) . ',' . floatval($fTaxAmount) . ')'; return ( Db::getInstance()->Execute($sQuery) ); } /** * populateWrappingOrdersDetail() method insert wrapping order * * @param int $iOrderId * @param float $fTaxExcl * @param float $fTaxIncl * @param float $fTaxAmount * @return bool */ public static function populateWrappingOrdersDetail($iOrderId, $fTaxExcl, $fTaxIncl, $fTaxAmount) { // set query $sQuery = 'INSERT INTO ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_order_wrapping (SHOP_ID, WRA_ID_ORDER, WRA_TAX_EXCL, WRA_TAX_INCL, WRA_TAX_AMOUNT) ' . 'VALUES(' . pSQL(OrderTaxProfitReport::$iShopId) . ', ' . pSQL($iOrderId) . ', ' . floatval($fTaxExcl) . ',' . floatval($fTaxIncl) . ',' . floatval($fTaxAmount) . ')'; return ( Db::getInstance()->Execute($sQuery) ); } /** * populateWholeSalePrice() method insert wrapping order * * @param int $iOrderId * @param float $fWholePrice * @param int $iOrderDetailId * @return bool */ public static function populateWholeSalePrice($iOrderId, $fWholePrice,$iOrderDetailId) { // set query $sQuery = 'INSERT INTO ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_wholesale_price (WHP_ID_ORDER, WHP_ID_ORDER_DETAIL , SHOP_ID, WHP_PRICE) ' . 'VALUES(' . pSQL($iOrderId) . ',' . pSQL($iOrderDetailId) . ' ,' . pSQL(OrderTaxProfitReport::$iShopId) .', ' . floatval($fWholePrice) . ')'; return ( Db::getInstance()->Execute($sQuery) ); } /** * getReport() method returns all matched records of 'orders' and 'products' table * * @param array $aParams * @return array = matched records */ public static function getReport(array $aParams) { // set $aReport = array(); $sQuery = 'SELECT '; // get fields $aFields = BT_OtprModuleTools::getColAttributes($aParams['aTemplateCols'], 'db'); $sFrom = ' FROM ' . _DB_PREFIX_ . 'orders as o' . ' LEFT JOIN ' . _DB_PREFIX_ . 'order_detail as od ON (o.id_order = od.id_order)' . ' LEFT JOIN ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_order_discount as ood ON (od.id_order_detail = ood.DISC_ID_ORDER_DETAIL)' . ' LEFT JOIN ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_wholesale_price as owp ON (od.id_order_detail = owp.WHP_ID_ORDER_DETAIL)'; // use case - order group if (isset($aParams['sGroup']) && $aParams['sGroup'] == 'order') { $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . strtolower(_OTPR_MODULE_NAME) . '_order_wrapping as oow ON (o.id_order = oow.WRA_ID_ORDER)'; } // use case - credit slip group if (!empty($aParams['sGroup']) && $aParams['sGroup'] == 'credit') { $sFrom .= ' INNER JOIN ' . _DB_PREFIX_ . 'order_slip as os ON (o.id_order = os.id_order)' . ' LEFT JOIN ' . _DB_PREFIX_ . 'order_slip_detail as osd ON (osd.id_order_detail = od.id_order_detail AND osd.id_order_slip = os.id_order_slip)'; } // use case - others group else { $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'order_history as oh ON (o.id_order = oh.id_order)' . ' LEFT JOIN ' . _DB_PREFIX_ . 'order_state_lang as osl ON (oh.id_order_state = osl.id_order_state AND osl.id_lang = ' . OrderTaxProfitReport::$iCurrentLang . ')'; } // generic join $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'product as p ON (p.id_product = od.product_id)' . ' LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute as pa ON (pa.id_product_attribute = od.product_attribute_id)'; // hack for getting currency under 1.4.0.1 if (version_compare(_PS_VERSION_, '1.4.0.1', '<')) { $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'currency as cu ON (o.id_currency = cu.id_currency)'; } // hack for getting tax rate elseif (version_compare(_PS_VERSION_, '1.5', '>')) { $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'order_detail_tax as odt ON od.id_order_detail = odt.id_order_detail ' . ' LEFT JOIN ' . _DB_PREFIX_ . 'tax as t ON (odt.id_tax = t.id_tax)' . ' LEFT JOIN ' . _DB_PREFIX_ . 'shop as s ON (o.id_shop = s.id_shop)'; } // use case - "product" group if (isset($aParams['sGroup'])) { switch ($aParams['sGroup']) { case 'product' : $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'category_lang as cl ON (p.id_category_default = cl.id_category AND cl.id_lang = ' . OrderTaxProfitReport::$iCurrentLang . (version_compare(_PS_VERSION_, '1.5', '>')? ' AND cl.id_shop = ' . OrderTaxProfitReport::$iShopId : '') . ')' . ' LEFT JOIN ' . _DB_PREFIX_ . 'manufacturer as m ON (m.id_manufacturer = p.id_manufacturer)' . ' LEFT JOIN ' . _DB_PREFIX_ . 'supplier as sp ON p.id_supplier = sp.id_supplier' ; // Only if the user has decided to display preoduct photos in product report if (!empty($aParams['mPhotos'])) { $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'image as i ON (p.id_product = i.id_product AND i.cover = 1)'; self::$_mShowPhotos = $aParams['mPhotos']; } // hack for getting tax rate if (version_compare(_PS_VERSION_, '1.5', '>')) { $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'product_supplier as ps ON (ps.id_product = od.product_id AND od.product_attribute_id = ps.id_product_attribute AND p.id_supplier = ps.id_supplier)'; } // use case - display combination name if (!empty($aParams['bUseAttribute'])) { if (!empty($aFields['product_ref'])) { $aFields['product_ref'] = str_replace('p.reference', 'IFNULL(pa.reference, p.reference)', $aFields['product_ref']); } // use case - display product supplier ref in product attribute table if (!empty($aFields['product_supplier_ref']) && version_compare(_PS_VERSION_, '1.5', '<')) { $aFields['product_supplier_ref'] = str_replace('p.supplier_reference', 'IFNULL(pa.supplier_reference, p.supplier_reference)', $aFields['product_supplier_ref']); } } // replace EAN13 and UPC code if (!empty($aFields['product_ean'])) { $aFields['product_ean'] = str_replace('p.ean13', 'IF(pa.ean13 IS NOT NULL OR pa.reference <> "", pa.ean13, p.ean13)', $aFields['product_ean']); } if (!empty($aFields['product_upc']) && version_compare(_PS_VERSION_, '1.4', '>')) { $aFields['product_upc'] = str_replace('p.upc', 'IF(pa.upc IS NOT NULL OR pa.upc <> "", pa.upc, p.upc)', $aFields['product_upc']); } // activate specific column calculation $bSpecificColumn = true; break; case 'brand' : $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'manufacturer as m ON (m.id_manufacturer = p.id_manufacturer)'; // activate specific column calculation $bSpecificColumn = true; break; case 'supplier' : $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'supplier as sp ON p.id_supplier = sp.id_supplier'; // activate specific column calculation $bSpecificColumn = true; break; case 'category' : $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'category_lang as cl ON (p.id_category_default = cl.id_category AND cl.id_lang = ' . OrderTaxProfitReport::$iCurrentLang . (version_compare(_PS_VERSION_, '1.5', '>')? ' AND cl.id_shop = ' . OrderTaxProfitReport::$iShopId : '') . ')'; // activate specific column calculation $bSpecificColumn = true; break; default : break; } } // use case - get carrier and payment method data for all versions and tax info for versions < 1.4 if (!empty($aParams['sReportName']) && in_array($aParams['sReportName'], array('all', 'vatonly', 'profitonly', 'basic', 'credit'))) { $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'carrier as car ON (o.id_carrier = car.id_carrier)'; if (version_compare(_PS_VERSION_, '1.4.0.1', '<')) { $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'tax as ct ON (car.id_tax = ct.id_tax)'; } } $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'customer as c ON (o.id_customer = c.id_customer)' . ' LEFT JOIN ' . _DB_PREFIX_ . 'address as a ON (o.id_address_invoice = a.id_address)' . ' LEFT JOIN ' . _DB_PREFIX_ . 'country_lang as co ON (co.id_country = a.id_country AND co.id_lang = '.OrderTaxProfitReport::$iCurrentLang.')' ; // use case - filtering on customer groups if (!empty($aParams['aCustomerGroup']) && is_array($aParams['aCustomerGroup']) ) { $sFrom .= ' LEFT JOIN ' . _DB_PREFIX_ . 'customer_group as cg ON (o.id_customer = cg.id_customer)'; } // use case - get only data of one or many countries if (!empty($aParams['aCountryIds']) && is_array($aParams['aCountryIds']) ) { $sFrom .= ' WHERE 1 = 1 AND co.id_country IN(' . implode(', ', $aParams['aCountryIds']) .')'; } else { $sFrom .= ' WHERE 1 = 1 '; } // concatenate $sQuery .= implode(', ', $aFields) . $sFrom; // use case - over 1.5 $sQuery .= version_compare(_PS_VERSION_, '1.5', '>') && !BT_OtprModuleTools::checkGroupMultiShop()? ' AND o.id_shop = ' . pSQL(OrderTaxProfitReport::$iShopId) : ''; // set max order history if (empty($aParams['sGroup']) || (!empty($aParams['sGroup']) && $aParams['sGroup'] != 'credit')) { $sQuery .= ' AND oh.id_order_history = (SELECT MAX(od2.id_order_history) FROM ' . _DB_PREFIX_ . 'order_history as od2 WHERE o.id_order = od2.id_order)'; } // use case - Order start date filter if (isset($aParams['iOrderStartDate'])) { $sQuery .= ' AND (o.date_add is not NULL AND UNIX_TIMESTAMP(o.date_add) >= ' . pSQL($aParams['iOrderStartDate']) . ')'; } // use case - Order end date filter if (isset($aParams['iOrderEndDate'])) { $sQuery .= ' AND (o.date_add is not NULL AND UNIX_TIMESTAMP(o.date_add) <= ' . pSQL($aParams['iOrderEndDate']) . ')'; } // use case - invoice start date filter if (isset($aParams['iInvoiceStartDate'])) { $sQuery .= ' AND (o.invoice_date is not NULL AND UNIX_TIMESTAMP(o.invoice_date) >= ' . pSQL($aParams['iInvoiceStartDate']) . ')'; } // use case - invoice end date filter if (isset($aParams['iInvoiceEndDate'])) { $sQuery .= ' AND (o.invoice_date is not NULL AND UNIX_TIMESTAMP(o.invoice_date) <= ' . pSQL($aParams['iInvoiceEndDate']) . ')'; } // use case - delivery start date filter if (isset($aParams['iDeliveryStartDate'])) { $sQuery .= ' AND (o.delivery_date is not NULL AND UNIX_TIMESTAMP(o.delivery_date) >= ' . pSQL($aParams['iDeliveryStartDate']) . ')'; } // use case - delivery end date filter if (isset($aParams['iDeliveryEndDate'])) { $sQuery .= ' AND (o.delivery_date is not NULL AND UNIX_TIMESTAMP(o.delivery_date) <= ' . pSQL($aParams['iDeliveryEndDate']) . ')'; } // use case - credit slip start date filter if (isset($aParams['iCreditStartDate'])) { $sQuery .= ' AND (os.date_add is not NULL AND UNIX_TIMESTAMP(os.date_add) >= ' . pSQL($aParams['iCreditStartDate']) . ')'; } // use case - invoice end date filter if (isset($aParams['iCreditEndDate'])) { $sQuery .= ' AND (os.date_add is not NULL AND UNIX_TIMESTAMP(os.date_add) <= ' . pSQL($aParams['iCreditEndDate']) . ')'; } // use case - min order number filter if (isset($aParams['iOrderStart'])) { $sQuery .= ' AND o.id_order >= ' . pSQL($aParams['iOrderStart']); } // use case - max order number filter if (isset($aParams['iOrderEnd'])) { $sQuery .= ' AND o.id_order <= ' . pSQL($aParams['iOrderEnd']); } // use case - min invoice number filter if (isset($aParams['iInvoiceStart'])) { $sQuery .= ' AND o.invoice_number >= ' . pSQL($aParams['iInvoiceStart']); } // use case - max invoice number filter if (isset($aParams['iInvoiceEnd'])) { $sQuery .= ' AND o.invoice_number <= ' . pSQL($aParams['iInvoiceEnd']); } // use case - min credit slip number filter if (isset($aParams['iCreditSlipStart'])) { $sQuery .= ' AND os.id_order >= ' . pSQL($aParams['iCreditSlipStart']); } // use case - max credit slip number filter if (isset($aParams['iCreditSlipEnd'])) { $sQuery .= ' AND os.id_order <= ' . pSQL($aParams['iCreditSlipEnd']); } // use case - tax rate if (isset($aParams['fTaxRate'])) { if(version_compare(_PS_VERSION_, '1.5', '>')) { $sQuery .= ' AND t.rate = ' . $aParams['fTaxRate']; } else { $sQuery .= ' AND od.tax_rate = ' . $aParams['fTaxRate']; } } // use case - status if (!empty($aParams['aOrderStatus']) && empty($aParams['sGroup']) || (!empty($aParams['sGroup']) && $aParams['sGroup'] != 'credit') ) { $sQuery .= ' AND oh.id_order_state IN(' . implode(', ', $aParams['aOrderStatus']) .')'; } // use case - categories filter if (!empty($aParams['aSearchCategories']) && is_array($aParams['aSearchCategories']) ) { $sQuery .= ' AND p.id_category_default IN(' . implode(', ', $aParams['aSearchCategories']) .')'; } // use case - manufacturers filter if (!empty($aParams['aSearchManufacturers']) && is_array($aParams['aSearchManufacturers']) ) { $sQuery .= ' AND p.id_manufacturer IN(' . implode(', ', $aParams['aSearchManufacturers']) .')'; } // use case - suppliers filter if (!empty($aParams['aSearchSuppliers']) && is_array($aParams['aSearchSuppliers']) ) { $sQuery .= ' AND p.id_supplier IN(' . implode(', ', $aParams['aSearchSuppliers']) .')'; } // use case - customer group filter if (!empty($aParams['aCustomerGroup']) && is_array($aParams['aCustomerGroup']) ) { $sQuery .= ' AND cg.id_group IN(' . implode(', ', $aParams['aCustomerGroup']) .')'; } // use case - display product attribute name if (!empty($aParams['bUseAttribute'])) { $aParams['sGroupBy'] = $aParams['sGroupBy'] . ', od.product_attribute_id'; } // set group by $sQuery .= ' GROUP BY ' . $aParams['sGroupBy']; // use case - order key $sQuery .= ' ORDER BY ' . (!empty($aParams['sSortField'])? $aParams['sSortField']: $aParams['sOrderBy']); // use case - way $sQuery .= ' ' . (!empty($aParams['sWayType'])? $aParams['sWayType']: 'ASC'); // echo $sQuery; // get orders records $aOrders = Db::getInstance()->ExecuteS($sQuery); // destruct unset($sQuery); // set variable $aTotals = array(); $aSortOrders = array(); $aHeadings = array(); $aTooltips = array(); if (!empty($aParams['sOutputType'])) { self::$_sOutputType = $aParams['sOutputType']; } // use case - check empty joined record if (!empty($aOrders)) { if (!empty($aParams['bHeadings'])) { $bTotal = true; // get headings $aHeadings = BT_OtprModuleTools::getColAttributes($aParams['aTemplateCols'], 'title', $aParams['bUtf8']); $aTooltips = BT_OtprModuleTools::getColAttributes($aParams['aTemplateCols'], 'tooltip', $aParams['bUtf8']); } else { $bTotal = false; } // set foreach ($aOrders as $nKey => &$aOrder) { $bEmpty = true; foreach ($aOrder as $sField => &$mVal) { // set field not empty $bEmpty = false; // use case - calculate current order and total if necessary if (in_array($aParams['sGroup'], $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['group'])) { // use case - numeric values only if ($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['type'] == 'n' || $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['type'] == 'm' || $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['type'] == 'i' // special case: m is for product photos which will be an URL ) { // use case - calculate with PHP and not with MySQL if (!empty($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['calculate']['unit'])) { // get array of compute $aOperate = $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['calculate']['unit']; // count $mVal = self::_calculate($sField, $aOperate, $aOrder); } if (($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['type'] == 'n' || $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['type'] == 'i') && empty($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['no_total']) ) { // use case - calculate total if ($bTotal) { if (empty($aTotals[$sField])) { $aTotals[$sField] = 0; } $aTotals[$sField] += $mVal; } } else { $aTotals[$sField] = null; } } else { // use case - decode utf-8 if (false === $aParams['bUtf8']) { $mVal = utf8_decode($mVal); } $aTotals[$sField] = null; } } else { $aTotals[$sField] = null; } } // use case - php sort if (!empty($aParams['sSortPhpField']) && isset($aOrder[$aParams['sSortPhpField']]) && empty($bSpecificColumn) ) { $aSortOrders[$aOrder[$aParams['sSortPhpField']]][] = $aOrder; } } } // use case - calculate specific column if (!empty($bSpecificColumn) && !empty($bTotal)) { $aSpecificColumns = array(); $aCumulativeColumns = array(); // get specific columns foreach ($aFields as $sName => $sVal) { if (!empty($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sName]['calculation'])) { $aSpecificColumns[$sName] = $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sName]['calculation']; } if (!empty($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sName]['cumulative'])) { $aCumulativeColumns[$sName] = $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sName]['cumulative']; } } // loop on result in order to calculate specific column foreach ($aOrders as $nKey => &$aOrder) { foreach ($aSpecificColumns as $sName => $sLinkedColumn) { // calculate percentage of line / total if (intval($aTotals[$sLinkedColumn]) != 0) { $aOrder[$sName] = ($aOrder[$sLinkedColumn] * 100) / $aTotals[$sLinkedColumn]; } } // use case - php sort if (!empty($aParams['sSortPhpField']) && isset($aOrder[$aParams['sSortPhpField']]) ) { $aSortOrders[$aOrder[$aParams['sSortPhpField']]][] = $aOrder; } else { // use case - process cumulative columns foreach ($aCumulativeColumns as $sName => $sLinkedColumn) { if (isset($aOrders[($nKey-1)][$sName])) { $aOrder[$sName] = floatval($aOrders[($nKey-1)][$sName]) + floatval($aOrder[$sLinkedColumn]); } else { $aOrder[$sName] = floatval($aOrder[$sLinkedColumn]); } } } } } // use case - final php sort if (!empty($aSortOrders)) { $aOrders = array(); $sWay = !empty($aParams['sWayType'])? $aParams['sWayType'] : 'ASC'; if ($sWay == 'DESC') { krsort($aSortOrders, SORT_NUMERIC); } else { ksort($aSortOrders, SORT_NUMERIC); } // use case - re-assign in indexed array, because it could have same sort keys in tmp array foreach ($aSortOrders as $aTmpOrders) { foreach ($aTmpOrders as $nKey => $aTmpOrder) { if (!empty($aCumulativeColumns)) { // last elt $aLastElt = end($aOrders); // use case - process cumulative columns foreach ($aCumulativeColumns as $sName => $sLinkedColumn) { if (isset($aLastElt[$sName])) { $aTmpOrder[$sName] = floatval($aLastElt[$sName]) + floatval($aTmpOrder[$sLinkedColumn]); } else { $aTmpOrder[$sName] = floatval($aTmpOrder[$sLinkedColumn]); } } } $aOrders[] = $aTmpOrder; } } unset($aSortOrders); } // last process to make rounding on numeric values and adding suffix string foreach ($aOrders as $nKey => &$aOrder) { foreach ($aOrder as $sColumn => &$mVal) { if ($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sColumn]['type'] == 'n') { $mVal = BT_OtprModuleTools::round($mVal, OrderTaxProfitReport::$aConfiguration[_OTPR_MODULE_NAME . '_FLOAT_NUMBER']); if (OrderTaxProfitReport::$aConfiguration[_OTPR_MODULE_NAME . '_FLOAT_SEPARATOR'] == ',') { $mVal = number_format($mVal, OrderTaxProfitReport::$aConfiguration[_OTPR_MODULE_NAME . '_FLOAT_NUMBER'], ',', ''); } } $mVal = self::_setDefaultMsgSuffix($sColumn, $mVal); } } // use case - recalculate totals if (!empty($aTotals)) { // detect all specific total to calculate foreach ($GLOBALS[_OTPR_MODULE_NAME . '_COLS'] as $sField => $aField) { if (in_array($aParams['sGroup'], $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['group']) && !empty($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['calculate']['global']) && isset($aTotals[$sField]) ) { // get array of compute $aOperate = $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['calculate']['global']; // count $aTotals[$sField] = self::_calculate($sField, $aOperate, $aTotals); } } // use case - put suffix string foreach ($aTotals as $sField => &$mTotal) { if (!empty($mTotal) && is_numeric($mTotal)) { $mTotal = BT_OtprModuleTools::round($mTotal, OrderTaxProfitReport::$aConfiguration[_OTPR_MODULE_NAME . '_FLOAT_NUMBER']); if (OrderTaxProfitReport::$aConfiguration[_OTPR_MODULE_NAME . '_FLOAT_SEPARATOR'] == ',') { $mTotal = number_format($mTotal, OrderTaxProfitReport::$aConfiguration[_OTPR_MODULE_NAME . '_FLOAT_NUMBER'], ',', ''); } } if (!empty($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['prefix'])) { // use case - decode HTML if (!empty($aParams['bHtmlDecode'])) { $mTotal = strip_tags(html_entity_decode($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['prefix'])) . $mTotal; } else { $mTotal = $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['prefix'] . $mTotal; } } if (!empty($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['suffix']) && empty($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['no_total'])) { // use case - decode HTML if (!empty($aParams['bHtmlDecode'])) { $mTotal .= strip_tags(html_entity_decode($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['suffix'])); } else { $mTotal .= $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['suffix']; } } } } // return orders return ( array('orders' => $aOrders, 'headings' => $aHeadings, 'totals' => $aTotals, 'tooltips' => $aTooltips) ); } /** * getCategories() method returns chosen categories to display on tab * * @return array */ public static function getCategories() { $aFormatCat = array(); // return Home categories $aHomeCat = Category::getCategories(intval(OrderTaxProfitReport::$iCurrentLang), false); if (!empty($aHomeCat)) { // set recursive tree $aTmp = current($aHomeCat); $aFirst = current($aTmp); $aFormatCat = BT_OtprModuleTools::recursiveCategoryTree($aHomeCat, array(), $aFirst, 1); unset($aTmp); unset($aFirst); } return $aFormatCat; } /** * getTax() method returns different existing tax * * @return array */ public static function getTax() { $aTax = array(); // set query $sQuery = 'SELECT DISTINCT(rate) as tax_rate FROM ' . _DB_PREFIX_ . 'tax ORDER BY rate'; $aTax = Db::getInstance()->ExecuteS($sQuery); return $aTax; } /** * getCustomerGroup() method returns different existing customer group * * @return array */ public static function getCustomerGroup() { // set query if (version_compare(_PS_VERSION_, '1.3.0.4', '>=')) { $sQuery = 'SELECT DISTINCT(id_default_group) as id FROM ' . _DB_PREFIX_ . 'customer'; } else { $sQuery = 'SELECT id_group as id FROM ' . _DB_PREFIX_ . 'group'; } return Db::getInstance()->ExecuteS($sQuery); } /** * _calculate() method returns counting result * * @param string $sField * @param array $aOperate * @param array $aData * @return numeric : int or float */ private static function _calculate($sField, array $aOperate, array $aData) { // set variables $nTotal = 0; // use case - specific compute switch ($sField) { case 'total_tax' : if (isset($aData[$aOperate[0]])) { $nTotal = $aData[$aOperate[0]] + $aData[$aOperate[1]] - abs($aData[$aOperate[2]]) + $aData[$aOperate[3]]; } break; case 'prod_total_tax' : if (isset($aData[$aOperate[0]]) && isset($aData[$aOperate[1]]) ) { $nTotal = $aData[$aOperate[0]] - abs($aData[$aOperate[1]]); } break; case 'gross_margin' : if (isset($aData[$aOperate[0]]) && isset($aData[$aOperate[1]]) ) { $nTotal = ($aData[$aOperate[0]] / $aData[$aOperate[1]]) * $aOperate[2]; } break; case 'net_margin' : if (isset($aData[$aOperate[0]]) && isset($aData[$aOperate[1]]) && isset($aData[$aOperate[2]]) && isset($aData[$aOperate[3]]) && isset($aData[$aOperate[4]]) && isset($aData[$aOperate[5]]) && isset($aData[$aOperate[6]]) ) { $fTotalProdWithReduc = $aData[$aOperate[0]] - abs($aData[$aOperate[1]]); if ($fTotalProdWithReduc > 0) { $fResult1 = ($aData[$aOperate[0]] - abs($aData[$aOperate[1]]) + $aData[$aOperate[2]] - $aData[$aOperate[3]]); $fResult2 = ($aData[$aOperate[4]] - abs($aData[$aOperate[5]]) + $aData[$aOperate[6]]); $nTotal = ($fResult1 / (($fResult2 <= 0)? 1 : $fResult2)) * $aOperate[7]; } else { $nTotal = (($aData[$aOperate[0]] - abs($aData[$aOperate[1]]) - $aData[$aOperate[3]]) / $aData[$aOperate[0]]) * $aOperate[7]; } } break; case 'net_profit' : if (isset($aData[$aOperate[0]]) && isset($aData[$aOperate[1]]) && isset($aData[$aOperate[2]]) ) { $nTotal = $aData[$aOperate[0]] - abs($aData[$aOperate[1]]) + $aData[$aOperate[2]]; } break; case 'prod_net_profit' : if (isset($aData[$aOperate[0]]) && isset($aData[$aOperate[1]]) && isset($aData[$aOperate[2]]) ) { $nTotal = $aData[$aOperate[0]] - $aData[$aOperate[1]] - abs($aData[$aOperate[2]]); } break; case 'prod_gross_profit' : if (isset($aData[$aOperate[0]]) && isset($aData[$aOperate[1]]) ) { $nTotal = $aData[$aOperate[0]] - $aData[$aOperate[1]]; } break; case 'prod_gross_margin' : if (isset($aData[$aOperate[0]]) && isset($aData[$aOperate[1]]) && floatval($aData[$aOperate[2]]) != 0 ) { $nTotal = (($aData[$aOperate[0]] - $aData[$aOperate[1]]) / $aData[$aOperate[2]]) * $aOperate[3]; } break; case 'prod_net_margin' : if (isset($aData[$aOperate[0]]) && isset($aData[$aOperate[1]]) && isset($aData[$aOperate[2]]) && floatval($aData[$aOperate[3]]) != 0 ) { $nTotal = (($aData[$aOperate[0]] - $aData[$aOperate[1]] - abs($aData[$aOperate[2]])) / $aData[$aOperate[3]]) * $aOperate[4]; } break; case 'id_image': if (version_compare(_PS_VERSION_, '1.5', '>')) { $link = Context::getContext()->link; } else { global $link; } $sImageLink = $link->getImageLink('product-image', $aData[$aOperate[0]] . '-' . $aData[$aOperate[1]], self::$_mShowPhotos); $nTotal = ''; break; case 'products_ordered': if (version_compare(_PS_VERSION_, '1.5', '>')) { $link = Context::getContext()->link; $sCustomerLink = $link->getAdminLink('AdminCustomers') . '&viewcustomer&id_customer='.$aData[$aOperate[0]]; } else { global $cookie; $token = Tools::getAdminToken('AdminCustomers'.(int)(Tab::getIdFromClassName('AdminCustomers')).(Tools::getValue('id_employee', $cookie->id_employee))); $sCustomerLink = $_SERVER['SCRIPT_NAME'] . '?tab=AdminCustomers&viewcustomer&id_customer=' . $aData[$aOperate[0]] . '&viewcustomer&token=' . $token; } $nTotal = '' . OrderTaxProfitReport::$oModule->l('View products', 'module-dao_class') . ''; break; case 'slip_total_no_tax' : if (array_key_exists($aOperate[0], $aData) && array_key_exists($aOperate[1], $aData) ) { $nTotal = $aData[$aOperate[0]] + $aData[$aOperate[1]]; } break; case 'slip_total_tax' : if (array_key_exists($aOperate[0], $aData) && array_key_exists($aOperate[1], $aData) ) { $nTotal = $aData[$aOperate[0]] + $aData[$aOperate[1]]; } break; case 'slip_total_incl' : if (array_key_exists($aOperate[0], $aData) && array_key_exists($aOperate[1], $aData) && array_key_exists($aOperate[2], $aData) && array_key_exists($aOperate[3], $aData) ) { $nTotal = $aData[$aOperate[0]] + $aData[$aOperate[1]] + $aData[$aOperate[2]] + $aData[$aOperate[3]]; } break; default: if (isset($aOperate[0])) { $nTotal = $aOperate[0]; } break; } return $nTotal; } /** * _setDefaultMsgSuffix() method set default msg * * @param string $sField * @param mixed $mVal * @return string */ private static function _setDefaultMsgSuffix($sField, $mVal) { // use case - current field needs to display default message if (!empty($GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['defaulttext']) && empty($mVal) ) { if (self::$_sOutputType != 'csv') { $mVal = '' . $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['defaulttext'] . ''; } else { $mVal = $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['defaulttext']; } } else { $mVal .= $GLOBALS[_OTPR_MODULE_NAME . '_COLS'][$sField]['suffix']; } return $mVal; } /** * _decodeAndStrip() method set default msg * * @param mixed $mVal * @return string */ private static function _decodeAndStrip($mVal) { return ( str_replace(';', ',', strip_tags(html_entity_decode($mVal))) ); } }