From 87010acdcc0d452dd43585f39fc3ee4549e85779 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Zieli=C5=84ski?= Date: Tue, 3 Dec 2024 09:55:11 +0000 Subject: [PATCH] Commit old changes --- REST/functions.php | 6 +- include/language/en_us.EcmDropdownEditor.php | 5 +- include/language/pl_pl.EcmDropdownEditor.php | 5 +- .../EcmActions/metadata/detailviewdefs.php | 12 +- modules/EcmActions/metadata/editviewdefs.php | 180 +- modules/EcmActions/vardefs.php | 15 +- .../EcmProducts/javascript/stockAddress.js | 24 +- modules/EcmProducts/stockAddress.php | 2 +- .../BimIT-Reports/lib/xlsxGenerator.php | 1200 +++++++++ .../productionSchedule/productionSchedule.js | 190 ++ .../productionSchedule/productionSchedule.php | 172 ++ .../productionSchedule/productionSchedule.tpl | 202 ++ .../productsBySales/productsBySales.js | 97 +- .../productsBySales/productsBySales.php | 69 +- .../productsBySales/productsBySales.tpl | 38 +- modules/EcmReports/index.php | 5 +- modules/EcmSales/EcmSale.php | 2258 +++++++++-------- modules/EcmStockStates/rebuildStates.php | 2 +- themes/Sugar5/tpls/_headerModuleList.tpl | 5 + 19 files changed, 3167 insertions(+), 1320 deletions(-) create mode 100644 modules/EcmReports/BimIT-Reports/lib/xlsxGenerator.php create mode 100644 modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.js create mode 100644 modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.php create mode 100644 modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.tpl diff --git a/REST/functions.php b/REST/functions.php index c0cb292a..7138f836 100644 --- a/REST/functions.php +++ b/REST/functions.php @@ -49,10 +49,10 @@ $newPositionList = array(); $total_netto = 0; $total_brutto = 0; $total_discount = 0; $vats = array(); foreach ( $sale->position_list as $product ) { - echo 'Produkt: '.$product->product_code.''; - $p = getProduct($product->product_code); + echo 'Produkt: '.$product->product_code; + $p = getProduct(trim($product->product_code)); if (!$p) { - echo '  Produkt nie istnieje w bazie E5
'; + echo '  (produkt nie istnieje w bazie E5)
'; $gotAllProducts = false; continue; } else { diff --git a/include/language/en_us.EcmDropdownEditor.php b/include/language/en_us.EcmDropdownEditor.php index 9778bb8f..4432d9b2 100644 --- a/include/language/en_us.EcmDropdownEditor.php +++ b/include/language/en_us.EcmDropdownEditor.php @@ -1,5 +1,5 @@ array ( @@ -71,6 +71,7 @@ $customDoms = array ( '349b50d1-0a7b-b3bd-e72e-662b42ca98ae' => 'Foam 400ml', 'cb66a685-53e1-5f87-0a25-66967c7cb63b' => 'Doypack 210x285mm', '75f4bd2a-51a8-0767-635e-66dde15af79e' => 'Foam 200ml', + '225115e4-1ce2-9a98-b7a0-672930e3318c' => 'Blister tabletki 10szt. 2 g', ), 'ecmproducts_brand_dom' => array ( @@ -149,6 +150,8 @@ $customDoms = array ( 'd5f819ff-297b-c0d8-cfcd-66d0d0103806' => 'EcoExpert', '4144e574-4870-fa26-25a0-66d85b094f7b' => 'Office Discount', 'e00b0e4a-ba66-796d-3bcb-66d89240c2cd' => 'Printus', + '661bc56d-f77f-6d98-98be-672a06cf59ee' => 'AVCedukacja', + '8d09cc5f-2348-6d22-80dc-6736057e390d' => 'Seltino', ), 'ecmproducts_category_dom' => array ( diff --git a/include/language/pl_pl.EcmDropdownEditor.php b/include/language/pl_pl.EcmDropdownEditor.php index 914e9018..8acd75e2 100644 --- a/include/language/pl_pl.EcmDropdownEditor.php +++ b/include/language/pl_pl.EcmDropdownEditor.php @@ -1,5 +1,5 @@ array ( @@ -71,6 +71,7 @@ $customDoms = array ( '349b50d1-0a7b-b3bd-e72e-662b42ca98ae' => 'Pianka 400ml', 'cb66a685-53e1-5f87-0a25-66967c7cb63b' => 'Doypack 210x285mm', '75f4bd2a-51a8-0767-635e-66dde15af79e' => 'Pianka 200ml', + '225115e4-1ce2-9a98-b7a0-672930e3318c' => 'Blister tabletki 10szt. 2 g', ), 'ecmproducts_brand_dom' => array ( @@ -149,6 +150,8 @@ $customDoms = array ( 'd5f819ff-297b-c0d8-cfcd-66d0d0103806' => 'EcoExpert', '4144e574-4870-fa26-25a0-66d85b094f7b' => 'Office Discount', 'e00b0e4a-ba66-796d-3bcb-66d89240c2cd' => 'Printus', + '661bc56d-f77f-6d98-98be-672a06cf59ee' => 'AVCedukacja', + '8d09cc5f-2348-6d22-80dc-6736057e390d' => 'Seltino', ), 'ecmproducts_category_dom' => array ( diff --git a/modules/EcmActions/metadata/detailviewdefs.php b/modules/EcmActions/metadata/detailviewdefs.php index 0e601b1c..1fb75db6 100644 --- a/modules/EcmActions/metadata/detailviewdefs.php +++ b/modules/EcmActions/metadata/detailviewdefs.php @@ -58,14 +58,22 @@ $viewdefs [$module_name] = array ( 0 => array ( 'name' => 'category', 'label' => 'LBL_CATEGORY' - ) + ), + 1 => array ( + 'name' => 'shape', + 'label' => 'Forma' + ) ), 2 => array ( 0 => array ( 'name' => 'time', 'customCode' => '{$fields.time.value}', 'label' => 'LBL_TIME' - ) + ), + 1 => array ( + 'name' => 'performance', + 'label' => 'Wydajność' + ) ), 3 => array ( 0 => array ( diff --git a/modules/EcmActions/metadata/editviewdefs.php b/modules/EcmActions/metadata/editviewdefs.php index 6276eaa3..d91a8e9d 100644 --- a/modules/EcmActions/metadata/editviewdefs.php +++ b/modules/EcmActions/metadata/editviewdefs.php @@ -1,31 +1,31 @@ array ( - 'templateMeta' => array ( - 'maxColumns' => '2', - 'widths' => array ( - 0 => array ( - 'label' => '10', - 'field' => '30' - ), - 1 => array ( - 'label' => '10', - 'field' => '30' - ) - ), - 'useTabs' => false, - 'tabDefs' => array ( - 'DEFAULT' => array ( - 'newTab' => false, - 'panelDefault' => 'expanded' - ), - 'LBL_EDITVIEW_PANEL1' => array ( - 'newTab' => false, - 'panelDefault' => 'expanded' - ) - ), - 'javascript' => ' +$viewdefs [$module_name] = array( + 'EditView' => array( + 'templateMeta' => array( + 'maxColumns' => '2', + 'widths' => array( + 0 => array( + 'label' => '10', + 'field' => '30' + ), + 1 => array( + 'label' => '10', + 'field' => '30' + ) + ), + 'useTabs' => false, + 'tabDefs' => array( + 'DEFAULT' => array( + 'newTab' => false, + 'panelDefault' => 'expanded' + ), + 'LBL_EDITVIEW_PANEL1' => array( + 'newTab' => false, + 'panelDefault' => 'expanded' + ) + ), + 'javascript' => ' @@ -33,63 +33,73 @@ $viewdefs [$module_name] = array ( ', - 'includes' => array ( - 0 => array ( - 'file' => 'include/JSON.js' - ) - ) - ), - 'panels' => array ( - 'default' => array ( - 0 => array ( - 0 => array ( - 'name' => 'name', - 'label' => 'LBL_NAME', - 'tabIndex' => '100', - 'displayParams' => array ( - 'size' => 40 - ) - ), - 1 => array ( - 'name' => 'indeks', - 'label' => 'LBL_INDEKS', - 'tabindex' => '120', - ) - ), - 1 => array ( - 0 => array ( - 'name' => 'category', - 'label' => 'LBL_CATEGORY', - 'tabIndex' => '101', - ) - ), - 2 => array ( - 0 => array ( - 'name' => 'time', - 'customCode' => "{include file='modules/EcmActions/tpl/EditViewTime.tpl'}", - 'label' => 'LBL_TIME', - 'tabIndex' => '105', - ) - ), - 3 => array ( - 0 => array ( - 'name' => 'cost_action', - 'label' => 'LBL_COST_ACTION', - 'tabIndex' => '106', - ) - ), - 4 => array ( - 0 => array ( - 'name' => 'cost_hour', - 'label' => 'LBL_COST_HOUR', - 'tabIndex' => '107', - ) - ), - 6 => array ( - 0 => 'description' - ) - ) - ) - ) -); + 'includes' => array( + 0 => array( + 'file' => 'include/JSON.js' + ) + ) + ), + 'panels' => array( + 'default' => array( + 0 => array( + 0 => array( + 'name' => 'name', + 'label' => 'LBL_NAME', + 'tabIndex' => '100', + 'displayParams' => array( + 'size' => 40 + ) + ), + 1 => array( + 'name' => 'indeks', + 'label' => 'LBL_INDEKS', + 'tabindex' => '120', + ) + ), + 1 => array( + 0 => array( + 'name' => 'category', + 'label' => 'LBL_CATEGORY', + 'tabIndex' => '101', + ), + 1 => array( + 'name' => 'shape', + 'label' => 'Forma', + 'tabIndex' => '101', + ) + ), + 2 => array( + 0 => array( + 'name' => 'time', + 'customCode' => "{include file='modules/EcmActions/tpl/EditViewTime.tpl'}", + 'label' => 'LBL_TIME', + 'tabIndex' => '105', + ), + 1 => array ( + 'name' => 'performance', + 'label' => 'Wydajność', + 'tabIndex' => '101', + ) + ), + 3 => array( + 0 => array( + 'name' => 'cost_action', + 'label' => 'LBL_COST_ACTION', + 'tabIndex' => '106', + ) + ), + 4 => array( + 0 => array( + 'name' => 'cost_hour', + 'label' => 'LBL_COST_HOUR', + 'tabIndex' => '107', + ) + ), + 6 => array( + 0 => 'description' + ) + ) + ) + ) +) ?> diff --git a/modules/EcmActions/vardefs.php b/modules/EcmActions/vardefs.php index 85262184..24c6061b 100644 --- a/modules/EcmActions/vardefs.php +++ b/modules/EcmActions/vardefs.php @@ -129,7 +129,20 @@ $dictionary ['EcmAction'] = array ( 'size' => '20', 'enable_range_search' => false, 'precision' => '2' - ) + ), + 'shape' => array( + 'name' => 'shape', + 'options' => 'ecmproducts_shape_dom', + 'vname' => 'Forma', + 'len' => 36, + 'type' => 'enum' + ), + 'performance' => array( + 'name' => 'performance', + 'vname' => 'Wydajność', + 'type' => 'decimal', + 'len' => '15,2', + ), ), 'relationships' => array (), 'optimistic_locking' => true, diff --git a/modules/EcmProducts/javascript/stockAddress.js b/modules/EcmProducts/javascript/stockAddress.js index 462488ab..991aef82 100644 --- a/modules/EcmProducts/javascript/stockAddress.js +++ b/modules/EcmProducts/javascript/stockAddress.js @@ -114,12 +114,12 @@ function isAddressValid(id) { return false; } const segments = $(id).val().split("."); - if (parseInt(segments[0]) > 17) { - $(id + "Error").html("Błąd pierwszego segmentu [zakres 01-20]"); + if (parseInt(segments[0]) > 99) { + $(id + "Error").html("Błąd pierwszego segmentu [zakres 01-99]"); return false; } - if (parseInt(segments[1]) > 15) { - $(id + "Error").html("Błąd drugiego segmentu [zakres 01-15]"); + if (parseInt(segments[1]) > 99) { + $(id + "Error").html("Błąd drugiego segmentu [zakres 01-99]"); return false; } return true; @@ -138,24 +138,24 @@ $(document).ready(function () { $("#address").mask("AB.CD.E.F", { placeholder: "__.__._._", translation: { - A: { pattern: /[0-2]/ }, + A: { pattern: /[0-9]/ }, B: { pattern: /[0-9]/ }, - C: { pattern: /[0-1]/ }, + C: { pattern: /[0-9]/ }, D: { pattern: /[0-9]/ }, - E: { pattern: /[1-5]/ }, - F: { pattern: /[0-5]/ }, + E: { pattern: /[1-9]/ }, + F: { pattern: /[0-9]/ }, } }); if ($("#newAddress")) { $("#newAddress").mask("AB.CD.E.F", { placeholder: "__.__._._", translation: { - A: { pattern: /[0-2]/ }, + A: { pattern: /[0-9]/ }, B: { pattern: /[0-9]/ }, - C: { pattern: /[0-1]/ }, + C: { pattern: /[0-9]/ }, D: { pattern: /[0-9]/ }, - E: { pattern: /[1-5]/ }, - F: { pattern: /[0-5]/ }, + E: { pattern: /[1-9]/ }, + F: { pattern: /[0-9]/ }, } }); $("#newAddress").focus(() => $("#newAddressError").html("")); diff --git a/modules/EcmProducts/stockAddress.php b/modules/EcmProducts/stockAddress.php index d1c04c41..c4911210 100644 --- a/modules/EcmProducts/stockAddress.php +++ b/modules/EcmProducts/stockAddress.php @@ -35,7 +35,7 @@ break; } } else { - $pRes = $db->query("SELECT DISTINCT id, code FROM ecmproducts WHERE deleted=0 AND active=1"); + $pRes = $db->query("SELECT DISTINCT id, code FROM ecmproducts WHERE deleted=0 AND status != 'end_of_life';"); $codes = array(); while ($p = $db -> fetchByAssoc($pRes)) { $index = str_replace("'", "'", $p['code']); diff --git a/modules/EcmReports/BimIT-Reports/lib/xlsxGenerator.php b/modules/EcmReports/BimIT-Reports/lib/xlsxGenerator.php new file mode 100644 index 00000000..9475ebe4 --- /dev/null +++ b/modules/EcmReports/BimIT-Reports/lib/xlsxGenerator.php @@ -0,0 +1,1200 @@ +subject = ''; + $this->title = ''; + $this->author = ''; + $this->company = ''; + $this->manager = ''; + $this->description = ''; + $this->keywords = ''; + $this->category = ''; + $this->language = 'en-US'; + $this->lastModifiedBy = ''; + $this->application = __CLASS__; + + $this->curSheet = -1; + $this->defaultFont = 'Calibri'; + $this->defaultFontSize = 10; + $this->rtl = false; + $this->sheets = []; + $this->extLinkId = 0; + $this->SI = []; // sharedStrings index + $this->SI_KEYS = []; // & keys + + // https://c-rex.net/projects/samples/ooxml/e1/Part4/OOXML_P4_DOCX_numFmts_topic_ID0E6KK6.html + $this->NF = [ + self::N_RUB => '#,##0.00\ "₽"', + self::N_DOLLAR => '[$$-1]#,##0.00', + self::N_EURO => '#,##0.00\ [$€-1]' + ]; + $this->NF_KEYS = array_flip($this->NF); + + $this->BR_STYLE = [ + self::B_NONE => 'none', + self::B_THIN => 'thin', + self::B_MEDIUM => 'medium', + self::B_DASHED => 'dashed', + self::B_DOTTED => 'dotted', + self::B_THICK => 'thick', + self::B_DOUBLE => 'double', + self::B_HAIR => 'hair', + self::B_MEDIUM_DASHED => 'mediumDashed', + self::B_DASH_DOT => 'dashDot', + self::B_MEDIUM_DASH_DOT => 'mediumDashDot', + self::B_DASH_DOT_DOT => 'dashDotDot', + self::B_MEDIUM_DASH_DOT_DOT => 'mediumDashDotDot', + self::B_SLANT_DASH_DOT => 'slantDashDot' + ]; + + $this->XF = [ // styles 0 - num fmt, 1 - align, 2 - font, 3 - fill, 4 - font color, 5 - bgcolor, 6 - border, 7 - font size + [self::N_NORMAL, self::A_DEFAULT, self::F_NORMAL, self::FL_NONE, 0, 0, '', 0], + [self::N_NORMAL, self::A_DEFAULT, self::F_NORMAL, self::FL_GRAY_125, 0, 0, '', 0], // hack + ]; + $this->XF_KEYS[implode('-', $this->XF[0])] = 0; // & keys + $this->XF_KEYS[implode('-', $this->XF[1])] = 1; + $this->template = [ + '_rels/.rels' => ''."\r\n" + .''."\r\n" + .''."\r\n" + .''."\r\n" + .''."\r\n" + .'', + 'docProps/app.xml' => ''."\r\n" + .''."\r\n" + .'0'."\r\n" + .'{APP}'."\r\n" + .'{COMPANY}'."\r\n" + .'{MANAGER}'."\r\n" + .'', + 'docProps/core.xml' => ''."\r\n" + .''."\r\n" + .'{DATE}'."\r\n" + .'{TITLE}'."\r\n" + .'{SUBJECT}'."\r\n" + .'{AUTHOR}'."\r\n" + .'{LAST_MODIFY_BY}'."\r\n" + .'{KEYWORD}'."\r\n" + .'{DESCRIPTION}'."\r\n" + .'{CATEGORY}'."\r\n" + .'{LANGUAGE}'."\r\n" + .'{DATE}'."\r\n" + .'1'."\r\n" + .'', + 'xl/_rels/workbook.xml.rels' => ''."\r\n" + .'' + ."\r\n{RELS}\r\n", + 'xl/worksheets/sheet1.xml' => ''."\r\n" + .''."\r\n" + .''."\r\n" + ."{SHEETVIEWS}\r\n{COLS}\r\n{ROWS}\r\n{AUTOFILTER}{MERGECELLS}{HYPERLINKS}", + 'xl/worksheets/_rels/sheet1.xml.rels' => ''."\r\n" + .'{HYPERLINKS}', + 'xl/sharedStrings.xml' => ''."\r\n" + .'{STRINGS}', + 'xl/styles.xml' => ''."\r\n" + .'' + ."\r\n{NUMFMTS}\r\n{FONTS}\r\n{FILLS}\r\n{BORDERS}\r\n" + .'' + ."\r\n{XF}\r\n" + .'', + 'xl/workbook.xml' => ''."\r\n" + .''."\r\n" + .'{SHEETS}', + '[Content_Types].xml' => ''."\r\n" + .''."\r\n" + .''."\r\n" + .''."\r\n" + .''."\r\n" + .''."\r\n" + .''."\r\n" + .' +' + ."\r\n{TYPES}", + ]; + } + public static function create($title = null) + { + $xlsx = new static(); + if ($title) { + $xlsx->setTitle($title); + } + return $xlsx; + } + + public static function fromArray(array $rows, $sheetName = null) + { + $xlsx = new static(); + $xlsx->addSheet($rows, $sheetName); + if ($sheetName) { + $xlsx->setTitle($sheetName); + } + return $xlsx; + } + + public function addSheet(array $rows, $name = null) + { + $this->curSheet++; + if ($name === null) { // autogenerated sheet names + $name = ($this->title ? mb_substr($this->title, 0, 31) : 'Sheet') . ($this->curSheet + 1); + } else { + $name = mb_substr($name, 0, 31); + $names = []; + foreach ($this->sheets as $sh) { + $names[mb_strtoupper($sh['name'])] = 1; + } + for ($i = 0; $i < 100; $i++) { + $postfix = ' (' . $i . ')'; + $new_name = ($i === 0) ? $name : $name . $postfix; + if (mb_strlen($new_name) > 31) { + $new_name = mb_substr($name, 0, 31 - mb_strlen($postfix)) . $postfix; + } + $NEW_NAME = mb_strtoupper($new_name); + if (!isset($names[$NEW_NAME])) { + $name = $new_name; + break; + } + } + } + $this->sheets[$this->curSheet] = ['name' => $name, 'hyperlinks' => [], 'mergecells' => [], 'colwidth' => [], 'autofilter' => '', 'frozen' => '']; + if (isset($rows[0]) && is_array($rows[0])) { + $this->sheets[$this->curSheet]['rows'] = $rows; + } else { + $this->sheets[$this->curSheet]['rows'] = []; + } + return $this; + } + + public function __toString() + { + $fh = fopen('php://memory', 'wb'); + if (!$fh) { + return ''; + } + if (!$this->_write($fh)) { + fclose($fh); + return ''; + } + $size = ftell($fh); + fseek($fh, 0); + return (string)fread($fh, $size); + } + + public function save() + { + return $this->saveAs(($this->title ?: gmdate('YmdHi')) . '.xlsx'); + } + public function saveAs($filename) + { + $fh = fopen(str_replace(["\0","\r","\n","\t",'"'], '', $filename), 'wb'); + if (!$fh) { + return false; + } + if (!$this->_write($fh)) { + fclose($fh); + return false; + } + fclose($fh); + return true; + } + + public function download() + { + return $this->downloadAs(($this->title ?: gmdate('YmdHi')) . '.xlsx'); + } + + public function downloadAs($filename) + { + $fh = fopen('php://memory', 'wb'); + if (!$fh) { + return false; + } + if (!$this->_write($fh)) { + fclose($fh); + return false; + } + $size = ftell($fh); + header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + header('Content-Disposition: attachment; filename="' . str_replace(["\0","\r","\n","\t",'"'], '', $filename) . '"'); + header('Last-Modified: ' . gmdate('D, d M Y H:i:s \G\M\T', time())); + header('Content-Length: ' . $size); + while (ob_get_level()) { + ob_end_clean(); + } + fseek($fh, 0); + //Some servers disable fpassthru function. The alternative, stream_get_contents, use more memory + if (function_exists('fpassthru')) { + fpassthru($fh); + } else { + echo stream_get_contents($fh); + } + fclose($fh); + return true; + } + + protected function _write($fh) + { + $dirSignatureE = "\x50\x4b\x05\x06"; // end of central dir signature + $zipComments = 'Generated by ' . __CLASS__ . ' PHP class, thanks sergey.shuchkin@gmail.com'; + if (!$fh) { + return false; + } + $cdrec = ''; // central directory content + $entries = 0; // number of zipped files + $cnt_sheets = count($this->sheets); + if ($cnt_sheets === 0) { + $this->addSheet([], 'No data'); + $cnt_sheets = 1; + } + foreach ($this->template as $cfilename => $template) { + if ($cfilename === 'xl/_rels/workbook.xml.rels') { + $s = ''; + for ($i = 0; $i < $cnt_sheets; $i++) { + $s .= '\r\n"; + } + $s .= '' . "\r\n"; + $s .= ''; + + $template = str_replace('{RELS}', $s, $template); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } elseif ($cfilename === 'xl/workbook.xml') { + $s = ''; + foreach ($this->sheets as $k => $v) { + $s .= ''; + } + $search = ['{SHEETS}', '{APP}']; + $replace = [$s, self::esc($this->application)]; + $template = str_replace($search, $replace, $template); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } elseif ($cfilename === 'docProps/app.xml') { + $search = ['{APP}', '{COMPANY}', '{MANAGER}']; + $replace = [self::esc($this->application), self::esc($this->company), self::esc($this->manager)]; + $template = str_replace($search, $replace, $template); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } elseif ($cfilename === 'docProps/core.xml') { + $search = ['{DATE}', '{AUTHOR}', '{TITLE}', '{SUBJECT}', '{KEYWORD}', '{DESCRIPTION}', '{CATEGORY}', '{LANGUAGE}', '{LAST_MODIFY_BY}']; + $replace = [gmdate('Y-m-d\TH:i:s\Z'), self::esc($this->author), self::esc($this->title), self::esc($this->subject), self::esc($this->keywords), self::esc($this->description), self::esc($this->category), self::esc($this->language), self::esc($this->lastModifiedBy)]; + $template = str_replace($search, $replace, $template); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } elseif ($cfilename === 'xl/sharedStrings.xml') { + $si_cnt = count($this->SI); + if ($si_cnt) { + $si = []; + foreach ($this->SI as $s) { + $si[] = '' . (preg_match('/^\s|\s$/', $s) ? '' . $s . '' : '' . $s . '') . ''; + } + $template = str_replace(['{CNT}', '{STRINGS}'], [$si_cnt, implode("\r\n", $si)], $template); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } + } elseif ($cfilename === 'xl/worksheets/sheet1.xml') { + foreach ($this->sheets as $k => $v) { + $filename = 'xl/worksheets/sheet' . ($k + 1) . '.xml'; + $xml = $this->_sheetToXML($k, $template); + $this->_writeEntry($fh, $cdrec, $filename, $xml); + $entries++; + } + $xml = null; + } elseif ($cfilename === 'xl/worksheets/_rels/sheet1.xml.rels') { + foreach ($this->sheets as $k => $v) { + if ($this->extLinkId) { + $RH = []; + $filename = 'xl/worksheets/_rels/sheet' . ($k + 1) . '.xml.rels'; + foreach ($v['hyperlinks'] as $h) { + if ($h['ID']) { + $RH[] = ''; + } + } + $xml = str_replace('{HYPERLINKS}', implode("\r\n", $RH), $template); + $this->_writeEntry($fh, $cdrec, $filename, $xml); + $entries++; + } + } + $xml = null; + } elseif ($cfilename === '[Content_Types].xml') { + $TYPES = ['']; + foreach ($this->sheets as $k => $v) { + $TYPES[] = ''; + if ($this->extLinkId) { + $TYPES[] = ''; + } + } + $template = str_replace('{TYPES}', implode("\r\n", $TYPES), $template); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } elseif ($cfilename === 'xl/styles.xml') { + $NF = $XF = $FONTS = $F_KEYS = $FILLS = $FL_KEYS = []; + $BR = ['']; + $BR_KEYS = [0 => 0]; + foreach ($this->NF as $k => $v) { + $NF[] = ''; + } + foreach ($this->XF as $xf) { + // 0 - num fmt, 1 - align, 2 - font, 3 - fill, 4 - font color, 5 - bgcolor, 6 - border, 7 - font size + // fonts + $F_KEY = $xf[2] . '-' . $xf[4] . '-' . $xf[7]; + if (isset($F_KEYS[$F_KEY])) { + $F_ID = $F_KEYS[$F_KEY]; + } else { + $F_ID = $F_KEYS[$F_KEY] = count($FONTS); + $FONTS[] = '' + . ($xf[7] ? '' : '') + . ($xf[2] & self::F_BOLD ? '' : '') + . ($xf[2] & self::F_ITALIC ? '' : '') + . ($xf[2] & self::F_UNDERLINE ? '' : '') + . ($xf[2] & self::F_STRIKE ? '' : '') + . ($xf[2] & self::F_HYPERLINK ? '' : '') + . ($xf[2] & self::F_COLOR ? '' : '') + . ''; + } + // fills + $FL_KEY = $xf[3] . '-' . $xf[5]; + if (isset($FL_KEYS[$FL_KEY])) { + $FL_ID = $FL_KEYS[$FL_KEY]; + } else { + $FL_ID = $FL_KEYS[$FL_KEY] = count($FILLS); + $FILLS[] = '' : ' />') + . ''; + } + $align = ''; + if ($xf[1] & self::A_LEFT) { + $align .= ' horizontal="left"'; + } elseif ($xf[1] & self::A_RIGHT) { + $align .= ' horizontal="right"'; + } elseif ($xf[1] & self::A_CENTER) { + $align .= ' horizontal="center"'; + } + if ($xf[1] & self::A_TOP) { + $align .= ' vertical="top"'; + } elseif ($xf[1] & self::A_MIDDLE) { + $align .= ' vertical="center"'; + } elseif ($xf[1] & self::A_BOTTOM) { + $align .= ' vertical="bottom"'; + } + if ($xf[1] & self::A_WRAPTEXT) { + $align .= ' wrapText="1"'; + } + + // border + $BR_ID = 0; + if ($xf[6] !== '') { + $b = $xf[6]; + if (isset($BR_KEYS[$b])) { + $BR_ID = $BR_KEYS[$b]; + } else { + $BR_ID = count($BR_KEYS); + $BR_KEYS[$b] = $BR_ID; + $border = ''; + $ba = explode(' ', $b); + if (!isset($ba[1])) { + $ba[] = $ba[0]; + $ba[] = $ba[0]; + $ba[] = $ba[0]; + } + if (!isset($ba[4])) { // diagonal + $ba[] = 'none'; + } + $sides = ['left' => 3, 'right' => 1, 'top' => 0, 'bottom' => 2, 'diagonal' => 4]; + foreach ($sides as $side => $idx) { + $s = 'thin'; + $c = ''; + $va = explode('#', $ba[$idx]); + if (isset($va[1])) { + $s = $va[0] === '' ? 'thin' : $va[0]; + $c = $va[1]; + } elseif (in_array($va[0], $this->BR_STYLE, true)) { + $s = $va[0]; + } else { + $c = $va[0]; + } + if (strlen($c) === 6) { + $c = 'FF' . $c; + } + if ($s && $s !== 'none') { + $border .= '<' . $side . ' style="' . $s . '">' + . '' + . ''; + } else { + $border .= '<' . $side . '/>'; + } + } + $border .= ''; + $BR[] = $border; + } + } + $XF[] = ' 0 ? ' applyNumberFormat="1"' : '') + . ($F_ID > 0 ? ' applyFont="1"' : '') + . ($FL_ID > 0 ? ' applyFill="1"' : '') + . ($BR_ID > 0 ? ' applyBorder="1"' : '') + . ($align ? ' applyAlignment="1">' : '/>'); + } + // wrap collections + array_unshift($NF, ''); + $NF[] = ''; + array_unshift($XF, ''); + $XF[] = ''; + array_unshift($FONTS, ''); + $FONTS[] = ''; + array_unshift($FILLS, ''); + $FILLS[] = ''; + array_unshift($BR, ''); + $BR[] = ''; + + $template = str_replace( + ['{NUMFMTS}', '{FONTS}', '{XF}', '{FILLS}', '{BORDERS}'], + [implode("\r\n", $NF), implode("\r\n", $FONTS), implode("\r\n", $XF), implode("\r\n", $FILLS), implode("\r\n", $BR)], + $template + ); + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } else { + $this->_writeEntry($fh, $cdrec, $cfilename, $template); + $entries++; + } + } + $before_cd = ftell($fh); + fwrite($fh, $cdrec); + // end of central dir + fwrite($fh, $dirSignatureE); + fwrite($fh, pack('v', 0)); // number of this disk + fwrite($fh, pack('v', 0)); // number of the disk with the start of the central directory + fwrite($fh, pack('v', $entries)); // total # of entries "on this disk" + fwrite($fh, pack('v', $entries)); // total # of entries overall + fwrite($fh, pack('V', mb_strlen($cdrec, '8bit'))); // size of central dir + fwrite($fh, pack('V', $before_cd)); // offset to start of central dir + fwrite($fh, pack('v', mb_strlen($zipComments, '8bit'))); // .zip file comment length + fwrite($fh, $zipComments); + + return true; + } + + protected function _writeEntry($fh, &$cdrec, $cfilename, $data) + { + $zipSignature = "\x50\x4b\x03\x04"; // local file header signature + $dirSignature = "\x50\x4b\x01\x02"; // central dir header signature + + $e = []; + $e['uncsize'] = mb_strlen($data, '8bit'); + // if data to compress is too small, just store it + if ($e['uncsize'] < 256) { + $e['comsize'] = $e['uncsize']; + $e['vneeded'] = 10; + $e['cmethod'] = 0; + $zdata = $data; + } else { // otherwise, compress it + $zdata = gzcompress($data); + $zdata = substr(substr($zdata, 0, -4), 2); // fix crc bug (thanks to Eric Mueller) + $e['comsize'] = mb_strlen($zdata, '8bit'); + $e['vneeded'] = 10; + $e['cmethod'] = 8; + } + $e['bitflag'] = 0; + $e['crc_32'] = crc32($data); + + // Convert date and time to DOS Format, and set then + $date = getdate(); + $e['dostime'] = ( + (($date['year'] - 1980) << 25) + | ($date['mon'] << 21) + | ($date['mday'] << 16) + | ($date['hours'] << 11) + | ($date['minutes'] << 5) + | ($date['seconds'] >> 1) + ); + + $e['offset'] = ftell($fh); + + fwrite($fh, $zipSignature); + fwrite($fh, pack('v', $e['vneeded'])); // version_needed + fwrite($fh, pack('v', $e['bitflag'])); // general_bit_flag + fwrite($fh, pack('v', $e['cmethod'])); // compression_method + fwrite($fh, pack('V', $e['dostime'])); // lastmod datetime + fwrite($fh, pack('V', $e['crc_32'])); // crc-32 + fwrite($fh, pack('V', $e['comsize'])); // compressed_size + fwrite($fh, pack('V', $e['uncsize'])); // uncompressed_size + fwrite($fh, pack('v', mb_strlen($cfilename, '8bit'))); // file_name_length + fwrite($fh, pack('v', 0)); // extra_field_length + fwrite($fh, $cfilename); // file_name + // ignoring extra_field + fwrite($fh, $zdata); + + // Append it to central dir + $e['external_attributes'] = (substr($cfilename, -1) === '/' && !$zdata) ? 16 : 32; // Directory or file name + $e['comments'] = ''; + + $cdrec .= $dirSignature; + $cdrec .= "\x0\x0"; // version made by + $cdrec .= pack('v', $e['vneeded']); // version needed to extract + $cdrec .= "\x0\x0"; // general bit flag + $cdrec .= pack('v', $e['cmethod']); // compression method + $cdrec .= pack('V', $e['dostime']); // lastmod datetime + $cdrec .= pack('V', $e['crc_32']); // crc32 + $cdrec .= pack('V', $e['comsize']); // compressed filesize + $cdrec .= pack('V', $e['uncsize']); // uncompressed filesize + $cdrec .= pack('v', mb_strlen($cfilename, '8bit')); // file name length + $cdrec .= pack('v', 0); // extra field length + $cdrec .= pack('v', mb_strlen($e['comments'], '8bit')); // file comment length + $cdrec .= pack('v', 0); // disk number start + $cdrec .= pack('v', 0); // internal file attributes + $cdrec .= pack('V', $e['external_attributes']); // internal file attributes + $cdrec .= pack('V', $e['offset']); // relative offset of local header + $cdrec .= $cfilename; + $cdrec .= $e['comments']; + } + + protected function _sheetToXML($idx, $template) + { + // locale floats fr_FR 1.234,56 -> 1234.56 + $_loc = setlocale(LC_NUMERIC, 0); + setlocale(LC_NUMERIC, 'C'); + $COLS = []; + $ROWS = []; + // $SHEETVIEWS = 'rtl ? ' rightToLeft="1"' : '').'>'; + $SHEETVIEWS = ''; + $PANE = ''; + if (count($this->sheets[$idx]['rows'])) { + $ROWS[] = ''; + if ($this->sheets[$idx]['frozen'] !== '' || isset($this->sheets[$idx]['frozen'][0]) || isset($this->sheets[$idx]['frozen'][1])) { + // $AC = 'A1'; // Active Cell + $x = $y = 0; + if (is_string($this->sheets[$idx]['frozen'])) { + $AC = $this->sheets[$idx]['frozen']; + self::cell2coord($AC, $x, $y); + } else { + if (isset($this->sheets[$idx]['frozen'][0])) { + $x = $this->sheets[$idx]['frozen'][0]; + } + if (isset($this->sheets[$idx]['frozen'][1])) { + $y = $this->sheets[$idx]['frozen'][1]; + } + $AC = self::coord2cell($x, $y); + } + if ($x > 0 || $y > 0) { + $split = ''; + if ($x > 0) { + $split .= ' xSplit="' . $x . '"'; + } + if ($y > 0) { + $split .= ' ySplit="' . $y . '"'; + } + $activepane = 'bottomRight'; + if ($x > 0 && $y === 0) { + $activepane = 'topRight'; + } + if ($x === 0 && $y > 0) { + $activepane = 'bottomLeft'; + } + $PANE .= ''; + $PANE .= ''; + } + } + if ($this->rtl || $PANE) { + $SHEETVIEWS .= ' +rtl ? ' rightToLeft="1"' : ''); + $SHEETVIEWS .= $PANE ? ">\r\n" . $PANE . "\r\n" : ' />'; + $SHEETVIEWS .= "\r\n"; + } + $COLS[] = ''; + $CUR_ROW = 0; + $COL = []; + foreach ($this->sheets[$idx]['rows'] as $r) { + $CUR_ROW++; + $row = ''; + $CUR_COL = 0; + $RH = 0; // row height + foreach ($r as $v) { + $CUR_COL++; + if (!isset($COL[$CUR_COL])) { + $COL[$CUR_COL] = 0; + } + $cname = self::coord2cell($CUR_COL-1) . $CUR_ROW; + if ($v === null || $v === '') { + $row .= ''; + continue; + } + $ct = $cv = $cf = null; + $N = $A = $F = $FL = $C = $BG = $FS = $FR = 0; + $BR = ''; + if (is_string($v)) { + if ($v[0] === "\0") { // RAW value as string + $v = substr($v, 1); + $vl = mb_strlen($v); + } else { + if (strpos($v, '<') !== false) { // tags? + if (strpos($v, '') !== false) { + $F += self::F_BOLD; + } + if (strpos($v, '') !== false) { + $F += self::F_ITALIC; + } + if (strpos($v, '') !== false) { + $F += self::F_UNDERLINE; + } + if (strpos($v, '') !== false) { + $F += self::F_STRIKE; + } + if (preg_match('/]+)>/', $v, $m)) { + if (preg_match('/ color="([^"]+)"/', $m[1], $m2)) { + $F += self::F_COLOR; + $c = ltrim($m2[1], '#'); + $C = strlen($c) === 8 ? $c : ('FF' . $c); + } + if (preg_match('/ bgcolor="([^"]+)"/', $m[1], $m2)) { + $FL += self::FL_COLOR; + $c = ltrim($m2[1], '#'); + $BG = strlen($c) === 8 ? $c : ('FF' . $c); + } + if (preg_match('/ height="([^"]+)"/', $m[1], $m2)) { + $RH = $m2[1]; + } + if (preg_match('/ nf="([^"]+)"/', $m[1], $m2)) { + $c = htmlspecialchars_decode($m2[1], ENT_QUOTES); + $N = $this->getNumFmtId($c); + } + if (preg_match('/ border="([^"]+)"/', $m[1], $m2)) { + $b = htmlspecialchars_decode($m2[1], ENT_QUOTES); + if ($b && $b !== 'none') { + $BR = $b; + } + } + if (preg_match('/ font-size="([^"]+)"/', $m[1], $m2)) { + $FS = (int)$m2[1]; + if ($RH === 0) { // fix row height + $RH = ($FS > $this->defaultFontSize) ? round($FS * 1.50, 1) : 0; + } + } + } + if (strpos($v, '') !== false) { + $A += self::A_LEFT; + } + if (strpos($v, '
') !== false) { + $A += self::A_CENTER; + } + if (strpos($v, '') !== false) { + $A += self::A_RIGHT; + } + if (strpos($v, '') !== false) { + $A += self::A_TOP; + } + if (strpos($v, '') !== false) { + $A += self::A_MIDDLE; + } + if (strpos($v, '') !== false) { + $A += self::A_BOTTOM; + } + if (strpos($v, '') !== false) { + $A += self::A_WRAPTEXT; + } + if (preg_match('/(.*?)<\/a>/i', $v, $m)) { + $F += self::F_HYPERLINK; + + $h = explode('#', $m[1]); + if (count($h) === 1) { + if (strpos($h[0], '!') > 0) { // internal hyperlink + $this->sheets[$idx]['hyperlinks'][] = ['ID' => null, 'R' => $cname, 'H' => null, 'L' => $m[1]]; + } else { + $this->extLinkId++; + $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->extLinkId, 'R' => $cname, 'H' => $m[1], 'L' => '']; + } + } else { + $this->extLinkId++; + $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->extLinkId, 'R' => $cname, 'H' => $h[0], 'L' => $h[1]]; + } + } + // formatted raw? + if (preg_match('/(.*)<\/raw>/', $v, $m)) { + $FR = 1; + $v = $m[1]; + } elseif (preg_match('/]*)>/', $v, $m)) { + $cf = strip_tags($v); + $v = 0; + if (preg_match('/ v="([^"]+)"/', $m[1], $m2)) { + $v = $m2[1]; + } + } else { + $v = strip_tags($v); + } + } // \tags + $vl = mb_strlen($v); + if ($FR) { + $v = htmlspecialchars_decode($v); + $vl = mb_strlen($v); + } elseif ($N) { + $cv = ltrim($v, '+'); + } elseif ($v === '0' || preg_match('/^[-+]?[1-9]\d{0,14}$/', $v)) { // Integer as General + $cv = ltrim($v, '+'); + if ($vl > 10) { + $N = self::N_INT; // [1] 0 + } + } elseif (preg_match('/^[-+]?(0|[1-9]\d*)\.(\d+)$/', $v, $m)) { + $cv = ltrim($v, '+'); + if (strlen($m[2]) < 3) { + $N = self::N_DEC; + } + } elseif (preg_match('/^\$[-+]?[0-9\.]+$/', $v)) { // currency $? + $N = self::N_DOLLAR; + $cv = ltrim($v, '+$'); + } elseif (preg_match('/^[-+]?[0-9\.]+( ₽| €)$/u', $v, $m)) { // currency ₽ €? + if ($m[1] === ' ₽') { + $N = self::N_RUB; + } elseif ($m[1] === ' €') { + $N = self::N_EURO; + } + $cv = trim($v, ' +₽€'); + } elseif (preg_match('/^([-+]?\d+)%$/', $v, $m)) { + $cv = round($m[1] / 100, 2); + $N = self::N_PERCENT_INT; // [9] 0% + } elseif (preg_match('/^([-+]?\d+\.\d+)%$/', $v, $m)) { + $cv = round($m[1] / 100, 4); + $N = self::N_PRECENT_DEC; // [10] 0.00% + } elseif (preg_match('/^(\d\d\d\d)-(\d\d)-(\d\d)$/', $v, $m)) { + $cv = self::date2excel($m[1], $m[2], $m[3]); + $N = self::N_DATE; // [14] mm-dd-yy + } elseif (preg_match('/^(\d\d)\/(\d\d)\/(\d\d\d\d)$/', $v, $m)) { + $cv = self::date2excel($m[3], $m[2], $m[1]); + $N = self::N_DATE; // [14] mm-dd-yy + } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $v, $m)) { + $cv = self::date2excel(0, 0, 0, $m[1], $m[2], $m[3]); + $N = self::N_TIME; // time + } elseif (preg_match('/^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$/', $v, $m)) { + $cv = self::date2excel($m[1], $m[2], $m[3], $m[4], $m[5], $m[6]); + $N = ((int)$m[1] === 0) ? self::N_TIME : self::N_DATETIME; // [22] m/d/yy h:mm + } elseif (preg_match('/^(\d\d)\/(\d\d)\/(\d\d\d\d) (\d\d):(\d\d):(\d\d)$/', $v, $m)) { + $cv = self::date2excel($m[3], $m[2], $m[1], $m[4], $m[5], $m[6]); + $N = self::N_DATETIME; // [22] m/d/yy h:mm + } elseif (preg_match('/^[0-9+-.]+$/', $v)) { // Long ? + $A += ($A & (self::A_LEFT | self::A_CENTER)) ? 0 : self::A_RIGHT; + } elseif (preg_match('/^https?:\/\/\S+$/i', $v)) { // Hyperlink ? + $h = explode('#', $v); + $this->extLinkId++; + $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->extLinkId, 'R' => $cname, 'H' => $h[0], 'L' => isset($h[1]) ? $h[1] : '']; + $F += self::F_HYPERLINK; + } elseif (preg_match("/^[a-zA-Z0-9_\.\-]+@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/", $v)) { // email? + $this->extLinkId++; + $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->extLinkId, 'R' => $cname, 'H' => 'mailto:' . $v, 'L' => '']; + $F += self::F_HYPERLINK; + } elseif (strpos($v,"\n") !== false) { + $A |= self::A_WRAPTEXT; + } + + if (($N === self::N_DATE || $N === self::N_DATETIME) && $cv < 0) { + $cv = null; + $N = 0; + } + + } + if ($cv === null) { + $v = self::esc($v); + if ($cf) { + $ct = 'str'; + $cv = $v; + } elseif (mb_strlen($v) > 160) { + $ct = 'inlineStr'; + $cv = $v; + } else { + $ct = 's'; // shared string + $cv = false; + $skey = '~' . $v; + if (isset($this->SI_KEYS[$skey])) { + $cv = $this->SI_KEYS[$skey]; + } + if ($cv === false) { + $this->SI[] = $v; + $cv = count($this->SI) - 1; + $this->SI_KEYS[$skey] = $cv; + } + } + } + } elseif (is_int($v)) { + $vl = mb_strlen((string)$v); + $cv = $v; + } elseif (is_float($v)) { + $vl = mb_strlen((string)$v); + $cv = $v; + } elseif ($v instanceof \DateTime) { + $vl = 16; + $cv = self::date2excel($v->format('Y'), $v->format('m'), $v->format('d'), $v->format('H'), $v->format('i'), $v->format('s')); + $N = self::N_DATETIME; // [22] m/d/yy h:mm + } else { + continue; + } + $COL[$CUR_COL] = max($vl, $COL[$CUR_COL]); + $cs = 0; + if (($N + $A + $F + $FL + $FS > 0) || $BR !== '') { + if ($FL === self::FL_COLOR) { + $FL += self::FL_SOLID; + } + if (($F & self::F_HYPERLINK) && !($F & self::F_COLOR)) { + $F += self::F_COLOR; + $C = 'FF0563C1'; + } + $XF_KEY = $N . '-' . $A . '-' . $F . '-' . $FL . '-' . $C . '-' . $BG . '-' . $BR . '-' . $FS; + if (isset($this->XF_KEYS[$XF_KEY])) { + $cs = $this->XF_KEYS[$XF_KEY]; + } + if ($cs === 0) { + $cs = count($this->XF); + $this->XF_KEYS[$XF_KEY] = $cs; + $this->XF[] = [$N, $A, $F, $FL, $C, $BG, $BR, $FS]; + } + } + $row .= '' + . ($cf ? '' . $cf . '' : '') + . ($ct === 'inlineStr' ? '' . $cv . '' : '' . $cv . '') . "\r\n"; + } + $ROWS[] = '' . $row . ""; + } + foreach ($COL as $k => $max) { + $w = isset($this->sheets[$idx]['colwidth'][$k]) ? $this->sheets[$idx]['colwidth'][$k] : min($max + 1, 60); + $COLS[] = ''; + } + $COLS[] = ''; + $ROWS[] = ''; + $REF = 'A1:' . self::coord2cell(count($COL)-1) . $CUR_ROW; + } else { + $ROWS[] = ''; + $REF = 'A1:A1'; + } + + $AUTOFILTER = ''; + if ($this->sheets[$idx]['autofilter']) { + $AUTOFILTER = ''; + } + + $MERGECELLS = []; + if (count($this->sheets[$idx]['mergecells'])) { + $MERGECELLS[] = ''; + $MERGECELLS[] = ''; + foreach ($this->sheets[$idx]['mergecells'] as $m) { + $MERGECELLS[] = ''; + } + $MERGECELLS[] = ''; + } + + $HYPERLINKS = []; + if (count($this->sheets[$idx]['hyperlinks'])) { + $HYPERLINKS[] = ''; + foreach ($this->sheets[$idx]['hyperlinks'] as $h) { + $HYPERLINKS[] = ''; + } + $HYPERLINKS[] = ''; + } + + //restore locale + setlocale(LC_NUMERIC, $_loc); + + return str_replace( + ['{REF}', '{COLS}', '{ROWS}', '{AUTOFILTER}', '{MERGECELLS}', '{HYPERLINKS}', '{SHEETVIEWS}'], + [ + $REF, + implode("\r\n", $COLS), + implode("\r\n", $ROWS), + $AUTOFILTER, + implode("\r\n", $MERGECELLS), + implode("\r\n", $HYPERLINKS), + $SHEETVIEWS + ], + $template + ); + } + + public function setDefaultFont($name) + { + $this->defaultFont = $name; + return $this; + } + + public function setDefaultFontSize($size) + { + $this->defaultFontSize = $size; + return $this; + } + + public function setTitle($title) + { + $this->title = $title; + return $this; + } + public function setSubject($subject) + { + $this->subject = $subject; + return $this; + } + public function setAuthor($author) + { + $this->author = $author; + return $this; + } + public function setCompany($company) + { + $this->company = $company; + return $this; + } + public function setManager($manager) + { + $this->manager = $manager; + return $this; + } + public function setKeywords($keywords) + { + $this->keywords = $keywords; + return $this; + } + public function setDescription($description) + { + $this->description = $description; + return $this; + } + public function setCategory($category) + { + $this->category = $category; + return $this; + } + + public function setLanguage($language) + { + $this->language = $language; + return $this; + } + + public function setApplication($application) + { + $this->application = $application; + return $this; + } + public function setLastModifiedBy($lastModifiedBy) + { + $this->lastModifiedBy = $lastModifiedBy; + return $this; + } + + /** + * @param $range string 'A2:B10' + * @return $this + */ + public function autoFilter($range) + { + $this->sheets[$this->curSheet]['autofilter'] = $range; + return $this; + } + + public function mergeCells($range) + { + $this->sheets[$this->curSheet]['mergecells'][] = $range; + return $this; + } + + public function setColWidth($col, $width) + { + $this->sheets[$this->curSheet]['colwidth'][$col] = $width; + return $this; + } + public function rightToLeft($value = true) + { + $this->rtl = $value; + return $this; + } + + public function freezePanes($cell) + { + $this->sheets[$this->curSheet]['frozen'] = $cell; + return $this; + } + + public function getNumFmtId($code) + { + if (isset($this->NF[$code])) { // id? + return (int)$code; + } + if (isset($this->NF_KEYS[$code])) { + return $this->NF_KEYS[$code]; + } + $id = 197 + count($this->NF); // custom + $this->NF[$id] = $code; + $this->NF_KEYS[$code] = $id; + return $id; + } + + public static function date2excel($year, $month, $day, $hours = 0, $minutes = 0, $seconds = 0) + { + $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400; + $year = (int) $year; + $month = (int) $month; + $day = (int) $day; +// echo "y=$year m=$month d=$day h=$hours m=$minutes s=$seconds".PHP_EOL; + if ($year === 0) { + return $excelTime; + } + // self::CALENDAR_WINDOWS_1900 + $excel1900isLeapYear = 1; + if (($year === 1900) && ($month <= 2)) { + $excel1900isLeapYear = 0; + } + $myExcelBaseDate = 2415020; + // Julian base date Adjustment + if ($month > 2) { + $month -= 3; + } else { + $month += 9; + --$year; + } + $century = floor($year / 100); + $decade = $year - floor($year / 100) * 100; +// echo "y=$year m=$month d=$day cent=$century dec=$decade h=$hours m=$minutes s=$seconds".PHP_EOL; + // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0) + $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myExcelBaseDate + $excel1900isLeapYear; + return (float)$excelDate + $excelTime; + } + + + + public static function esc($str) + { + // XML UTF-8: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] + // but we use fast version + return str_replace(['&', '<', '>', "\x00", "\x03", "\x0B"], ['&', '<', '>', '', '', ''], $str); + } + + + public static function raw($value) + { + return "\0" . $value; + } + + public static function cell2coord($cell, &$x, &$y) + { + $x = $y = 0; + if (preg_match('/^([A-Z]+)(\d+)$/', $cell, $m)) { + $len = strlen($m[1]); + for ($i = 0; $i < $len; $i++) { + $int = ord($m[1][$i]) - 65; // A -> 0, B -> 1 + $int += ($i === $len - 1) ? 0 : 1; + $x += $int * pow(26, $len-$i-1); + } + $y = ((int)$m[2]) - 1; + } + } + + public static function coord2cell($x, $y = null) + { + $c = ''; + for ($i = $x; $i >= 0; $i = ((int)($i / 26)) - 1) { + $c = chr(65 + $i % 26) . $c; + } + return $c . ($y === null ? '' : ($y + 1)); + } + +} \ No newline at end of file diff --git a/modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.js b/modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.js new file mode 100644 index 00000000..b994dff6 --- /dev/null +++ b/modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.js @@ -0,0 +1,190 @@ +/*jshint esversion: 6 */ + +$(document).ready(function () { + $.tablesorter.addParser({ + id: "production_date", + is: function () { + return false; + }, + format: function (s, table, cell) { + return $(cell).find("input[id^=production-date]").val() || "1970-01-01"; + }, + parsed: false, + type: "text" + }); + $("#allTable").tablesorter({ + sortList: [[3, 1]], + theme: "blue", + widthFixed: true, + widgets: ["filter", "zebra", "stickyHeaders"], + fixedWidth: true, + widgetOptions: { + resizable: false, + filter_formatter: { + 7: function (cell, index) { + return $.tablesorter.filterFormatter.select2(cell, index, { + match: true + }); + }, + 8: function (cell, index) { + return $.tablesorter.filterFormatter.select2(cell, index, { + match: true + }); + }, + 9: function (cell, index) { + return $.tablesorter.filterFormatter.select2(cell, index, { + match: true + }); + }, + 10: function (cell, index) { + return $.tablesorter.filterFormatter.select2(cell, index, { + match: true + }); + }, + 12: function (cell, index) { + return $.tablesorter.filterFormatter.select2(cell, index, { + match: true + }); + }, + 13: function (cell, index) { + return $.tablesorter.filterFormatter.select2(cell, index, { + match: true + }); + }, + }, + filter_functions: { + 3: function (e, f, i) { + return f.includes(i); + } + } + }, + headers: { + 3: { sorter: "production_date" }, + }, + }); + $("#duplicateBtn").click(() => duplicatePositions()); + $("#deleteBtn").click(() => { removePositions(); }); + $("#excelBtn").click(() => { exportExcel(); }); + $("#pdfBtn").click(() => { window.alert("In progress."); }); + $("#productionBtn").click(() => { window.alert("In progress."); }); +}); + +function editQty(id) { + $("#edit-" + id).css("display", "none"); + $("#qty-" + id).css("display", "none"); + $("#qtyInput-" + id).css("display", "inline"); + $("#qtyInput-" + id).select(); + $("#save-" + id).css("display", "inline-block"); +} +function saveQty(id) { + showLoader("Trwa aktualizacja..."); + $("#edit-" + id).css("display", "inline-block"); + $("#qty-" + id).css("display", "inline"); + $("#qtyInput-" + id).css("display", "none"); + $("#save-" + id).css("display", "none"); + $.ajax({ + method: "get", + url: $(location).attr("href") + "&to_pdf=1&ajaxAction=saveQty&id=" + id + "&qty=" + $("#qtyInput-" + id).val(), + success: function () { + $("#qty-" + id).html($("#qtyInput-" + id).val()); + hideLoader(); + }, + }); +} +function duplicatePositions() { + var ids = []; + $("input.allCheck:checkbox:checked").each(function () { + ids.push($(this).val()); + }); + if (ids.length === 0) { + window.alert("Wybierz pozycje zamówień"); + return; + } + var userResponse = window.confirm("Zduplikować pozycje?"); + if (!userResponse) { return; } + showLoader("Duplikowanie..."); + $.ajax({ + method: "get", + url: $(location).attr("href") + "&to_pdf=1&ajaxAction=duplicatePositions&ids=" + ids.join("|"), + success: function () { + window.location.reload(); + }, + }); +} +function removePositions() { + var ids = []; + $("input.allCheck:checkbox:checked").each(function () { + ids.push($(this).val()); + }); + if (ids.length === 0) { + window.alert("Wybierz pozycje zamówień"); + return; + } + var userResponse = window.confirm("Usunąć pozycje?"); + if (!userResponse) { return; } + showLoader("Usuwanie..."); + $.ajax({ + method: "get", + url: $(location).attr("href") + "&to_pdf=1&ajaxAction=removePositions&ids=" + ids.join("|"), + success: function () + { + window.location.reload(); + }, + }); +} +function saveProductionDate(id) { + $.ajax({ + method: "get", + url: $(location).attr("href") + "&to_pdf=1&ajaxAction=saveProductionDate&id=" + id + "&date=" + $("#production-date-" + id).val(), + }); +} +function editDescription(id) { + $("#edit-description-" + id).css("display", "none"); + $("#description-" + id).css("display", "none"); + $("#descriptionInput-" + id).css("display", "inline"); + $("#descriptionInput-" + id).select(); + $("#save-description-" + id).css("display", "inline-block"); +} +function saveDescription(id) { + $("#edit-description-" + id).css("display", "inline-block"); + $("#description-" + id).css("display", "inline"); + $("#descriptionInput-" + id).css("display", "none"); + $("#save-description-" + id).css("display", "none"); + $.ajax({ + method: "get", + url: $(location).attr("href") + "&to_pdf=1&ajaxAction=saveProductDescription&id=" + id + "&description=" + $("#descriptionInput-" + id).val(), + success: function (data) { + $("#description-" + id).html($("#descriptionInput-" + id).val()); + }, + }); +} +function showLoader(msg = "Pobieranie danych") { + $.blockUI({ + css: { + border: "none", + padding: "15px", + backgroundColor: "#000", + "-webkit-border-radius": "10px", + "-moz-border-radius": "10px", + opacity: 0.5, + "font-weight": "bold", + "font-size": "16px", + color: "#fff", + }, + message: msg + }); +} +function hideLoader() { + $.unblockUI(); +} +function exportExcel() { + showLoader("Generowanie pliku..."); + $.ajax({ + method: "get", + url: $(location).attr("href") + "&to_pdf=1&ajaxAction=exportExcel", + success: function (data) + { + window.console.log(data); + }, + }); +} \ No newline at end of file diff --git a/modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.php b/modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.php new file mode 100644 index 00000000..f27f326a --- /dev/null +++ b/modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.php @@ -0,0 +1,172 @@ += '$dateFrom' AND ps.production_date <= '$dateTo' + ORDER BY s.delivery_date, s.register_date, s.document_no"; + + $rows = $db->query($query); + $data = array(); + $i = 0; + while ($r = $db->fetchByAssoc($rows)) { + $row = array(); + $i++; + $row['position'] = $i; + $row['id'] = $r['id']; + $row['productName'] = strlen($r['name']) > 55 ? substr($r['name'], 0, 55) . "..." : $r['name']; + $row['productFullName'] = $r['name']; + $row['productCode'] = strlen($r['code']) > 20 ? substr($r['code'], 0, 20) . "..." : $r['code']; + $row['productFullCode'] = $r['code']; + $row['productId'] = $r['ecmproduct_id']; + $row['productQty'] = $r['quantity']; + $row['qty'] = $r['scheduledQuantity']; + $row['productKind'] = $r['kind']; + $row['productSize'] = $r['size']; + $row['productShape'] = $app_list_strings['ecmproducts_shape_dom'][$r['shape']]; + $row['productBrand'] = $app_list_strings['ecmproducts_brand_dom'][$r['brand']]; + $row['orderNo'] = $r['document_no']; + $row['orderId'] = $r['id']; + $row['orderStatus'] = $app_list_strings['ecmsales_status_dom'][$r['status']]; + $row['orderType'] = $app_list_strings['ecmsales_type_dom'][$r['type']]; + $row['orderParent'] = $r['parent_name']; + $row['orderParentId'] = $r['parent_id']; + $row['orderSendDate'] = $r['send_date']; + $row['orderItemId'] = $r['item_id']; + $row['description'] = strlen($r['description']) > 0 ? substr($r['description'], 0, 30) : ''; + $row['fullDescription'] = $r['description']; + $row['shippingTo'] = ($r['shipping_address_name'] == 'Adres korespondencyjny' ? '' : $r['shipping_address_name']); + $row['productionDate'] = $r['production_date'] == '0000-00-00' ? '' : $r['production_date']; + $row['productStockState'] = $r['stockState'] | 0; + + $data[] = $row; + } + + $smarty = new Sugar_Smarty(); + $smarty->assign("data", $data); + $smarty->assign("dateFrom", $GLOBALS['timedate']->to_display_date($dateFrom)); + $smarty->assign("dateTo", $GLOBALS['timedate']->to_display_date($dateTo)); + echo $smarty->display('modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.tpl'); +} else { + switch ($_GET['ajaxAction']) { + case 'saveQty': + saveQty($_GET['id'], $_GET['qty']); + break; + case 'duplicatePositions': + duplicatePositions($_GET['ids']); + break; + case 'removePositions': + removePositions($_GET['ids']); + break; + case 'saveProductionDate': + saveProductionDate($_GET['id'], $_GET['date']); + break; + case 'saveProductDescription': + saveProductDescription($_GET['id'], $_GET['description']); + break; + case 'exportExcel': + exportExcel(); + break; + } +} + +function saveQty($id, $qty) +{ + $db = $GLOBALS['db']; + $query = sprintf("UPDATE productionScheduler SET quantity='%d' WHERE id='%s'", $qty, $id); + $db->query($query); +} + +function duplicatePositions($ids) +{ + $db = $GLOBALS['db']; + global $current_user; + $ids = explode("|", $ids); + foreach ($ids as $id) { + $res = $db->fetchByAssoc($db->query("SELECT * FROM productionScheduler WHERE id ='$id'")); + $query = sprintf("INSERT INTO productionScheduler VALUES ('%s', '%s', '%s', '%d', NOW(), NOW(), '%s', '%s', 0, '%s', '%d', '%s', '%s');", + generateUuidV4(), $res['ecmsaleitem_id'], $res['ecmsale_id'], $res['quantity'], $current_user->id, $current_user->id, $res['ecmproduct_id'], + $res['is_component'], $res['production_date'], $res['description']); + $db->query($query); + } +} + +function removePositions($ids) +{ + $db = $GLOBALS['db']; + global $current_user; + $ids = explode("|", $ids); + $query = sprintf("UPDATE productionScheduler SET deleted=1, modified_user_id='%s', date_modified=NOW() WHERE id IN ('%s')", + $current_user->id, join("','", $ids)); + $db->query($query); +} +function saveProductionDate($id, $date) +{ + $db = $GLOBALS['db']; + $date = date("Y-m-d", strtotime($date)); + if ($date == '1970-01-01') { + $db->query("UPDATE productionScheduler SET production_date=NULL WHERE id='$id'"); + } else { + $db->query("UPDATE productionScheduler SET production_date='$date' WHERE id='$id'"); + } +} +function saveProductDescription($id, $description) +{ + $db = $GLOBALS['db']; + $description = mysql_escape_string($description); + $db->query("UPDATE productionScheduler SET description='$description' WHERE id='$id'"); + echo "UPDATE productionScheduler SET description='$description' WHERE id='$id'"; +} +function exportExcel() { + echo 'bhhh'; + require_once 'modules/EcmReports/BimIT-Reports/lib/xlsxGenerator.php'; + echo 'qqqqqq'; + $books = [ + ['ISBN', 'title', 'author', 'publisher', 'ctry' ], + [618260307, 'The Hobbit', 'J. R. R. Tolkien', 'Houghton Mifflin', 'USA'], + [908606664, 'Slinky Malinki', 'Lynley Dodd', 'Mallinson Rendel', 'NZ'] + ]; + echo 'a'; + $xlsx = Shuchkin\SimpleXLSXGen::fromArray( $books ); + echo json_encode($xlsx); + $xlsx->saveAs('books.xlsx'); + echo 'done'; +} +function generateUuidV4() +{ + $data = openssl_random_pseudo_bytes(16); + $data[6] = chr(ord($data[6]) & 0x0f | 0x40); + $data[8] = chr(ord($data[8]) & 0x3f | 0x80); + return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); +} \ No newline at end of file diff --git a/modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.tpl b/modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.tpl new file mode 100644 index 00000000..d18a2d78 --- /dev/null +++ b/modules/EcmReports/BimIT-Reports/productionSchedule/productionSchedule.tpl @@ -0,0 +1,202 @@ + + + + + + + + + + + + + + + + + +
+ + +

Harmonogram Produkcji

+
+
+ + +
+ + + + + + + +
+ Data produkcji: od +   + + + +   + do +   + + Enter Date + +    +
+
+ + +    + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + {foreach from=$data item=ROW name=loop} + + + + + + + + + + + + + + + + + + + {/foreach} + +
 IndeksNazwaData produkcjiIlośćIlość ZSStanZS E5TypStatusZamawiającyOdbiorcaFormaMarkaData wysyłkiUwagi
+ + + + + {$ROW.productCode} + + + {$ROW.productName} + + + + + +
+ +
{$ROW.qty} +
+ +
+ {$ROW.productQty} + + {$ROW.productStockState} + + + {$ROW.orderNo} + + + {$ROW.orderType} + + {$ROW.orderStatus} + + + {$ROW.orderParent} + + + {$ROW.shippingTo} + + {$ROW.productShape} + + {$ROW.productBrand} + + {$ROW.orderSendDate} + +
+ +
{$ROW.description} +
+ +
+
diff --git a/modules/EcmReports/BimIT-Reports/productsBySales/productsBySales.js b/modules/EcmReports/BimIT-Reports/productsBySales/productsBySales.js index e72f5bce..ffdaccbb 100644 --- a/modules/EcmReports/BimIT-Reports/productsBySales/productsBySales.js +++ b/modules/EcmReports/BimIT-Reports/productsBySales/productsBySales.js @@ -1,15 +1,4 @@ $(document).ready(function () { - $.tablesorter.addParser({ - id: 'production_date', - is: function (s, table, cell, $cell) { - return false; - }, - format: function (s, table, cell, cellIndex) { - return $(cell).find("input[id^=production-date]").val() || "1970-01-01"; - }, - parsed: false, - type: 'text' - }); $("#allTable").tablesorter({ sortList: [[13, 1]], theme: 'blue', @@ -51,9 +40,6 @@ $(document).ready(function () { }, }, }, - headers: { - 16: { sorter: 'production_date'}, - }, }); $("#allTable").bind('filterEnd', function (event, config) { updateAllPositions(); @@ -202,7 +188,14 @@ function drawComponents(data) { $("#componentsTableContainer").html(componentsTablePrototype()); data.forEach((el, index) => { var tr = $(""); - tr.append(""); + var position = ""; + if (el.scheduled > 0) { + position += '
' + } else { + position += '
'; + } + position += "\"\""; + tr.append(position); tr.append("" + (index + 1) + ""); tr.append("
" + el.productCode + ""); tr.append("" + el.productName + ""); @@ -286,7 +279,6 @@ function getRawMaterials() { cids }, success: function (data) { - console.log(data); var result = JSON.parse(data); RawMaterials = result; drawRawMaterials(result); @@ -416,46 +408,21 @@ function orderRawMaterials() { $("#orderRawMaterialsForm").submit(); } } -function saveProductionDate(id) { - $.ajax({ - method: 'get', - url: $(location).attr('href') + "&to_pdf=1&ajaxAction=saveProductionDate&itemId=" + id + "&date=" + $("#production-date-" + id).val(), - }); -} -function editComment(positionId) { - $("#edit-" + positionId).css("display", "none"); - $("#description-" + positionId).css("display", "none"); - $("#descriptionInput-" + positionId).css("display", "inline"); - $("#descriptionInput-" + positionId).select(); - $("#save-" + positionId).css("display", "inline-block"); -} -function saveComment(id) { - $("#edit-" + id).css("display", "inline-block"); - $("#description-" + id).css("display", "inline"); - $("#descriptionInput-" + id).css("display", "none"); - $("#save-" + id).css("display", "none"); - $.ajax({ - method: 'get', - url: $(location).attr('href') + "&to_pdf=1&ajaxAction=saveProductDescription&itemId=" + id + "&description=" + $("#descriptionInput-" + id).val(), - success: function (data) { - $("#description-" + id).html($("#descriptionInput-" + id).val()); - }, - }); -} -function showLoader() { +function showLoader(msg = "Pobieranie danych") { + $.blockUI({ css: { - border: 'none', - padding: '15px', - backgroundColor: '#000', - '-webkit-border-radius': '10px', - '-moz-border-radius': '10px', - opacity: .5, - 'font-weight': 'bold', - 'font-size': '16px', - color: '#fff', + border: "none", + padding: "15px", + backgroundColor: "#000", + "-webkit-border-radius": "10px", + "-moz-border-radius": "10px", + opacity: 0.5, + "font-weight": "bold", + "font-size": "16px", + color: "#fff", }, - message: "Pobieranie danych..." + message: msg }); } function hideLoader() { @@ -502,4 +469,28 @@ function componentsTablePrototype() { } function rawMaterialsTablePrototype() { return '
PozycjaIndeksNazwaIlośćJM.StanZamówionoDostawcaZamówienie
0
' +} +function addToProductionScheduler(orderItemId) { + showLoader("Trwa dodawanie elementu do harmonogramu produkcji..."); + $.ajax({ + method: "get", + url: $(location).attr("href") + "&to_pdf=1&ajaxAction=addToProductionScheduler&itemId=" + orderItemId, + success: function () + { + hideLoader(); + window.alert("Dodano do harmonogramu produkcji."); + }, + }); +} +function addComponentToProductionScheduler(productId, qty) { + showLoader("Trwa dodawanie elementu do harmonogramu produkcji..."); + $.ajax({ + method: "get", + url: $(location).attr("href") + "&to_pdf=1&ajaxAction=addComponentToProductionScheduler&productId=" + productId + "&qty=" + qty, + success: function () + { + hideLoader(); + window.alert("Dodano do harmonogramu produkcji."); + }, + }); } \ No newline at end of file diff --git a/modules/EcmReports/BimIT-Reports/productsBySales/productsBySales.php b/modules/EcmReports/BimIT-Reports/productsBySales/productsBySales.php index 8af5e301..53d1c50a 100644 --- a/modules/EcmReports/BimIT-Reports/productsBySales/productsBySales.php +++ b/modules/EcmReports/BimIT-Reports/productsBySales/productsBySales.php @@ -1,4 +1,4 @@ - '$dateFrom'"; if (is_array($_GET['exclude']) && count($_GET['exclude']) > 0) { foreach ($_GET['exclude'] as $name) { @@ -66,7 +69,7 @@ if (!isset($_GET['ajaxAction'])) { $allQuery .= " OR s.delivery_date IS NULL"; $typesWhere = " OR s.delivery_date IS NULL"; } - $allQuery .= " ORDER BY s.delivery_date ASC, s.register_date ASC, s.document_no ASC"; + $allQuery .= "GROUP BY si.id ORDER BY s.delivery_date, s.register_date, s.document_no"; $rows = $db->query($allQuery); $allData = array(); @@ -100,6 +103,7 @@ if (!isset($_GET['ajaxAction'])) { $row['shippingTo'] = ($r['shipping_address_name'] == 'Adres korespondencyjny' ? '' : $r['shipping_address_name']); $row['productionDate'] = $r['production_date']; $row['productStockState'] = $r['stockState'] | 0; + $row['scheduled'] = $r['scheduled']; if ($_GET['hideReadyProducts'] == "false" || $row['productQty'] > $row['productStockState']) { $allData[] = $row; @@ -135,12 +139,16 @@ if (!isset($_GET['ajaxAction'])) { break; case 'getRawMaterials': echo getRawMaterials($_POST['ids'], $_POST['cids']); - case 'saveProductionDate': - saveProductionDate($_GET['itemId'], $_GET['date']); break; case 'saveProductDescription': saveProductDescription($_GET['itemId'], $_GET['description']); break; + case 'addToProductionScheduler': + addToProductionScheduler($_GET['itemId']); + break; + case 'addComponentToProductionScheduler': + addComponentToProductionScheduler($_GET['productId'], $_GET['qty']); + break; } } @@ -169,13 +177,16 @@ function getComponents($ids, $dateFrom, $dateTo) $rows = $db->query($productsQuery); $componentsData = array(); while ($r = $db->fetchByAssoc($rows)) { - $componentsQuery = "SELECT p.code, p.name, c.quantity, p.unit_id, c.ecmcomponent_id, ss.quantity as stockState, p.group_ks + $componentsQuery = "SELECT p.code, p.name, c.quantity, p.unit_id, c.ecmcomponent_id, ss.quantity as stockState, + p.group_ks, COUNT(ps.id) AS scheduled FROM ecmproductcomponents as c INNER JOIN ecmproducts AS p ON p.id = c.ecmcomponent_id LEFT JOIN ecmstockstates AS ss ON ss.product_id = p.id AND ss.stock_id = '368479db-22c5-0220-3a14-4bc426b1c709' - WHERE c.ecmproduct_id = '" . $r['ecmproduct_id'] . "'"; + LEFT JOIN productionScheduler AS ps + ON p.id = ps.ecmproduct_id AND ps.is_component = 1 AND ps.deleted=0 + WHERE c.ecmproduct_id = '" . $r['ecmproduct_id'] . "' GROUP BY p.id"; $crows = $db->query($componentsQuery); while ($cr = $db->fetchByAssoc($crows)) { $exists = findProduct($componentsData, $cr['ecmcomponent_id']); @@ -221,6 +232,7 @@ function getComponents($ids, $dateFrom, $dateTo) $row['productGroupKS'] = $cr['group_ks']; $row['orders'] = $orders; $row['productStockState'] = (!empty($cr['stockState'])) ? $cr['stockState'] : 0; + $row['scheduled'] = $cr['scheduled']; $componentsData[] = $row; } } @@ -315,25 +327,6 @@ function getRawMaterials($ids, $cids) echo json_encode($rawMaterialsData); } - -function saveProductionDate($itemId, $date) -{ - $db = $GLOBALS['db']; - $date = date("Y-m-d", strtotime($date)); - if ($date == '1970-01-01') { - $db->query("UPDATE ecmsaleitems SET production_date=NULL WHERE id='$itemId'"); - } else { - $db->query("UPDATE ecmsaleitems SET production_date='$date' WHERE id='$itemId'"); - } -} - -function saveProductDescription($itemId, $description) -{ - $db = $GLOBALS['db']; - $description = mysql_escape_string($description); - $db->query("UPDATE ecmsaleitems SET description='$description' WHERE id='$itemId'"); -} - function getProductRawMaterials($productId, $quantity) { $db = $GLOBALS['db']; @@ -356,3 +349,27 @@ function getProductRawMaterials($productId, $quantity) return $response; } } + +function addToProductionScheduler($orderItemId) { + $db = $GLOBALS['db']; + global $current_user; + $res = $db->fetchByAssoc($db->query("SELECT quantity, ecmproduct_id, production_date, description, ecmsale_id FROM ecmsaleitems WHERE id ='$orderItemId'")); + $query = sprintf("INSERT INTO productionScheduler VALUES ('%s', '%s', '%s', '%d', NOW(), NOW(), '%s', '%s', 0, '%s', 0, '%s', '%s');", + generateUuidV4(), $orderItemId, $res['ecmsale_id'], $res['quantity'], $current_user->id, $current_user->id, $res['ecmproduct_id'], $res['production_date'], $res['description']); + $db->query($query); +} + +function addComponentToProductionScheduler($productId, $qty) { + $db = $GLOBALS['db']; + global $current_user; + $query = sprintf("INSERT INTO productionScheduler VALUES ('%s', null, null, '%d', NOW(), NOW(), '%s', '%s', 0, '%s', 1, null, null);", + generateUuidV4(), $qty, $current_user->id, $current_user->id, $productId); + $db->query($query); +} + +function generateUuidV4() { + $data = openssl_random_pseudo_bytes(16); + $data[6] = chr(ord($data[6]) & 0x0f | 0x40); + $data[8] = chr(ord($data[8]) & 0x3f | 0x80); + return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); +} diff --git a/modules/EcmReports/BimIT-Reports/productsBySales/productsBySales.tpl b/modules/EcmReports/BimIT-Reports/productsBySales/productsBySales.tpl index 2f3fed1b..f6e6fdb9 100644 --- a/modules/EcmReports/BimIT-Reports/productsBySales/productsBySales.tpl +++ b/modules/EcmReports/BimIT-Reports/productsBySales/productsBySales.tpl @@ -92,7 +92,7 @@ {/foreach} - + @@ -164,8 +164,6 @@ Data rejestracji Data wysyłki Data dostawy - Data produkcji - Uwagi @@ -179,6 +177,10 @@ {/if} +
+ {if $ROW.scheduled > 0} +
+ {/if} @@ -233,34 +235,6 @@ {$ROW.orderDeliveryDate} - - - - - - -
- -
{$ROW.description} -
- - {/foreach} @@ -268,7 +242,7 @@ 0 - + diff --git a/modules/EcmReports/index.php b/modules/EcmReports/index.php index bf1ff98d..be5d4f80 100755 --- a/modules/EcmReports/index.php +++ b/modules/EcmReports/index.php @@ -1,7 +1,8 @@ \ No newline at end of file + } \ No newline at end of file diff --git a/modules/EcmSales/EcmSale.php b/modules/EcmSales/EcmSale.php index 7032985e..be79319e 100644 --- a/modules/EcmSales/EcmSale.php +++ b/modules/EcmSales/EcmSale.php @@ -1,6 +1,6 @@ 'notes', - 'email_id' => 'emails' - // 'account_id' => 'account', - // 'contact_id' => 'contact', - ); - function EcmSale() { - parent::SugarBean (); - $this->setupCustomFields ( 'EcmSales' ); - foreach ( $this->field_defs as $field ) { - $this->field_name_map [$field ['name']] = $field; - } - } - var $new_schema = true; - function get_summary_text() { - return "$this->name"; - } - function create_list_query($order_by, $where, $show_deleted = 0) { - // Fill in the assigned_user_name - $custom_join = $this->custom_fields->getJOIN (); - $query = "SELECT "; - $query .= "ecmsales.* +require_once('data/SugarBean.php'); +require_once('include/utils.php'); + +class EcmSale extends SugarBean +{ + var $field_name_map = array(); + // STANDARD FIELDS + var $id; + var $date_entered; + var $date_modified; + var $modified_user_id; + var $assigned_user_id; + var $name; + var $description; + // TABLE COLUMNS + var $edi_file; + var $number; + var $document_no; + var $parent_type; + var $parent_name; + var $parent_id; + var $type; + var $status; + var $register_date; + var $parent_address_street; + var $parent_address_city; + var $parent_address_postalcode; + var $parent_address_country; + var $subtotal; + var $total; + var $discount; + var $to_vatid; + var $ecmlanguage; + var $to_is_vat_free; + var $header_text; + var $footer_text; + var $ads_text; + var $template_id; + var $template_name; + var $email_id; + var $parent_name_copy; + var $parent_contact_name; + var $parent_contact_title; + var $ecmpaymentcondition_id; + var $ecmpaymentcondition_name; + var $ecmpaymentcondition_text; + var $ecmdeliverycondition_id; + var $ecmdeliverycondition_name; + var $ecmdeliverycondition_text; + var $validtill_date; + var $order_origin; + var $contact_id; + var $contact_name; + var $show_images_on_offers; + var $currency_symbol; + var $currency_id; + var $show_ean; + var $template; + var $pdf; + var $position_list; + var $parser; + var $account; + var $contact; + var $user; + var $mfp; + // added 4.03.2009 + var $pricebook_id; + var $show_recipient_code; + // RELATED FIELDS + var $created_by; + var $created_by_name; + var $modified_by_name; + var $assigned_user_name; + // SUBPANELS RELATED + // MODULE OBJECT DETAILS + var $module_dir = "EcmSales"; + var $table_name = "ecmsales"; + var $object_name = "EcmSale"; + // RELATED TABLE NAMES + // USED TO RETRIEVE RELATED FIELDS FROM FORM POSTS. + var $additional_column_fields = array( + 'assigned_user_name', + 'assigned_user_id', + 'modified_user_id', + 'created_by' + ); + // RELATIONSHIP FIELDS + var $relationship_fields = array( + 'note_id' => 'notes', + 'email_id' => 'emails' + // 'account_id' => 'account', + // 'contact_id' => 'contact', + ); + var $new_schema = true; + + function EcmSale() + { + parent::SugarBean(); + $this->setupCustomFields('EcmSales'); + foreach ($this->field_defs as $field) { + $this->field_name_map [$field ['name']] = $field; + } + } + + static function CreateImgStatus($id, $status) + { + global $app_list_strings; + return ''; + } + + function get_summary_text() + { + return "$this->name"; + } + + function create_list_query($order_by, $where, $show_deleted = 0) + { + // Fill in the assigned_user_name + $custom_join = $this->custom_fields->getJOIN(); + $query = "SELECT "; + $query .= "ecmsales.* ,wz.id as wzid ,users.user_name as assigned_user_name"; - if ($custom_join) { - $query .= $custom_join ['select']; - } - $query .= " FROM ecmsales + if ($custom_join) { + $query .= $custom_join ['select']; + } + $query .= " FROM ecmsales LEFT JOIN users ON ecmsales.assigned_user_id=users.id LEFT JOIN ecmstockdocouts as wz ON wz.ecmsale_id=ecmsales.id"; - $query .= " "; - if ($custom_join) { - $query .= $custom_join ['join']; - } - $where_auto = '1=1'; - if ($show_deleted == 0) { - $where_auto = " $this->table_name.deleted=0 "; - } else if ($show_deleted == 1) { - $where_auto = " $this->table_name.deleted=1 "; - } - if($_GET['show_empty_wz'])$where_auto.=" AND wz.id is null"; - if ($where != "") - $query .= "where $where AND " . $where_auto; - else - $query .= "where " . $where_auto; - if (substr_count ( $order_by, '.' ) > 0) { - $query .= " ORDER BY $order_by"; - } else if ($order_by != "") - $query .= " ORDER BY $order_by"; - else - $query .= " ORDER BY ecmsales.date_entered"; - return $query; - } - function create_export_query($order_by, $where) { - $custom_join = $this->custom_fields->getJOIN (); - $query = "SELECT + $query .= " "; + if ($custom_join) { + $query .= $custom_join ['join']; + } + $where_auto = '1=1'; + if ($show_deleted == 0) { + $where_auto = " $this->table_name.deleted=0 "; + } else if ($show_deleted == 1) { + $where_auto = " $this->table_name.deleted=1 "; + } + if ($_GET['show_empty_wz']) $where_auto .= " AND wz.id is null"; + if ($where != "") + $query .= "where $where AND " . $where_auto; + else + $query .= "where " . $where_auto; + if (substr_count($order_by, '.') > 0) { + $query .= " ORDER BY $order_by"; + } else if ($order_by != "") + $query .= " ORDER BY $order_by"; + else + $query .= " ORDER BY ecmsales.date_entered"; + return $query; + } + + function create_export_query($order_by, $where) + { + $custom_join = $this->custom_fields->getJOIN(); + $query = "SELECT ecmsales.*, users.user_name assigned_user_name"; - if ($custom_join) { - $query .= $custom_join ['select']; - } - $query .= " FROM ecmsales "; - $query .= " LEFT JOIN users + if ($custom_join) { + $query .= $custom_join ['select']; + } + $query .= " FROM ecmsales "; + $query .= " LEFT JOIN users ON ecmsales.assigned_user_id=users.id"; - if ($custom_join) { - $query .= $custom_join ['join']; - } - $query .= ""; - $where_auto = " ecmsales.deleted=0 + if ($custom_join) { + $query .= $custom_join ['join']; + } + $query .= ""; + $where_auto = " ecmsales.deleted=0 "; - if ($where != "") - $query .= " where $where AND " . $where_auto; - else - $query .= " where " . $where_auto; - if ($order_by != "") - $query .= " ORDER BY $order_by"; - else - $query .= " ORDER BY ecmsales.name"; - return $query; - } - function fill_in_additional_list_fields() { - } - function fill_in_additional_detail_fields() { - // FILL IN THE ASSIGNED_USER_NAME - $this->assigned_user_name = get_assigned_user_name ( $this->assigned_user_id ); - $this->created_by_name = get_assigned_user_name ( $this->created_by ); - $this->modified_by_name = get_assigned_user_name ( $this->modified_user_id ); - /* - $result = $this->db->query ( "SELECT status, parent_id, contact_id, template_id, assigned_user_id FROM ecmsales WHERE id='$this->id'" ); - if (is_resource ( $result )) { - $row = $this->db->fetchByAssoc ( $result ); - if ($row) { - $this->status = $row ['status']; - $this->parent_id = $row ['parent_id']; - $this->contact_id = $row ['contact_id']; - $this->template_id = $row ['template_id']; - $this->assigned_user_id = $row ['assigned_user_id']; - } - } - */ - /* - * $query = "select `number`, `template_id` from `ecmsales` where `id`='$this->id' limit 1"; $r = $this->db->query($query); if($r) { $r = $this->db->fetchByAssoc($r); $this->template_id = $r['template_id']; $this->number = $r['number']; $this->setTemplate(); $this->document_no = $this->formatNumber(); } - */ - } - function get_list_view_data() { - global $current_language; - $this->fill_in_additional_detail_fields (); - $app_list_strings = return_app_list_strings_language ( $current_language ); - $mod_strings = return_module_language ( $current_language, 'EcmSales' ); - $the_array = parent::get_list_view_data (); - // THE NEW LISTVIEW CODE ONLY FETCHES COLUMNS THAT WE'RE DISPLAYING AND NOT ALL - // THE COLUMNS SO WE NEED THESE CHECKS. - if($this->ecmproduct_id!=''){ - //add subpanel data - $tmp=$this->getPriceFromDocument($this->ecmproduct_id); - - $the_array ['QUANTITY'] = format_number ( $tmp['quantity'] ); - $the_array ['PRICE_NETTO'] = format_number ( $tmp['price_netto'] ); - $the_array ['TOTAL_NETTO'] = format_number ( $tmp['total_netto'] ); - } - $this->retrieve($this->id); - $the_array ['NAME'] = (($this->name == "") ? $this->document_no : $this->name); - - $a = new EcmStockDocOut(); - $a->retrieve_by_string_fields(['ecmsale_id'=>$this->id]); - - if($a->id)$the_array ['WZ'] = "".$a->document_no.""; - else $the_array ['WZ'] = $this->wz_name; - - $a = new EcmInvoiceOut(); - $a->retrieve_by_string_fields(['so_id'=>$this->id]); - $the_array ['FV'] = "".$a->document_no.""; - - $the_array ['TOTAL'] = format_number ( $this->total_netto ); - $a = new Account(); - $a->retrieve($this->parent_id); - $the_array ['SHOP_NUMBER'] =($this->shop_number!="" ? $this->shop_number:$a->shop_number); - //create image options - $op = ''; - - $the_array ['ZS'] = "".$this->edi_zs_document_no.""; - - $the_array['OPTIONS'] = $op; + if ($where != "") + $query .= " where $where AND " . $where_auto; + else + $query .= " where " . $where_auto; + if ($order_by != "") + $query .= " ORDER BY $order_by"; + else + $query .= " ORDER BY ecmsales.name"; + return $query; + } - return $the_array; - } - function getPriceFromDocument($product){ - $zap=$this->db->query("select quantity,price_netto,total_netto from ecmsaleitems where id='".$product."'"); - $dane=$this->db->fetchByAssoc($zap); - return $dane; - } - function getStatusMenuInfo($inJSON = true) { - global $app_list_strings; - $arr = array (); - foreach ( $app_list_strings ['ecmsales_status_dom'] as $key => $value ) { - $arr [$key] = array ( - 'enabled' => '
' . $value . '
', - 'disabled' => '
' . $value . '
' - ); - } - $json = getJSONobj (); - if ($inJSON) - return str_replace ( '"', '\"', $json->encode ( $arr ) ); - else - return $arr; - } - function create_new_list_query($order_by, $where, $filter = array(), $params = array(), $show_deleted = 0, $join_type = '', $return_array = false, $parentbean, $singleSelect = false) { - echo ''; - echo ''; - echo ''; - echo ''; - if($_GET['show_empty_wz'])$where.='ecmsales.wz_name is null'; + function fill_in_additional_list_fields() + { + } - $ret=parent::create_new_list_query ( $order_by, $where, $filter, $params, $show_deleted, $join_type, $return_array, $parentbean, $singleSelect ); - //$ret['from'].=" left outer join ecmstockdocouts as wz on wz.ecmsale_id=ecmsales.id"; - //echo print_r($ret,true); - return $ret; - } - static function CreateImgStatus($id, $status) { - global $app_list_strings; - return ''; - } - - /** - * BUILDS A GENERIC SEARCH BASED ON THE QUERY STRING USING OR. - * DO NOT INCLUDE ANY $THIS-> BECAUSE THIS IS CALLED ON WITHOUT HAVING THE CLASS INSTANTIATED. - */ - function build_generic_where_clause($the_query_string) { - $where_clauses = Array (); - $the_query_string = PearDatabase::quote ( from_html ( $the_query_string ) ); - array_push ( $where_clauses, "ecmsales.name like '$the_query_string%'" ); - $the_where = ""; - foreach ( $where_clauses as $clause ) { - if ($the_where != "") - $the_where .= " or "; - $the_where .= $clause; - } - return $the_where; - } - function set_notification_body($xtpl, $simplemodule) { - global $mod_strings, $app_list_strings; - $xtpl->assign ( "NAME", $simplemodule->name ); - $xtpl->assign ( "DESCRIPTION", $simplemodule->description ); - return $xtpl; - } - function bean_implements($interface) { - switch ($interface) { - case 'ACL' : - return true; - } - return false; - } - function save($check_notify = FALSE) { - global $current_user; - if (!$this->id || $this->id=='') { - // generate number - $this->number = $this->generateNumber(); - $this->document_no = $this->formatNumber($this->number); - } - $this->vats_summary = htmlspecialchars($this->vats_summary); - $return_id = parent::save ( $check_notify ); - $this->savePositions($return_id); - return $return_id; - } - // ***************************Start Managing Positions*************************// - function constructInsertQuery($data, $table = '') { - if ($table == '' && isset ( $this->object_name ) && $this->object_name != '') { - $table = strtolower ( $this->object_name ) . "items"; - } else - return ""; - $keys = array (); - $values = array (); - foreach ( $data as $key => $value ) { - $keys [] = $key; - if (is_array ( $value )) - $values [] = $value [1] . str_replace ( "'", "\'", $value [0] ) . $value [1]; - else - $values [] = "'" . str_replace ( "'", "\'", $value ) . "'"; - } - $q = "insert into `$table` (`"; - $q .= implode ( '`, `', $keys ); - $q .= "`) values ("; - $q .= implode ( ", ", $values ); - $q .= ");"; - return $q; - } - function savePositions($id = null, $position_list = null) { - global $current_user, $timedate; - if ($position_list == null) - $position_list = $this->position_list; - if ($id == null) - $id = $this->id; - if (count ( $position_list ) > 0) - $this->deleteAssignedPositions ( $id ); - $arr = array (); - $position = 0; - for($i = 0; $i < count ( $position_list ); $i ++) { - if ($position_list [$i] ['name'] == '') - continue; - $p = $position_list [$i]; - if (! empty ( $p ['category_id'] ) || $p ['category_id'] == '') { - require_once ("modules/EcmProducts/EcmProduct.php"); - $pr = new EcmProduct (); - $pr->retrieve ( $p ['id'] ); - $p ['category_id'] = $pr->product_category_id; - } - $arr = array ( - 'id' => create_guid (), - 'date_entered' => array ( - 'NOW()', - '' - ), - 'date_modified' => array ( - 'NOW()', - '' - ), - 'modified_user_id' => $current_user->id, - 'assigned_user_id' => $current_user->id, - 'created_by' => $current_user->id, - 'deleted' => '0', - strtolower ( $this->object_name ) . '_id' => $id, - 'ecmproduct_id' => $p ['product_id'], - 'position' => $position, - 'code' => $p ['product_code'], - 'name' => $p ['name'], - 'quantity' => ((empty ( $p ['quantity'] ) || $p ['quantity'] == '') ? 0 : $p ['quantity']), - 'price_start' => ((empty ( $p ['price_start'] ) || $p ['price_start'] == '') ? 0 : $p ['price_start']), - 'price_netto' => ((empty ( $p ['price_netto'] ) || $p ['price_netto'] == '') ? 0 : $p ['price_netto']), - 'price_brutto'=> ($p['price_netto']+($p['price_netto']*($p ['ecmvat_name']/100))), - 'total_brutto'=> ($p['total_netto']+($p['total_netto']*($p ['ecmvat_name']/100))), - 'discount' => ((empty ( $p ['discount'] ) || $p ['discount'] == '') ? 0 : $p ['discount']), - 'total_netto' => ((empty ( $p ['total_netto'] ) || $p ['total_netto'] == '') ? 0 : $p ['total_netto']), - 'dd_unit_id' => $p ['unit_id'], - 'dd_unit_name' => $p['unit_name'], - 'ecmvat_id' => $p ['ecmvat_id'], - 'ecmvat_name' => $p ['ecmvat_name'], - 'ecmvat_value' => $p ['ecmvat_value'], - 'ecmproductcategory_id' => $p ['category_id'], - 'recipient_code' => $p ['recipient_code'], - 'ean' => $p['product_ean'], - 'brand_label' => $p['product_brand_label'], - 'description' => $p['product_description'], - ); - if (isset($p['product_production_date']) && strlen($p['product_production_date']) > 5) { + function get_list_view_data() + { + global $current_language; + $this->fill_in_additional_detail_fields(); + $app_list_strings = return_app_list_strings_language($current_language); + $mod_strings = return_module_language($current_language, 'EcmSales'); + $the_array = parent::get_list_view_data(); + // THE NEW LISTVIEW CODE ONLY FETCHES COLUMNS THAT WE'RE DISPLAYING AND NOT ALL + // THE COLUMNS SO WE NEED THESE CHECKS. + if ($this->ecmproduct_id != '') { + //add subpanel data + $tmp = $this->getPriceFromDocument($this->ecmproduct_id); + + $the_array ['QUANTITY'] = format_number($tmp['quantity']); + $the_array ['PRICE_NETTO'] = format_number($tmp['price_netto']); + $the_array ['TOTAL_NETTO'] = format_number($tmp['total_netto']); + } + $this->retrieve($this->id); + $the_array ['NAME'] = (($this->name == "") ? $this->document_no : $this->name); + + $a = new EcmStockDocOut(); + $a->retrieve_by_string_fields(['ecmsale_id' => $this->id]); + + if ($a->id) $the_array ['WZ'] = "" . $a->document_no . ""; + else $the_array ['WZ'] = $this->wz_name; + + $a = new EcmInvoiceOut(); + $a->retrieve_by_string_fields(['so_id' => $this->id]); + $the_array ['FV'] = "" . $a->document_no . ""; + + $the_array ['TOTAL'] = format_number($this->total_netto); + $a = new Account(); + $a->retrieve($this->parent_id); + $the_array ['SHOP_NUMBER'] = ($this->shop_number != "" ? $this->shop_number : $a->shop_number); + //create image options + $op = ''; + + $the_array ['ZS'] = "" . $this->edi_zs_document_no . ""; + + $the_array['OPTIONS'] = $op; + + return $the_array; + } + + function fill_in_additional_detail_fields() + { + // FILL IN THE ASSIGNED_USER_NAME + $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id); + $this->created_by_name = get_assigned_user_name($this->created_by); + $this->modified_by_name = get_assigned_user_name($this->modified_user_id); + /* + $result = $this->db->query ( "SELECT status, parent_id, contact_id, template_id, assigned_user_id FROM ecmsales WHERE id='$this->id'" ); + if (is_resource ( $result )) { + $row = $this->db->fetchByAssoc ( $result ); + if ($row) { + $this->status = $row ['status']; + $this->parent_id = $row ['parent_id']; + $this->contact_id = $row ['contact_id']; + $this->template_id = $row ['template_id']; + $this->assigned_user_id = $row ['assigned_user_id']; + } + } + */ + /* + * $query = "select `number`, `template_id` from `ecmsales` where `id`='$this->id' limit 1"; $r = $this->db->query($query); if($r) { $r = $this->db->fetchByAssoc($r); $this->template_id = $r['template_id']; $this->number = $r['number']; $this->setTemplate(); $this->document_no = $this->formatNumber(); } + */ + } + + function getPriceFromDocument($product) + { + $zap = $this->db->query("select quantity,price_netto,total_netto from ecmsaleitems where id='" . $product . "'"); + $dane = $this->db->fetchByAssoc($zap); + return $dane; + } + + function create_new_list_query($order_by, $where, $filter = array(), $params = array(), $show_deleted = 0, $join_type = '', $return_array = false, $parentbean, $singleSelect = false) + { + echo ''; + echo ''; + echo ''; + echo ''; + if ($_GET['show_empty_wz']) $where .= 'ecmsales.wz_name is null'; + + $ret = parent::create_new_list_query($order_by, $where, $filter, $params, $show_deleted, $join_type, $return_array, $parentbean, $singleSelect); + //$ret['from'].=" left outer join ecmstockdocouts as wz on wz.ecmsale_id=ecmsales.id"; + //echo print_r($ret,true); + return $ret; + } + + function getStatusMenuInfo($inJSON = true) + { + global $app_list_strings; + $arr = array(); + foreach ($app_list_strings ['ecmsales_status_dom'] as $key => $value) { + $arr [$key] = array( + 'enabled' => '
' . $value . '
', + 'disabled' => '
' . $value . '
' + ); + } + $json = getJSONobj(); + if ($inJSON) + return str_replace('"', '\"', $json->encode($arr)); + else + return $arr; + } + + /** + * BUILDS A GENERIC SEARCH BASED ON THE QUERY STRING USING OR. + * DO NOT INCLUDE ANY $THIS-> BECAUSE THIS IS CALLED ON WITHOUT HAVING THE CLASS INSTANTIATED. + */ + function build_generic_where_clause($the_query_string) + { + $where_clauses = array(); + $the_query_string = PearDatabase::quote(from_html($the_query_string)); + array_push($where_clauses, "ecmsales.name like '$the_query_string%'"); + $the_where = ""; + foreach ($where_clauses as $clause) { + if ($the_where != "") + $the_where .= " or "; + $the_where .= $clause; + } + return $the_where; + } + + function set_notification_body($xtpl, $simplemodule) + { + global $mod_strings, $app_list_strings; + $xtpl->assign("NAME", $simplemodule->name); + $xtpl->assign("DESCRIPTION", $simplemodule->description); + return $xtpl; + } + + function save($check_notify = FALSE) + { + global $current_user; + if (!$this->id || $this->id == '') { + // generate number + $this->number = $this->generateNumber(); + $this->document_no = $this->formatNumber($this->number); + } + $this->vats_summary = htmlspecialchars($this->vats_summary); + $return_id = parent::save($check_notify); + $this->savePositions($return_id); + return $return_id; + } + + function generateNumber() + { + $db = $GLOBALS['db']; + $r = $db->fetchByAssoc($db->query("SELECT count(id) as c FROM ecmsales WHERE YEAR(register_date)='" . date('Y') . "'")); + + if (!$r || !$r['c'] || $r['c'] == '') + $count = 0; + else + $count = intval($r['c']); + + $count++; + + //has 5 digits? + $tmp = strval($count); + while (strlen($tmp) < 5) + $tmp = '0' . $tmp; + + return date("Ymd") . $tmp; + } + + // ***************************Start Managing Positions*************************// + + function formatNumber($number) + { + $n = intval(substr($number, 8, 5)); + $y = substr($number, 0, 4); + + //has 3 digits? + while (strlen($n) < 3) + $n = '0' . $n; + + return 'ZS ' . $n . '/' . $y; + } + + function savePositions($id = null, $position_list = null) + { + global $current_user, $timedate; + if ($position_list == null) + $position_list = $this->position_list; + if ($id == null) + $id = $this->id; + if (count($position_list) > 0) + $this->deleteAssignedPositions($id); + $arr = array(); + $position = 0; + for ($i = 0; $i < count($position_list); $i++) { + if ($position_list [$i] ['name'] == '') + continue; + $p = $position_list [$i]; + if (!empty ($p ['category_id']) || $p ['category_id'] == '') { + require_once("modules/EcmProducts/EcmProduct.php"); + $pr = new EcmProduct (); + $pr->retrieve($p ['id']); + $p ['category_id'] = $pr->product_category_id; + } + $itemId = create_guid(); + $arr = array( + 'id' => $itemId, + 'date_entered' => array( + 'NOW()', + '' + ), + 'date_modified' => array( + 'NOW()', + '' + ), + 'modified_user_id' => $current_user->id, + 'assigned_user_id' => $current_user->id, + 'created_by' => $current_user->id, + 'deleted' => '0', + strtolower($this->object_name) . '_id' => $id, + 'ecmproduct_id' => $p ['product_id'], + 'position' => $position, + 'code' => $p ['product_code'], + 'name' => $p ['name'], + 'quantity' => ((empty ($p ['quantity']) || $p ['quantity'] == '') ? 0 : $p ['quantity']), + 'price_start' => ((empty ($p ['price_start']) || $p ['price_start'] == '') ? 0 : $p ['price_start']), + 'price_netto' => ((empty ($p ['price_netto']) || $p ['price_netto'] == '') ? 0 : $p ['price_netto']), + 'price_brutto' => ($p['price_netto'] + ($p['price_netto'] * ($p ['ecmvat_name'] / 100))), + 'total_brutto' => ($p['total_netto'] + ($p['total_netto'] * ($p ['ecmvat_name'] / 100))), + 'discount' => ((empty ($p ['discount']) || $p ['discount'] == '') ? 0 : $p ['discount']), + 'total_netto' => ((empty ($p ['total_netto']) || $p ['total_netto'] == '') ? 0 : $p ['total_netto']), + 'dd_unit_id' => $p ['unit_id'], + 'dd_unit_name' => $p['unit_name'], + 'ecmvat_id' => $p ['ecmvat_id'], + 'ecmvat_name' => $p ['ecmvat_name'], + 'ecmvat_value' => $p ['ecmvat_value'], + 'ecmproductcategory_id' => $p ['category_id'], + 'recipient_code' => $p ['recipient_code'], + 'ean' => $p['product_ean'], + 'brand_label' => $p['product_brand_label'], + 'description' => $p['product_description'], + ); + if (isset($p['product_production_date']) && strlen($p['product_production_date']) > 5) { $arr['production_date'] = $p['product_production_date']; } - // else { - // $arr['production_date'] = null; - //} - $this->db->query ( $this->constructInsertQuery ( $arr ) ); - - $this->db->query("INSERT INTO log VALUES ('".mysql_escape_string($this->constructInsertQuery ( $arr ))."')"); - $position ++; - } - } - function getPosition($position) { - if (! is_array ( $position )) - return ''; - global $timedate; - $return_array = array (); - $return_array ['product_id'] = $position ['ecmproduct_id']; - $return_array ['position'] = $position ['position']; - $return_array ['product_code'] = $position ['code']; - $return_array ['name'] = $position ['name']; - $return_array ['quantity'] = $position ['quantity']; - $return_array ['price_start'] = $position ['price_start']; - $return_array ['price_netto'] = $position ['price_netto']; - $return_array ['price_sell'] = $position ['price_start']; - $return_array ['price_total_sell'] = $position ['total_netto']; - $return_array ['discount'] = $position ['discount']; - $return_array ['total_netto'] = $position ['total_netto']; - $return_array ['total_brutto'] = $position ['total_brutto']; - $return_array ['unit_id'] = $position ['dd_unit_id']; - $return_array ['unit_name'] = $position ['dd_unit_name']; - $return_array ['ecmvat_id'] = $position ['ecmvat_id']; - $return_array ['ecmvat_name'] = $position ['ecmvat_name']; - $return_array ['ecmvat_value'] = $position ['ecmvat_value']; - $return_array ['recipient_code'] = $position ['recipient_code']; - $return_array ['product_supplier_code'] = $position ['recipient_code']; - $return_array ['product_ean'] = $position ['ean']; - $return_array ['product_brand_label'] = $position ['brand_label']; + + $this->db->query($this->constructInsertQuery($arr)); + $position++; + + // update production scheduler + $this->db->query(sprintf("UPDATE productionScheduler SET ecmsaleitem_id = '%s' WHERE ecmsale_id='%s' AND ecmproduct_id='%s';", + $itemId, $id, $p['product_id'])); + } + } + + function deleteAssignedPositions() + { + if (isset ($this->id) && $this->id != '') { + $query = "DELETE FROM `" . strtolower($this->object_name) . "items` WHERE `" . strtolower($this->object_name) . "_id`='" . $this->id . "'"; + $r = $this->db->query($query); + if ($r) + return true; + } + return false; + } + + function constructInsertQuery($data, $table = '') + { + if ($table == '' && isset ($this->object_name) && $this->object_name != '') { + $table = strtolower($this->object_name) . "items"; + } else + return ""; + $keys = array(); + $values = array(); + foreach ($data as $key => $value) { + $keys [] = $key; + if (is_array($value)) + $values [] = $value [1] . str_replace("'", "\'", $value [0]) . $value [1]; + else + $values [] = "'" . str_replace("'", "\'", $value) . "'"; + } + $q = "insert into `$table` (`"; + $q .= implode('`, `', $keys); + $q .= "`) values ("; + $q .= implode(", ", $values); + $q .= ");"; + return $q; + } + + function getPositionList($array = false) + { + if (isset ($this->id) && $this->id != '') { + $query = "SELECT * FROM `" . strtolower($this->object_name) . "items` WHERE `" . strtolower($this->object_name) . "_id`='" . $this->id . "' order by position asc"; + $r = $this->db->query($query); + $return_array = array(); + if ($r) { + while ($w = $this->db->fetchByAssoc($r)) { + $return_array [] = $this->getPosition($w); + } + $json = getJSONobj(); + return $array ? $return_array : $json->encode($return_array); + } + } + return $array ? false : '[]'; + } + + function getPosition($position) + { + if (!is_array($position)) + return ''; + global $timedate; + $return_array = array(); + $return_array ['product_id'] = $position ['ecmproduct_id']; + $return_array ['position'] = $position ['position']; + $return_array ['product_code'] = $position ['code']; + $return_array ['name'] = $position ['name']; + $return_array ['quantity'] = $position ['quantity']; + $return_array ['price_start'] = $position ['price_start']; + $return_array ['price_netto'] = $position ['price_netto']; + $return_array ['price_sell'] = $position ['price_start']; + $return_array ['price_total_sell'] = $position ['total_netto']; + $return_array ['discount'] = $position ['discount']; + $return_array ['total_netto'] = $position ['total_netto']; + $return_array ['total_brutto'] = $position ['total_brutto']; + $return_array ['unit_id'] = $position ['dd_unit_id']; + $return_array ['unit_name'] = $position ['dd_unit_name']; + $return_array ['ecmvat_id'] = $position ['ecmvat_id']; + $return_array ['ecmvat_name'] = $position ['ecmvat_name']; + $return_array ['ecmvat_value'] = $position ['ecmvat_value']; + $return_array ['recipient_code'] = $position ['recipient_code']; + $return_array ['product_supplier_code'] = $position ['recipient_code']; + $return_array ['product_ean'] = $position ['ean']; + $return_array ['product_brand_label'] = $position ['brand_label']; $return_array ['product_description'] = $position ['description']; $return_array ['product_production_date'] = $position ['production_date']; - $ecmStockOperations = new EcmStockOperation(); - - $return_array ['stock_state']=($ecmStockOperations->getRealStock($position ['ecmproduct_id'])); - - $return_array ['reservation']=$return_array ['stock_state']; - - return $return_array; - } - function getPositionList($array = false) { - if (isset ( $this->id ) && $this->id != '') { - $query = "SELECT * FROM `" . strtolower ( $this->object_name ) . "items` WHERE `" . strtolower ( $this->object_name ) . "_id`='" . $this->id . "' order by position asc"; - $r = $this->db->query ( $query ); - $return_array = array (); - if ($r) { - while ( $w = $this->db->fetchByAssoc ( $r ) ) { - $return_array [] = $this->getPosition ( $w ); - } - $json = getJSONobj (); - return $array ? $return_array : $json->encode ( $return_array ); - } - } - return $array ? false : '[]'; - } - function deleteAssignedPositions() { - if (isset ( $this->id ) && $this->id != '') { - $query = "DELETE FROM `" . strtolower ( $this->object_name ) . "items` WHERE `" . strtolower ( $this->object_name ) . "_id`='" . $this->id . "'"; - $r = $this->db->query ( $query ); - if ($r) - return true; - } - return false; - } - function formatPositions($position_list) { - return; - if (! is_array ( $position_list ) || count ( $position_list ) == 0) - return false; - global $app_list_strings; - require_once ('modules/Currencies/Currency.php'); - foreach ( $position_list as $key => $value ) { - $position_list [$key] ['unit_id'] = $app_list_strings ['ecmproducts_unit_dom'] [$value ['unit_id']]; - $position_list [$key] ['category_id'] = $app_list_strings ['ecmproducts_category_dom'] [$value ['category_id']]; - // $position_list[$key]['vat_id'] = format_number($value['vat_id']).'%'; - $position_list [$key] ['discount'] = format_number ( $value ['discount'] ) . '%'; - if (isset ( $currency ) && ($currency->id == $this->currency_id)) { - } else { - $currency = new Currency (); - $currency->retrieve ( $this->currency_id ); - } - $position_list [$key] ['price'] = format_number ( $value ['price'] ) . ' ' . $currency->iso4217; - $position_list [$key] ['total'] = format_number ( $value ['total'] ) . ' ' . $currency->iso4217; - // $position_list[$key]['price'] = format_number($value['price']).' PLN'; - // $position_list[$key]['total'] = format_number($value['total']).' PLN'; - $this->currency_symbol = $currency->iso4217; - } - return $position_list; - } - - function sendSoap($id){ - ini_set ( "soap.wsdl_cache_enabled", "0" ); - require_once ("nusoap/nusoap.php"); - - $soapUrl = 'http://system.saas-systems.pl/soap.php?wsdl'; - $soapUser = 'admin'; - $soapPassword = 'rudemodz123'; - - $client = new nusoap_client ( $soapUrl, 'wsdl' ); - - $login_parameters = array ( - 'user_auth' => array ( - 'user_name' => $soapUser, - 'password' => md5 ( $soapPassword ), - 'version' => '1' - ), - 'application_name' => 'SoapTest', - 'name_value_list' => array () - ); - - $login_result = $client->call ( 'login', $login_parameters ); - - if ($login_result ['id'] != '') { - $session_id = $login_result ['id']; - - - $sdi = new EcmSale(); - $sdi->retrieve($id); - $sdi_fields = array (); - - $sdi_fields [] = array ( - "name" => 'id', - "value" => $sdi->edi_zs_id - ); - - $sdi_fields [] = array ( - "name" => 'edi_zs_id', - "value" => $sdi->id - ); - - $sdi_fields [] = array ( - "name" => 'edi_zs_document_no', - "value" => $sdi->document_no - ); - - - $set_entry_parameters = array ( - // session id - "session" => $session_id, - - // The name of the module from which to retrieve records. - "module_name" => "EcmSales", - - // Record attributes - "name_value_list" => $sdi_fields - ) - ; - - $set_entry_result = $client->call ( "set_entry", $set_entry_parameters ); - - - } - } - // ***************************End Managing Positions*************************// - function ACLAccess($view, $is_owner = 'not_set') { - global $current_user; - $file = 'modules/EcmGroupSales/EcmGroupSale.php'; - if (file_exists ( $file )) { - require_once ($file); - $cc = EcmGroupSale::loadSettings ( true ); - } else - return true; - if (is_admin ( $current_user )) { - switch ($view) { - case 'confirming' : - return ($this->status == "s20"); - case 'send_to_confirm' : - return ($this->status == "s10"); - case 'pdf_toolbar' : - return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40"); - } - return true; - } - if ($is_owner == 'not_set') { - $is_owner = $this->isOwner ( $current_user->id ); - } - // if we don't implent acls return true - if (! $this->bean_implements ( 'ACL' )) - return true; - $view = strtolower ( $view ); - if ($cc ['user_manager_role']) { // Manager - switch ($view) { - case 'list' : - case 'index' : - case 'listview' : - return ACLController::checkAccess ( $this->module_dir, 'list', true ); - case 'edit' : - case 'save' : - case 'popupeditview' : - case 'editview' : - return (ACLController::checkAccess ( $this->module_dir, 'edit', $is_owner )); - case 'view' : - case 'detail' : - case 'detailview' : - return ACLController::checkAccess ( $this->module_dir, 'view', $is_owner ); - case 'delete' : - return ACLController::checkAccess ( $this->module_dir, 'delete', $is_owner ); - case 'export' : - return ACLController::checkAccess ( $this->module_dir, 'export', $is_owner ); - case 'import' : - return ACLController::checkAccess ( $this->module_dir, 'import', true ); - case 'send_to_confirm' : - return ($this->status == "s10"); - case 'can_commit' : - return true; - case 'confirming' : - return ($this->status == "s20"); - case 'auto_commiting' : - return true; - case 'pdf_toolbar' : - return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40"); - } - } else if ($cc ['user_representative_extra_role']) { // Representative Extra - switch ($view) { - case 'list' : - case 'index' : - case 'listview' : - return ACLController::checkAccess ( $this->module_dir, 'list', true ); - case 'edit' : - return (ACLController::checkAccess ( $this->module_dir, 'edit', $is_owner ) && ($this->status == "s10" || $this->status == "s40")); - case 'save' : - case 'popupeditview' : - case 'editview' : - return (ACLController::checkAccess ( $this->module_dir, 'edit', $is_owner )); - case 'view' : - case 'detail' : - case 'detailview' : - return ACLController::checkAccess ( $this->module_dir, 'view', $is_owner ); - case 'delete' : - return (ACLController::checkAccess ( $this->module_dir, 'delete', $is_owner ) && $this->status == "s10"); - case 'export' : - return ACLController::checkAccess ( $this->module_dir, 'export', $is_owner ); - case 'import' : - return ACLController::checkAccess ( $this->module_dir, 'import', true ); - case 'quote_to_sale' : - case 'quote_to_invoice' : - return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40" && $this->status != "s60"); - case 'send_to_confirm' : - return ($this->status == "s10"); - case 'send_email' : - return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40"); - case 'can_commit' : - return true; - case 'confirming' : - return false; - case 'auto_commiting' : - return true; - case 'pdf_toolbar' : - return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40"); - } - } else if ($cc ['user_representative_role']) { // Representative - switch ($view) { - case 'list' : - case 'index' : - case 'listview' : - return ACLController::checkAccess ( $this->module_dir, 'list', true ); - case 'edit' : - return (ACLController::checkAccess ( $this->module_dir, 'edit', $is_owner ) && ($this->status == "s10" || $this->status == "s40")); - case 'save' : - case 'popupeditview' : - case 'editview' : - return (ACLController::checkAccess ( $this->module_dir, 'edit', $is_owner )); - case 'view' : - case 'detail' : - case 'detailview' : - return ACLController::checkAccess ( $this->module_dir, 'view', $is_owner ); - case 'delete' : - return (ACLController::checkAccess ( $this->module_dir, 'delete', $is_owner ) && $this->status == "s10"); - case 'export' : - return ACLController::checkAccess ( $this->module_dir, 'export', $is_owner ); - case 'import' : - return ACLController::checkAccess ( $this->module_dir, 'import', true ); - case 'quote_to_sale' : - case 'quote_to_invoice' : - return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40" && $this->status != "s60"); - case 'send_to_confirm' : - return ($this->status == "s10"); - case 'send_email' : - return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40"); - case 'can_commit' : - return false; - case 'confirming' : - return false; - case 'auto_commiting' : - return false; - case 'pdf_toolbar' : - return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40"); - } - } - // if it is not one of the above views then it should be implemented on the page level - return true; - } - - //mz generate number - function generateNumber() { - $db = $GLOBALS['db']; - $r = $db->fetchByAssoc($db->query("SELECT count(id) as c FROM ecmsales WHERE YEAR(register_date)='".date('Y')."'")); + $ecmStockOperations = new EcmStockOperation(); - if (!$r || !$r['c'] || $r['c']=='') - $count = 0; - else - $count = intval($r['c']); - - $count++; - - //has 5 digits? - $tmp = strval($count); - while (strlen($tmp) < 5) - $tmp = '0'.$tmp; - - return date("Ymd").$tmp; - } - - function formatNumber($number) { - $n = intval(substr($number, 8,5)); - $y = substr($number,0,4); - - //has 3 digits? - while (strlen($n) < 3) - $n = '0'.$n; - - return 'ZS '.$n.'/'.$y; - } - - function CreateQueryFromPost($array){ - $field_array=array(); - if($array['date_from']!='')$field_array[]="delivery_date>='".date("Y-m-d",strtotime($array['date_from']))."'"; - if($array['date_to']!='')$field_array[]="delivery_date<='".date("Y-m-d",strtotime($array['date_to']))."'"; - if($array['date_send_from']!='')$field_array[]="send_date>='".date("Y-m-d",strtotime($array['date_send_from']))."'"; - if($array['date_send_to']!='')$field_array[]="send_date<='".date("Y-m-d",strtotime($array['date_send_to']))."'"; - if($array['time_from']!='')$field_array[]="date_entered>='".date("Y-m-d",strtotime($array['time_from']))."'"; - if($array['time_to']!='')$field_array[]="date_entered<='".date("Y-m-d",strtotime($array['time_to']))."'"; - if($array['account_id']!='')$field_array[]="parent_id='".$array['account_id']."'"; - if($array['account_name']!='')$field_array[]="parent_name like '".$array['account_name']."'"; - if($array['parent_order_no']!='')$field_array[]="parent_document_no='".$array['parent_order_no']."'"; - switch ($array ['sale_type']) { - case 'all' : - $field_array[] = "type IN ('sales_order', 'gratis')"; - break; - case 'sale' : - $field_array[] = "type='sales_order'"; - break; - case 'gratis' : - $field_array[] = "type='gratis'"; - break; - } - - if (count ( $field_array ) > 0) - $where = " and " . implode ( " and ", $field_array ); - else - $where = ""; - $z = "select * from ecmsales where deleted='0' and status!='s10' " . $where; - if ($array['sale_type']=='all') - $z.=" ORDER BY type DESC"; - return $z; - } - - function GetArrayResultFromQuery($query){ - $db = $GLOBALS ['db']; - $w = $db->query ($query ); - echo mysql_error (); - $bb = 0; - $i=0; - $result_array=array(); - $sum_total_qty=0; - $sum_total_netto=0; - $sum_total_brutto=0; - $sum_total_invoice=0; - $sum_total_vat=0; - - $wal_query="select * from currency_nbp_archive order by date desc limit 3"; - - $ik=$db->query($wal_query); - $wal=[]; - while($walutki = $db->fetchByAssoc ( $ik)){ - $wal[$walutki['currency_id']]=$walutki['value']; - } - while ( $r = $db->fetchByAssoc ( $w ) ) { - $rrr = $db->fetchByAssoc ( $db->query ( "select id from ecmstockdocouts where ecmsale_id='" . $r ['id'] . "' and deleted='0'" ) ); - - if ($_REQUEST ['wz'] == 1 && $rrr ['id']) - continue; - $ww = $db->query ( "select quantity,price_netto as price,ecmvat_value from ecmsaleitems where ecmsale_id='" . $r ['id'] . "' and deleted='0'" ); - $total_netto = 0; - $total_brutto = 0; - $total_invoice = 0; - $total_vat = 0; - $total_qty = 0; - while ( $rr = $db->fetchByAssoc ( $ww ) ) { - $total_qty += $rr ['quantity']; - $total_netto += ($rr ['quantity'] * $rr ['price']); - $total_brutto += $rr ['quantity'] * $rr ['price'] * (1 + $rr ['ecmvat_value'] / 100); - $total_vat += $rr ['quantity'] * $rr ['price'] * ($rr ['ecmvat_value'] / 100); - } - if ($rrr ['id']) { - $rinv = $db->fetchByAssoc ( $db->query ( "select id, total_netto from ecminvoiceouts where wz_id='" . $rrr ['id'] . "' AND deleted='0'" ) ); - $total_invoice = $rinv ['total_netto']; - // $wi=$db->query("select price,quantity from ecminvoiceoutitems where ecminvoiceout_id='".$rinv['id']."' and deleted='0'"); - // while($ri=$db->fetchByAssoc($wi)){ - // $total_invoice+=$ri['quantity']*$ri['price']; - // } - } else { - $inv = null; - $wi = null; - $ri = null; - $rwz = null; - } - - $rsale = $db->fetchByAssoc ( $db->query ( "select sum(quantity*price_netto) as qty from ecmsaleitems where ecmsale_id='" . $r ['id'] . "'" ) ); - $rwz = $db->fetchByAssoc ( $db->query ( "select id from ecmstockdocouts where ecmsale_id='" . $r ['id'] . "' and deleted='0'" ) ); - $rwzi = $db->fetchByAssoc ( $db->query ( "select sum(quantity*price_sell) as qty from ecmstockdocoutitems where ecmstockdocout_id='" . $rwz ['id'] . "'" ) ); + $return_array ['stock_state'] = ($ecmStockOperations->getRealStock($position ['ecmproduct_id'])); + + $return_array ['reservation'] = $return_array ['stock_state']; + + return $return_array; + } + + function formatPositions($position_list) + { + return; + if (!is_array($position_list) || count($position_list) == 0) + return false; + global $app_list_strings; + require_once('modules/Currencies/Currency.php'); + foreach ($position_list as $key => $value) { + $position_list [$key] ['unit_id'] = $app_list_strings ['ecmproducts_unit_dom'] [$value ['unit_id']]; + $position_list [$key] ['category_id'] = $app_list_strings ['ecmproducts_category_dom'] [$value ['category_id']]; + // $position_list[$key]['vat_id'] = format_number($value['vat_id']).'%'; + $position_list [$key] ['discount'] = format_number($value ['discount']) . '%'; + if (isset ($currency) && ($currency->id == $this->currency_id)) { + } else { + $currency = new Currency (); + $currency->retrieve($this->currency_id); + } + $position_list [$key] ['price'] = format_number($value ['price']) . ' ' . $currency->iso4217; + $position_list [$key] ['total'] = format_number($value ['total']) . ' ' . $currency->iso4217; + // $position_list[$key]['price'] = format_number($value['price']).' PLN'; + // $position_list[$key]['total'] = format_number($value['total']).' PLN'; + $this->currency_symbol = $currency->iso4217; + } + return $position_list; + } + + // ***************************End Managing Positions*************************// + + function sendSoap($id) + { + ini_set("soap.wsdl_cache_enabled", "0"); + require_once("nusoap/nusoap.php"); + + $soapUrl = 'http://system.saas-systems.pl/soap.php?wsdl'; + $soapUser = 'admin'; + $soapPassword = 'rudemodz123'; + + $client = new nusoap_client ($soapUrl, 'wsdl'); + + $login_parameters = array( + 'user_auth' => array( + 'user_name' => $soapUser, + 'password' => md5($soapPassword), + 'version' => '1' + ), + 'application_name' => 'SoapTest', + 'name_value_list' => array() + ); + + $login_result = $client->call('login', $login_parameters); + + if ($login_result ['id'] != '') { + $session_id = $login_result ['id']; + + + $sdi = new EcmSale(); + $sdi->retrieve($id); + $sdi_fields = array(); + + $sdi_fields [] = array( + "name" => 'id', + "value" => $sdi->edi_zs_id + ); + + $sdi_fields [] = array( + "name" => 'edi_zs_id', + "value" => $sdi->id + ); + + $sdi_fields [] = array( + "name" => 'edi_zs_document_no', + "value" => $sdi->document_no + ); + + + $set_entry_parameters = array( + // session id + "session" => $session_id, + + // The name of the module from which to retrieve records. + "module_name" => "EcmSales", + + // Record attributes + "name_value_list" => $sdi_fields + ); + + $set_entry_result = $client->call("set_entry", $set_entry_parameters); + + + } + } + + //mz generate number + + function ACLAccess($view, $is_owner = 'not_set') + { + global $current_user; + $file = 'modules/EcmGroupSales/EcmGroupSale.php'; + if (file_exists($file)) { + require_once($file); + $cc = EcmGroupSale::loadSettings(true); + } else + return true; + if (is_admin($current_user)) { + switch ($view) { + case 'confirming' : + return ($this->status == "s20"); + case 'send_to_confirm' : + return ($this->status == "s10"); + case 'pdf_toolbar' : + return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40"); + } + return true; + } + if ($is_owner == 'not_set') { + $is_owner = $this->isOwner($current_user->id); + } + // if we don't implent acls return true + if (!$this->bean_implements('ACL')) + return true; + $view = strtolower($view); + if ($cc ['user_manager_role']) { // Manager + switch ($view) { + case 'list' : + case 'index' : + case 'listview' : + return ACLController::checkAccess($this->module_dir, 'list', true); + case 'edit' : + case 'save' : + case 'popupeditview' : + case 'editview' : + return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner)); + case 'view' : + case 'detail' : + case 'detailview' : + return ACLController::checkAccess($this->module_dir, 'view', $is_owner); + case 'delete' : + return ACLController::checkAccess($this->module_dir, 'delete', $is_owner); + case 'export' : + return ACLController::checkAccess($this->module_dir, 'export', $is_owner); + case 'import' : + return ACLController::checkAccess($this->module_dir, 'import', true); + case 'send_to_confirm' : + return ($this->status == "s10"); + case 'can_commit' : + return true; + case 'confirming' : + return ($this->status == "s20"); + case 'auto_commiting' : + return true; + case 'pdf_toolbar' : + return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40"); + } + } else if ($cc ['user_representative_extra_role']) { // Representative Extra + switch ($view) { + case 'list' : + case 'index' : + case 'listview' : + return ACLController::checkAccess($this->module_dir, 'list', true); + case 'edit' : + return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner) && ($this->status == "s10" || $this->status == "s40")); + case 'save' : + case 'popupeditview' : + case 'editview' : + return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner)); + case 'view' : + case 'detail' : + case 'detailview' : + return ACLController::checkAccess($this->module_dir, 'view', $is_owner); + case 'delete' : + return (ACLController::checkAccess($this->module_dir, 'delete', $is_owner) && $this->status == "s10"); + case 'export' : + return ACLController::checkAccess($this->module_dir, 'export', $is_owner); + case 'import' : + return ACLController::checkAccess($this->module_dir, 'import', true); + case 'quote_to_sale' : + case 'quote_to_invoice' : + return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40" && $this->status != "s60"); + case 'send_to_confirm' : + return ($this->status == "s10"); + case 'send_email' : + return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40"); + case 'can_commit' : + return true; + case 'confirming' : + return false; + case 'auto_commiting' : + return true; + case 'pdf_toolbar' : + return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40"); + } + } else if ($cc ['user_representative_role']) { // Representative + switch ($view) { + case 'list' : + case 'index' : + case 'listview' : + return ACLController::checkAccess($this->module_dir, 'list', true); + case 'edit' : + return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner) && ($this->status == "s10" || $this->status == "s40")); + case 'save' : + case 'popupeditview' : + case 'editview' : + return (ACLController::checkAccess($this->module_dir, 'edit', $is_owner)); + case 'view' : + case 'detail' : + case 'detailview' : + return ACLController::checkAccess($this->module_dir, 'view', $is_owner); + case 'delete' : + return (ACLController::checkAccess($this->module_dir, 'delete', $is_owner) && $this->status == "s10"); + case 'export' : + return ACLController::checkAccess($this->module_dir, 'export', $is_owner); + case 'import' : + return ACLController::checkAccess($this->module_dir, 'import', true); + case 'quote_to_sale' : + case 'quote_to_invoice' : + return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40" && $this->status != "s60"); + case 'send_to_confirm' : + return ($this->status == "s10"); + case 'send_email' : + return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40"); + case 'can_commit' : + return false; + case 'confirming' : + return false; + case 'auto_commiting' : + return false; + case 'pdf_toolbar' : + return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40"); + } + } + // if it is not one of the above views then it should be implemented on the page level + return true; + } + + function bean_implements($interface) + { + switch ($interface) { + case 'ACL' : + return true; + } + return false; + } + + function CreateQueryFromPost($array) + { + $field_array = array(); + if ($array['date_from'] != '') $field_array[] = "delivery_date>='" . date("Y-m-d", strtotime($array['date_from'])) . "'"; + if ($array['date_to'] != '') $field_array[] = "delivery_date<='" . date("Y-m-d", strtotime($array['date_to'])) . "'"; + if ($array['date_send_from'] != '') $field_array[] = "send_date>='" . date("Y-m-d", strtotime($array['date_send_from'])) . "'"; + if ($array['date_send_to'] != '') $field_array[] = "send_date<='" . date("Y-m-d", strtotime($array['date_send_to'])) . "'"; + if ($array['time_from'] != '') $field_array[] = "date_entered>='" . date("Y-m-d", strtotime($array['time_from'])) . "'"; + if ($array['time_to'] != '') $field_array[] = "date_entered<='" . date("Y-m-d", strtotime($array['time_to'])) . "'"; + if ($array['account_id'] != '') $field_array[] = "parent_id='" . $array['account_id'] . "'"; + if ($array['account_name'] != '') $field_array[] = "parent_name like '" . $array['account_name'] . "'"; + if ($array['parent_order_no'] != '') $field_array[] = "parent_document_no='" . $array['parent_order_no'] . "'"; + switch ($array ['sale_type']) { + case 'all' : + $field_array[] = "type IN ('sales_order', 'gratis')"; + break; + case 'sale' : + $field_array[] = "type='sales_order'"; + break; + case 'gratis' : + $field_array[] = "type='gratis'"; + break; + } + + if (count($field_array) > 0) + $where = " and " . implode(" and ", $field_array); + else + $where = ""; + $z = "select * from ecmsales where deleted='0' and status!='s10' " . $where; + if ($array['sale_type'] == 'all') + $z .= " ORDER BY type DESC"; + return $z; + } + + function GetArrayResultFromQuery($query) + { + $db = $GLOBALS ['db']; + $w = $db->query($query); + echo mysql_error(); + $bb = 0; + $i = 0; + $result_array = array(); + $sum_total_qty = 0; + $sum_total_netto = 0; + $sum_total_brutto = 0; + $sum_total_invoice = 0; + $sum_total_vat = 0; + + $wal_query = "select * from currency_nbp_archive order by date desc limit 3"; + + $ik = $db->query($wal_query); + $wal = []; + while ($walutki = $db->fetchByAssoc($ik)) { + $wal[$walutki['currency_id']] = $walutki['value']; + } + while ($r = $db->fetchByAssoc($w)) { + $rrr = $db->fetchByAssoc($db->query("select id from ecmstockdocouts where ecmsale_id='" . $r ['id'] . "' and deleted='0'")); + + if ($_REQUEST ['wz'] == 1 && $rrr ['id']) + continue; + $ww = $db->query("select quantity,price_netto as price,ecmvat_value from ecmsaleitems where ecmsale_id='" . $r ['id'] . "' and deleted='0'"); + $total_netto = 0; + $total_brutto = 0; + $total_invoice = 0; + $total_vat = 0; + $total_qty = 0; + while ($rr = $db->fetchByAssoc($ww)) { + $total_qty += $rr ['quantity']; + $total_netto += ($rr ['quantity'] * $rr ['price']); + $total_brutto += $rr ['quantity'] * $rr ['price'] * (1 + $rr ['ecmvat_value'] / 100); + $total_vat += $rr ['quantity'] * $rr ['price'] * ($rr ['ecmvat_value'] / 100); + } + if ($rrr ['id']) { + $rinv = $db->fetchByAssoc($db->query("select id, total_netto from ecminvoiceouts where wz_id='" . $rrr ['id'] . "' AND deleted='0'")); + $total_invoice = $rinv ['total_netto']; + // $wi=$db->query("select price,quantity from ecminvoiceoutitems where ecminvoiceout_id='".$rinv['id']."' and deleted='0'"); + // while($ri=$db->fetchByAssoc($wi)){ + // $total_invoice+=$ri['quantity']*$ri['price']; + // } + } else { + $inv = null; + $wi = null; + $ri = null; + $rwz = null; + } + + $rsale = $db->fetchByAssoc($db->query("select sum(quantity*price_netto) as qty from ecmsaleitems where ecmsale_id='" . $r ['id'] . "'")); + $rwz = $db->fetchByAssoc($db->query("select id from ecmstockdocouts where ecmsale_id='" . $r ['id'] . "' and deleted='0'")); + $rwzi = $db->fetchByAssoc($db->query("select sum(quantity*price_sell) as qty from ecmstockdocoutitems where ecmstockdocout_id='" . $rwz ['id'] . "'")); + + + $ecmstockdocout_id = $rwz ['id']; + if ($ecmstockdocout_id) { + $sum_wz_qty += $rwzi ['qty']; + $sum_sale_qty += $rsale ['qty']; + } + $qty_diff = $rwzi ['qty'] - $rsale ['qty']; + $diff_minus = $diff_plus = 0; + $rst = $rsale ['qty']; + $rwt = $rwzi ['qty']; + $percent = number_format((100 * $rwzi ['qty'] / $rsale ['qty']), 2, ",", ".") . "%"; + $order_total = 0; + $wz_total = 0; + $wz_green = 0; + $wz_red = 0; + if ($ecmstockdocout_id) { + $pr = 0; + $wsale = $db->query("select quantity,price_netto as price,code,ecmproduct_id from ecmsaleitems where deleted='0' and ecmsale_id='" . $r ['id'] . "' order by code"); + while ($rsale = $db->fetchByAssoc($wsale)) { + $qty = 0; + $wwz = $db->query("select quantity,price_sell from ecmstockdocoutitems where deleted='0' and ecmproduct_id='" . $rsale ['ecmproduct_id'] . "' and ecmstockdocout_id='" . $ecmstockdocout_id . "'"); + while ($rwz = $db->fetchByAssoc($wwz)) { + $qty += $rwz ['quantity'] * $rwz ['price_sell']; + } + if ($rsale ['quantity'] * $rsale ['price'] > $qty) + $color = "red"; + elseif ($rsale ['quantity'] * $rsale ['price'] < $qty) + $color = "green"; + else + $color = "black"; + + if ($rsale ['quantity'] * $rsale ['price'] > $qty) + $diff_minus += $qty - $rsale ['quantity'] * $rsale ['price']; + if ($rsale ['quantity'] * $rsale ['price'] < $qty) + $diff_plus += $qty - $rsale ['quantity'] * $rsale ['price']; + + $sum [$rsale ['ecmproduct_id']] ['wz'] += $qty; + $sum [$rsale ['ecmproduct_id']] ['sale'] += $rsale ['quantity'] * $rsale ['price']; + $rpro = $db->fetchByAssoc($db->query("select deliverydate,name from ecmproducts where id='" . $rsale ['ecmproduct_id'] . "'")); + $stock_q = $db->fetchByAssoc($db->query("select sum(quantity) as quantity from ecmstockoperations where product_id='" . $rsale ['ecmproduct_id'] . "'")); + + if ($color == "red" && $rpro ['deliverydate'] != "0000-00-00") + $eta = $rpro ['deliverydate']; + else + $eta = ""; + $order = $rsale ['quantity'] * $rsale ['price']; + $result_array[$i]['products'][$pr]['id'] = $rsale ['ecmproduct_id']; + $result_array[$i]['products'][$pr]['code'] = $rsale ['code']; + $result_array[$i]['products'][$pr]['name'] = $rpro['name']; + $result_array[$i]['products'][$pr]['stock'] = $rpro['name']; + $result_array[$i]['products'][$pr]['order'] = $order; + $result_array[$i]['products'][$pr]['quantity'] = $stock_q['quantity']; + $result_array[$i]['products'][$pr]['wz'] = $qty; + $result_array[$i]['products'][$pr]['eta'] = $eta; + + //totals + $order_total += $order; + $wz_total += $qty; + + + $pr++; + } + } + if ($r['type'] != 'gratis') { + // guziczki kochane + + $rwz = $db->fetchByAssoc($db->query("select id from ecmstockdocouts where ecmsale_id='" . $r ['id'] . "' and deleted='0'")); + + $rfv = $db->fetchByAssoc($db->query("select id,document_no from ecminvoiceouts where wz_id='" . $rwz ['id'] . "' and deleted='0' and canceled='0'")); + if ($rwz ['id'] && $rfv ['id']) { + $sw = 'yes'; + $sw_id = $rfv ['id']; + $sw_nr = $rfv ['document_no']; + } elseif ($rwz ['id'] && !$rfv ['id']) { + $sw_id = $rwz ['id']; + $sw = 'no'; + } else { + $tmp = ''; + $sw = 'none'; + $sw_id = ''; + } + $t .= $tmp; + $rrr = $db->fetchByAssoc($db->query("select id,document_no from ecmstockdocouts where ecmsale_id='" . $r ['id'] . "' and deleted='0'")); + if ($rrr ['id']) { + + $ed = "disabled"; + $title = $rrr ['document_no']; + $wz_idd = $rrr['id']; + } else { + $onclick = ' onclick="javascript:window.open(\'index.php?module=EcmStockDocOuts&action=EditView&parent_doc_type=EcmSales&parent_doc_id=' . $r ['id'] . '\',\'_newtab\');"'; + $ed = "enabled"; + $title = "Create WZ"; + } + } else { + $rw = $db->fetchByAssoc($db->query("select id,document_no from ecmstockdocinsideouts where ecmsale_id='" . $r ['id'] . "'")); + if ($rw['id'] != '') { + $rwed = "disabled"; + $rw_t = $rw ['document_no']; + $rw_id = $rw['id']; + } else { + $rwonclick = ' onclick="javascript:window.open(\'index.php?module=EcmStockDocinsideOuts&action=EditView&parent_doc_type=EcmSales&parent_doc_id=' . $r ['id'] . '\',\'_newtab\');"'; + $rwed = "enabled"; + $rw_t = "Utwórz RW"; + } + } + $result_array[$i]['wz_switch'] = $ed; + $result_array[$i]['wz_name'] = $title; + $result_array[$i]['wz_id'] = $wz_idd; + $result_array[$i]['rw_switch'] = $rwed; + $result_array[$i]['rw_name'] = $rw_t; + $result_array[$i]['rw_id'] = $rw_id; + $result_array[$i]['type'] = $r['type']; + $result_array[$i]['fv_switch'] = $sw; + $result_array[$i]['fv_id'] = $sw_id; + $result_array[$i]['fv_name'] = $sw_nr; + $result_array[$i]['products']['order_total'] = $order_total; + $result_array[$i]['products']['wz_total'] = $wz_total; + $result_array[$i]['products']['minus'] = $diff_minus; + $result_array[$i]['products']['plus'] = $diff_plus; + $result_array[$i]['position'] = $i + 1; + $result_array[$i]['id'] = $r['id']; + $result_array[$i]['number'] = $r['number']; + $result_array[$i]['document_no'] = $r['document_no']; + $result_array[$i]['parent_name'] = $r['parent_name']; + $result_array[$i]['parent_id'] = $r['parent_id']; + $result_array[$i]['delivery_date'] = $r['delivery_date']; + $result_array[$i]['send_date'] = $r['send_date']; + $result_array[$i]['send_accepted'] = $r['send_accepted']; + $result_array[$i]['quantity'] = $total_qty; + $result_array[$i]['total_netto'] = $total_netto; + $result_array[$i]['total_brutto'] = $total_brutto; + $result_array[$i]['total_vat'] = $total_vat; + $result_array[$i]['total_invoice'] = $total_invoice; + $result_array[$i]['percent'] = $percent; + $result_array[$i]['currency'] = $r['currency_id']; + + $i++; + $sum_total_qty += $total_qty; + $sum_total_netto += $total_netto * ($r['currency_id'] != 'PLN' ? $wal[$r['currency_id']] : 1); + $sum_total_brutto += $total_brutto * ($r['currency_id'] != 'PLN' ? $wal[$r['currency_id']] : 1); + $sum_total_invoice += $total_invoice * ($r['currency_id'] != 'PLN' ? $wal[$r['currency_id']] : 1); + $sum_total_vat += $total_vat * ($r['currency_id'] != 'PLN' ? $wal[$r['currency_id']] : 1); + $percent = (100 * $sum_wz_qty / $sum_sale_qty); + } + $result_array['total_quantity'] = $sum_total_qty; + $result_array['total_netto'] = $sum_total_netto; + $result_array['total_brutto'] = $sum_total_brutto; + $result_array['total_invoice'] = $sum_total_invoice; + $result_array['total_vat'] = $sum_total_vat; + $result_array['total_percent'] = $percent; + + $rst = 0; + $rwt = 0; + $diff_plus = $diff_minus = 0; + $c1 = 0; + $ww = $db->query("select id from ecmproducts where deleted='0' order by code asc"); + while ($rr = $db->fetchByAssoc($ww)) { + $k = $rr ['id']; + if (!$sum [$k]) + continue; + $rpro = $db->fetchByAssoc($db->query("select code,deliverydate from ecmproducts where id='" . $k . "'")); + if ($sum [$k] ['wz'] < $sum [$k] ['sale']) + $color = "red"; + elseif ($sum [$k] ['wz'] > $sum [$k] ['sale']) + $color = "green"; + else + $color = "black"; + $rst += $sum [$k] ['sale']; + $rwt += $sum [$k] ['wz']; + + if ($sum [$k] ['sale'] > $sum [$k] ['wz']) + $diff_minus += $sum [$k] ['wz'] - $sum [$k] ['sale']; + if ($sum [$k] ['sale'] < $sum [$k] ['wz']) + $diff_plus += $sum [$k] ['wz'] - $sum [$k] ['sale']; + + if ($color == "red" && $rpro ['deliverydate'] != "0000-00-00") + $eta = $rpro ['deliverydate']; + else + $eta = ""; + + $result_array['total_product'][$c1]['code'] = $rpro ['code']; + $result_array['total_product'][$c1]['id'] = $k; + $result_array['total_product'][$c1]['order'] = $sum [$k] ['sale']; + $result_array['total_product'][$c1]['wz'] = $sum [$k] ['wz']; + $result_array['total_product'][$c1]['eta'] = $eta; + $c1++; + } + $result_array['total_product']['order_total'] = $rst; + $result_array['total_product']['wz_total'] = $rwt; + $result_array['total_product']['minus'] = $diff_minus; + $result_array['total_product']['plus'] = $diff_plus; + + + return $result_array; + } + + function UploadXML() + { + $allowedExts = array("xml"); + $temp = explode(".", $_FILES["file"]["name"]); + $extension = end($temp); + $name = date("Y_d_m") . str_replace(" ", "", str_replace("_", "", str_replace(".", "", microtime()))) . '.' . $extension; + + if ($_FILES["file"]["error"] > 0) { + return '0'; + } else { + if (file_exists("modules/EcmSales/upload_xml/" . $_FILES["file"]["name"])) { + return '0'; + } else { + move_uploaded_file($_FILES["file"]["tmp_name"], + "modules/EcmSales/upload_xml/" . $name); + return $name; + } + } + } + + function CreateMultiPDF($post) + { + ini_set('max_execution_time', 9999999999); + $filename = array(); + global $current_user; + foreach ($post as $id) { + + $strPath = dirname(__FILE__) . "\\"; + if ($id == '') continue; + $this->retrieve($id); + + // $pdf2 = new PDFMerger; + //$ab [] = $this->createPdfFileName (); + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, 'https://' . $_SERVER['SERVER_ADDR'] . '/index.php?action=Authenticate&module=Users&return_module=Users&return_action=Login&user_name=db&user_password=rudemodz&login_theme=Sugar&login_language=en_us'); + // curl_setopt($ch, CURLOPT_POSTFIELDS,'user_name=db&user_password='.$pass.''); + + curl_setopt($ch, CURLOPT_POST, 1); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3"); + curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3"); + $page = curl_exec($ch); + + // echo $pass = md5('rudemodz'); + $up = 'https://' . $_SERVER['SERVER_ADDR'] . '/index.php?module=EcmSales&action=createPDF&to_pdf=1&show_img=0&show_ean=0&show_ean2=0&show_recipient_code=0&record=' . $id . ''; + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_URL, $up); + + $page = curl_exec($ch); + + $fp = fopen('pdftmp/' . $this->createPdfFileName() . '', 'w'); + fwrite($fp, $page); + fclose($fp); + $filename [] = $this->createPdfFileName(); + } + $fp = fopen('generatorfifi_' . $current_user->user_name . '.php', 'w'); + $s = "user_name . '_' . date("hysmd"); + foreach ($filename as $k) { + $s .= "->addPDF('pdftmp/" . $k . "', 'all')\n"; + } + $s .= "->merge('file', 'pdftmp/" . $file; + $s .= ".pdf');"; + // $b=microtime(); + fwrite($fp, $s); + fclose($fp); + // echo microtime(); + + $up = 'https://' . $_SERVER['SERVER_ADDR'] . '/generatorfifi_' . $current_user->user_name . '.php'; + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_URL, $up); + + $page = curl_exec($ch); + + return $file . '.pdf'; + } + + function createPdfFileName($format = true) + { + global $mod_strings; + + $arr1 = array('\\', '/', ':', '*', '?', '"', '<', '>', '|', ' '); + + $arr2 = array('', '', '', '', '', '\'', '[', ']', '', '_'); + + $tmp = $this->document_no; + + if ($format) + + $tmp = str_replace($arr1, $arr2, $mod_strings['LBL_PDF_FILENAME'] . $tmp . '.pdf'); + + else + + $tmp = $mod_strings['LBL_PDF_FILENAME'] . $tmp . '.pdf'; + + //$mod = return_module_language($current_language, 'EcmInvoiceOuts'); + + //return urlencode( + + // return $mod['LBL_PDF_INVOICE_FILE_NAME'].$tmp.'.pdf';//); + + return $tmp; //); + + } - - $ecmstockdocout_id = $rwz ['id']; - if ($ecmstockdocout_id) { - $sum_wz_qty += $rwzi ['qty']; - $sum_sale_qty += $rsale ['qty']; - } - $qty_diff = $rwzi ['qty'] - $rsale ['qty']; - $diff_minus = $diff_plus = 0; - $rst = $rsale ['qty']; - $rwt = $rwzi ['qty']; - $percent = number_format ( (100 * $rwzi ['qty'] / $rsale ['qty']), 2, ",", "." ) . "%"; - $order_total=0; - $wz_total=0; - $wz_green=0; - $wz_red=0; - if ($ecmstockdocout_id) { - $pr=0; - $wsale = $db->query ( "select quantity,price_netto as price,code,ecmproduct_id from ecmsaleitems where deleted='0' and ecmsale_id='" . $r ['id'] . "' order by code" ); - while ( $rsale = $db->fetchByAssoc ( $wsale ) ) { - $qty = 0; - $wwz = $db->query ( "select quantity,price_sell from ecmstockdocoutitems where deleted='0' and ecmproduct_id='" . $rsale ['ecmproduct_id'] . "' and ecmstockdocout_id='" . $ecmstockdocout_id . "'" ); - while ( $rwz = $db->fetchByAssoc ( $wwz ) ) { - $qty += $rwz ['quantity'] * $rwz ['price_sell']; - } - if ($rsale ['quantity'] * $rsale ['price'] > $qty) - $color = "red"; - elseif ($rsale ['quantity'] * $rsale ['price'] < $qty) - $color = "green"; - else - $color = "black"; - - if ($rsale ['quantity'] * $rsale ['price'] > $qty) - $diff_minus += $qty - $rsale ['quantity'] * $rsale ['price']; - if ($rsale ['quantity'] * $rsale ['price'] < $qty) - $diff_plus += $qty - $rsale ['quantity'] * $rsale ['price']; - - $sum [$rsale ['ecmproduct_id']] ['wz'] += $qty; - $sum [$rsale ['ecmproduct_id']] ['sale'] += $rsale ['quantity'] * $rsale ['price']; - $rpro = $db->fetchByAssoc ( $db->query ( "select deliverydate,name from ecmproducts where id='" . $rsale ['ecmproduct_id'] . "'" ) ); - $stock_q = $db->fetchByAssoc ( $db->query ( "select sum(quantity) as quantity from ecmstockoperations where product_id='" . $rsale ['ecmproduct_id'] . "'" ) ); - - if ($color == "red" && $rpro ['deliverydate'] != "0000-00-00") - $eta = $rpro ['deliverydate']; - else - $eta = ""; - $order=$rsale ['quantity'] * $rsale ['price']; - $result_array[$i]['products'][$pr]['id']=$rsale ['ecmproduct_id']; - $result_array[$i]['products'][$pr]['code']=$rsale ['code']; - $result_array[$i]['products'][$pr]['name']=$rpro['name']; - $result_array[$i]['products'][$pr]['stock']=$rpro['name']; - $result_array[$i]['products'][$pr]['order']=$order; - $result_array[$i]['products'][$pr]['quantity']=$stock_q['quantity']; - $result_array[$i]['products'][$pr]['wz']=$qty; - $result_array[$i]['products'][$pr]['eta']=$eta; - - //totals - $order_total+=$order; - $wz_total+=$qty; - - - $pr++; - } - } - if($r['type']!='gratis'){ - // guziczki kochane - - $rwz = $db->fetchByAssoc ( $db->query ( "select id from ecmstockdocouts where ecmsale_id='" . $r ['id'] . "' and deleted='0'" ) ); - - $rfv = $db->fetchByAssoc ( $db->query ( "select id,document_no from ecminvoiceouts where wz_id='" . $rwz ['id'] . "' and deleted='0' and canceled='0'" ) ); - if ($rwz ['id'] && $rfv ['id']) { - $sw='yes'; - $sw_id=$rfv ['id']; - $sw_nr=$rfv ['document_no']; - } elseif ($rwz ['id'] && ! $rfv ['id']) { - $sw_id=$rwz ['id']; - $sw='no'; - } else { - $tmp = ''; - $sw='none'; - $sw_id=''; - } - $t .= $tmp; - $rrr = $db->fetchByAssoc ( $db->query ( "select id,document_no from ecmstockdocouts where ecmsale_id='" . $r ['id'] . "' and deleted='0'" ) ); - if ($rrr ['id']) { - - $ed = "disabled"; - $title = $rrr ['document_no']; - $wz_idd=$rrr['id']; - } else { - $onclick = ' onclick="javascript:window.open(\'index.php?module=EcmStockDocOuts&action=EditView&parent_doc_type=EcmSales&parent_doc_id=' . $r ['id'] . '\',\'_newtab\');"'; - $ed = "enabled"; - $title = "Create WZ"; - } - } else { - $rw = $db->fetchByAssoc ( $db->query ( "select id,document_no from ecmstockdocinsideouts where ecmsale_id='" . $r ['id'] . "'" ) ); - if($rw['id']!=''){ - $rwed = "disabled"; - $rw_t = $rw ['document_no']; - $rw_id=$rw['id']; - } else { - $rwonclick = ' onclick="javascript:window.open(\'index.php?module=EcmStockDocinsideOuts&action=EditView&parent_doc_type=EcmSales&parent_doc_id=' . $r ['id'] . '\',\'_newtab\');"'; - $rwed = "enabled"; - $rw_t = "Utwórz RW"; - } - } - $result_array[$i]['wz_switch']=$ed; - $result_array[$i]['wz_name']=$title; - $result_array[$i]['wz_id']=$wz_idd; - $result_array[$i]['rw_switch']=$rwed; - $result_array[$i]['rw_name']=$rw_t; - $result_array[$i]['rw_id']=$rw_id; - $result_array[$i]['type']=$r['type']; - $result_array[$i]['fv_switch']=$sw; - $result_array[$i]['fv_id']=$sw_id; - $result_array[$i]['fv_name']=$sw_nr; - $result_array[$i]['products']['order_total']=$order_total; - $result_array[$i]['products']['wz_total']=$wz_total; - $result_array[$i]['products']['minus']=$diff_minus; - $result_array[$i]['products']['plus']=$diff_plus; - $result_array[$i]['position']=$i+1; - $result_array[$i]['id']=$r['id']; - $result_array[$i]['number']=$r['number']; - $result_array[$i]['document_no']=$r['document_no']; - $result_array[$i]['parent_name']=$r['parent_name']; - $result_array[$i]['parent_id']=$r['parent_id']; - $result_array[$i]['delivery_date']=$r['delivery_date']; - $result_array[$i]['send_date']=$r['send_date']; - $result_array[$i]['send_accepted']=$r['send_accepted']; - $result_array[$i]['quantity']=$total_qty ; - $result_array[$i]['total_netto']=$total_netto ; - $result_array[$i]['total_brutto']=$total_brutto ; - $result_array[$i]['total_vat']=$total_vat ; - $result_array[$i]['total_invoice']=$total_invoice ; - $result_array[$i]['percent']=$percent; - $result_array[$i]['currency']=$r['currency_id']; - - $i++; - $sum_total_qty += $total_qty; - $sum_total_netto += $total_netto * ($r['currency_id']!='PLN' ? $wal[$r['currency_id']] : 1); - $sum_total_brutto += $total_brutto * ($r['currency_id']!='PLN' ? $wal[$r['currency_id']] : 1); - $sum_total_invoice += $total_invoice * ($r['currency_id']!='PLN' ? $wal[$r['currency_id']] : 1); - $sum_total_vat += $total_vat * ($r['currency_id']!='PLN' ? $wal[$r['currency_id']] : 1); - $percent = (100 * $sum_wz_qty / $sum_sale_qty); - } - $result_array['total_quantity']=$sum_total_qty; - $result_array['total_netto']=$sum_total_netto; - $result_array['total_brutto']=$sum_total_brutto; - $result_array['total_invoice']=$sum_total_invoice; - $result_array['total_vat']=$sum_total_vat; - $result_array['total_percent']=$percent; - - $rst = 0; - $rwt = 0; - $diff_plus = $diff_minus = 0; - $c1=0; - $ww = $db->query ( "select id from ecmproducts where deleted='0' order by code asc" ); - while ( $rr = $db->fetchByAssoc ( $ww ) ) { - $k = $rr ['id']; - if (! $sum [$k]) - continue; - $rpro = $db->fetchByAssoc ( $db->query ( "select code,deliverydate from ecmproducts where id='" . $k . "'" ) ); - if ($sum [$k] ['wz'] < $sum [$k] ['sale']) - $color = "red"; - elseif ($sum [$k] ['wz'] > $sum [$k] ['sale']) - $color = "green"; - else - $color = "black"; - $rst += $sum [$k] ['sale']; - $rwt += $sum [$k] ['wz']; - - if ($sum [$k] ['sale'] > $sum [$k] ['wz']) - $diff_minus += $sum [$k] ['wz'] - $sum [$k] ['sale']; - if ($sum [$k] ['sale'] < $sum [$k] ['wz']) - $diff_plus += $sum [$k] ['wz'] - $sum [$k] ['sale']; - - if ($color == "red" && $rpro ['deliverydate'] != "0000-00-00") - $eta = $rpro ['deliverydate']; - else - $eta = ""; - - $result_array['total_product'][$c1]['code']=$rpro ['code']; - $result_array['total_product'][$c1]['id']=$k; - $result_array['total_product'][$c1]['order']=$sum [$k] ['sale']; - $result_array['total_product'][$c1]['wz']=$sum [$k] ['wz']; - $result_array['total_product'][$c1]['eta']=$eta; - $c1++; - } - $result_array['total_product']['order_total']=$rst; - $result_array['total_product']['wz_total']=$rwt; - $result_array['total_product']['minus']=$diff_minus; - $result_array['total_product']['plus']=$diff_plus; - - - return $result_array; - } - function createPdfFileName($format=true) { - global $mod_strings; - - $arr1 = Array('\\', '/', ':', '*', '?' , '"', '<', '>', '|', ' '); - - $arr2 = Array('', '', '', '', '', '\'', '[', ']', '', '_'); - - $tmp = $this->document_no; - - if($format) - - $tmp = str_replace($arr1, $arr2, $mod_strings['LBL_PDF_FILENAME'].$tmp.'.pdf'); - - else - - $tmp = $mod_strings['LBL_PDF_FILENAME'].$tmp.'.pdf'; - - //$mod = return_module_language($current_language, 'EcmInvoiceOuts'); - - //return urlencode( - - // return $mod['LBL_PDF_INVOICE_FILE_NAME'].$tmp.'.pdf';//); - - return $tmp; //); - - } - - function UploadXML(){ - $allowedExts = array("xml"); - $temp = explode(".", $_FILES["file"]["name"]); - $extension = end($temp); - $name=date("Y_d_m").str_replace(" ","",str_replace("_","",str_replace(".","",microtime()))).'.'.$extension; - - if ($_FILES["file"]["error"] > 0) { - return '0'; - } else { - if (file_exists("modules/EcmSales/upload_xml/" . $_FILES["file"]["name"])) { - return '0'; - } else { - move_uploaded_file($_FILES["file"]["tmp_name"], - "modules/EcmSales/upload_xml/" . $name); - return $name; - } - } - } - - function CreateMultiPDF($post){ - ini_set('max_execution_time', 9999999999); - $filename=array(); - global $current_user; - foreach($post as $id){ - - $strPath = dirname ( __FILE__ ) . "\\"; - if($id=='')continue; - $this->retrieve ( $id ); - - // $pdf2 = new PDFMerger; - //$ab [] = $this->createPdfFileName (); - - $ch = curl_init (); - curl_setopt ( $ch, CURLOPT_URL, 'https://'.$_SERVER['SERVER_ADDR'].'/index.php?action=Authenticate&module=Users&return_module=Users&return_action=Login&user_name=db&user_password=rudemodz&login_theme=Sugar&login_language=en_us' ); - // curl_setopt($ch, CURLOPT_POSTFIELDS,'user_name=db&user_password='.$pass.''); - - curl_setopt ( $ch, CURLOPT_POST, 1 ); - curl_setopt ( $ch, CURLOPT_HEADER, 0 ); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 ); - curl_setopt ( $ch, CURLOPT_COOKIEJAR, 'cookie.txt' ); - curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); - curl_setopt ( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3" ); - curl_setopt ( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3" ); - $page = curl_exec ( $ch ); - - // echo $pass = md5('rudemodz'); - $up = 'https://'.$_SERVER['SERVER_ADDR'].'/index.php?module=EcmSales&action=createPDF&to_pdf=1&show_img=0&show_ean=0&show_ean2=0&show_recipient_code=0&record=' . $id . ''; - curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true ); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt ( $ch, CURLOPT_URL, $up ); - - $page = curl_exec ( $ch ); - - $fp = fopen ( 'pdftmp/' . $this->createPdfFileName () . '', 'w' ); - fwrite ( $fp, $page ); - fclose ( $fp ); - $filename [] = $this->createPdfFileName (); - } - $fp = fopen ( 'generatorfifi_'.$current_user->user_name.'.php', 'w' ); - $s = "user_name .'_'. date ( "hysmd" ); - foreach ( $filename as $k ) { - $s .= "->addPDF('pdftmp/" . $k . "', 'all')\n"; - } - $s .= "->merge('file', 'pdftmp/" . $file; - $s .= ".pdf');"; - // $b=microtime(); - fwrite ( $fp, $s ); - fclose ( $fp ); - // echo microtime(); - - $up = 'https://'.$_SERVER['SERVER_ADDR'].'/generatorfifi_'.$current_user->user_name.'.php'; - curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true ); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt ( $ch, CURLOPT_URL, $up ); - - $page = curl_exec ( $ch ); - - return $file.'.pdf'; - } - } + ?> \ No newline at end of file diff --git a/modules/EcmStockStates/rebuildStates.php b/modules/EcmStockStates/rebuildStates.php index 0fee07d0..ef73d59c 100755 --- a/modules/EcmStockStates/rebuildStates.php +++ b/modules/EcmStockStates/rebuildStates.php @@ -9,7 +9,7 @@ set_time_limit(1000000); $sarr=array(); $parr=array(); -// https://crm.e5.pl/index.php?module=EcmStockStates&action=rebuildStates&ids=2096adf3-d888-a84f-c7ec-59f810381701,75d70d0d-8f48-bf2c-3cd7-63a426511e9e,8f0d5583-468a-9c14-83b2-50a25be72052,cbead744-99e9-7d1c-0d7e-58622d8e6d8b,e95ac585-b616-b83f-e5e4-4ae5952dae8f +// https://crm.e5.pl/index.php?module=EcmStockStates&action=rebuildStates&ids=20e88740-56f6-7306-1008-647450c5e4fd,d783e0de-2ea0-f783-d29b-5bffea73981c if (isset($_GET['ids'])) { $ids = explode(',', $_GET['ids']); diff --git a/themes/Sugar5/tpls/_headerModuleList.tpl b/themes/Sugar5/tpls/_headerModuleList.tpl index 290325f1..45ff7ba1 100644 --- a/themes/Sugar5/tpls/_headerModuleList.tpl +++ b/themes/Sugar5/tpls/_headerModuleList.tpl @@ -157,6 +157,11 @@ Planowanie produkcji {/if} + {if $group=='Produkcja'} +
  • + Harmonogram produkcji +
  • + {/if} {/foreach}