✏️ 正在编辑: swinvoiceexport.php
路径:
/home/bpioifn/www/pigmentse/modules/swinvoiceexport/swinvoiceexport.php
提示:
您可以编辑任何文件(包括二进制文件),但请注意不当修改可能导致文件损坏。
<?php /** * Invoice Export Module * * @author Sora Websoft SARL <support@sora-websoft.com> * @copyright 2012-2019 Sora Websoft SARL * @license Copyright (c) SARL Sora Websoft */ class Swinvoiceexport extends Module { public $sHtml; public function __construct() { $this->name = 'swinvoiceexport'; $this->tab = 'export'; $this->version = '2.3.0'; $this->displayName = $this->l('Invoice Export'); $this->author = 'Sora Websoft'; $this->need_instance = 1; $this->description = $this->l('Export invoices to .csv format'); $this->bootstrap = true; $this->module_key = 'd20d3274078049efa4d325d2e5a85c5f'; parent::__construct(); } public function install() { if (!parent::install() || !$this->registerHook('displayBackOfficeHeader')) { return false; } return true; } public function uninstall() { if (!parent::uninstall()) { return false; } return true; } public function getContent() { if (Tools::getValue('dlcsv')) { return $this->getDownloadProcess(); } if (_PS_VERSION_ <= 1.5 && Tools::getValue('ajax')) { if (Tools::getValue('action') == 'makeExport') { return $this->AjaxProcessMakeExport(); } } if (Tools::isSubmit('saveswinvoiceexport')) { $sDateStart = Tools::getValue('date_start'); $sDateEnd = Tools::getValue('date_end'); if (empty($sDateStart) || empty($sDateEnd)) { $this->sHtml .= $this->displayError($this->l('Fields Date Start and Date End are required')); } else { $sDateStart = self::getUSDate($sDateStart); $sDateEnd = self::getUSDate($sDateEnd); if (strtotime($sDateStart) > strtotime($sDateEnd)) { $this->sHtml .= $this->displayError($this->l('Date Start must not be more than the Date End')); } else { $aOrderState = OrderState::getOrderStates($this->context->language->id); $sStatesIds = ''; foreach ($aOrderState as $os) { if (Tools::getIsset('id_order_state_'.$os['id_order_state'])) { $sStatesIds .= $os['id_order_state'].','; } $sStates = Tools::substr($sStatesIds, 0, -1); } if (empty($sStatesIds)) { $sStates = 'all'; } $sParams = '&configure='.$this->name.'&startjob=1&ds='.$sDateStart; $sParams .= '&de='.$sDateEnd.'&encode='.Tools::getValue('id_encode').'&orderstate='.$sStates; Tools::redirectAdmin(Context::getContext()->link->getAdminLink('AdminModules').$sParams); } } } $sPath = _PS_MODULE_DIR_.$this->name.'/export/'; if (!is_writable($sPath)) { $this->context->controller->errors[] = sprintf($this->l('%s must be writable, please change permission on this dir in your FTP'), $sPath); } else { $this->sHtml .= $this->getLastUrlExport(); } $this->sHtml .= $this->displayFormSettings().$this->getFooter(); return $this->sHtml; } public function displayFormSettings() { $default_lang = (int)Configuration::get('PS_LANG_DEFAULT'); $aOrderState = OrderState::getOrderStates($this->context->language->id); $fields_form = array( 'legend' => array( 'title' => $this->l('Export Invoices'), ), 'input' => array( array( 'label' => $this->l('Start date'), 'type' => 'text', 'name' => 'date_start', 'id' => 'datepicker', 'lang' => false, 'col' => '3', 'maxlength' => 10, ), array( 'label' => $this->l('End date'), 'type' => 'text', 'name' => 'date_end', 'id' => 'datepicker2', 'lang' => false, 'col' => '3', 'maxlength' => 10, ), array( 'type' => 'checkbox', 'label' => $this->l('Export only States'), 'name' => 'id_order_state', 'col' => 4, 'default_value' => 0, 'class' => 'selectswinvoice', 'values' => array( 'query' => $aOrderState, 'id' => 'id_order_state', 'name' => 'name', ), 'desc' => '<span style="color:red">'.$this->l('Keep empty for export all states').'</span>', ), array( 'type' => 'select', 'label' => $this->l('Output format'), 'name' => 'id_encode', 'col' => 4, 'default_value' => 1, 'class' => 'selectswinvoice', 'options' => array( 'query' => $this->getEncodeMode(), 'id' => 'id_encode', 'name' => 'encode_mode', ), ), ), 'submit' => array( 'title' => $this->l('Export Invoices'), ), ); if (version_compare(_PS_VERSION_, '1.6.0.0', '<')) { $fields_form['input'][0]['desc'] = $this->l('Start export date'); $fields_form['input'][1]['desc'] = $this->l('End export date'); $fields_form['input'][3]['desc'] = $this->l('Output CSV format'); } else { $fields_form['input'][0]['hint'] = $this->l('Start export date'); $fields_form['input'][1]['hint'] = $this->l('End export date'); $fields_form['input'][3]['hint'] = $this->l('Output CSV format'); } $helper = new HelperForm(); $helper->module = $this; $helper->default_form_language = $default_lang; $helper->allow_employee_form_lang = $default_lang; $helper->toolbar_scroll = true; $helper->title = $this->displayName; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name; $helper->submit_action = 'save'.$this->name; $helper->fields_value = $this->getFormValues(); return $helper->generateForm(array(array('form' => $fields_form))); } private function getLastUrlExport() { if (file_exists(_PS_MODULE_DIR_.$this->name.'/export/invoices.csv')) { return $this->getDownloadLink(); } } public function getFooter() { $sLang = $this->l('module %s, version %s - PrestaShop %s compatible'); $this->context->smarty->assign(array( 'footerimg' => $this->_path.'views/img/footer.png', 'swVersion' => (version_compare(_PS_VERSION_, '1.6.0.0', '<') ? 1 : 0), 'footerlinefirst' => sprintf($this->l('Developped by %s'), $this->author), 'footerlinesecond' => sprintf($sLang, $this->displayName, $this->version, '1.5 - 1.7') )); return $this->display(__FILE__, 'views/templates/admin/configure.tpl'); } public function getDownloadLink() { $this->context->smarty->assign(array( 'sMsg' => $this->l('Click here for download last Invoice export'), 'sLink' => $this->getCSVurl(), 'swVersion' => (version_compare(_PS_VERSION_, '1.6.0.0', '<') ? 1 : 0) )); return $this->display(__FILE__, 'views/templates/admin/configure_infos.tpl'); } public static function getUSDate($sDate) { $sDate = explode('/', $sDate); return $sDate[2].'-'.$sDate[1].'-'.$sDate[0]; } public static function getFRDate($sDate) { $sDate = explode('-', $sDate); return $sDate[2].'/'.$sDate[1].'/'.$sDate[0]; } public function getFormValues() { $fields_value = array(); $fields_value['date_start'] = (Tools::getValue('ds') ? $this->getFRDate(Tools::getValue('ds')) : ''); $fields_value['date_end'] = (Tools::getValue('de') ? $this->getFRDate(Tools::getValue('de')) : ''); $fields_value['id_order_state'] = (Tools::getValue('id_order_state') ? Tools::getValue('id_order_state') : '1'); $fields_value['id_encode'] = (Tools::getValue('id_encode') ? Tools::getValue('id_encode') : '1'); return $fields_value; } private function getEncodeMode() { return array( array('id_encode' => 1, 'encode_mode' => 'UTF-8 '.$this->l('For OpenOffice, LibreOffice')), array('id_encode' => 2, 'encode_mode' => 'windows-1252 '.$this->l('For Microsoft Office')), ); } public function hookdisplaybackOfficeHeader($params) { if (Tools::getValue('configure') == $this->name) { if (_PS_VERSION_ >= 1.5 && method_exists($this->context->controller, 'addJquery')) { $this->context->controller->addJquery(); $this->context->controller->addJqueryUI('ui.datepicker'); } $this->context->controller->addCSS(__PS_BASE_URI__.'js/jquery/ui/themes/base/jquery.ui.theme.css'); $this->context->controller->addCSS(__PS_BASE_URI__.'js/jquery/ui/themes/base/jquery.ui.datepicker.css'); if (Tools::getIsset('startjob') && Tools::getValue('ds') && Tools::getValue('de')) { $this->context->controller->addJS(_MODULE_DIR_.$this->name.'/views/js/'.$this->name.'.js'); $this->context->smarty->assign(array( 'processing' => 1, 'url' => Context::getContext()->link->getAdminLink('AdminModules'), 'name' => $this->name, 'csvurl' => $this->getCSVurl(), 'ds' => Tools::getValue('ds'), 'de' => Tools::getValue('de'), 'encode' => Tools::getValue('encode'), 'orderstate' => Tools::getValue('orderstate'), )); } return $this->display(__FILE__, 'views/templates/admin/configure_header.tpl'); } } public function ajaxProcessMakeExport() { if (Tools::getValue('datestart') && Tools::getValue('dateend')) { $sCSV = $sTitleTaxProductCSV = $sTitleTaxCSV = ''; if (version_compare(_PS_VERSION_, '1.7.0', '<')) { $sCurrencySign = 'sign'; } else { $sCurrencySign = 'iso_code'; } $sql = 'SELECT oi.`id_order` as gid_order,oi.`number` as number, oi.`total_paid_tax_incl` as t_invoice, oi.`total_products` as t_products,oi.`total_products_wt` as t_products_wt, oi.`total_shipping_tax_incl` as t_shipping_wt, oi.`total_shipping_tax_excl` as t_shipping, oi.`total_wrapping_tax_incl` as t_wrapping_wt, oi.`total_wrapping_tax_excl` as t_wrapping, oi.`total_paid_tax_excl` as t_invoice_ht, DATE_FORMAT(oi.`date_add`, "%d/%m/%Y") as date, ods.`payment` as mpayment, ods.`current_state`, cur.`'.$sCurrencySign.'` as currency_sign, cu.`lastname` as clastname, cu.`firstname` as cfirstname, cy.`name` as country, op.`transaction_id`, GROUP_CONCAT(odt.`id_tax` SEPARATOR "-") as taxids FROM `'._DB_PREFIX_.'order_invoice` AS oi LEFT JOIN `'._DB_PREFIX_.'orders` ods ON (ods.`id_order` = oi.`id_order`) LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order` = oi.`id_order`) LEFT JOIN `'._DB_PREFIX_.'order_detail_tax` odt ON (odt.`id_order_detail` = od.`id_order_detail`) LEFT JOIN `'._DB_PREFIX_.'customer` cu ON (cu.`id_customer` = ods.`id_customer`) LEFT JOIN `'._DB_PREFIX_.'address` ad ON (ad.`id_address` = ods.`id_address_delivery`) LEFT JOIN `'._DB_PREFIX_.'country_lang` cy ON (cy.`id_country` = ad.`id_country`) LEFT JOIN `'._DB_PREFIX_.'order_invoice_payment` oip ON (oip.`id_order_invoice` = oi.`id_order_invoice`) LEFT JOIN `'._DB_PREFIX_.'order_payment` op ON (op.`id_order_payment` = oip.`id_order_payment`) LEFT JOIN `'._DB_PREFIX_.'currency` cur ON (cur.`id_currency` = ods.`id_currency`) WHERE cy.`id_lang`='.(int)$this->context->language->id.' AND oi.`date_add` >="'.pSQL(Tools::getValue('datestart')).' 00:00:00" AND oi.`date_add` <="'.pSQL(Tools::getValue('dateend')).' 23:59:59"'. ((int)$this->context->shop->id > 0 ? ' AND ods.`id_shop` ='.(int)$this->context->shop->id : '').' GROUP BY oi.`id_order_invoice` ORDER BY oi.date_add DESC'; /* echo '<pre>'.$sql.'</pre>'; die; */ if ($aRes = Db::getInstance()->ExecuteS($sql)) { $file = fopen(_PS_MODULE_DIR_.$this->name.'/export/invoices.csv', 'w'); $aS = array(); if (Tools::getValue('orderstate') && Tools::getValue('orderstate') != 'all') { $aStatesID = Tools::getValue('orderstate'); $aS = explode(',', $aStatesID); } $sTaxesIDs = ''; foreach ($aRes as $r) { if (!empty($r['taxids'])) { $sTaxesIDs .= $r['taxids'].'-'; } } if (empty($sTaxesIDs)) { $sTaxesIDs .= '0-'; } $aTaxesIDs = array(); if (!empty($sTaxesIDs)) { $aTaxesIDs = explode('-', Tools::substr($sTaxesIDs, 0, -1)); /* Dédoublonnement des ids taxes */ $aTaxesIDs = array_unique($aTaxesIDs); $aTaxesIDs = array_values($aTaxesIDs); for ($i = 0; $i < sizeof($aTaxesIDs); $i++) { $sql = 'SELECT `rate` FROM `'._DB_PREFIX_.'tax` WHERE `id_tax` = '.(int)$aTaxesIDs[$i].' ORDER BY `id_tax` ASC'; $sTaxRate = Db::getInstance()->getValue($sql); if (empty($sTaxRate)) { $sTaxRate = 0; } $number = number_format($sTaxRate, 2, '.', ''); $sTitleTaxProductCSV .= $this->l('Products tax excl.').' '.$number.'%;'; $sTitleTaxCSV .= $this->l('Products tax amount').' '.$number.'%;'; } } $sCSV .= $this->l('invoice date').';'; $sCSV .= $this->l('invoice number').';'; $sCSV .= $this->l('ID transaction').';'; $sCSV .= $this->l('Customer name').';'; $sCSV .= $this->l('Invoice tax incl.').';'; $sCSV .= $this->l('Total Products tax incl. without global reduction').';'; $sCSV .= $this->l('Total Products tax excl. without global reduction').';'; $sCSV .= $this->l('Total Products tax incl. with global reduction').';'; $sCSV .= $this->l('Total Products tax excl. with global reduction').';'; $sCSV .= $sTitleTaxProductCSV; $sCSV .= $sTitleTaxCSV; $sCSV .= $this->l('Wrapping tax incl.').';'; $sCSV .= $this->l('Wrapping tax excl.').';'; $sCSV .= $this->l('Wrapping tax amount').';'; $sCSV .= $this->l('Shipping tax incl.').';'; $sCSV .= $this->l('Shipping tax excl.').';'; $sCSV .= $this->l('Shipping tax amount').';'; $sCSV .= $this->l('Payment').';'; $sCSV .= $this->l('Currency sign').';'; $sCSV .= $this->l('Country destination').';'; $sCSV .= $this->l('State'); $sCSV .= "\n"; $i = 0; foreach ($aRes as $r) { $sql = 'SELECT oh.id_order_state, os.name as osl_name FROM `'._DB_PREFIX_.'order_history` AS oh LEFT JOIN `'._DB_PREFIX_.'order_state_lang` os ON (os.`id_order_state` = oh.`id_order_state`) WHERE oh.`id_order`='.(int)$r['gid_order'].' AND os.`id_lang`='.(int)$this->context->language->id.' ORDER BY oh.id_order_history DESC'; $h = Db::getInstance()->getRow($sql); $oState = $h['id_order_state']; $sOStateName = $h['osl_name']; if (empty($oState)) { $oState = $r['current_state']; $sql = 'SELECT `name` as osl_name FROM `'._DB_PREFIX_.'order_state_lang` WHERE `id_order_state`='.(int)$oState.' AND `id_lang`='.(int)$this->context->language->id; $sOStateName = Db::getInstance()->getValue($sql); } if (in_array($oState, $aS) || empty($aS)) { $i++; $sCSV .= $r['date'].';'; $sCSV .= sprintf('%06d', $r['number']).';'; $sCSV .= $r['transaction_id'].';'; $sCSV .= $r['clastname'].' '.$r['cfirstname'].';'; $sCSV .= number_format($r['t_invoice'], 2, '.', '').';'; $sCSV .= number_format($r['t_products_wt'], 2, '.', '').';'; $sCSV .= $r['t_products'].';'; $sCSV .= number_format(($r['t_invoice'] - $r['t_shipping_wt']), 2, '.', '').';'; $sCSV .= number_format(($r['t_invoice_ht'] - $r['t_shipping']), 6, '.', '').';'; for ($i = 0; $i < sizeof($aTaxesIDs); $i++) { $product_by_tax = $product_HT = 0; if ($aTaxesIDs[$i] > 0) { $sql = 'SELECT odt.`total_amount` as t_amount, od.`total_price_tax_excl` as priceht FROM `'._DB_PREFIX_.'order_detail_tax` as odt LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order_detail` = odt.`id_order_detail`) WHERE odt.`id_tax` = '.(int)$aTaxesIDs[$i].' AND od.`id_order`='.(int)$r['gid_order']; } else { $sql = 'SELECT 0 as t_amount, od.`total_price_tax_excl` as priceht FROM `'._DB_PREFIX_.'order_detail` od WHERE od.`id_order`='.(int)$r['gid_order'].' AND tax_rate=0'; } if ($aRes = Db::getInstance()->ExecuteS($sql)) { foreach ($aRes as $t) { $product_HT += $t['priceht']; if ($t['t_amount'] > 0) { $product_by_tax += $t['t_amount']; } } } $sCSV .= number_format($product_HT, 2, '.', '').';'; $sCSV .= number_format($product_by_tax, 2, '.', '').';'; } $sCSV .= number_format($r['t_wrapping_wt'], 2, '.', '').';'; $sCSV .= number_format($r['t_wrapping'], 2, '.', '').';'; $sCSV .= number_format(($r['t_wrapping_wt'] - $r['t_wrapping']), 2, '.', '').';'; $sCSV .= number_format($r['t_shipping_wt'], 2, '.', '').';'; $sCSV .= number_format($r['t_shipping'], 2, '.', '').';'; $sCSV .= number_format(($r['t_shipping_wt'] - $r['t_shipping']), 2, '.', '').';'; $sCSV .= $r['mpayment'].';'; $sCSV .= $r['currency_sign'].';'; $sCSV .= $r['country'].';'; $sCSV .= $sOStateName.';'; $sCSV .= "\n"; } } if ($i > 0) { if (Tools::getValue('encode') == 1) { fwrite($file, $sCSV); } else { fwrite($file, iconv("UTF-8", "windows-1252//IGNORE", $sCSV)); } fclose($file); echo Tools::jsonEncode('ok'); } } } die; } private function getCSVurl() { $sCurrentIndex = AdminController::$currentIndex; $sToken = Tools::getAdminTokenLite('AdminModules'); return $sCurrentIndex.'&dlcsv=1&configure='.$this->name.'&token='.$sToken; } private function getDownloadProcess() { $sPath = _PS_MODULE_DIR_.$this->name.'/export/invoices.csv'; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($sPath)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: '.filesize($sPath)); readfile($sPath); die; } }
💾 保存文件
← 返回文件管理器