Add php files

This commit is contained in:
2025-05-12 15:44:39 +00:00
parent c951760058
commit 82d5804ac4
9534 changed files with 2638137 additions and 0 deletions

View File

@@ -0,0 +1,134 @@
<?php
//ini_set('display_errors',1);
require_once ('modules/EcmInvoiceOuts/EcmInvoiceOut.php');
global $mod_strings, $app_list_strings;
$accountName = null;
$accountId = null;
if(isSet($_REQUEST["accountName"])){
$accountName = $_REQUEST["accountName"];
}
if(isSet($_REQUEST["accountId"])){
$accountId = $_REQUEST["accountId"];
}
$to_pdf = false;
if(isSet($_GET ['to_pdf']) && $_GET ['to_pdf'] =='1'){
$to_pdf = true;
}
if (isset($accountId) && $accountId!='') {
$where['accountId'] = $accountId;
} else if (!isset($accountId) && isset($accountName) && strlen($accountName) > 0) {
$where['accountName'] = $accountName;
}
try {
$tmp = new DateTime(date('Y-m-31'));
$tmp2 = new DateTime(date('Y-m-01'));
$tmp2->sub(new DateInterval('P1Y'));
$where['register_date_to'] = $tmp->format('Y-m-d');
$where['register_date_from'] = $tmp2->format('Y-m-d');
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
$data = AnalysisEcmQuote($where);
$rows = array();
if(count($data)>0){
foreach ($data as $key => $value) {
$rows['created'][] = $value['created'];
$rows['accepted'][] = $value['accepted'];
$rows['not_accepted'][] = $value['not_accepted'];
}
}
$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("DATA", $data);
$smarty->assign("ROWS", $rows);
$smarty->assign("accountName", $accountName);
$smarty->assign("accountId", $accountId);
if ($to_pdf) {
$output = $smarty->fetch('modules/EcmReports/tpls/PDF/AnalysisProductSale.tpl');
include_once ("include/MPDF57/mpdf.php");
$p = new mPDF('', 'A4', NULL, 'helvetica', 10, 10, 10, 10, 5, 5);
$p->writeHTML($output);
$p->Output('RaportSprzedazy.pdf', 'I');
} else {
echo $smarty->display('modules/EcmReports/tpls/AnalysisEcmQuote.tpl');
}
function AnalysisEcmQuote($where) {
global $db;
$query = "SELECT status, register_date FROM ecmquotes WHERE deleted=0 ";
//die(1);
if (isset($where) && is_array($where) && count($where) > 0) {
$wherereturn = array();
foreach ($where as $key => $value) {
switch ($key) {
case 'register_date_from':
$wherereturn[] = "register_date>='" . $value . "'";
break;
case 'register_date_to':
$wherereturn[] = "register_date<='" . $value . "'";
break;
case 'accountName':
$wherereturn[] = "parent_name LIKE '%" . trim($value) . "%'";
$wherereturn[] = "parent_type ='Accounts'";
break;
case 'accountId':
$wherereturn[] = "parent_id = '" . trim($value) . "'";
break;
}
}
if (count($wherereturn) > 0) {
$query .= " AND " . implode(" AND ", $wherereturn);
}
}
$query .= " ORDER BY register_date";
$result = $db->query($query);
$return = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$return[substr($row['register_date'], 0, 7)][$row['status']] += 1;
}
} else {
$return = NULL;
}
if(count($return)<12){
try {
$currentDate = new DateTime(date('Y-m-01'));
$date = new DateTime(date('Y-m-01'));
$date->sub(new DateInterval('P1Y'));
$register_date_fill = $date->format('Y-m');
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
while(count($return)<12){
if(!isset($return[$register_date_fill])){
$return[$register_date_fill]['total_purchase'] = 0;
$return[$register_date_fill]['total_netto'] = 0;
}
$date->add(new DateInterval('P1M'));
$register_date_fill = $date->format('Y-m');
}
}
ksort($return);
$formated_return;
foreach ($return as $data => $row){
$split = split("-",$data);
$formated_return[$split[1] .".".$split[0]] = $row;
}
return $formated_return;
}
?>

View File

@@ -0,0 +1,260 @@
<?php
require_once ('modules/EcmInvoiceOuts/EcmInvoiceOut.php');
global $mod_strings, $app_list_strings;
$db = $GLOBALS['db'];
$productCategoryList = getProductCategoryList();
$accountName = $_REQUEST["accountName"];
$accountId = $_REQUEST["accountId"];
$productName = $_REQUEST["productName"];
$productId = $_REQUEST["productId"];
if (isset($productId) && $productId != '') {
$where['productId'] = $productId;
} else if (!isset($productId) && isset($productName) && strlen($productName) > 0) {
$where['productName'] = $productName;
}
if (isset($accountId) && $accountId!='') {
$where['accountId'] = $accountId;
} else if (!isset($accountId) && isset($accountName) && strlen($accountName) > 0) {
$where['accountName'] = $accountName;
}
try {
$tmp = new DateTime(date('Y-m-31'));
$tmp2 = new DateTime(date('Y-m-01'));
$tmp2->sub(new DateInterval('P1Y'));
$where['register_date_to'] = $tmp->format('Y-m-d');
$where['register_date_from'] = $tmp2->format('Y-m-d');
// $where['register_date_to'] = '2015-07-31';
// $where['register_date_from'] = '2015-07-01';
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
$relationsQuery = " FROM `ecminvoiceouts`
INNER JOIN `accounts` ON
(accounts.id = ecminvoiceouts.parent_id)
INNER JOIN `ecminvoiceoutitems` ON
(ecminvoiceoutitems.ecminvoiceout_id = ecminvoiceouts.id)
INNER JOIN `ecmproducts` ON
(ecmproducts.id = ecminvoiceoutitems.ecmproduct_id)
" /*. $relationsQueryReceipts*/ . "
";
$stock_array = array(""=>"");
$stock_request = $db->query("SELECT id, name FROM ecmstocks WHERE deleted=0");
while($row = $db->fetchByAssoc($stock_request)){ $stock_array[$row['id']] = $row['name']; }
$group_ks_without_filter = [];
$group_ks_result_without_filter = $db->query("SELECT DISTINCT `ks_group` " . $relationsQuery . " ORDER BY `ks_group`");
while($row = $db->fetchByAssoc($group_ks_result_without_filter)) {
if($app_list_strings['ecmproducts_group_ks_dom'][ $row['ks_group']]!=NULL){
$group_ks_without_filter[$row['ks_group']] = $app_list_strings['ecmproducts_group_ks_dom'][ $row['ks_group'] ];
}
}
$group_ks_without_filter_2 = [];
$group_ks_result_without_filter_2 = $db->query("SELECT DISTINCT `ks_group2` " . $relationsQuery . " ORDER BY `ks_group2`");
while($row = $db->fetchByAssoc($group_ks_result_without_filter_2)) {
if($app_list_strings['ecmproducts_group2_ks_dom'][ $row['ks_group2']]!=NULL){
$group_ks_without_filter_2[$row['ks_group2']] = $app_list_strings['ecmproducts_group2_ks_dom'][ $row['ks_group2'] ];
}
}
//$where['type'] = 'correct';
//$where['type'] = 'normal';
if(isset($_REQUEST['product_group']) && !empty($_REQUEST['product_group'])){
$where['product_group']=$_REQUEST['product_group'];
}
if(isset($_REQUEST['product_group_2']) && !empty($_REQUEST['product_group_2'])){
$where['product_group_2']=$_REQUEST['product_group_2'];
}
if(isset($_REQUEST['stocks']) && !empty($_REQUEST['stocks'])){
$where['stocks']=$_REQUEST['stocks'];
}
$where['deleted'] = 0;
$where['canceled'] = 0;
if($_REQUEST['submit']){
$data = AnalysisProductSale($where);
$rows = array();
foreach ($data as $key => $value) {
$rows['netto'][] = $value['total_netto'];
// $rows['total_brutto'][] = $value['total_brutto'];
$rows['ilosc'][] = $value['quantity'];
$rows['srednia'][]=$value['total_netto']/$value['quantity'];
$rows['marza'][] = $value['total_netto'] - $value['total_purchase'];
$rows['marzaprocent'][] = (($value['total_netto'] - $value['total_purchase']) * 100) / $value['total_netto'];
}
}
$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("DATA", $data);
$smarty->assign("ROWS", $rows);
$smarty->assign("stock_array", $stock_array);
$smarty->assign("product_group", $group_ks_without_filter);
$smarty->assign("product_group_2", $group_ks_without_filter_2);
$smarty->assign("productCategoryList", $productCategoryList);
$smarty->assign("productCategorySelected", $productCategorySelected);
$smarty->assign("accountName", $accountName);
$smarty->assign("accountId", $accountId);
$smarty->assign("productName", $productName);
$smarty->assign("productId", $productId);
if ($_GET ['to_pdf'] == '1') {
$output = $smarty->fetch('modules/EcmReports/tpls/PDF/AnalysisPZ.tpl');
include_once ("include/MPDF57/mpdf.php");
$p = new mPDF('', 'A4', NULL, 'helvetica', 10, 10, 10, 10, 5, 5);
$p->writeHTML($output);
$p->Output('RaportSprzedazy.pdf', 'I');
} else {
echo $smarty->display('modules/EcmReports/tpls/AnalysisPZ.tpl');
}
function AnalysisProductSale($where) {
global $db;
$query = "SELECT total_netto, i.stock_id,p.price ,p.ecmstockdocin_id as ecminvoiceout_id, p.ecmproduct_id, p.code, p.name, p.quantity , i.register_date, i.currency_value, i.currency_id FROM ecmstockdocinitems p, ecmstockdocins i,ecmproducts s WHERE p.ecmstockdocin_id = i.id and s.id=p.ecmproduct_id";
//die(1);
if (isset($where) && is_array($where) && count($where) > 0) {
$wherereturn = array();
/* if(!array_key_exists('stocks',$where)){
$wherereturn[] = "i.stock_id IN ('" . implode("','",$value) . "')";
}*/
foreach ($where as $key => $value) {
//print_r($key);print_r('<br><br>');
//print_r($value);print_r('<br><br>');
switch ($key) {
case 'register_date_from':
$wherereturn[] = "i.register_date>='" . $value . "'";
break;
case 'register_date_to':
$wherereturn[] = "i.register_date<='" . $value . "'";
break;
case 'accountName':
$wherereturn[] = "i.parent_name LIKE '%" . trim($value) . "%'";
$wherereturn[] = "i.parent_type ='Accounts'";
break;
case 'product_group':
$wherereturn[] = "s.ks_group IN ('" . implode("','",$value) . "')";
break;
case 'product_group_2':
$wherereturn[] = "s.ks_group2 IN ('" . implode("','",$value) . "')";
break;
case 'productId':
$wherereturn[] = "p.ecmproduct_id = '" . trim($value) . "'";
break;
case 'accountId':
$wherereturn[] = "i.parent_id = '" . trim($value) . "'";
break;
case 'stocks':
$wherereturn[] = "i.stock_id IN ('" . implode("','",$value) . "')";
break;
default:
$wherereturn[] = "i." . $key . " = '" . $value . "'";
break;
}
}
if (count($wherereturn) > 0) {
$query .= " AND " . implode(" AND ", $wherereturn);
}
}
$query .= " ORDER BY i.register_date";
//echo $query;
//print_r($query);
$result = $db->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
//print_r($row);
$currency = 1;
if($row['type']!='K'){
if($row['currency_value']!=''&& $row['currency_value']!='0'){
$currency = $row['currency_value'];
}elseif($row['currency_value_nbp']!=''){
$currency = $row['currency_value_nbp'];
}
}
if($row['type']==''){
$return[substr($row['register_date'], 0, 7)]['total_netto'] += round($row['price']* $row['quantity'],2);
$return[substr($row['register_date'], 0, 7)]['quantity'] += $row['quantity'];
}else{
$return[substr($row['register_date'], 0, 7)]['total_purchase'] += round($row['price_purchase'] * $row['quantity_corrected'] ,2);
$return[substr($row['register_date'], 0, 7)]['total_netto'] += $row['total_netto_corrected']* $currency;
}
}
} else {
$return = NULL;
}
if(count($return)<12){
try {
$currentDate = new DateTime(date('Y-m-01'));
$date = new DateTime(date('Y-m-01'));
$date->sub(new DateInterval('P1Y'));
$register_date_fill = $date->format('Y-m');
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
while(count($return)<12){
if(!isset($return[$register_date_fill])){
$return[$register_date_fill]['total_purchase'] = 0;
$return[$register_date_fill]['total_netto'] = 0;
}
$date->add(new DateInterval('P1M'));
$register_date_fill = $date->format('Y-m');
}
}
ksort($return);
$formated_return;
foreach ($return as $data => $row){
$split = split("-",$data);
$formated_return[$split[1] .".".$split[0]] = $row;
}
return $formated_return;
}
function getProductCategoryList() {
global $db;
$resultArray = NULL;
$query = "SELECT id, name FROM ecmproductcategories WHERE deleted=0 ORDER BY name, date_entered";
$result = $db->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultArray[$row['id']] = $row['name'];
};
}
return $resultArray;
}
?>

View File

@@ -0,0 +1,243 @@
<?php
require_once ('modules/EcmInvoiceOuts/EcmInvoiceOut.php');
global $mod_strings, $app_list_strings;
$db = $GLOBALS['db'];
$productCategoryList = getProductCategoryList();
$accountName = $_REQUEST["accountName"];
$accountId = $_REQUEST["accountId"];
$productName = $_REQUEST["productName"];
$productId = $_REQUEST["productId"];
if (isset($productId) && $productId != '') {
$where['productId'] = $productId;
} else if (!isset($productId) && isset($productName) && strlen($productName) > 0) {
$where['productName'] = $productName;
}
if (isset($accountId) && $accountId!='') {
$where['accountId'] = $accountId;
} else if (!isset($accountId) && isset($accountName) && strlen($accountName) > 0) {
$where['accountName'] = $accountName;
}
try {
$tmp = new DateTime(date('Y-m-31'));
$tmp2 = new DateTime(date('Y-m-01'));
$tmp2->sub(new DateInterval('P1Y'));
$where['register_date_to'] = $tmp->format('Y-m-d');
$where['register_date_from'] = $tmp2->format('Y-m-d');
// $where['register_date_to'] = '2015-07-31';
// $where['register_date_from'] = '2015-07-01';
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
$relationsQuery = " FROM `ecminvoiceouts`
INNER JOIN `accounts` ON
(accounts.id = ecminvoiceouts.parent_id)
INNER JOIN `ecminvoiceoutitems` ON
(ecminvoiceoutitems.ecminvoiceout_id = ecminvoiceouts.id)
INNER JOIN `ecmproducts` ON
(ecmproducts.id = ecminvoiceoutitems.ecmproduct_id)
" /*. $relationsQueryReceipts*/ . "
";
$stock_array = array(""=>"");
$stock_request = $db->query("SELECT id, name FROM ecmstocks WHERE deleted=0");
while($row = $db->fetchByAssoc($stock_request)){ $stock_array[$row['id']] = $row['name']; }
$group_ks_without_filter = [];
$group_ks_result_without_filter = $db->query("SELECT DISTINCT `ks_group` " . $relationsQuery . " ORDER BY `ks_group`");
while($row = $db->fetchByAssoc($group_ks_result_without_filter)) { $group_ks_without_filter[$row['ks_group']] = $app_list_strings['ecmproducts_group_ks_dom'][ $row['ks_group'] ]; }
$group_ks_without_filter_2 = [];
$group_ks_result_without_filter_2 = $db->query("SELECT DISTINCT `ks_group2` " . $relationsQuery . " ORDER BY `ks_group2`");
while($row = $db->fetchByAssoc($group_ks_result_without_filter_2)) {
if($app_list_strings['ecmproducts_group2_ks_dom'][ $row['ks_group2']]!=NULL){
$group_ks_without_filter_2[$row['ks_group2']] = $app_list_strings['ecmproducts_group2_ks_dom'][ $row['ks_group2'] ];
}
}
//$where['type'] = 'correct';
//$where['type'] = 'normal';
if(isset($_REQUEST['product_group_2']) && !empty($_REQUEST['product_group_2'])){
$where['product_group_2']=$_REQUEST['product_group_2'];
}
if(isset($_REQUEST['product_group']) && !empty($_REQUEST['product_group'])){
$where['product_group']=$_REQUEST['product_group'];
}
if(isset($_REQUEST['stocks']) && !empty($_REQUEST['stocks'])){
$where['stocks']=$_REQUEST['stocks'];
}
$where['deleted'] = 0;
$where['canceled'] = 0;
if($_REQUEST['submit']){
$data = AnalysisProductSale($where);
$rows = array();
foreach ($data as $key => $value) {
$rows['netto'][] = $value['total_netto'];
// $rows['total_brutto'][] = $value['total_brutto'];
$rows['kupno'][] = $value['total_purchase'];
$rows['marza'][] = $value['total_netto'] - $value['total_purchase'];
$rows['ilosc'][]= $value['quantity'];
$rows['srednia'][]=$value['total_netto']/$value['quantity'];
$rows['marzaprocent'][] = (($value['total_netto'] - $value['total_purchase']) * 100) / $value['total_netto'];
}
}
$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("DATA", $data);
$smarty->assign("ROWS", $rows);
$smarty->assign("stock_array", $stock_array);
$smarty->assign("product_group", $group_ks_without_filter);
$smarty->assign("product_group_2", $group_ks_without_filter_2);
$smarty->assign("productCategoryList", $productCategoryList);
$smarty->assign("productCategorySelected", $productCategorySelected);
$smarty->assign("accountName", $accountName);
$smarty->assign("accountId", $accountId);
$smarty->assign("productName", $productName);
$smarty->assign("productId", $productId);
if ($_GET ['to_pdf'] == '1') {
$output = $smarty->fetch('modules/EcmReports/tpls/PDF/AnalysisProductSale.tpl');
include_once ("include/MPDF57/mpdf.php");
$p = new mPDF('', 'A4', NULL, 'helvetica', 10, 10, 10, 10, 5, 5);
$p->writeHTML($output);
$p->Output('RaportSprzedazy.pdf', 'I');
} else {
echo $smarty->display('modules/EcmReports/tpls/AnalysisProductSale.tpl');
}
function AnalysisProductSale($where) {
global $db;
$query = "SELECT p.quantity_corrected, p.total_brutto_corrected,i.stock_id, p.total_netto_corrected ,p.ecminvoiceout_id, p.ecmproduct_id, p.code, p.name, p.total_netto, p.total_brutto, p.price_purchase, p.quantity , i.register_date, i.type, i.currency_value, i.currency_value_nbp, i.currency_id FROM ecminvoiceoutitems p, ecminvoiceouts i,ecmproducts s WHERE p.ecminvoiceout_id = i.id and s.id=p.ecmproduct_id";
//die(1);
if (isset($where) && is_array($where) && count($where) > 0) {
$wherereturn = array();
foreach ($where as $key => $value) {
//print_r($key);print_r('<br><br>');
//print_r($value);print_r('<br><br>');
switch ($key) {
case 'register_date_from':
$wherereturn[] = "i.register_date>='" . $value . "'";
break;
case 'register_date_to':
$wherereturn[] = "i.register_date<='" . $value . "'";
break;
case 'accountName':
$wherereturn[] = "i.parent_name LIKE '%" . trim($value) . "%'";
$wherereturn[] = "i.parent_type ='Accounts'";
break;
case 'product_group':
$wherereturn[] = "s.ks_group IN ('" . implode("','",$value) . "')";
break;
case 'product_group_2':
$wherereturn[] = "s.ks_group2 IN ('" . implode("','",$value) . "')";
break;
case 'productId':
$wherereturn[] = "p.ecmproduct_id = '" . trim($value) . "'";
break;
case 'accountId':
$wherereturn[] = "i.parent_id = '" . trim($value) . "'";
break;
case 'stocks':
$wherereturn[] = "i.stock_id IN ('" . implode("','",$value) . "')";
break;
default:
$wherereturn[] = "i." . $key . " = '" . $value . "'";
break;
}
}
if (count($wherereturn) > 0) {
$query .= " AND " . implode(" AND ", $wherereturn);
}
}
$query .= " ORDER BY i.register_date";
//echo $query;
//print_r($query);
$result = $db->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$currency = 1;
if($row['type']!='K'){
if($row['currency_value']!=''&& $row['currency_value']!='0'){
$currency = $row['currency_value'];
}elseif($row['currency_value_nbp']!=''){
$currency = $row['currency_value_nbp'];
}
}
if($row['type']=='normal'){
$return[substr($row['register_date'], 0, 7)]['total_purchase'] += round($row['price_purchase']* $row['quantity'],2);
$return[substr($row['register_date'], 0, 7)]['total_netto'] += $row['total_netto']* $currency;
$return[substr($row['register_date'], 0, 7)]['quantity'] += $row['quantity'];
}else{
$return[substr($row['register_date'], 0, 7)]['total_purchase'] += round($row['price_purchase'] * $row['quantity_corrected'] ,2);
$return[substr($row['register_date'], 0, 7)]['total_netto'] += $row['total_netto_corrected']* $currency;
$return[substr($row['register_date'], 0, 7)]['quantity'] += $row['quantity_corrected'];
}
}
} else {
$return = NULL;
}
if(count($return)<12){
try {
$currentDate = new DateTime(date('Y-m-01'));
$date = new DateTime(date('Y-m-01'));
$date->sub(new DateInterval('P1Y'));
$register_date_fill = $date->format('Y-m');
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
while(count($return)<12){
if(!isset($return[$register_date_fill])){
$return[$register_date_fill]['total_purchase'] = 0;
$return[$register_date_fill]['total_netto'] = 0;
}
$date->add(new DateInterval('P1M'));
$register_date_fill = $date->format('Y-m');
}
}
ksort($return);
$formated_return;
foreach ($return as $data => $row){
$split = split("-",$data);
$formated_return[$split[1] .".".$split[0]] = $row;
}
return $formated_return;
}
function getProductCategoryList() {
global $db;
$resultArray = NULL;
$query = "SELECT id, name FROM ecmproductcategories WHERE deleted=0 ORDER BY name, date_entered";
$result = $db->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultArray[$row['id']] = $row['name'];
};
}
return $resultArray;
}
?>

View File

@@ -0,0 +1,36 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
global $sugar_version, $sugar_config, $current_user, $app_strings, $mod_strings, $current_user, $app_list_strings;
require_once('modules/EcmReports/EcmReport.php');
require_once('modules/EcmReports/Forms.php');
require_once ('include/time.php');
require_once('include/json_config.php');
$json_config = new json_config();
$focus = new EcmReport();
if(isset($_REQUEST['record']))$focus->retrieve($_REQUEST['record']);
require_once('include/MVC/View/SugarView.php');
if(file_exists('modules/EcmReports/views/view.detail.php')) {
require_once('modules/EcmReports/views/view.detail.php');
$detail = new EcmReport();
}
else{
require_once('include/MVC/View/views/view.detail.php');
$detail = new ViewDetail();
$detail->ss = new Sugar_Smarty();
$detail->module = 'EcmReports';
}
global $app_list_strings;
$detail->bean = $focus;
$detail->preDisplay();
echo $detail->display();
?>

161
modules/EcmReports/EcmReport.php Executable file
View File

@@ -0,0 +1,161 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*********************************************************************************
* Description: TODO: To be written.
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
* Contributor(s): ______________________________________..
********************************************************************************/
require_once('data/SugarBean.php');
require_once('include/utils.php');
class EcmReport extends SugarBean {
var $field_name_map = array();
var $id;
var $date_entered;
var $date_modified;
var $modified_user_id;
var $assigned_user_id;
var $name;
var $value;
var $module_dir = 'EcmReports';
var $table_name = "ecmreports";
var $object_name = "EcmReport";
var $new_schema = true;
var $additional_column_fields = array('assigned_user_name', 'assigned_user_id');
function EcmReport() {
parent::SugarBean();
$this->setupCustomFields('EcmReports');
foreach($this->field_defs as $field){
$this->field_name_map[$field['name']] = $field;
}
}
function get_summary_text(){
return $this->name;
}
function create_list_query($order_by, $where, $show_deleted = 0){
$custom_join = $this->custom_fields->getJOIN();
$query ="SELECT ";
$query.="ecmreports.*,users.user_name as assigned_user_name";
if($custom_join)$query.=$custom_join['select'];
$query.=" FROM ecmreports ";
$query.="LEFT JOIN users ON ecmreports.assigned_user_id=users.id";
$query.=" ";
if($custom_join)$query.=$custom_join['join'];
$where_auto='1=1';
if($show_deleted==0)$where_auto=" $this->table_name.deleted=0 ";
elseif($show_deleted==1)$where_auto=" $this->table_name.deleted=1 ";
if($where!="")$query.="where $where AND ".$where_auto;
else $query.="where ".$where_auto;
if(substr_count($order_by,'.')>0)$query .= " ORDER BY $order_by";
elseif($order_by != "")$query .= " ORDER BY $order_by";
else $query .= " ORDER BY ecmreports.name";
return $query;
}
function create_export_query($order_by,$where){
$custom_join = $this->custom_fields->getJOIN();
$query ="SELECT ";
$query.="ecmreports.*,users.user_name as assigned_user_name";
if($custom_join)$query.=$custom_join['select'];
$query.=" FROM ecmreports ";
$query.="LEFT JOIN users ON ecmreports.assigned_user_id=users.id";
$query.=" ";
if($custom_join)$query.=$custom_join['join'];
$where_auto='1=1';
if($show_deleted==0)$where_auto=" $this->table_name.deleted=0 ";
elseif($show_deleted==1)$where_auto=" $this->table_name.deleted=1 ";
if($where!="")$query.="where $where AND ".$where_auto;
else $query.="where ".$where_auto;
if(substr_count($order_by,'.')>0)$query .= " ORDER BY $order_by";
elseif($order_by != "")$query .= " ORDER BY $order_by";
else $query .= " ORDER BY ecmreports.name";
return $query;
}
function fill_in_additional_list_fields(){
}
function fill_in_additional_detail_fields(){
parent::fill_in_additional_detail_fields();
}
function get_list_view_data(){
global $current_language;
$the_array=parent::get_list_view_data();
$app_list_strings=return_app_list_strings_language($current_language);
$mod_strings=return_module_language($current_language,'EcmReports');
$the_array['NAME']=(($this->name == "") ? "<em>blank</em>" : $this->name);
$the_array['ENCODED_NAME']=$this->name;
return $the_array;
}
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,"ecmreports.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,$ecmreport)
{
global $mod_strings,$app_list_strings;
$xtpl->assign("ECMREPORT_SUBJECT",$ecmreport->name);
return $xtpl;
}
function bean_implements($interface){
switch($interface){
case 'ACL':return true;
}
return false;
}
function save($check_notify=FALSE){
return parent::save($check_notify);
}
}
?>

View File

@@ -0,0 +1,5 @@
<?php
include 'modules/EcmReports/optima/ExportOptima.php';
?>

358
modules/EcmReports/Kartoteka.php Executable file
View File

@@ -0,0 +1,358 @@
<?php
// partie
include 'EcmConfig.php';
ini_set('memory_limit','-1');
ini_set('max_execution_time','-1');
if (! defined ( 'sugarEntry' ) || ! sugarEntry)
die ( 'Not A Valid Entry Point' );
$db = $GLOBALS['db'];
global $app_list_strings;
$doc_name=array('EcmStockDocInsideIns'=>'PW','EcmStockDocMoves'=>'MM','EcmStockDocCorrects'=>'KS','EcmStockDocIns'=>'PZ','EcmStockDocOuts'=>'WZ','EcmStockDocInsideOuts'=>'RW','EcmInvoiceOuts'=>"FK",'EcmInvoiceOuts2'=>"KF");
/*
* Magazyny
*/
$datastocks = array ();
$users = array ();
$queryStocks = "SELECT
name,
id
FROM ecmstocks
where deleted= 0";
$rowsStocks = $db->query ( $queryStocks );
$s=array();
while ( $rowStocks = $db->fetchByAssoc ( $rowsStocks ) ) {
$stocks ["name"] = $rowStocks ["name"];
$stocks ["id"] = $rowStocks ["id"];
$datastocks [] = $stocks;
$s[$stocks ["id"]]['name']=$stocks ["name"];
}
if($_GET['date_from']==''){
$_GET['date_from']=date('01.m.Y');
} else {
$date_from=date('Y-m-d 00:00:01',strtotime($_GET['date_from']));
}
if( $_GET['date_to']==''){
$_GET['date_to']=date('t.m.Y');
} else {
$date_to=date('Y-m-d 23:59:59',strtotime($_GET['date_to']));
}
/*
* Dodatkowe parametry do zapytania
*/
if ($_GET ['selectStock'] != "")
$add_where .= " AND stock_id = '" . $_GET ["selectStock"] . "' ";
if ($_GET ['selectProductActive'] != ""){
$where= " WHERE product_active = '" . $_GET ["selectProductActive"] . "' ";
} else {
$where='';
}
$_GET['selectShowEmpty']=1;
$r1 = $db->query("SELECT id, name, code, unit_id FROM ecmproducts ".$where." ORDER BY name ASC");
//var_dump("SELECT id, name, code, unit_id FROM ecmproducts ".$where." ORDER BY name ASC");
$docs = array();
$i=0;
$total_quantity_old=0;
$total_value_old=0;
while ($tmp2 = $db->fetchByAssoc($r1)) {
$r = $db->query(
"SELECT * FROM ecmstockoperations WHERE product_id='" . $tmp2['id'] . "' ".$add_where." AND in_id IS NULL AND type=0 AND date_entered <='".$date_from."'");
$l = 0;
$i=$tmp2['id'];
if ($r->num_rows > 0) {
$docs[$i]['unit_id']=$app_list_strings['ecmproducts_unit_dom'][$tmp2['unit_id']];
$docs[$i]['product_id']=$tmp2['id'];
$docs[$i]['product_name']=$tmp2['name'];
$docs[$i]['product_code']=$tmp2['code'];
$docs[$i]['total_quantity_old']=0;
$docs[$i]['total_price_old']=0;
}
while ($tmp = $db->fetchByAssoc($r)) {
$ii = $db->query(
"select * from ecmstockoperations where in_id='" . $tmp['id'] .
"' and type=1 and date_entered <='".$date_from."'");
if ($ii->num_rows > 0) {
// licz ilość dla użytych
$quantity_tmp = $tmp['quantity'];
while ($tmp2 = $db->fetchByAssoc($ii)) {
$quantity_tmp -= $tmp2['quantity'];
}
if($quantity_tmp==0){
$db->query("update ecmstockoperations set used=1 where id='".$tmp['id']."'");
continue;
}
$doc['quantity'] = $quantity_tmp;
$doc['parent_name'] = $tmp['parent_name'];
$doc['part_no'] = $tmp['part_no'];
$doc['price'] = $tmp['price'];
$doc['parent_type'] = $doc_name[$tmp['parent_type']];
$doc['parent_type2'] = $tmp['parent_type'];
$doc['parent_id'] = $tmp['parent_id'];
$doc['product_id'] = $tmp2['id'];
// $doc['date_entered'] = $n->register_date;
$doc['position_value'] = $doc['quantity']*$tmp['price'];
$total_quantity_old+=$doc['quantity'];
$total_value_old+=round($doc['quantity']*$tmp['price'],2);
//$docs[$i-1]['add'][] = $doc;
$docs[$i]['total_price_old']+=($doc['quantity']*$tmp['price'] );
$docs[$i]['total_quantity_old']+=($doc['quantity']);
} else {
// dla całych
$doc['quantity'] = $tmp['quantity'];
$doc['parent_name'] = $tmp['parent_name'];
$doc['price'] = $tmp['price'];
$doc['part_no'] = $tmp['part_no'];
$doc['parent_type'] = $doc_name[$tmp['parent_type']];
$doc['parent_id'] = $tmp['parent_id'];
// $doc['date_entered'] = $n->register_date;
$doc['product_id'] = $tmp2['id'];
$doc['position_value'] = $doc['quantity']*$tmp['price'];
$total_quantity_old+=$doc['quantity'];
$total_value_old+=round($doc['quantity']*$tmp['price'],2);
// $docs[$i-1]['add'][] = $doc;
$docs[$i]['total_price_old']+=($doc['quantity']*$tmp['price'] );
$docs[$i]['total_quantity_old']+=($doc['quantity']);
}
if ($r->num_rows > 1) {
$docs[$i]['price']=$docs[$i]['total_price_old']/$docs[$i]['total_quantity_old'];
$docs[$i]['parent_name']='';
$docs[$i]['parent_type']='';
} if ($r->num_rows < 2 ){
$docs[$i]['price']=$tmp['price'];
$doc[$i]['part_no'] = $tmp['part_no'];
$docs[$i]['parent_id'] = $tmp['parent_id'];
$docs[$i]['parent_name']=$tmp['parent_name'];
// $docs[$i-1]['date_entered'] = $n->register_date;
$docs[$i]['parent_type'] = $doc_name[$tmp['parent_type']];
}else {
$docs[$i]['price']=$docs[$i]['total_price_old']/$docs[$i]['total_quantity_old'];
$docs[$i]['parent_name']='';
$docs[$i]['parent_type']='';
}
}
if( $docs[$i]['total_quantity_old']==0 && $_GET['selectShowEmpty']!='')unset($docs[$i]);
}
$r1 = $db->query("select id,name,code,unit_id from ecmproducts ".$where." order by name asc");
$i=0;
$total_quantity_now=0;
$total_value_now=0;
while ($tmp2 = $db->fetchByAssoc($r1)) {
$r = $db->query(
"select * from ecmstockoperations where
product_id='" . $tmp2['id'] . "'
".$add_where."
and in_id is null and used=0 and type=0 and date_entered <='".$date_to."'");
$i=$tmp2['id'];
$l = 0;
if ($r->num_rows > 0) {
$docs[$i]['unit_id']=$app_list_strings['ecmproducts_unit_dom'][$tmp2['unit_id']];
$docs[$i]['product_id']=$tmp2['id'];
$docs[$i]['product_name']=$tmp2['name'];
$docs[$i]['product_code']=$tmp2['code'];
$docs[$i]['total_quantity_now']=0;
$docs[$i]['total_price_now']=0;
}
while ($tmp = $db->fetchByAssoc($r)) {
$ii = $db->query(
"select * from ecmstockoperations where in_id='" . $tmp['id'] .
"' and type=1 and date_entered <='".$date_to."'");
if ($ii->num_rows > 0) {
// licz ilość dla użytych
$quantity_tmp = $tmp['quantity'];
while ($tmp2 = $db->fetchByAssoc($ii)) {
$quantity_tmp -= $tmp2['quantity'];
}
if($quantity_tmp==0){
$db->query("update ecmstockoperations set used=1 where id='".$tmp['id']."'");
continue;
}
$doc['quantity'] = $quantity_tmp;
$doc['parent_name'] = $tmp['parent_name'];
$doc['part_no'] = $tmp['part_no'];
$doc['price'] = $tmp['price'];
$doc['parent_type'] = $doc_name[$tmp['parent_type']];
$doc['parent_type2'] = $tmp['parent_type'];
$doc['parent_id'] = $tmp['parent_id'];
$doc['product_id'] = $tmp2['id'];
// $doc['date_entered'] = $n->register_date;
$doc['position_value'] = $doc['quantity']*$tmp['price'];
$total_quantity_now+=$doc['quantity'];
$total_value_now+=round($doc['quantity']*$tmp['price'],2);
//$docs[$i-1]['add'][] = $doc;
$docs[$i]['total_price_now']+=($doc['quantity']*$tmp['price'] );
$docs[$i]['total_quantity_now']+=($doc['quantity']);
} else {
// dla całych
$doc['quantity'] = $tmp['quantity'];
$doc['parent_name'] = $tmp['parent_name'];
$doc['price'] = $tmp['price'];
$doc['part_no'] = $tmp['part_no'];
$doc['parent_type'] = $doc_name[$tmp['parent_type']];
$doc['parent_id'] = $tmp['parent_id'];
// $doc['date_entered'] = $n->register_date;
$doc['product_id'] = $tmp2['id'];
$doc['position_value'] = $doc['quantity']*$tmp['price'];
$total_quantity_now+=$doc['quantity'];
$total_value_now+=round($doc['quantity']*$tmp['price'],2);
// $docs[$i-1]['add'][] = $doc;
$docs[$i]['total_price_now']+=($doc['quantity']*$tmp['price'] );
$docs[$i]['total_quantity_now']+=($doc['quantity']);
}
if ($r->num_rows > 1) {
$docs[$i]['price']=$docs[$i]['total_price_now']/$docs[$i]['total_quantity_now'];
$docs[$i]['parent_name']='';
$docs[$i]['parent_type']='';
} if ($r->num_rows < 2 ){
$docs[$i]['price']=$tmp['price'];
$doc[$i]['part_no'] = $tmp['part_no'];
$docs[$i]['parent_id'] = $tmp['parent_id'];
$docs[$i]['parent_name']=$tmp['parent_name'];
// $docs[$i-1]['date_entered'] = $n->register_date;
$docs[$i]['parent_type'] = $doc_name[$tmp['parent_type']];
}else {
$docs[$i]['price']=$docs[$i]['total_price_now']/$docs[$i]['total_quantity_now'];
$docs[$i]['parent_name']='';
$docs[$i]['parent_type']='';
}
}
if( $docs[$i]['total_quantity_now']==0 && $_GET['selectShowEmpty']!='')unset($docs[$i]);
}
$r1 = $db->query("select id,name,code,unit_id from ecmproducts ".$where." order by name asc");
$i=0;
$przychod_w=0;
$przychod_q=0;
$rozchod_q=0;
$doc=array();
$rozchod_w=0;
while ($tmp2 = $db->fetchByAssoc($r1)) {
$r = $db->query(
"select * from ecmstockoperations where
product_id='" . $tmp2['id'] . "'
".$add_where."
and in_id is null and type=0 and date_entered <='".$date_to."' and date_entered >='".$date_from."'");
$i=$tmp2['id'];
$l = 0;
if ($r->num_rows > 0) {
$docs[$i]['unit_id']=$app_list_strings['ecmproducts_unit_dom'][$tmp2['unit_id']];
$docs[$i]['product_id']=$tmp2['id'];
$docs[$i]['product_name']=$tmp2['name'];
$docs[$i]['product_code']=$tmp2['code'];
$docs[$i]['rozchod_q']=0;
$docs[$i]['rozchod_w']=0;
$docs[$i]['przychod_q']=0;
$docs[$i]['przychod_w']=0;
}
while ($tmp = $db->fetchByAssoc($r)) {
$module=substr($tmp['parent_type'], 0, -1);
$doc2 = new $module();
$doc2->retrieve($tmp['parent_id']);
$docs[$i]['przychod_w']+=($tmp['quantity']*$tmp['price'] );
$docs[$i]['przychod_q']+=($tmp['quantity']);
$przychod_w+=($tmp['quantity']*$tmp['price'] );;
$przychod_q+=($tmp['quantity']);
if($doc2->type=='correct'){
$doc[$tmp['type']]['EcmInvoiceOuts2']+=($tmp['quantity']*$tmp['price'] );
} else {
$doc[$tmp['type']][$tmp['parent_type']]+=($tmp['quantity']*$tmp['price'] );
}
}
$ii = $db->query(
"select * from ecmstockoperations where product_id='" . $tmp2['id'] .
"' and type=1 and date_entered <='".$date_to."' ".$add_where." and date_entered >='".$date_from."'");
if ($ii->num_rows > 0) {
// licz ilość dla użytych
$quantity_tmp = $tmp['quantity'];
while ($tmp2 = $db->fetchByAssoc($ii)) {
$docs[$i]['rozchod_w']+=($tmp2['quantity']*$tmp2['price'] );
$docs[$i]['rozchod_q']+=($tmp2['quantity']);
$rozchod_w+=($tmp2['quantity']*$tmp2['price'] );
$rozchod_q+=($tmp2['quantity']);
$doc[$tmp2['type']][$tmp2['parent_type']]+=($tmp2['quantity']*$tmp2['price'] );
}
}
}
// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty->assign ( "MOD", $mod_strings );
$smarty->assign ( "DATA", $doc );
$smarty->assign ( "doc_name", $doc_name );
$smarty->assign ( "date_from", $_GET['date_from'] );
$smarty->assign ( "date_to", $_GET['date_to'] );
$smarty->assign ( "TOTAL_VALUE_OLD", $total_value_old );
$smarty->assign ( "TOTAL_QUANTITY_OLD", $total_quantity_old );
$smarty->assign ( "TOTAL_VALUE_NOW", $total_value_now );
$smarty->assign ( "TOTAL_QUANTITY_NOW", $total_quantity_now );
$smarty->assign ( "rozchod_w", $rozchod_w );
$smarty->assign ( "rozchod_q", $rozchod_q );
$smarty->assign ( "przychod_w", $przychod_w );
$smarty->assign ( "przychod_q", $przychod_q );
$smarty->assign ( "CONSIGNMENTS",$EcmConfig['consignments']);
$smarty->assign ( "STOCKS", $datastocks );
$smarty->assign ( "selectStock", $_GET ["selectStock"]);
$smarty->assign ( "selectProductActive", $_GET ["selectProductActive"] );
$smarty->assign ( "selectProductEol", $_GET ["selectProductEol"] );
$smarty->assign ( "selectShowEmpty", $_GET ["selectShowEmpty"] );
// Eksport do PDF
if( $_GET['toPDF'] == '1' ) {
$output = $smarty->fetch( 'modules/EcmReports/tpls/PDF//Kartoteka.tpl' );
include_once ("include/MPDF57/mpdf.php");
unset($smarty);
$p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 25, 10, 5, 5 );
$p->setFooter('Strona {PAGENO} z {nbpg}');
$comp = new EcmSysInfo();
$p->SetHTMLHeader('<p style="text-align:left;font-size: 10px;">'.$comp->name.'<br>
Kartoteka ruchu towarów - Podsumowanie<br>Data wydruku: '.date("d.m.Y").'<br>Stan magazynowy za okres: '.$_GET['date_from'].' - '.$_GET['date_to'].'<br>Magazyn: '.$s[$_GET ["selectStock"]]['name']. '<br>Strona {PAGENO} z {nbpg}</p>');
//$p->setTitle($mod_strings["LBL_REPORT_STOCKS_DOCS"]);
//echo $output;
$p->writeHTML( $output );
$p->Output ();
} else {
$smarty->display ( 'modules/EcmReports/tpls/Kartoteka.tpl' );
}
?>

67
modules/EcmReports/Menu.php Executable file
View File

@@ -0,0 +1,67 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*********************************************************************************
* Description: TODO To be written.
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
* Contributor(s): ______________________________________..
********************************************************************************/
global $mod_strings;
/*
* !!!! Menu dla tego modułu jest sztywno wpisane w _headerModuleList.tpl szablonu
* -_- boruta jak chuj krzychu!
*/
/*if(ACLController::checkAccess('EcmReports', 'list', true))
$module_menu[]=array("index.php?module=EcmReports&action=ReportStocks&return_module=EcmReports&return_action=DetailView", "Raport stanów magazynowych","EcmReports", 'EcmReports');
if(ACLController::checkAccess('EcmReports', 'list', true))
$module_menu[]=array("index.php?module=EcmReports&action=ReportSales&return_module=EcmReports&return_action=DetailView", "Raport sprzadaży z podziałem na kategorie","EcmReports", 'EcmReports');
if(ACLController::checkAccess('EcmReports', 'list', true))
$module_menu[]=array("index.php?module=EcmReports&action=ReportSalesByContractor&return_module=EcmReports&return_action=DetailView", "Raport sprzadaży z podziałem na kontrahentów","EcmReports", 'EcmReports');
if(ACLController::checkAccess('EcmReports', 'list', true))
$module_menu[]=array("index.php?module=EcmReports&action=ListDailySales&return_module=EcmReports&return_action=DetailView", "Raport sprzadaży z podziałem na dokumenty","EcmReports", 'EcmReports');
if(ACLController::checkAccess('EcmReports', 'list', true))
$module_menu[]=array("index.php?module=EcmReports&action=ReportAcceptance&return_module=EcmReports&return_action=DetailView", "Raport akceptacji","EcmReports", 'EcmReports');
if(ACLController::checkAccess('EcmReports', 'list', true))
$module_menu[]=array("index.php?module=EcmReports&action=ReportValue&return_module=EcmReports&return_action=DetailView", "Raport wartości","EcmReports", 'EcmReports');
*/
?>

View File

@@ -0,0 +1,304 @@
<?php
function getStartValues($product_id,$stock,$date_from){
$db = $GLOBALS['db'];
$r1 = $db->query("select id,name,code,unit_id from ecmproducts where id='".$product_id."' ");
$docs = array();
$i=0;
$total_quantity_old=0;
$total_value_old=0;
while ($tmp2 = $db->fetchByAssoc($r1)) {
$r = $db->query(
"select * from ecmstockoperations where
product_id='" . $tmp2['id'] . "'
and stock_id = '" . $stock . "'
and in_id is null and type=0 and date_entered <='".$date_from."'");
$l = 0;
$i=$tmp2['id'];
if ($r->num_rows > 0) {
$docs[$i]['unit_id']=$app_list_strings['ecmproducts_unit_dom'][$tmp2['unit_id']];
$docs[$i]['unit_precision']=$app_list_strings['ecmproducts_unit_dom_precision'][$tmp2['unit_id']];
$docs[$i]['product_id']=$tmp2['id'];
$docs[$i]['product_name']=$tmp2['name'];
$docs[$i]['product_code']=$tmp2['code'];
$docs[$i]['total_quantity_old']=0;
$docs[$i]['total_price_old']=0;
}
while ($tmp = $db->fetchByAssoc($r)) {
$ii = $db->query(
"select * from ecmstockoperations where in_id='" . $tmp['id'] .
"' and type=1 and date_entered <='".$date_from."'");
if ($ii->num_rows > 0) {
// licz ilość dla użytych
$quantity_tmp = $tmp['quantity'];
while ($tmp2 = $db->fetchByAssoc($ii)) {
$quantity_tmp -= $tmp2['quantity'];
}
if($quantity_tmp==0){
$db->query("update ecmstockoperations set used=1 where id='".$tmp['id']."'");
continue;
}
$doc['quantity'] = $quantity_tmp;
$doc['parent_name'] = $tmp['parent_name'];
$doc['part_no'] = $tmp['part_no'];
$doc['price'] = $tmp['price'];
$doc['parent_type'] = $doc_name[$tmp['parent_type']];
$doc['parent_type2'] = $tmp['parent_type'];
$doc['parent_id'] = $tmp['parent_id'];
$doc['product_id'] = $tmp2['id'];
// $doc['date_entered'] = $n->register_date;
$doc['position_value'] = $doc['quantity']*$tmp['price'];
$total_quantity_old+=$doc['quantity'];
$total_value_old+=round($doc['quantity']*$tmp['price'],2);
//$docs[$i-1]['add'][] = $doc;
$docs[$i]['total_price_old']+=($doc['quantity']*$tmp['price'] );
$docs[$i]['total_quantity_old']+=($doc['quantity']);
} else {
// dla całych
$doc['quantity'] = $tmp['quantity'];
$doc['parent_name'] = $tmp['parent_name'];
$doc['price'] = $tmp['price'];
$doc['part_no'] = $tmp['part_no'];
$doc['parent_type'] = $doc_name[$tmp['parent_type']];
$doc['parent_id'] = $tmp['parent_id'];
// $doc['date_entered'] = $n->register_date;
$doc['product_id'] = $tmp2['id'];
$doc['position_value'] = $doc['quantity']*$tmp['price'];
$total_quantity_old+=$doc['quantity'];
$total_value_old+=round($doc['quantity']*$tmp['price'],2);
// $docs[$i-1]['add'][] = $doc;
$docs[$i]['total_price_old']+=($doc['quantity']*$tmp['price'] );
$docs[$i]['total_quantity_old']+=($doc['quantity']);
}
if ($r->num_rows > 1) {
$docs[$i]['price']=$docs[$i]['total_price_old']/$docs[$i]['total_quantity_old'];
$docs[$i]['parent_name']='';
$docs[$i]['parent_type']='';
} if ($r->num_rows < 2 ){
$docs[$i]['price']=$tmp['price'];
$doc[$i]['part_no'] = $tmp['part_no'];
$docs[$i]['parent_id'] = $tmp['parent_id'];
$docs[$i]['parent_name']=$tmp['parent_name'];
// $docs[$i-1]['date_entered'] = $n->register_date;
$docs[$i]['parent_type'] = $doc_name[$tmp['parent_type']];
}else {
$docs[$i]['price']=$docs[$i]['total_price_old']/$docs[$i]['total_quantity_old'];
$docs[$i]['parent_name']='';
$docs[$i]['parent_type']='';
}
}
//if( $docs[$i]['total_quantity_old']==0 && $_GET['selectShowEmpty']!='')unset($docs[$i]);
}
return array($total_quantity_old,$total_value_old);
}
function getStateAfterOperation($id,$product_id,$stock_id){
$nr=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select counter from ecmstockoperations where id='".$id."'"));
$res=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("
select
sum(CASE
WHEN (type=0)
then @t :=+quantity
else @t :=-quantity
end) as tt
,sum(CASE WHEN (type=0) then @t :=+quantity*price else @t :=-quantity*price end) as tt2
from ecmstockoperations where product_id='".$product_id."' and stock_id='".$stock_id."' and counter <= '".$nr['counter']."'"));
return $res;
}
function getOperations($product_id,$stock,$date_from,$date_to,$quantity,$val){
$db = $GLOBALS['db'];
$result=array();
$doc_name=array('EcmStockDocInsideIns'=>'PW','EcmStockDocMoves'=>'MM','EcmStockDocCorrects'=>'KS','EcmStockDocIns'=>'PZ','EcmStockDocInsideOuts'=>'RW','EcmStockDocOuts'=>'WZ','EcmInvoiceOuts'=>'FK');
$sum['in_quantity']=0;
$sum['in_value']=0;
$sum['out_quantity']=0;
$sum['out_value']=0;
$sum['after_quantity']=$quantity;
$sum['after_value']=$val;
$p= new EcmProduct();
$p->retrieve($product_id);
$product_name=$p->name;
$product_code=$p->code;
$r1 = $db->query("select id,date_entered,quantity,type,price,parent_type,parent_id from ecmstockoperations where product_id='".$product_id."' and stock_id='".$stock."' and date_entered >='".$date_from."' and date_entered <='".$date_to."' order by date_entered asc");
$lp=1;
while($dane=$db->fetchByAssoc($r1)){
$dane['lp']=$lp;
$dane['product_name']=$product_name;
$dane['product_code']=$product_code;
$dane['value']=$dane['quantity']*$dane['price'];
$module=substr($dane['parent_type'], 0, -1);
$doc = new $module();
$doc->retrieve($dane['parent_id']);
if($doc->type=='correct'){
$dane['doc_code']='KF';
} else {
$dane['doc_code']=$doc_name[$dane['parent_type']];
}
$dane['doc_name']=$doc->document_no;
$dane['doc_parent_name']=$doc->parent_name;
$after=getStateAfterOperation($dane['id'],$product_id,$stock);;
$dane['after_quantity']=$after['tt'];
$dane['after_value']=$after['tt2'];
$dane['correct']=$doc->type;
if($dane['type']==0){
if($dane['correct']=='correct'){
$sum['out_quantity']-=$dane['quantity'];
$sum['out_value']-=$dane['value'];
$sum['after_quantity']+=$dane['quantity'];
$sum['after_value']+=$dane['value'];
} else {
$sum['in_quantity']+=$dane['quantity'];
$sum['in_value']+=$dane['value'];
$sum['after_quantity']+=$dane['quantity'];
$sum['after_value']+=$dane['value'];
}
} else {
$sum['out_quantity']+=$dane['quantity'];
$sum['out_value']+=$dane['value'];
$sum['after_quantity']-=$dane['quantity'];
$sum['after_value']-=$dane['value'];
}
if($doc->type=='correct'){
$dane['quantity']=$dane['quantity']*-1;
$dane['value']=$dane['quantity']*$dane['price'];
}
$result[]=$dane;
$lp++;
}
return array($result,$sum);
}
$db = $GLOBALS['db'];
global $app_list_strings;
$datastocks = array ();
$users = array ();
$queryStocks = "SELECT
name,
id
FROM ecmstocks
where deleted= 0";
$rowsStocks = $db->query ( $queryStocks );
$s=array();
while ( $rowStocks = $db->fetchByAssoc ( $rowsStocks ) ) {
$stocks ["name"] = $rowStocks ["name"];
$stocks ["id"] = $rowStocks ["id"];
$datastocks [] = $stocks;
$s[$stocks ["id"]]['name']=$stocks ["name"];
}
if($_GET['date_from']==''){
$_GET['date_from']=date('01.m.Y');
} else {
$date_from=date('Y-m-d 00:00:01',strtotime($_GET['date_from']));
}
if($_GET['date_to']==''){
$_GET['date_to']=date('t.m.Y');
} else {
$date_to=date('Y-m-d 23:59:59',strtotime($_GET['date_to']));
}
$show_result=false;
if(isset($_REQUEST['submit']) && $_REQUEST['submit']!=''){
$show_result=true;
$p = new EcmProduct();
$p->retrieve($_GET['product_id']);
$product_indeks=$p->code;
$lists = return_app_list_strings_language('pl_pl');
$product_unit= $lists['ecmproducts_unit_dom'][$p->unit_id];
$startData=getStartValues($_GET ["product_id"],$_GET ["selectStock"],$date_from);
$start_quantity=$startData[0];
$start_value=$startData[1];
$data=getOperations($_GET ["product_id"],$_GET ["selectStock"],$date_from,$date_to,$start_quantity,$start_value);
$records=$data[0];
$sumTable=$data[1];
}
// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty->assign ( "MOD", $mod_strings );
$smarty->assign ( "DATA", $records );
$smarty->assign ( "sumTable", $sumTable );
$smarty->assign ( "SHOW_RESULT", $show_result );
$smarty->assign ( "date_from", $_GET['date_from'] );
$smarty->assign ( "date_to", $_GET['date_to'] );
$smarty->assign ( "TOTAL_VALUE_OLD", $total_value_old );
$smarty->assign ( "TOTAL_QUANTITY_OLD", $total_quantity_old );
$smarty->assign ( "TOTAL_VALUE_NOW", $total_value_now );
$smarty->assign ( "TOTAL_QUANTITY_NOW", $total_quantity_now );
$smarty->assign ( "rozchod_w", $rozchod_w );
$smarty->assign ( "rozchod_q", $rozchod_q );
$smarty->assign ( "przychod_w", $przychod_w );
$smarty->assign ( "przychod_q", $przychod_q );
$smarty->assign ("CONSIGNMENTS",$EcmConfig['consignments']);
$smarty->assign ( "STOCKS", $datastocks );
$smarty->assign ( "selectStock", $_GET ["selectStock"]);
$smarty->assign ( "selectProductActive", $_GET ["selectProductActive"] );
$smarty->assign ( "selectProductEol", $_GET ["selectProductEol"] );
$smarty->assign ( "selectShowEmpty", $_GET ["selectShowEmpty"] );
$smarty->assign ( "product_id", $_GET ["product_id"] );
$smarty->assign ( "product_name", $_GET ["product_name"] );
$smarty->assign ( "product_indeks", $product_indeks);
$smarty->assign ( "product_unit", $product_unit );
$smarty->assign ( "start_quantity", $start_quantity );
$smarty->assign ( "start_value", $start_value );
// Eksport do PDF
if( $_GET['toPDF'] == '1' ) {
$output = $smarty->fetch( 'modules/EcmReports/tpls/PDF/ProductOptionHistory.tpl' );
include_once ("include/MPDF57/mpdf.php");
unset($smarty);
$p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 25, 10, 5, 5 );
$p->setFooter('Strona {PAGENO} z {nbpg}');
$comp = new EcmSysInfo();
$p->SetHTMLHeader('<p style="text-align:left;font-size: 10px;">'.$comp->name.'<br>
Raport operacji magazynowych<br>Data wydruku: '.date("d.m.Y").'<br>Stan magazynowy za okres: '.$_GET['date_from'].' - '.$_GET['date_to'].'<br>Magazyn: '.$s[$_GET ["selectStock"]]['name']. '<br>Strona {PAGENO} z {nbpg}</p>');
//$p->setTitle($mod_strings["LBL_REPORT_STOCKS_DOCS"]);
//echo $output;
$p->writeHTML( $output );
$p->Output ();
} else {
$smarty->display ( 'modules/EcmReports/tpls/ProductOperationHistory.tpl' );
}
?>

View File

@@ -0,0 +1,118 @@
<?php
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
$db=$GLOBALS['db'];
$ss = new Sugar_Smarty ();
$lists=array();
$users=array();
$OrderByDateList=array();
$moduleLabels['accounts']='Kontrahenci';
$moduleLabels['ecmproducts']='Produkty';
$moduleLabels['ecmquotes']='Oferty';
$moduleLabels['ecmsales']='Zamówienia sprzedaży';
$moduleLabels['ecminvoiceouts']='Faktury';
$moduleLabels['ecmprepaymentinvoices']='Faktury zaliczkowe';
$moduleLabels['ecmreceipts']='Paragony';
$moduleLabels['notes']='Notatki';
$moduleLabels['tasks']='Zadania';
$moduleLabels['documents']='Dokumenty';
if($_REQUEST['date_from']=== null)$_REQUEST['date_from']=date('01.m.Y');
if($_REQUEST['date_to']===null)$_REQUEST['date_to']=date('t.m.Y');
$date_from =$_REQUEST['date_from'];
$date_to=$_REQUEST['date_to'];
$querys['accounts']="select id,created_by,date_entered,date_modified,name from accounts where date_entered >='".date('Y-m-d',strtotime($date_from))."' and date_entered <='".date('Y-m-d',strtotime($date_to))."'";
$querys['ecmproducts']="select id,created_by,date_entered,date_modified,name from ecmproducts where date_entered >='".date('Y-m-d',strtotime($date_from))."' and date_entered <='".date('Y-m-d',strtotime($date_to))."'";
$querys['ecmquotes']="select id,created_by,date_entered,date_modified,name from ecmquotes where date_entered >='".date('Y-m-d',strtotime($date_from))."' and date_entered <='".date('Y-m-d',strtotime($date_to))."'";
$querys['ecmsales']="select id,created_by,date_entered,date_modified,name from ecmsales where date_entered >='".date('Y-m-d',strtotime($date_from))."' and date_entered <='".date('Y-m-d',strtotime($date_to))."'";
$querys['ecminvoiceouts']="select id,created_by,date_entered,date_modified,name from ecminvoiceouts where date_entered >='".date('Y-m-d',strtotime($date_from))."' and date_entered <='".date('Y-m-d',strtotime($date_to))."'";
$querys['ecmprepaymentinvoices']="select id,created_by,date_entered,date_modified,name from ecmprepaymentinvoices where date_entered >='".date('Y-m-d',strtotime($date_from))."' and date_entered <='".date('Y-m-d',strtotime($date_to))."'";
$querys['ecmreceipts']="select id,created_by,date_entered,date_modified,name from ecmreceipts where date_entered >='".date('Y-m-d',strtotime($date_from))."' and date_entered <='".date('Y-m-d',strtotime($date_to))."'";
$querys['notes']="select id,created_by,date_entered,date_modified,name from notes where date_entered >='".date('Y-m-d',strtotime($date_from))."' and date_entered <='".date('Y-m-d',strtotime($date_to))."'";
$querys['tasks']="select id,created_by,date_entered,date_modified,name from tasks where date_entered >='".date('Y-m-d',strtotime($date_from))."' and date_entered <='".date('Y-m-d',strtotime($date_to))."'";
$querys['documents']="select id,created_by,date_entered,date_modified,document_number as name from documents where date_entered >='".date('Y-m-d',strtotime($date_from))."' and date_entered <='".date('Y-m-d',strtotime($date_to))."'";
$user_query='select id,first_name,last_name from users where deleted=0';
$ss->assign("date_to", $date_to);
$ss->assign("date_from", $date_from);
if($_REQUEST['process']){
$zap=$db->query($user_query);
while($dane=$db->fetchByAssoc($zap)){
if($dane['id']==1)continue;
$dane['nr']=1;
$users[$dane['id']]=$dane;
$lists[$dane['id']]=null;
foreach ($querys as $key => $val){
$lists[$dane['id']][$key] =null;
}
}
foreach ($querys as $key => $val){
$nr=1;
$res=$db->query($val);
while($dane=$db->fetchByAssoc($res)){
if($dane['created_by']==1)continue;
$dane['sort']=date('YmdHis',strtotime($dane['date_entered']));
$lists[$dane['created_by']][$key][]=$dane;
$dane['module']=$key;
$dane['nr']=$users[$dane['created_by']]['nr'];
$OrderByDateList[$dane['created_by']][]=$dane;
$users[$dane['created_by']]['nr']++;
}
}
$zap=$db->query($user_query);
while($dane=$db->fetchByAssoc($zap)){
if(count($OrderByDateList[$dane['id']])>0){
aasort($OrderByDateList[$dane['id']],"sort");
}
}
$ss->assign("lists", $lists);
$ss->assign("OrderByDateList", $OrderByDateList);
$ss->assign("users", $users);
$ss->assign("moduleLabels", $moduleLabels);
$ss->assign("colWidth", round(90/count($moduleLabels),2));
}
$content = $ss->fetch ( 'modules/EcmReports/tpls/RaportAktywnosci.tpl' );
echo $content;
?>

View File

@@ -0,0 +1,136 @@
<?php
if ($_REQUEST ['date_from'] != "") {
$date_from = $_REQUEST ['date_from'];
} else {
$date = new DateTime ();
$date->modify ( "-1 month" );
$date_from = $date->format ( "01.m.Y" );
}
if ($_REQUEST ['date_to'] != "") {
$date_to = $_REQUEST ['date_to'];
} else {
$date = new DateTime ();
$date->modify ( "-1 month" );
$date_to = $date->format ( "t.m.Y" );
}
if ($_REQUEST ['file_id'] != "") {
$file_id = $_REQUEST ['file_id'];
} else {
$file_id='';
}
$query="select file_id,file_name,user_id,file_date from orders group by file_id";
$res=$GLOBALS['db']->query($query);
$files = [];
while($dane=$GLOBALS['db']->fetchByAssoc($res)){
$user = new User();
$user->retrieve($dane['user_id']);
$dane['user_name']=$user->full_name;
$files[]=$dane;
}
if ($_REQUEST ['submit']) {
$query = "SELECT
p.name,
p.code,
o.product_id,
o.parent_id,
o.buy_quantity,
p.price_msh as sell_price,
o.sell_quantity,
o.sell_price as purchase_price
FROM
orders o
INNER JOIN
ecmproducts p ON p.id = o.product_id
WHERE
o.date >= '".date("Y-m-d 00:00:00",strtotime($date_from))."'
AND o.date <= '".date("Y-m-d 23:59:59",strtotime($date_to))."'
AND o.file_id = '".$file_id."'
GROUP BY o.id
";
/* INNER JOIN
ecminvoiceoutitems i ON i.ecmproduct_id = p.id
*/
// echo $query;
$res=$GLOBALS['db']->query($query);
$products=[];
while($row=$GLOBALS['db']->fetchByAssoc($res)){
$row['total_purchase']=$row['sell_quantity']*$row['sell_price'];
$row['total_sell']=$row['purchase_price']*$row['sell_quantity'];
$products[$row['parent_id']]['produkty'][]=$row;
if($row['sell_price']==""){
$products[$row['parent_id']]['brak_ceny_odsprzedazy']=1;
}
if($row['purchase_price']==""){
$products[$row['parent_id']]['brak_ceny_zakupu']=1;
}
$products[$row['parent_id']]['total_sell']=$row['total_sell']+$products[$row['parent_id']]['total_sell'];
}
$query = "SELECT
a.name,
o.parent_id,
SUM(p.price_msh * o.sell_quantity) AS 'total_purchase',
SUM(o.buy_quantity) AS 'purchase_quantity',
SUM(o.purchase_price * o.sell_quantity) AS 'total_sell',
SUM(o.sell_quantity) AS 'sell_quantity',
p.price_msh
FROM
orders o
INNER JOIN
accounts a ON a.id = o.parent_id
INNER JOIN
ecmproducts p ON p.id = o.product_id
WHERE
o.date >= '".date("Y-m-d 00:00:00",strtotime($date_from))."'
AND o.date <= '".date("Y-m-d 23:59:59",strtotime($date_to))."'
AND o.file_id = '".$file_id."'
GROUP BY parent_id
ORDER BY total_sell DESC";
$res=$GLOBALS['db']->query($query);
$rows=[];
$totals=[];
while($row=$GLOBALS['db']->fetchByAssoc($res)){
$row['products']=$products[$row['parent_id']]['produkty'];
$row['total_sell']=$products[$row['parent_id']]['total_sell'];
$row['brak_ceny_odsprzedazy']=$products[$row['parent_id']]['brak_ceny_odsprzedazy'];
$row['brak_ceny_zakupu']=$products[$row['parent_id']]['brak_ceny_zakupu'];
$rows[$row['parent_id']]=$row;
$totals['total_sell']+=$row['total_sell'];
$totals['sell_quantity']+=$row['sell_quantity'];
$totals['total_purchase']+=$row['total_purchase'];
$totals['purchase_quantity']+=$row['purchase_quantity'];
}
}
$smarty = new Sugar_Smarty ();
$smarty->assign ( "rows", $rows);
$smarty->assign ( 'MOD', $mod_strings );
$smarty->assign ( 'files', $files );
$smarty->assign ( 'file_id', $file_id );
$smarty->assign ( 'uploaded', $uploaded );
$smarty->assign ( 'date_from', $date_from );
$smarty->assign ( 'total',$totals) ;
$smarty->assign ( 'date_to', $date_to );
$smarty->assign ( 'dateFormat', '%d.%m.%Y' );
echo $smarty->fetch ( "modules/EcmReports/tpls/RaportMM.html" );
?>

View File

@@ -0,0 +1,25 @@
<?php
class FileHandler{
public $target_dir='upload/';
public $input_name='fileToUpload';
public $target_file;
public $orginal_file;
public $file_id;
public $file_date;
public function __construct(){
$this->file_id=create_guid();
$this->target_file=$this->target_dir.basename($this->file_id.'.xls');
$this->orginal_file=$_FILES[$this->input_name]["name"];
}
public function uploadFile(){
if (move_uploaded_file($_FILES[$this->input_name]["tmp_name"], $this->target_file)) {
$this->file_date= date ("Y-m-d H:i:s", filemtime($this->target_file));
return true;
} else {
return false;
}
}
}
?>

View File

@@ -0,0 +1,60 @@
<?php
class Order{
public $id;
public $product_id;
public $parent_id;
public $purchase_price;
public $sell_price;
public $sell_quantity;
public $buy_quantity;
public $date;
public $file_id;
public $file_name;
public $file_date;
public $user_id;
public function __construct(){
global $current_user;
$this->id = create_guid();
$this->user_id=$current_user->id;
}
public function setProductId($string){
$product_name = explode(" ",$string);
$product = new EcmProduct();
$product->retrieve_by_string_fields(['code'=>$product_name[1]]);
$this->product_id=$product->id;
$this->purchase_price=$product->price_msh;
}
public function getPrice(){
$query="select c.price_brutto from ecminvoiceoutitems c
inner join ecminvoiceouts i on i.id=c.ecminvoiceout_id
inner join accounts a on a.id= i.parent_id
where c.ecmproduct_id='".$this->product_id."' and a.parent_id=1249 and i.deleted=0 and i.canceled=0 order by i.date_entered desc limit 1";
$res=$GLOBALS['db']->query($query);
$files = [];
$dane=$GLOBALS['db']->fetchByAssoc($res);
$this->sell_price=$dane['price_brutto'];
}
public function setParentId($string){
$parent = explode(" ",$string);
$account = new Account();
$account->retrieve_by_string_fields(['shop_number'=>substr($parent[0],0,4)]);
$this->parent_id=$account->id;
}
}
?>

View File

@@ -0,0 +1,105 @@
<?php
class ProductFactory{
public $rows;
public $purchase_price;
public $sell_price;
public $product_name;
public $date;
public $fileHandler;
static private $_objectCount=0;
public function __construct($rows,$date,FileHandler $fileHandler){
$this->rows=$rows;
$this->date;
$this->fileHandler=$fileHandler;
}
public function createProducts(){
foreach ($this->rows as $row){
$data =substr($row[1],0,10);
if($data=='Sprzedaz: '){
$this->date=date("Y-m-d 00:00:01",strtotime(substr($row[1],9,12)));
}
if($row[1]=='Artykul')continue;
if($row[2]=='Suma:')continue;
if($row[1]!="" && $row[2]=="" && $row[3]=="" && $row[4]==""){
continue;
}
if($row[1]!="" && $row[2]!="" && $row[3]!="" && $row[4]!=""){
$this->product_name=$row[1];
$this->purchase_price=$row[5];
$this->sell_price=$row[6];
}
$order = new Order();
$order->setProductId($this->product_name);
$order->setParentId($row[2]);
$order->sell_quantity=$row[3];
$order->buy_quantity=$row[4];
$order->getPrice();
$order->date=$this->date;
$order->file_id=$this->fileHandler->file_id;
$order->file_name=$this->fileHandler->orginal_file;
$order->file_date=$this->fileHandler->file_date;
$this->saveProduct($order);
self::$_objectCount++;
}
}
static public function getObjectCount()
{
return self::$_objectCount;
}
public function saveProduct($product){
$fields=[];
$values=[];
$types=[];
$type='s';
$types="";
foreach ($product as $key=>$value){
$fields[]= $key;
$values[]=$value;
$types.=$type;
}
$this->insert($types,'orders',$fields,$values);
}
public function SqlArrayReferenceValues(&$rawArray){
$refArray = array();
foreach($rawArray as $key => $value)
{
$refArray[$key] = &$rawArray[$key];
}
return $refArray;
}
public function insert($setType, $setTable, $setRow, $setValues) {
$change = function($values) {
return "?";
};
$row = join(",", $setRow);
$done = join(",", array_map($change, $setValues));
$insert = $GLOBALS['db']->database->prepare("INSERT INTO $setTable ($row) VALUES ($done)");
$params = $setValues;
$ww = array_merge(array($setType), $params);
call_user_func_array(array($insert, "bind_param"), $this->SqlArrayReferenceValues($ww));
$insert->execute();
$insert->close();
return $insert;
}
}
?>

View File

@@ -0,0 +1,24 @@
<?php
require_once ('include/spreadsheet-reader-master/php-excel-reader/excel_reader2.php');
require_once ('include/spreadsheet-reader-master/SpreadsheetReader.php');
class XlsReader {
public $reader;
public function __construct($file) {
$this->reader = new SpreadsheetReader ( $file );
$this->reader-> ChangeSheet(1);
}
public function getArray(){
$rows = [];
foreach ( $this->reader as $row ) {
$rows[]=$row;
}
return $rows;
}
}
?>

View File

@@ -0,0 +1,149 @@
<?php
if (! defined ( 'sugarEntry' ) || ! sugarEntry)
die ( 'Not A Valid Entry Point' );
/**
* ********************* PREPARE ********************
*/
global $app_list_strings;
setlocale(LC_MENETARY,"pl-PL");
$db = $GLOBALS ['db'];
$data = array ();
$date_from = NULL;
$date_to = NULL;
$user_id = NULL;
$doc_name = NULL;
$category_id = NULL;
$status = "";
$query = "";
$where = "";
$suma =0;
$whereraport = "";
// Pobieranie danych z formularza
if(!$_GET['first_load']){
$first_load = 0;
}else{
$first_load = $_GET['first_load'];
}
if(!$_GET['date_from']){
$date_from = NULL;
}else{
$date_from = $_GET['date_from'];
$where = $where. " d.date_entered >= STR_TO_DATE('".$date_from."','%d.%m.%Y') AND ";
}
if(!$_GET['date_to']){
$date_to = NULL;
}else{
$date_to = $_GET['date_to'];
$where = $where. " d.date_entered <= STR_TO_DATE('".$date_to."','%d.%m.%Y') AND ";
}
if(!$_GET['doc_name']){
$doc_name = NULL;
}else{
$doc_name = $_GET['doc_name'];
$where = $where. " d.document_name LIKE '%".$doc_name."%'AND ";
}
if(!$_GET['category_id']){
$category_id = NULL;
}else{
$category_id = $_GET['category_id'];
$where = $where. " d.category_id = '" . $category_id . "' AND ";
}
if($_GET['status']== NULL){
$status = NULL;
}else{
$status = $_GET['status'];
$whereraport = " du.document_id = d.id AND du.accepted = ". $status. " AND ";
$fromraport = " documents_user du, ";
}
//formatowanie daty
$Calendar_daFormat = str_replace("d","%d",str_replace("m","%m",str_replace("Y","%Y",$GLOBALS['timedate']->get_date_format())));
$currentDate = $GLOBALS['timedate']->to_display_date($date_from);
$date_from = $GLOBALS['timedate']->to_display_date($date_from);
$date_to = $GLOBALS['timedate']->to_display_date($date_to);
//Tworzenie zapytania zapytnaie do bazy
$query = "SELECT
DATE_FORMAT(DATE(d.document_date), '%d-%m-%Y') as docdate,
d.document_name as docname,
d.id as docid,
DATE_FORMAT(DATE(d.date_entered), '%d-%m-%Y') as docdateentered,
d.category_id as doccategory,
d.description as docdes,
ifnull(d.value,0) as docwartosc,
u.first_name as username,
u.last_name as userlastname
FROM
".
$fromraport . "
documents d
left join users u on u.id = d.created_by
left join accounts a on d.parent_id = a.id
WHERE
" . $where . $whereraport . " d.deleted = 0";
echo $query;
if($first_load==0){
$query ="";
$first_load =1;
}
/**
* ************* GET DATA FROM DB********************
*/
$rows = $db->query ( $query );
// prepare data for Smarty
while ( $r = $db->fetchByAssoc ( $rows ) ) {
$row = array ();
$row ['docname'] = $r ['docname'];
$row ['docdate'] = $r ['docdate'];
$row ['docid'] = $r ['docid'];
$row ['docdateentered'] = $r ['docdateentered'];
$row ['doccategory'] = $app_list_strings['document_category_dom'][$r ['doccategory']];
$row ['docdes'] = $r ['docdes'];
$row ['docwartosc'] = number_format($r ['docwartosc'], 2, ",", ".");
$row ['username'] = $r ['username'];
$row ['userlastname'] = $r ['userlastname'];
$suma +=$r ['docwartosc'];
// Wczytywanie raportów
$queryraport = "SELECT
accepted
FROM
documents_user
WHERE
document_id = '".$row['docid']."'";
$tmp = $db->query ( $queryraport );
if($tmp->num_rows == 0){
$row['docreport'] = 0;
}else{
$row['docreport'] = 1;
}
$data [] = $row;
}
/**
* ******************** SMARTY **********************
*/
// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty -> assign('MOD', $mod_strings);
$smarty -> assign('DATA', $data);
$smarty -> assign('SUMA',number_format($suma, 2, ",", "."));
$smarty -> assign('date_from', $date_from);
$smarty -> assign('date_to', $date_to );
$smarty -> assign('dateFormat', $Calendar_daFormat);
$smarty -> assign('doc_name', $doc_name);
$smarty -> assign('first_load', $first_load);
$smarty -> assign('PARENT_TYPE_LIST', $app_list_strings['parent_type_display2']);
$smarty -> assign('category', $app_list_strings['document_category_dom']);
$smarty -> assign('category_selected', $category_id);
$smarty -> assign('status', $status);
$smarty -> assign('statusy', array(
'' => '',
'0' => 'Oczekujące',
'1' => 'Zaakceptowane',
'2' => 'Odrzucone')
);
echo $smarty->display ( 'modules/EcmReports/tpls/ReportAcceptance.tpl' );
?>

View File

@@ -0,0 +1,306 @@
<?php
require_once ('include/utils.php');
$data = array();
$date_from = date("Y-M-D");
$date_to = date("Y-m-d");
$tmp3 = array();
$vat_id;
// Ustawienia daty
if (!$_GET ['date_from']) {
$date_from = date("Y-M-01");
} else {
$date_from = $_GET ['date_from'];
}
if (!$_GET ['date_to']) {
$date_to = date("Y-m-d");
} else {
$date_to = $_GET ['date_to'];
}
// formatowanie daty
$Calendar_daFormat = str_replace("d", "%d", str_replace("m", "%m", str_replace("Y", "%Y", $GLOBALS ['timedate']->get_date_format())));
$date_from = $GLOBALS ['timedate']->to_display_date($date_from);
$date_to = $GLOBALS ['timedate']->to_display_date($date_to);
$date = new DateTime ();
$current_date_formatted = $date->format('d.m.Y');
$category_list = $GLOBALS['app_list_strings'] ['document_category_dom'];
$category= array();
if (isset ( $_GET ['category'] )) {
foreach ( $_GET ['category'] as $selectedOption ) {
array_push($category, $selectedOption);
}
}
global $app_list_strings;
global $mod_strings;
$db = $GLOBALS ['db'];
$subquery = "SELECT id
FROM documents
WHERE deleted= '0'
AND document_date >= STR_TO_DATE('" . $date_from . "','%d.%m.%Y')
AND document_date <= STR_TO_DATE('" . $date_to . "','%d.%m.%Y') ";
$query = " SELECT
acc.id accid,
dcn.id document_id,
dcn.parent_id,
dcn.document_name as document_number,
dcn.document_date,
dcn.category_id,
dcn.active_date,
dcn.document_date as register_date,
dcn.currency_value,
dcn.currency_id,
acc.name,
acc.register_address_city,
acc.register_address_postalcode,
acc.register_address_street,
acc.to_vatid
FROM
documents_accounts da
LEFT JOIN
documents dcn ON da.document_id = dcn.id
LEFT JOIN
accounts acc ON da.parent_id = acc.id
WHERE
da.parent_type = 'Account'
AND da.deleted = '0' ";
$ilscZaznaczonychKategorii = count($category);
if($ilscZaznaczonychKategorii>=1){
$query.= " AND dcn.category_id IN (";
foreach ($category as $key => $val){
$query.= "'" . $val . "',";
}
$query = rtrim($query,',');
$query.=") ";
}
$query .= " AND dcn.id IN (SELECT
id
FROM
documents
WHERE
deleted = '0'
AND dcn.document_date IS NOT NULL
AND dcn.id IN (" . $subquery . "))
ORDER BY dcn.document_name";
$sumabrutto = 0;
$rows = $db->query($query);
while ($r = $db->fetchByAssoc($rows)) {
$row = array();
$queryvat = 'SELECT
id,
document_id,
vat_value,
vat_id,
netto,
vat
FROM
documents_vat where document_id = "' . $r ['document_id'] . '"
AND deleted = "0" AND netto !="0"
ORDER BY position';
$rowsv = $db->query($queryvat);
$row ['vaty'] = array();
$row ['vatsumapozycja'] = 0;
while ($rr = $db->fetchByAssoc($rowsv)) {
$tmp2 = array();
$tmp2 ['vat_value'] = $rr ['vat_value'];
$tmp2 ['vat_id'] = $rr ['vat_id'];
$tmp2 ['netto'] =($r['currency_id']!="PLN" ? $rr ['netto']* $r['currency_value'] : $rr ['netto']);
$tmp2 ['vat'] = ($r['currency_id']!="PLN" ? $rr ['vat']* $r['currency_value'] : $rr ['vat']);
$tmp2 ['sumabrutto'] += ($r['currency_id']!="PLN" ? $rr ['vat']* $r['currency_value'] : $rr ['vat'])+ ($r['currency_id']!="PLN" ? $rr ['netto']* $r['currency_value'] : $rr ['netto']);
$row ['vatsumapozycja'] += ($r['currency_id']!="PLN" ? $rr ['vat']* $r['currency_value'] : $rr ['vat']);
$row ['value'] += ($r['currency_id']!="PLN" ? $rr ['netto']* $r['currency_value'] : $rr ['netto'])+ ($r['currency_id']!="PLN" ? $rr ['vat']* $r['currency_value'] : $rr ['vat']);
$row ['vaty'] [] = $tmp2;
if (isset($tmp3 [$rr ['vat_value']])) {
$tmp3 [$rr ['vat_value']] ['sumanetto'] += ($r['currency_id']!="PLN" ? $rr ['netto']* $r['currency_value'] : $rr ['netto']);
$tmp3 [$rr ['vat_value']] ['sumavat'] += ($r['currency_id']!="PLN" ? $rr ['vat']* $r['currency_value'] : $rr ['vat']);
$sumanetto += ($r['currency_id']!="PLN" ? $rr ['netto']* $r['currency_value'] : $rr ['netto']);
$sumavat += ($r['currency_id']!="PLN" ? $rr ['vat']* $r['currency_value'] : $rr ['vat']);
// $sumabrutto += $sumanetto + $sumavat;
} else {
$tmp3 [$rr ['vat_value']] = array();
$tmp3 [$rr ['vat_value']] ['sumanetto'] = ($r['currency_id']!="PLN" ? $rr ['netto']* $r['currency_value'] : $rr ['netto']);
$tmp3 [$rr ['vat_value']] ['sumavat'] = ($r['currency_id']!="PLN" ? $rr ['vat']* $r['currency_value'] : $rr ['vat']);
$sumanetto += ($r['currency_id']!="PLN" ? $rr ['netto']* $r['currency_value'] : $rr ['netto']);
$sumavat += ($r['currency_id']!="PLN" ? $rr ['vat']* $r['currency_value'] : $rr ['vat']);
//$sumabrutto += $sumanetto + $sumavat;
}
$porownanie = ($tmp3[$rr['vat_value']]);
$tablica_z_podzielonymi_wartosciami_procentow = str_split($rr['vat_value']);
$suma_czarow=0;
foreach($tablica_z_podzielonymi_wartosciami_procentow as $key=>$t)
{ $suma_czarow += ord($t);}
$tab=(ord($tablica_z_podzielonymi_wartosciami_procentow));
}
$row ['document_id'] = $r ['document_id'];
$row ['id'] = $r ['accid'];
$row ['document_number'] = $r ['document_number'];
$row ['name'] = $r ['name'];
$row ['register_address_postalcode'] = $r ['register_address_postalcode'];
$row ['register_address_city'] = $r ['register_address_city'];
$row ['register_address_street'] = $r ['register_address_street'];
$row ['document_date'] = $r ['document_date'];
$row ['category_id'] = $r ['category_id'];
$row ['active_date'] = $r ['active_date'];
$row ['to_vatid'] = $r ['to_vatid'];
$row ['register_date'] = $r ['register_date'];
$sumabrutto=$sumabrutto+$row ['value'];
$data [] = $row;
$sumvat += $row ['vatsumapozycja'];
}
foreach ($tmp3 as $key => $value) {
if ($value ['sumavat'] == 0) {
$tmp3 [$key] ['sumavat'] = NULL;
}
}
$smarty = new Sugar_Smarty ();
$smarty->assign('MOD', $mod_strings);
$smarty->assign('date_from', $date_from);
$smarty->assign('date_to', $date_to);
$smarty->assign('dateFormat', $Calendar_daFormat);
$smarty->assign('netto', $dvnetto);
$smarty->assign('wartosc', $wartosc);
$smarty->assign('vat', $dvvat);
$smarty->assign('to_vatid', $to_vatid);
$smarty->assign('document_number', $document_number);
$smarty->assign('name', $name);
$smarty->assign('SumaNetto', $sumanetto);
$smarty->assign('SumaBrutto', $sumabrutto);
$smarty->assign('SumaVat', $sumvat);
$smarty->assign('vat', $vat);
$smarty->assign('vat_value', $tmp3);
$smarty->assign('value', $value);
$smarty->assign('category', $category_list);
$smarty->assign('category_selected', $category);
$smarty->assign('current_date_formatted', $current_date_formatted);
if ($_GET ['to_pdf'] == '1') {
$dataPart = NULL;
$dataPart = array_chunk($data, 25);
$pageVatSum = array();
$pageBruttoVat = array();
$partialVatSum = array();
$partialBruttoVat = array();
$tmpVatSum = array();
$tmpBruttoVat = array();
foreach ($tmp3 as $vatkey => $costampotrzebnego) {
$tmpVatSum [$vatkey] = array();
$tmpVatSum [$vatkey] ['netto'] = 0;
if ($costampotrzebnego['sumavat'] == null) {
$tmpVatSum [$vatkey] ['vat'] = 'null';
} else {
$tmpVatSum [$vatkey] ['vat'] = 0;
}
}
$tmpBruttoVat ['brutto'] = 0;
$tmpBruttoVat ['vat'] = 0;
foreach ($dataPart as $key => $value123) {
$pageVatSum [$key] = array();
$pageBruttoVat [$key] = array();
foreach ($tmp3 as $vatkey => $costampotrzebnego) {
$pageVatSum [$key] [$vatkey] = array();
$partialVatSum [$key] [$vatkey] = array();
$pageVatSum [$key] [$vatkey] ['netto'] = 0;
$partialVatSum [$key] [$vatkey] ['netto'] = 0;
if ($costampotrzebnego['sumavat'] == null) {
$pageVatSum [$key] [$vatkey] ['vat'] = 'null';
$partialVatSum [$key] [$vatkey] ['vat'] = 'null';
} else {
$pageVatSum [$key] [$vatkey] ['vat'] = 0;
$partialVatSum[$key] [$vatkey] ['vat'] = 0;
}
}
$pageBruttoVat [$key]['brutto'] = 0;
$pageBruttoVat [$key]['vat'] = 0;
foreach ($value123 as $key2 => $val123) {
foreach ($val123 ['vaty'] as $k => $vat123) {
$pageVatSum [$key] [$vat123 ['vat_value']] ['netto'] += $vat123 ['netto'];
$tmpVatSum [$vat123 ['vat_value']] ['netto'] += $vat123 ['netto'];
$kolejka = array_unshift ($kolejka, $vat123['netto']);
$kolejka1= array_unshift ($kolejka1, $vat123['vat']);
if ($vat123 ['vat'] != 0) {
$pageVatSum [$key] [$vat123 ['vat_value']] ['vat'] += $vat123 ['vat'];
$tmpVatSum [$vat123 ['vat_value']] ['vat'] += $vat123 ['vat'];
}
$pageBruttoVat [$key]['brutto'] += $vat123 ['netto'] + $vat123 ['vat'];
$pageBruttoVat [$key]['vat'] += $vat123 ['vat'];
$tmpBruttoVat ['brutto'] += $vat123 ['netto'] + $vat123 ['vat'];
$tmpBruttoVat ['vat'] += $vat123 ['vat'];
}
}
foreach ($tmpVatSum as $vatKey => $vatValue) {
$partialVatSum [$key] [$vatKey] ['netto'] += $vatValue ['netto'];
if ($vatValue['vat'] != 'null') {
$partialVatSum [$key] [$vatKey] ['vat'] += $vatValue ['vat'];
}
}
$partialBruttoVat [$key] ['brutto'] = $tmpBruttoVat ['brutto'];
$partialBruttoVat [$key] ['vat'] = $tmpBruttoVat ['vat'];
}
if(count($category)==0 || count($category) == count($category_list)){
$listaKategorii = 'WSZYSTKIE KATEGORIE';
}else{
$listaKategorii ='';
foreach($category as $key=>$value){
$listaKategorii .= $category_list[$value] . ', ';
}
$listaKategorii = rtrim(trim($listaKategorii),',');
}
$smarty->assign('listaKategorii', $listaKategorii);
$smarty->assign('pageBruttoVat', $pageBruttoVat);
$smarty->assign('pageVatSum', $pageVatSum);
$smarty->assign('partialBruttoVat', $partialBruttoVat);
$smarty->assign('partialVatSum', $partialVatSum);
$smarty->assign('dataPart', $dataPart);
$smarty -> assign('category_id', $app_list_strings['document_category_dom']);
$EcmSysInfo = new EcmSysInfo();
$smarty->assign("EcmSysInfo", $EcmSysInfo);
$smarty->assign('company_name',$EcmSysInfo);
$output = $smarty->fetch ( 'modules/EcmReports/tpls/PDF/ReportBuyesByVat.tpl' );
include_once ("include/MPDF57/mpdf.php");
$p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 35, 10, 5, 5 );
$p->setTitle ( $mod_strings ["LBL_REPORT_RECEIVE_REGISTER"] );
$p->setFooter ( '{PAGENO}' );
$p->writeHTML ( $output );
$p->Output ( 'RaportRejestrPrzyjecia.pdf', 'I' );
} else {
$smarty->assign('data', $data);
echo $smarty->display('modules/EcmReports/tpls/ReportBuyesByVat.tpl');
}
?>

View File

@@ -0,0 +1,661 @@
<?php
if (! defined('sugarEntry') || ! sugarEntry)
die('Not A Valid Entry Point');
/*****************************************************/
/*********************** PREPARE *********************/
/*****************************************************/
$db = $GLOBALS['db'];
global $app_list_strings;
$all_groups_ks = $app_list_strings["ecmproducts_group_ks_dom"];
if ($_GET['selectUser'] != "") {
$selectUser = $_GET['selectUser'];
} else {
$selectUser = "";
}
if ($_GET['selectPdfType'] != "") {
$selectPdfType = $_GET['selectPdfType'];
} else {
$selectPdfType = "";
}
$data = array();
$categoryArray = array();
$sum = array();
$sumSub = array();
$sumSub2 = array();
$searchBy = $_GET['groupByProducentsOrProducts'];
if (!$_GET['date_from'])
$date_from = date("Y-m-01");
else
$date_from = $_GET["date_from"];
if (!$_GET['date_to'])
$date_to = date("Y-m-d");
else
$date_to = $_GET["date_to"];
$contractorName = $_GET['account_name'];
$contractorId = $_GET['account_id'];
$searchByType = $_GET['type'];
$group_ks = $_GET["group_ks"];
if ($group_ks == '')
$group_ks = "%";
$date_from_to_query = new DateTime($date_from);
$date_to_to_query = new DateTime($date_to);
$datausers = array();
$users = array();
$queryUsers = "SELECT
first_name as 'first',
last_name as 'last',
id
FROM users
where deleted= 0
and status = 'Active';";
$rowsUsers = $db->query($queryUsers);
while ($rowUser = $db->fetchByAssoc($rowsUsers)) {
$users["first"] = $rowUser["first"];
$users["last"] = $rowUser["last"];
$users["id"] = $rowUser["id"];
$datausers[] = $users;
}
if ($searchBy == "contractor") {
$groupBy = "name";
} else {
$groupBy = "id";
}
if ($searchBy == "product") {
$query = "SELECT
pozycja.name,
pozycja.ecmproduct_id as 'id',
faktura.parent_id as 'parent_id',
produkt.code as 'code',
faktura.type as 'type',
sum(
CASE WHEN faktura.type!='correct'
THEN
CASE WHEN faktura.currency_value_nbp is null or faktura.currency_value_nbp='' or faktura.currency_value_nbp=0
THEN
pozycja.total_netto
ELSE
pozycja.total_netto*faktura.currency_value_nbp
END
ELSE
CASE WHEN pozycja.old_ecminvoiceoutitem_id IS null OR pozycja.old_ecminvoiceoutitem_id='' THEN
0
ELSE
CASE WHEN faktura.currency_value_nbp is null or faktura.currency_value_nbp='' or faktura.currency_value_nbp=0
THEN
pozycja.total_netto-pozycja.old_total_netto
ELSE
(pozycja.total_netto-pozycja.old_total_netto)*faktura.currency_value_nbp
END
END
END
) as netto,
sum(
CASE WHEN faktura.type!='correct'
THEN
pozycja.quantity
ELSE
pozycja.quantity_corrected
END
) as ilosc,";
if ($reportSales === 1) {
$query .= " sum( CASE WHEN faktura.type!='correct'
THEN
produkt.cena_produkcyjna*pozycja.quantity
ELSE
produkt.cena_produkcyjna*pozycja.quantity_corrected
END
) as koszt";
} else {
$query .= "
sum(
CASE WHEN faktura.type!='correct'
THEN
pozycja.price_purchase*pozycja.quantity
ELSE
pozycja.price_purchase*pozycja.quantity_corrected
END
) as koszt";
}
$query .= " FROM
ecminvoiceoutitems pozycja
JOIN
ecminvoiceouts faktura ON pozycja.ecminvoiceout_id = faktura.id
LEFT JOIN
ecmproducts produkt ON pozycja.ecmproduct_id = produkt.id
WHERE
faktura.register_date BETWEEN
'" . $date_from_to_query->format('Y-m-d') . "' AND
'" . $date_to_to_query->format('Y-m-d') . "'
and faktura.type like '" . $searchByType . "'
and faktura.canceled = 0
and faktura.deleted= 0";
if ($selectPdfType != "")
$query .= " and faktura.pdf_type='$selectPdfType'";
$query .= " and pozycja.deleted= 0 ";
if ($group_ks != '%') {
$query .= "AND produkt.group_ks LIKE '$group_ks'";
}
$query .= "GROUP BY pozycja.id
COLLATE utf8_polish_ci;";
} else if ($searchBy == "contractor") {
$query = "SELECT
faktura.parent_name as 'name',
faktura.parent_id as 'parent_id',
pozycja.name as 'product_name',
pozycja.ecmproduct_id as 'id',
faktura.type as 'type',
acco.parent_id as 'parent2',
faktura.parent_name as 'parent',
sum(
CASE WHEN faktura.type!='correct'
THEN
CASE WHEN faktura.currency_value_nbp is null or faktura.currency_value_nbp='' or faktura.currency_value_nbp=0
THEN
pozycja.total_netto
ELSE
pozycja.total_netto*faktura.currency_value_nbp
END
ELSE
CASE WHEN faktura.currency_value_nbp is null or faktura.currency_value_nbp='' or faktura.currency_value_nbp=0
THEN
pozycja.total_netto_corrected
ELSE
pozycja.total_netto_corrected * faktura.currency_value_nbp
END
END
) as netto,
sum(
CASE WHEN faktura.type!='correct'
THEN
pozycja.quantity
ELSE
pozycja.quantity_corrected
END
) as ilosc,";
if ($reportSales === 1) {
$query .= " sum( CASE WHEN faktura.type!='correct'
THEN
produkt.cena_produkcyjna*pozycja.quantity
ELSE
0
END
) as koszt";
} else {
$query .= "
sum(
CASE WHEN faktura.type!='correct'
THEN
pozycja.price_purchase*pozycja.quantity
ELSE
0
END
) as koszt";
}
$query .= " FROM
ecminvoiceoutitems pozycja
JOIN
ecminvoiceouts faktura ON pozycja.ecminvoiceout_id = faktura.id
LEFT JOIN
ecmproducts produkt ON pozycja.ecmproduct_id = produkt.id
JOIN
accounts acco ON acco.id = faktura.parent_id
WHERE
faktura.register_date BETWEEN
'" . $date_from_to_query->format('Y-m-d') . "' AND
'" . $date_to_to_query->format('Y-m-d') . "'
and faktura.type like '" . $searchByType . "'
and faktura.canceled = 0
and faktura.deleted= 0";
if ($selectPdfType != "")
$query .= " and faktura.pdf_type='$selectPdfType'";
$query .= " and pozycja.deleted= 0
and produkt.group_ks LIKE '$group_ks'";
$query .= "GROUP BY pozycja.id
COLLATE utf8_polish_ci;";
}
//echo $query;
/*****************************************************/
/*************** GET DATA FROM DB*********************/
/*****************************************************/
$rows = $db->query($query);
// prepare data for Smarty
while ($r = $db->fetchByAssoc($rows)) {
$row = prepareRow($r, $selectUser, $searchBy);
if ($row != null) {
$data[] = $row;
}
}
if (1 == 1) {
// E-Commerce data
$ecommercerows = getEcommerceData($date_from_to_query, $date_to_to_query, 'allegro', $searchByType, $searchBy);
foreach ($ecommercerows as $r) {
$row = prepareRow($r, $selectUser, $group_media_saturn_holding);
if ($row) {
$data[] = $row;
}
}
$ecommercerows = getEcommerceData($date_from_to_query, $date_to_to_query, 'shop', $searchByType, $searchBy);
foreach ($ecommercerows as $r) {
$row = prepareRow($r, $selectUser, $group_media_saturn_holding);
if ($row) {
$data[] = $row;
}
}
}
if ($searchBy != "") {
////////////////// SUM /////////////////////////////////
foreach ($data as $key => &$element) {
if ($element["netto"] != 0) {
$categoryArray[$element["kategoria"] == "" ? "Inne" : $element["kategoria"]][$element["podkategoria"] == "" ? "Reszta" : $element["podkategoria"]][$key] = $element;
} else {
//echo "Nie przechodzi: <br>";
//print_r( $element );
}
}
foreach ($categoryArray as $key => &$element) {
foreach ($element as $keyy => &$elementt) {
foreach ($elementt as $keyyy => &$elementtt) {
$sumSub["IloscSum"][$key] += $elementtt["ilosc"];
$sumSub["SoldSum"][$key] += $elementtt["netto"];
//if($elementtt["type"]=="normal")
//{
$sumSub["SoldSumNormal"][$key] += $elementtt["netto"];
$sumSub["IloscNormal"][$key] += $elementtt["ilosc"];
//}else{
// $sumSub["SoldSumNormal"][$key] += 0;
//$sumSub["IloscNormal"][$key] += 0;
// }
$sumSub["KosztSum"][$key] += $elementtt["koszt"];
$sumSub2["IloscSum"][$key][$keyy] += $elementtt["ilosc"];
$sumSub2["SoldSum"][$key][$keyy] += $elementtt["netto"];
//if($elementtt["type"]=="normal")
//{
$sumSub2["SoldSumNormal"][$key][$keyy] += $elementtt["netto"];
$sumSub2["IloscNormal"][$key][$keyy] += $elementtt["ilosc"];
//}else{
// $sumSub2["SoldSumNormal"][$key][$keyy] += 0;
// $sumSub2["IloscNormal"][$key][$keyy] += 0;
//}
$sumSub2["KosztSum"][$key][$keyy] += $elementtt["koszt"];
}
$categoryArray[$key][$keyy]["IloscSum2"] = $sumSub2["IloscSum"][$key][$keyy];
$categoryArray[$key][$keyy]["SoldSum2"] = $sumSub2["SoldSum"][$key][$keyy];
$categoryArray[$key][$keyy]["SoldSumNormal2"] = $sumSub2["SoldSumNormal"][$key][$keyy];
$categoryArray[$key][$keyy]["IloscNormal2"] = $sumSub2["IloscNormal"][$key][$keyy];
$categoryArray[$key][$keyy]["KosztSum2"] = $sumSub2["KosztSum"][$key][$keyy];
}
$categoryArray[$key]["IloscSum"] = $sumSub["IloscSum"][$key];
$categoryArray[$key]["SoldSum"] = $sumSub["SoldSum"][$key];
$categoryArray[$key]["SoldSumNormal"] = $sumSub["SoldSumNormal"][$key];
$categoryArray[$key]["IloscNormal"] = $sumSub["IloscNormal"][$key];
$categoryArray[$key]["KosztSum"] = $sumSub["KosztSum"][$key];
}
foreach ($categoryArray as $key => &$element) {
$sum["IloscSumSum"] += $sumSub["IloscSum"][$key];
$sum["SoldSumSum"] += $sumSub["SoldSum"][$key];
$sum["SoldSumSumNormal"] += $sumSub["SoldSumNormal"][$key];
$sum["IloscNormal"] += $sumSub["IloscNormal"][$key];
$sum["KosztSumSum"] += $sumSub["KosztSum"][$key];
}
$sum["SredniaSumSum"] = $sum["SoldSumSumNormal"] / $sum["IloscNormal"];
$sum["MarzaSumSum"] = ($sum["SoldSumSumNormal"] - $sum["KosztSumSum"]) / $sum["SoldSumSumNormal"] * 100;
function cmp($a, $b)
{
if ($a['name'] == $b['name']) {
return 0;
}
return ($a['name'] < $b['name']) ? -1 : 1;
}
function cmp2($a, $b)
{
if ($a['id'] == $b['id']) {
return 0;
}
return ($a['id'] < $b['id']) ? -1 : 1;
}
// grupowanie po kontrahentach
foreach ($categoryArray as $key1 => &$element1) {
foreach ($element1 as $key2 => &$element2) {
$tmp2[$key1][$key2]["IloscSum2"] = $categoryArray[$key1][$key2]["IloscSum2"];
$tmp2[$key1][$key2]["SoldSum2"] = $categoryArray[$key1][$key2]["SoldSum2"];
$tmp2[$key1][$key2]["SoldSumNormal2"] = $categoryArray[$key1][$key2]["SoldSumNormal2"];
$tmp2[$key1][$key2]["IloscNormal2"] = $categoryArray[$key1][$key2]["IloscNormal2"];
$tmp2[$key1][$key2]["KosztSum2"] = $categoryArray[$key1][$key2]["KosztSum2"];
if ($searchBy == "contractor") {
usort($element2, "cmp");
} else {
usort($element2, "cmp2");
}
$i = 0;
$tmp2[$key1][$key2][0] = array('name' => null);
foreach ($element2 as $count => &$element3) {
if ($element3[$groupBy] != $tmp2[$key1][$key2][$i][$groupBy]) {
if ($tmp2[$key1][$key2][$i][$groupBy] != null) {
$i++;
}
$tmp2[$key1][$key2][$i]["id"] = $element3["id"];
$tmp2[$key1][$key2][$i]["name"] = $element3["name"];
$tmp2[$key1][$key2][$i]["code"] = $element3["code"];
$tmp2[$key1][$key2][$i]["parent_id"] = $element3["parent_id"];
}
//if($element3["type"]=="normal")
//{
$tmp2[$key1][$key2][$i]["nettoNormal"] += $element3["netto"];
$tmp2[$key1][$key2][$i]["IloscNormal"] += $element3["ilosc"];
//}
$tmp2[$key1][$key2][$i]["ilosc"] += $element3["ilosc"];
$tmp2[$key1][$key2][$i]["netto"] += $element3["netto"];
$tmp2[$key1][$key2][$i]["koszt"] += $element3["koszt"];
}
$tmp2[$key1]["IloscSum"] = $categoryArray[$key1]["IloscSum"];
$tmp2[$key1]["SoldSum"] = $categoryArray[$key1]["SoldSum"];
$tmp2[$key1]["SoldSumNormal"] = $categoryArray[$key1]["SoldSumNormal"];
$tmp2[$key1]["IloscNormal"] = $categoryArray[$key1]["IloscNormal"];
$tmp2[$key1]["KosztSum"] = $categoryArray[$key1]["KosztSum"];
$sumSub2["MarzaSum"][$key1][$key2] = ($tmp2[$key1][$key2]["SoldSumNormal2"] - $tmp2[$key1][$key2]["KosztSum2"]) / $tmp2[$key1][$key2]["SoldSumNormal2"] * 100;
$sumSub2["SredniaSum"][$key1][$key2] = $tmp2[$key1][$key2]["SoldSumNormal2"] / $tmp2[$key1][$key2]["IloscNormal2"];
if ($key2 == "Reszta") {
if (is_array($sumSub2["SredniaSum"][$key1][$key2]) || $sumSub2["SredniaSum"][$key1][$key2] == '') {
$sumSub2["SredniaSum"][$key1][$key2] = 0;
}
}
$count1++;
$tmp2[$key1][$key2]["SredniaSum2"] = $sumSub2["SredniaSum"][$key1][$key2];
$tmp2[$key1][$key2]["MarzaSum2"] = $sumSub2["MarzaSum"][$key1][$key2];
}
$sumSub["MarzaSum"][$key1] = ($tmp2[$key1]["SoldSumNormal"] - $tmp2[$key1]["KosztSum"]) / $tmp2[$key1]["SoldSumNormal"] * 100;
$sumSub["SredniaSum"][$key1] = $tmp2[$key1]["SoldSumNormal"] / $tmp2[$key1]["IloscNormal"];
$tmp2[$key1]["SredniaSum"] = $sumSub["SredniaSum"][$key1];
$tmp2[$key1]["MarzaSum"] = $sumSub["MarzaSum"][$key1];
$categoryArray1 = $tmp2;
}
////////////////// SORT sumSub /////////////////////////////////
foreach ($categoryArray1 as $key1 => &$element) {
foreach ($element as $key2 => &$elements) {
foreach ($element as $key3 => &$element2) {
if ($sumSub2["SoldSum"][$key1][$key2] > $sumSub2["SoldSum"][$key1][$key3]) {
$tmp = $sumSub2["SoldSum"][$key1][$key2];
$sumSub2["SoldSum"][$key1][$key2] = $sumSub2["SoldSum"][$key1][$key3];
$sumSub2["SoldSum"][$key1][$key3] = $tmp;
}
}
}
}
foreach ($sumSub["SoldSum"] as $key1 => &$element) {
foreach ($sumSub["SoldSum"] as $key2 => &$element2) {
if ($sumSub["SoldSum"][$key1] > $sumSub["SoldSum"][$key2]) {
$tmp = $sumSub["SoldSum"][$key1];
$sumSub["SoldSum"][$key1] = $sumSub["SoldSum"][$key2];
$sumSub["SoldSum"][$key2] = $tmp;
}
}
}
////////////////// SORT array /////////////////////////////////
$newArray2;
foreach ($sumSub["SoldSum"] as $key1 => &$element1) {
foreach ($categoryArray1 as $key2 => &$element2) {
if ($sumSub["SoldSum"][$key1] == $categoryArray1[$key2]["SoldSum"]) {
$newArray2[$key2] = $categoryArray1[$key2];
}
}
}
$newArray1;
foreach ($newArray2 as $key1 => &$element1) {
foreach ($element1 as $key2 => &$element2) {
foreach ($element1 as $key3 => &$element3) {
if ($sumSub2["SoldSum"][$key1][$key2] == $newArray2[$key1][$key3]["SoldSum2"]) {
$newArray1[$key1][$key3] = $newArray2[$key1][$key3];
}
}
}
}
//wyliczanie dokładne marży i średniej dla produktów
foreach ($newArray1 as $key1 => &$element1) {
foreach ($element1 as $key2 => &$element2) {
foreach ($element2 as $key3 => &$element3) {
$newArray1[$key1][$key2][$key3]["marza"] = ($newArray1[$key1][$key2][$key3]["nettoNormal"] - $newArray1[$key1][$key2][$key3]["koszt"]) / $newArray1[$key1][$key2][$key3]["nettoNormal"] * 100;
$newArray1[$key1][$key2][$key3]["srednia"] = $newArray1[$key1][$key2][$key3]["nettoNormal"] / $newArray1[$key1][$key2][$key3]["IloscNormal"];
}
}
}
}
function prepareRow($r, $selectUser, $searchBy)
{
$db = $GLOBALS['db'];
$row = array();
$row["id"] = $r["id"];
if ($r["parent2"] == 1249)
$row["name"] = "Media Saturn Holding";
else
$row["name"] = $r["name"];
$row["code"] = $r["code"];
$row["parent_id"] = $r["parent_id"];
$row["type"] = $r["type"];
$userBool = 1;
if ($selectUser != "") {
$userBool = 0;
$querySelectUsers = "SELECT user.id,
first_name as 'first',
last_name as 'last'
FROM
accounts acc
JOIN
users user ON acc.assigned_user_id=user.id
WHERE acc.id='" . $r["parent_id"] . "';";
$rowsSelectUsers = $db->query($querySelectUsers);
while ($rowSelectUser = $db->fetchByAssoc($rowsSelectUsers)) {
if ($rowSelectUser["id"] == $selectUser) {
$userBool = 1;
} else {
$userBool = 0;
}
}
}
if ($userBool == 1) {
if ($searchBy == "contractor") {
$row["product_name"] = $r["product_name"];
} else {
$row["product_name"] = $r["name"];
}
$querySubCategory = "SELECT category.name as 'podkategoria'
FROM
ecmproductcategories_bean bean
JOIN
ecmproductcategories category ON bean.ecmproductcategory_id = category.id
WHERE bean.bean_id='" . $row["id"] . "'
and bean.position = '1'
and bean.deleted = '0'
and category.deleted = '0';";
$rowsSubCategory = $db->query($querySubCategory);
while ($rowSubCategory = $db->fetchByAssoc($rowsSubCategory)) {
$row["podkategoria"] = $rowSubCategory["podkategoria"];
}
$queryCategory = "SELECT category.name as 'kategoria'
FROM
ecmproductcategories_bean bean
JOIN
ecmproductcategories category ON bean.ecmproductcategory_id = category.id
WHERE bean.bean_id='" . $row["id"] . "'
and bean.position = '0'
and bean.deleted = '0'
and category.deleted = '0';";
$rowscategory = $db->query($queryCategory);
while ($rowcategory = $db->fetchByAssoc($rowscategory)) {
$row["kategoria"] = $rowcategory["kategoria"];
}
$row["ilosc"] = $r["ilosc"];
$row["netto"] = $r["netto"];
$row["srednia"] = $row["netto"] / $row["ilosc"];
$row["koszt"] = $r["koszt"];
//if($row["netto"]>$row["koszt"])
//{
$row["marza"] = ($row["netto"] - $row["koszt"]) / ($row["netto"]) * 100;
//}else{
//$row["marza"] = 0;
//}
return $row;
}
return null;
}
function getEcommerceData($date_from_to_query, $date_to_to_query, $type, $inv_type, $searchBy)
{
$db = $GLOBALS['db'];
$data = [];
if ($inv_type == 'correct') {
$inv_type = 'correcting';
}
if ($searchBy == 'product') {
$query = "
SELECT
ip.ecmproduct_id AS id,
p.name,
p.code,
SUM(CASE WHEN i.type ='normal'
THEN
ip.price_netto * ip.quantity
ELSE
(ip.price_netto * ip.quantity) - (ipc.price_netto * ipc.quantity)
END) AS netto,
SUM(CASE WHEN i.type ='normal'
THEN
ip.quantity
ELSE
ip.quantity - ipc.quantity
END) AS ilosc
FROM
ecommerce_invoices_products AS ip
INNER JOIN
ecmproducts AS p ON p.id = ip.ecmproduct_id
INNER JOIN
ecommerce_invoices AS i ON i.id = ip.invoice_id
LEFT JOIN
ecommerce_invoices_products AS ipc ON ipc.invoice_id = i.corrected_invoice_id AND ipc.ecmproduct_id = ip.ecmproduct_id
WHERE
i.register_date BETWEEN
'" . $date_from_to_query->format('Y-m-d') . "' AND
'" . $date_to_to_query->format('Y-m-d') . "' AND
i.origin = '$type' AND
i.type LIKE '$inv_type'
GROUP BY ip.ecmproduct_id";
} else {
if ($type == 'allegro') {
$parentName = 'Allegro';
} else {
$parentName = 'ABC-Czystosci.pl';
}
$query = "
SELECT
ip.ecmproduct_id AS id,
p.name AS product_name,
'$parentName' AS name,
p.code,
SUM(CASE WHEN i.type ='normal'
THEN
ip.price_netto * ip.quantity
ELSE
(ip.price_netto * ip.quantity) - (ipc.price_netto * ipc.quantity)
END) AS netto,
SUM(CASE WHEN i.type ='normal'
THEN
ip.quantity
ELSE
ip.quantity - ipc.quantity
END) AS ilosc
FROM
ecommerce_invoices_products AS ip
INNER JOIN
ecmproducts AS p ON p.id = ip.ecmproduct_id
INNER JOIN
ecommerce_invoices AS i ON i.id = ip.invoice_id
LEFT JOIN
ecommerce_invoices_products AS ipc ON ipc.invoice_id = i.corrected_invoice_id AND ipc.ecmproduct_id = ip.ecmproduct_id
WHERE
i.register_date BETWEEN
'" . $date_from_to_query->format('Y-m-d') . "' AND
'" . $date_to_to_query->format('Y-m-d') . "' AND
i.origin = '$type' AND
i.type LIKE '$inv_type'
GROUP BY ip.ecmproduct_id";
}
$rows = $db->query($query);
while ($r = $db->fetchByAssoc($rows)) {
if ($type == 'allegro') {
$r['parent'] = "Allegro";
$r['parent_id'] = "allegro";
$r['contructor_id'] = "allegro";
} else if ($type == 'shop') {
$r['parent'] = "ABC-Czystosci.pl";
$r['parent_id'] = "abc-czystosci.pl";
$r['contructor_id'] = "abc-czystosci.pl";
}
$q = "
SELECT AVG(i.price) AS sell_price
FROM ecmstockdocoutitems AS i
INNER JOIN ecmstockdocouts AS o ON i.ecmstockdocout_id = o.id
WHERE i.ecmproduct_id = '{$r['id']}' AND o.delivery_date BETWEEN '{$date_from_to_query->format('Y-m-d')}' AND '{$date_to_to_query->format('Y-m-d')}'
AND o.parent_id = 'b5612f7f-85e5-f930-293e-62cead14b424'
";
$price = $db->query($q);
$price = $db->fetchByAssoc($price);
$r['koszt'] = $price['sell_price'] * $r['ilosc'];
$data[] = $r;
}
return $data;
}

View File

@@ -0,0 +1,42 @@
<?php
require_once 'ReportSales.inc.php';
/*****************************************************/
/********************** SMARTY ***********************/
/*****************************************************/
$Calendar_daFormat = str_replace("d","%d",str_replace("m","%m",str_replace("Y","%Y",$GLOBALS['timedate']->get_date_format())));
// Default value from date input
$currentDate = $GLOBALS['timedate']->to_display_date($date_from);
$date_from = $GLOBALS['timedate']->to_display_date($date_from);
$date_to = $GLOBALS['timedate']->to_display_date($date_to);
// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty -> assign( "MOD", $mod_strings );
$smarty -> assign( "DATA", $newArray1);
$smarty -> assign( "date_from", $date_from );
$smarty -> assign( "date_to", $date_to );
$smarty -> assign("dateFormat", $Calendar_daFormat);
$smarty -> assign( "SUM", $sum);
$smarty -> assign("searchByType", $searchByType);
$smarty -> assign("searchBy", $searchBy);
$smarty -> assign( "USERS", $datausers);
$smarty -> assign( "selectUser", $selectUser);
$smarty -> assign( "selectedPdfType", $selectPdfType);
$smarty -> assign( "group_ks", $group_ks);
$smarty -> assign( "all_groups_ks", $all_groups_ks);
// Eksport do PDF
if( $_GET['toPDF'] == '1' ) {
$output = $smarty->fetch( 'modules/EcmReports/tpls/PDF/ReportSales.tpl' );
include_once ("include/MPDF57/mpdf.php");
$p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 10, 10, 5, 5 );
$p->setTitle($mod_strings["LBL_SUBPANEL_TITLE"]);
$p->writeHTML( $output );
$p->Output ('RaportSprzedazy.pdf', 'I');
} else {
echo $smarty->display ( 'modules/EcmReports/tpls/ReportSales.tpl' );
}
?>

View File

@@ -0,0 +1,45 @@
<?php
$reportSales = 1;
require_once 'ReportSales.inc';
/*****************************************************/
/********************** SMARTY ***********************/
/*****************************************************/
$Calendar_daFormat = str_replace("d","%d",str_replace("m","%m",str_replace("Y","%Y",$GLOBALS['timedate']->get_date_format())));
// Default value from date input
$currentDate = $GLOBALS['timedate']->to_display_date($date_from);
$date_from = $GLOBALS['timedate']->to_display_date($date_from);
$date_to = $GLOBALS['timedate']->to_display_date($date_to);
// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty -> assign( "MOD", $mod_strings );
$smarty -> assign( "DATA", $newArray1);
$smarty -> assign( "date_from", $date_from );
$smarty -> assign( "date_to", $date_to );
$smarty -> assign("dateFormat", $Calendar_daFormat);
$smarty -> assign( "SUM", $sum);
$smarty -> assign("searchByType", $searchByType);
$smarty -> assign("searchBy", $searchBy);
$smarty -> assign( "USERS", $datausers);
$smarty -> assign( "selectUser", $selectUser);
$smarty -> assign( "selectedPdfType", $selectPdfType);
$smarty -> assign( "group_ks", $group_ks);
$smarty -> assign( "all_groups_ks", $all_groups_ks);
$smarty -> assign( "reportSales", $reportSales);
// Eksport do PDF
if( $_GET['toPDF'] == '1' ) {
$output = $smarty->fetch( 'modules/EcmReports/tpls/PDF/ReportSales.tpl' );
include_once ("include/MPDF57/mpdf.php");
$p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 10, 10, 5, 5 );
$p->setTitle($mod_strings["LBL_SUBPANEL_TITLE"]);
$p->writeHTML( $output );
$p->Output ('RaportSprzedazy.pdf', 'I');
} else {
echo $smarty->display ( 'modules/EcmReports/tpls/ReportSales.tpl' );
}
?>

View File

@@ -0,0 +1,668 @@
<?php
if (! defined ( 'sugarEntry' ) || ! sugarEntry)
die ( 'Not A Valid Entry Point' );
/*****************************************************/
/*********************** PREPARE *********************/
/*****************************************************/
$db = $GLOBALS ['db'];
if($_GET['selectUser']!="")
{
$selectUser=$_GET['selectUser'];
}else{
$selectUser="";
}
if($_GET['selectPdfType']!="")
{
$selectPdfType=$_GET['selectPdfType'];
}else{
$selectPdfType="";
}
$source = $_GET["source"];
$group_media_saturn_holding = $_GET["group_media_saturn_holding"];
$data = array();
$categoryArray = array();
$sum = array();
$sumContracor = array();
$sumCategory = array();
$sumSubCategory = array();
if(!$_GET['date_from'])
$date_from = date("Y-m-01");
else
$date_from = $_GET["date_from"];
if(!$_GET['date_to'])
$date_to = date("Y-m-d");
else
$date_to = $_GET["date_to"];
$searchByType = $_GET['type'];
$date_from_to_query = new DateTime($date_from);
$date_to_to_query = new DateTime($date_to);
$datausers = array();
$users = array();
$queryUsers="SELECT
first_name as 'first',
last_name as 'last',
id
FROM users
;";
// Usuniete z powyzszego zapytania na polecenie Michała
//where deleted= 0
//and status = 'Active'
$rowsUsers= $db->query ($queryUsers);
while($rowUser = $db->fetchByAssoc ( $rowsUsers ))
{
$users["first"] = $rowUser["first"];
$users["last"] = $rowUser["last"];
$users["id"] = $rowUser["id"];
$datausers [] = $users;
}
$query = "SELECT
faktura.parent_name as 'parent',
acco.parent_id as 'parent_id',
faktura.parent_id as 'cotructor_id',
pozycja.name as 'name',
pozycja.ecmproduct_id as 'id',
pozycja.code,
faktura.type as 'type',
sale.order_source as 'source',
sum(
CASE WHEN faktura.type!='correct'
THEN
CASE WHEN faktura.currency_value_nbp is null or faktura.currency_value_nbp='' or faktura.currency_value_nbp=0
THEN
pozycja.total_netto
ELSE
pozycja.total_netto*faktura.currency_value_nbp
END
ELSE
CASE WHEN faktura.currency_value_nbp is null or faktura.currency_value_nbp='' or faktura.currency_value_nbp=0
THEN
pozycja.total_netto_corrected
ELSE
pozycja.total_netto_corrected*faktura.currency_value_nbp
END
END
) as netto,
sum(
CASE WHEN faktura.type!='correct'
THEN
pozycja.quantity
ELSE
pozycja.quantity_corrected
END
) as ilosc, ";
if($reportSales===1){
$query.="
sum( CASE WHEN faktura.type!='correct'
THEN
produkt.cena_produkcyjna*pozycja.quantity
ELSE
produkt.cena_produkcyjna*pozycja.quantity_corrected
END
) as koszt";
} else {
$query.="
sum(
CASE WHEN faktura.type!='correct'
THEN
pozycja.price_purchase*pozycja.quantity
ELSE
pozycja.price_purchase*pozycja.quantity_corrected
END
) as koszt";
}
$query.="
FROM
ecminvoiceoutitems pozycja
JOIN
ecminvoiceouts faktura ON pozycja.ecminvoiceout_id = faktura.id
LEFT JOIN
ecmproducts produkt ON pozycja.ecmproduct_id = produkt.id
JOIN
accounts acco ON acco.id = faktura.parent_id
LEFT JOIN
ecmsales sale ON sale.id = faktura.so_id
WHERE
faktura.register_date BETWEEN
'".$date_from_to_query->format('Y-m-d')."' AND
'".$date_to_to_query->format('Y-m-d')."'
and faktura.type like '".$searchByType."'
and faktura.canceled = 0
and faktura.deleted= 0";
if ($selectPdfType!="")
$query.= " and faktura.pdf_type='$selectPdfType'";
if ($source=='allegro') {
$query .= " and sale.order_source = 'allegro' ";
} else if ($source=='no-allegro') {
$query .= " and sale.order_source IS NULL ";
}
$query .= " and pozycja.deleted= 0
GROUP BY pozycja.id
ORDER BY faktura.parent_name
COLLATE utf8_polish_ci;";
/*****************************************************/
/*************** GET DATA FROM DB*********************/
/*****************************************************/
$rows = $db->query ($query);
// prepare data for Smarty
while($r = $db->fetchByAssoc ( $rows ))
{
$row = prepareRow($r, $selectUser, $group_media_saturn_holding);
if($row) {
$data [] = $row;
}
}
// E-Commerce data
$ecommercerows = getEcommerceData($date_from_to_query, $date_to_to_query, 'allegro', $searchByType);
foreach($ecommercerows as $r) {
$row = prepareRow($r, $selectUser, $group_media_saturn_holding);
if($row) {
$data [] = $row;
}
}
$ecommercerows = getEcommerceData($date_from_to_query, $date_to_to_query, 'shop', $searchByType);
foreach($ecommercerows as $r) {
$row = prepareRow($r, $selectUser, $group_media_saturn_holding);
if($row) {
$data [] = $row;
}
}
if($searchByType!="")
{
////////////////// SUM /////////////////////////////////
foreach( $data as $key=>&$element )
{
if($element["netto"]!=0)
{
$categoryArray[$element["parent"] == "" ? "Nieznany" : $element["parent"]][$element["kategoria"] == "" ? "Inne" : $element["kategoria"]][$element["podkategoria"] == "" ? "Reszta" : $element["podkategoria"]][$key] = $element;
}
}
foreach( $categoryArray as $parent=>&$elementParent )
{
foreach( $elementParent as $category=>&$elementCategory )
{
foreach( $elementCategory as $subcategory=>&$elementSubCategory )
{
foreach( $elementSubCategory as $product=>&$elementProduct )
{
$sumContracor["IloscSum"][$parent] += $elementProduct["ilosc"];
$sumContracor["SoldSum"][$parent] += $elementProduct["netto"];
//if($elementProduct["type"]=="normal")
//{
$sumContracor["SoldSumNormal"][$parent] += $elementProduct["netto"];
$sumContracor["IloscNormal"][$parent] += $elementProduct["ilosc"];
// }else{
// $sumContracor["SoldSumNormal"][$parent] += 0;
// $sumContracor["IloscNormal"][$parent] += 0;
//}
$sumContracor["KosztSum"][$parent] += $elementProduct["koszt"];
$sumCategory["IloscSum"][$parent][$category] += $elementProduct["ilosc"];
$sumCategory["SoldSum"][$parent][$category] += $elementProduct["netto"];
//if($elementProduct["type"]=="normal")
//{
$sumCategory["SoldSumNormal"][$parent][$category] += $elementProduct["netto"];
$sumCategory["IloscNormal"][$parent][$category] += $elementProduct["ilosc"];
//}else{
// $sumCategory["SoldSumNormal"][$parent][$category] += 0;
// $sumCategory["IloscNormal"][$parent][$category] += 0;
//}
$sumCategory["KosztSum"][$parent][$category] += $elementProduct["koszt"];
$sumSubCategory["IloscSum"][$parent][$category][$subcategory] += $elementProduct["ilosc"];
$sumSubCategory["SoldSum"][$parent][$category][$subcategory] += $elementProduct["netto"];
//if($elementProduct["type"]=="normal")
//{
$sumSubCategory["SoldSumNormal"][$parent][$category][$subcategory] += $elementProduct["netto"];
$sumSubCategory["IloscNormal"][$parent][$category][$subcategory] += $elementProduct["ilosc"];
//}else{
// $sumSubCategory["SoldSumNormal"][$parent][$category][$subcategory] += 0;
// $sumSubCategory["IloscNormal"][$parent][$category][$subcategory] += 0;
//}
$sumSubCategory["KosztSum"][$parent][$category][$subcategory] += $elementProduct["koszt"];
}
$sumSubCategory["MarzaSum"][$parent][$category][$subcategory] = ($sumSubCategory["SoldSumNormal"][$parent][$category][$subcategory]-$sumSubCategory["KosztSum"][$parent][$category][$subcategory])/$sumSubCategory["SoldSumNormal"][$parent][$category][$subcategory]*100;
$sumSubCategory["SredniaSum"][$parent][$category][$subcategory] = $sumSubCategory["SoldSumNormal"][$parent][$category][$subcategory]/$sumSubCategory["IloscNormal"][$parent][$category][$subcategory];
$categoryArray[$parent][$category][$subcategory]["IloscSum"] = $sumSubCategory["IloscSum"][$parent][$category][$subcategory];
$categoryArray[$parent][$category][$subcategory]["SoldSum"] = $sumSubCategory["SoldSum"][$parent][$category][$subcategory];
$categoryArray[$parent][$category][$subcategory]["SoldSumNormal"] = $sumSubCategory["SoldSumNormal"][$parent][$category][$subcategory];
$categoryArray[$parent][$category][$subcategory]["IloscNormal"] = $sumSubCategory["IloscNormal"][$parent][$category][$subcategory];
$categoryArray[$parent][$category][$subcategory]["SredniaSum"] = $sumSubCategory["SredniaSum"][$parent][$category][$subcategory];
$categoryArray[$parent][$category][$subcategory]["KosztSum"] = $sumSubCategory["KosztSum"][$parent][$category][$subcategory];
$categoryArray[$parent][$category][$subcategory]["MarzaSum"] = $sumSubCategory["MarzaSum"][$parent][$category][$subcategory];
}
$sumCategory["MarzaSum"][$parent][$category] = ($sumCategory["SoldSumNormal"][$parent][$category]-$sumCategory["KosztSum"][$parent][$category])/$sumCategory["SoldSumNormal"][$parent][$category]*100;
$sumCategory["SredniaSum"][$parent][$category] = $sumCategory["SoldSumNormal"][$parent][$category]/$sumCategory["IloscNormal"][$parent][$category];
$categoryArray[$parent][$category]["IloscSum"] = $sumCategory["IloscSum"][$parent][$category];
$categoryArray[$parent][$category]["SoldSum"] = $sumCategory["SoldSum"][$parent][$category];
$categoryArray[$parent][$category]["SoldSumNormal"] = $sumCategory["SoldSumNormal"][$parent][$category];
$categoryArray[$parent][$category]["IloscNormal"] = $sumCategory["IloscNormal"][$parent][$category];
$categoryArray[$parent][$category]["SredniaSum"] = $sumCategory["SredniaSum"][$parent][$category];
$categoryArray[$parent][$category]["KosztSum"] = $sumCategory["KosztSum"][$parent][$category];
$categoryArray[$parent][$category]["MarzaSum"] = $sumCategory["MarzaSum"][$parent][$category];
}
$sumContracor["MarzaSum"][$parent] = ($sumContracor["SoldSumNormal"][$parent]-$sumContracor["KosztSum"][$parent])/$sumContracor["SoldSumNormal"][$parent]*100;
$sumContracor["SredniaSum"][$parent] = $sumContracor["SoldSumNormal"][$parent]/$sumContracor["IloscNormal"][$parent];
$categoryArray[$parent]["IloscSum"] = $sumContracor["IloscSum"][$parent];
$categoryArray[$parent]["SoldSum"] = $sumContracor["SoldSum"][$parent];
$categoryArray[$parent]["SoldSumNormal"] = $sumContracor["SoldSumNormal"][$parent];
$categoryArray[$parent]["IloscNormal"] = $sumContracor["IloscNormal"][$parent];
$categoryArray[$parent]["SredniaSum"] = $sumContracor["SredniaSum"][$parent];
$categoryArray[$parent]["KosztSum"] = $sumContracor["KosztSum"][$parent];
$categoryArray[$parent]["MarzaSum"] = $sumContracor["MarzaSum"][$parent];
}
foreach( $categoryArray as $parent=>&$elementParent )
{
$sum["IloscSumSum"] += $sumContracor["IloscSum"][$parent];
$sum["SoldSumSum"] += $sumContracor["SoldSum"][$parent];
$sum["SoldSumNormal"] += $sumContracor["SoldSumNormal"][$parent];
$sum["IloscNormal"] += $sumContracor["IloscNormal"][$parent];
$sum["KosztSumSum"] += $sumContracor["KosztSum"][$parent];
}
$sum["MarzaSumSum"] = ($sum["SoldSumNormal"]-$sum["KosztSumSum"])/$sum["SoldSumNormal"]*100;
$sum["SredniaSumSum"] = $sum["SoldSumNormal"]/$sum["IloscNormal"];
//mz: dotąd jest OK
function cmp($a, $b)
{
if ($a["id"] == $b["id"]) {
return 0;
}
return ($a["id"] < $b["id"]) ? -1 : 1;
}
// grupowanie po kontrahentach
foreach($categoryArray as $parent=>&$elementParent )
{
$tmp2[$parent]["IloscSum"] = $categoryArray[$parent]["IloscSum"];
$tmp2[$parent]["SoldSum"] = $categoryArray[$parent]["SoldSum"];
$tmp2[$parent]["SoldSumNormal"] = $categoryArray[$parent]["SoldSumNormal"];
$tmp2[$parent]["IloscNormal"] = $categoryArray[$parent]["IloscNormal"];
$tmp2[$parent]["KosztSum"] = $categoryArray[$parent]["KosztSum"];
$tmp2[$parent]["SredniaSum"] = 0;
$tmp2[$parent]["SredniaSum"] = $categoryArray[$parent]["SredniaSum"];
$tmp2[$parent]["MarzaSum"] = $categoryArray[$parent]["MarzaSum"];
foreach($elementParent as $category=>&$elementCategory)
{
$tmp2[$parent][$category]["IloscSum"] = $categoryArray[$parent][$category]["IloscSum"];
$tmp2[$parent][$category]["SoldSum"] = $categoryArray[$parent][$category]["SoldSum"];
$tmp2[$parent][$category]["SoldSumNormal"] = $categoryArray[$parent][$category]["SoldSumNormal"];
$tmp2[$parent][$category]["IloscNormal"] = $categoryArray[$parent][$category]["IloscNormal"];
$tmp2[$parent][$category]["KosztSum"] = $categoryArray[$parent][$category]["KosztSum"];
$tmp2[$parent][$category]["SredniaSum"] = $categoryArray[$parent][$category]["SredniaSum"];
$tmp2[$parent][$category]["MarzaSum"] = $categoryArray[$parent][$category]["MarzaSum"];
foreach( $elementCategory as $subcategory=>&$elementSubCategory )
{
$tmp2[$parent][$category][$subcategory]["IloscSum"] = $categoryArray[$parent][$category][$subcategory]["IloscSum"];
$tmp2[$parent][$category][$subcategory]["SoldSum"] = $categoryArray[$parent][$category][$subcategory]["SoldSum"];
$tmp2[$parent][$category][$subcategory]["SoldSumNormal"] = $categoryArray[$parent][$category][$subcategory]["SoldSumNormal"];
$tmp2[$parent][$category][$subcategory]["IloscNormal"] = $categoryArray[$parent][$category][$subcategory]["IloscNormal"];
$tmp2[$parent][$category][$subcategory]["KosztSum"] = $categoryArray[$parent][$category][$subcategory]["KosztSum"];
$tmp2[$parent][$category][$subcategory]["SredniaSum"] = $categoryArray[$parent][$category][$subcategory]["SredniaSum"];
$tmp2[$parent][$category][$subcategory]["MarzaSum"] = $categoryArray[$parent][$category][$subcategory]["MarzaSum"];
usort($elementSubCategory, "cmp");
$i=0;
$tmp2[$parent][$category][$subcategory][0]= array ('is' => null);
foreach($elementSubCategory as $count=>&$element3)
{
if($element3["id"]!=$tmp2[$parent][$category][$subcategory][$i]["id"])
{
if($tmp2[$parent][$category][$subcategory][$i]["id"]!=null)
{
$i++;
}
}
$tmp2[$parent][$category][$subcategory][$i]["id"]=$element3["id"];
$tmp2[$parent][$category][$subcategory][$i]["name"]=$element3["name"];
$tmp2[$parent][$category][$subcategory][$i]["code"]=$element3["code"];
$tmp2[$parent][$category][$subcategory][$i]["parent_id"]=$element3["parent_id"];
$tmp2[$parent][$category][$subcategory][$i]["stan"] = $element3["stan"];
$tmp2[$parent][$category][$subcategory][$i]["wartosc"] = $element3["wartosc"];
$tmp2[$parent]["StanSum"] += $element3["stan"];
$tmp2[$parent]["WartoscSum"] += $element3["wartosc"];
$tmp2[$parent][$category]["StanSum"] += $element3["stan"];
$tmp2[$parent][$category]["WartoscSum"] += $element3["wartosc"];
$tmp2[$parent][$category][$subcategory]["StanSum"] += $element3["stan"];
$tmp2[$parent][$category][$subcategory]["WartoscSum"] += $element3["wartosc"];
$tmp2[$parent][$category][$subcategory][$i]["nettoNormal"] += $element3["netto"];
$tmp2[$parent][$category][$subcategory][$i]["IloscNormal"] += $element3["ilosc"];
$tmp2[$parent][$category][$subcategory][$i]["ilosc"] += $element3["ilosc"];
$tmp2[$parent][$category][$subcategory][$i]["netto"] += $element3["netto"];
$tmp2[$parent][$category][$subcategory][$i]["koszt"] += $element3["koszt"];
}
if(is_array($tmp2[$parent][$category][$subcategory]["SredniaSum"]) || $tmp2[$parent][$category][$subcategory]["SredniaSum"]=="")
{
$tmp2[$parent][$category][$subcategory]["SredniaSum"] = 0;
}
}
if(is_array($tmp2[$parent][$category]["SredniaSum"]))
{
$tmp2[$parent][$category]["SredniaSum"] = 0;
}
}
if(is_array($tmp2[$parent]["SredniaSum"]))
{
$tmp2[$parent]["SredniaSum"] = 0;
}
$categoryArray1=$tmp2;
}
////////////////// SORT sumSubCategory /////////////////////////////////
foreach( $categoryArray1 as $parent=>&$elementParent )
{
foreach( $elementParent as $category=>&$elementCategory )
{
foreach( $elementCategory as $SubCategory1=>&$elementSubCategory1)
{
foreach( $elementCategory as $SubCategory2=>&$elementSubCategory2 )
{
if($sumSubCategory["SoldSum"][$parent][$category][$SubCategory1]>$sumSubCategory["SoldSum"][$parent][$category][$SubCategory2])
{
$tmp=$sumSubCategory["SoldSum"][$parent][$category][$SubCategory1];
$sumSubCategory["SoldSum"][$parent][$category][$SubCategory1]=$sumSubCategory["SoldSum"][$parent][$category][$SubCategory2];
$sumSubCategory["SoldSum"][$parent][$category][$SubCategory2]=$tmp;
}
}
}
}
}
////////////////// SORT sumCategory /////////////////////////////////
foreach( $categoryArray1 as $parent=>&$elementParent )
{
foreach( $elementParent as $category1=>&$elementCategory1 )
{
foreach( $elementParent as $category2=>&$elementCategory2 )
{
if($sumCategory["SoldSum"][$parent][$category1]>$sumCategory["SoldSum"][$parent][$category2])
{
$tmp=$sumCategory["SoldSum"][$parent][$category1];
$sumCategory["SoldSum"][$parent][$category1]=$sumCategory["SoldSum"][$parent][$category2];
$sumCategory["SoldSum"][$parent][$category2]=$tmp;
}
}
}
}
////////////////// SORT $sumContracor /////////////////////////////////
foreach( $categoryArray1 as $parent1=>&$elementParent1 )
{
foreach( $categoryArray1 as $parent2=>&$elementParent2 )
{
if($sumContracor["SoldSum"][$parent1]>$sumContracor["SoldSum"][$parent2])
{
$tmp=$sumContracor["SoldSum"][$parent1];
$sumContracor["SoldSum"][$parent1]=$sumContracor["SoldSum"][$parent2];
$sumContracor["SoldSum"][$parent2]=$tmp;
}
}
}
////////////////// SORT array at sumContracor/////////////////////////////////
$newArray2;
foreach( $categoryArray1 as $parent1=>&$elementParent1 )
{
foreach( $categoryArray1 as $parent2=>&$elementParent2 )
{
if($sumContracor["SoldSum"][$parent1]==$categoryArray1[$parent2]["SoldSum"])
{
$newArray2[$parent2]=$categoryArray1[$parent2];
}
}
}
////////////////// SORT array at sumCategory/////////////////////////////////
$newArray1;
foreach( $newArray2 as $parent=>&$elementParent )
{
foreach( $elementParent as $category1=>&$elementCategory1 )
{
foreach( $elementParent as $category2=>&$elementCategory2 )
{
if($sumCategory["SoldSum"][$parent][$category1]==$newArray2[$parent][$category2]["SoldSum"])
{
$newArray1[$parent][$category2]=$newArray2[$parent][$category2];
}
}
}
}
////////////////// SORT array at sumSubCategory/////////////////////////////////
$newArray;
foreach( $newArray1 as $parent=>&$elementParent )
{
foreach( $elementParent as $category=>&$elementCategory )
{
foreach( $elementCategory as $subcategory1=>&$elementSubCategory )
{
foreach( $elementCategory as $subcategory2=>&$elementSubCategory )
{
if($sumSubCategory["SoldSum"][$parent][$category][$subcategory1]==$newArray1[$parent][$category][$subcategory2]["SoldSum2"])
{
$newArray[$parent][$category][$subcategory2]=$newArray1[$parent][$category][$subcategory2];
}
}
}
}
$newArray[$parent]["IloscSum"]=$newArray1[$parent]["IloscSum"];
$newArray[$parent]["SoldSum"]=$newArray1[$parent]["SoldSum"];
$newArray[$parent]["SredniaSum"]=$newArray1[$parent]["SredniaSum"];
$newArray[$parent]["KosztSum"]=$newArray1[$parent]["KosztSum"];
$newArray[$parent]["MarzaSum"]=$newArray1[$parent]["MarzaSum"];
}
//wyliczanie dokładne marży i średniej dla produktów
foreach( $newArray as $parent=>&$elementParent )
{
foreach( $elementParent as $category=>&$elementCategory )
{
foreach( $elementCategory as $subcategory=>&$elementSubCategory )
{
foreach( $elementSubCategory as $key=>&$element )
{
$newArray[$parent][$category][$subcategory][$key]["marza"] = ($newArray[$parent][$category][$subcategory][$key]["nettoNormal"]-$newArray[$parent][$category][$subcategory][$key]["koszt"])/$newArray[$parent][$category][$subcategory][$key]["nettoNormal"]*100;
$newArray[$parent][$category][$subcategory][$key]["srednia"] = $newArray[$parent][$category][$subcategory][$key]["nettoNormal"]/$newArray[$parent][$category][$subcategory][$key]["IloscNormal"];
}
}
}
}
}
function prepareRow($r, $selectUser, $group_media_saturn_holding) {
$db = $GLOBALS['db'];
$row = array();
$row["id"] = $r["id"];
$row["name"] = $r["name"];
$row["code"] = $r["code"];
$row["type"] = $r["type"];
$userBool=1;
if($selectUser!="")
{
$userBool=0;
$querySelectUsers="SELECT user.id,
first_name as 'first',
last_name as 'last'
FROM
accounts acc
JOIN
users user ON acc.assigned_user_id=user.id
WHERE acc.id='".$r["cotructor_id"]."';";
$rowsSelectUsers = $db->query ($querySelectUsers);
while($rowSelectUser = $db->fetchByAssoc ( $rowsSelectUsers ))
{
if($rowSelectUser["id"]==$selectUser)
{
$userBool=1;
}else{
$userBool=0;
}
}
}
if($userBool==1)
{
if($r["parent_id"]==1249 && $group_media_saturn_holding == "enabled")
{
$row["parent"] = "Media Saturn Holding";
}else{
$row["parent"] = $r["parent"];
}
$querySubCategory="SELECT category.name as 'podkategoria'
FROM
ecmproductcategories_bean bean
JOIN
ecmproductcategories category ON bean.ecmproductcategory_id = category.id
WHERE bean.bean_id='".$row["id"]."'
and category.deleted=0
and bean.deleted = '0'
and bean.position = 1;";
$rowsSubCategory = $db->query ($querySubCategory);
while($rowSubCategory = $db->fetchByAssoc ( $rowsSubCategory ))
{
$row["podkategoria"] = $rowSubCategory["podkategoria"];
}
$queryCategory="SELECT category.name as 'kategoria'
FROM
ecmproductcategories_bean bean
JOIN
ecmproductcategories category ON bean.ecmproductcategory_id = category.id
WHERE bean.bean_id='".$row["id"]."'
and category.deleted=0
and bean.deleted = '0'
and bean.position = 0;";
$rowscategory = $db->query ($queryCategory);
while($rowcategory = $db->fetchByAssoc ( $rowscategory ))
{
//echo "assadad";
$row["kategoria"] = $rowcategory["kategoria"];
}
$row["ilosc"] = $r["ilosc"];
$row["netto"] = $r["netto"];
$row["srednia"] = $row["netto"]/$row["ilosc"];
$row["srednia"] = 5;
$row["koszt"] = $r["koszt"];
//if($row["netto"]>$row["koszt"])
//{
$row["marza"] = ($row["netto"]-$row["koszt"])/($row["netto"])*100;
//}else{
// $row["marza"] = 5;
//$row["marza"] = ($row["netto"]-$row["koszt"])/($row["netto"])*100;
//}
return $row;
}
return null;
}
function getEcommerceData($date_from_to_query, $date_to_to_query, $type, $inv_type) {
$db = $GLOBALS['db'];
$data = [];
if ($inv_type == 'correct') {
$inv_type = 'correcting';
}
$query = "
SELECT
ip.ecmproduct_id AS id,
p.name,
p.code,
SUM(CASE WHEN i.type ='normal'
THEN
ip.price_netto * ip.quantity
ELSE
(ip.price_netto * ip.quantity) - (ipc.price_netto * ipc.quantity)
END) AS netto,
SUM(CASE WHEN i.type ='normal'
THEN
ip.quantity
ELSE
ip.quantity - ipc.quantity
END) AS ilosc
FROM
ecommerce_invoices_products AS ip
INNER JOIN
ecmproducts AS p ON p.id = ip.ecmproduct_id
INNER JOIN
ecommerce_invoices AS i ON i.id = ip.invoice_id
LEFT JOIN
ecommerce_invoices_products AS ipc ON ipc.invoice_id = i.corrected_invoice_id AND ipc.ecmproduct_id = ip.ecmproduct_id
WHERE
i.register_date BETWEEN
'".$date_from_to_query->format('Y-m-d')."' AND
'".$date_to_to_query->format('Y-m-d')."' AND
i.origin = '$type' AND
i.type LIKE '$inv_type'
GROUP BY ip.ecmproduct_id";
$rows = $db->query($query);
while($r = $db->fetchByAssoc($rows)) {
if ($type == 'allegro') {
$r['parent'] = "Allegro";
$r['parent_id'] = "allegro";
$r['contructor_id'] = "allegro";
} else if ($type == 'shop') {
$r['parent'] = "ABC-Czystosci.pl";
$r['parent_id'] = "abc-czystosci.pl";
$r['contructor_id'] = "abc-czystosci.pl";
}
$q = "
SELECT AVG(i.price) AS sell_price
FROM ecmstockdocoutitems AS i
INNER JOIN ecmstockdocouts AS o ON i.ecmstockdocout_id = o.id
WHERE i.ecmproduct_id = '{$r['id']}' AND o.delivery_date BETWEEN '{$date_from_to_query->format('Y-m-d')}' AND '{$date_to_to_query->format('Y-m-d')}'
AND o.parent_id = 'b5612f7f-85e5-f930-293e-62cead14b424'
";
$price = $db->query($q);
$price = $db->fetchByAssoc($price);
$r['koszt'] = $price['sell_price'] * $r['ilosc'];
$data[] = $r;
}
return $data;
}
?>

View File

@@ -0,0 +1,232 @@
<?php
global $mod_strings, $app_list_strings, $db;
// kontrahent
if(!$_REQUEST['date_from'])
$date_from = date("01.m.Y");
else
$date_from = $_REQUEST["date_from"];
if(!$_REQUEST['date_to'])
$date_to = date("d.m.Y");
else
$date_to = $_REQUEST["date_to"];
if(!class_exists('EcmInvoiceOut')){
include_once('modules/EcmInvoiceouts/EcmInvoiceout.php');
};
if(!class_exists('EcmReceipts')){
include_once('modules/EcmReceipts/EcmReceipt.php');
};
//get trader list
$query_trader = "select ecminvoiceouts.assigned_user_id AS user_id , concat(users.first_name, ' ', users.last_name) AS user_name FROM ecminvoiceouts, users WHERE ecminvoiceouts.deleted = 0 and ecminvoiceouts.canceled = 0 AND users.id = ecminvoiceouts.assigned_user_id group by user_id ORDER BY user_name";
$trader_result = $db->query($query_trader);
$trader_array = array(""=>"");
while($row = $db->fetchByAssoc($trader_result)){
$trader_array[$row['user_id']] = $row['user_name'];
}
//Get Stock List
$query_stock = "Select id, name from ecmstocks where deleted=0";
$stock_result = $db->query($query_stock);
$stock_array = array(""=>"");
while($row = $db->fetchByAssoc($stock_result)){
$stock_array[$row['id']] = $row['name'];
}
//Szykowanie zapytań
//Zakres dat
$whereInvoice['ecminvoiceouts'][] = 'register_date>="' . getFormatedDateForDB($date_from) . '"';
$whereInvoice['ecminvoiceouts'][] = 'register_date<="' . getFormatedDateForDB($date_to) . '"';
$whereRecipe['ecmrecipes'][] = 'register_date>="' . getFormatedDateForDB($date_from) . '"';
$whereRecipe['ecmrecipes'][] = 'register_date<="' . getFormatedDateForDB($date_to) . '"';
//Handlowiec
if($_REQUEST['trader'] != ""){
$whereInvoice['ecminvoiceouts'][] = 'assigned_user_id="' . $_REQUEST['trader'] . '"';
$whereRecipe['ecmrecipes'][] = 'assigned_user_id="' . $_REQUEST['trader'] . '"';
}
//Magazyn
$stocks = $_REQUEST['stocks'];
if(count($stocks)>0){
if(in_array("",$stocks)){
$indeks = array_search("",$stocks);
unset($stocks[$indeks]);
}
if(count($stocks)>0){
$stocksList = array();
$value = array_values ( $stocks );
$whereInvoice['ecminvoiceouts'][] = 'stock_id IN ("' . implode('","',$value) . '")';
$whereRecipe['ecmrecipes'][] = 'stock_id IN ("' . implode('","',$value) . '")';
}
}
//Grupa
$product_group = $_REQUEST['product_group'];
if(count($product_group)>0){
if(in_array("",$product_group)){
$indeks = array_search("",$product_group);
unset($product_group[$indeks]);
}
if(count($product_group)>0){
$product_group_list = array();
$value = array_values ( $product_group );
$whereInvoice['ecmproducts'][] = 'ks_group IN ("' . implode('","',$value) . '")';
$whereRecipe['ecmproducts'][] = 'ks_group IN ("' . implode('","',$value) . '")';
}
}
//Typ dokumentu
$document_sales_type = $_REQUEST['document_sales_type'];
if(count($document_sales_type)>0){
if(in_array("",$document_sales_type)){
$indeks = array_search("",$document_sales_type);
unset($document_sales_type[$indeks]);
}
if(count($document_sales_type)>0){
$tmpInvoiceType = array();
$tmpRecipeType = array();
$receiptDo = false;
$invoceDo = true;
foreach($document_sales_type as $key => $value){
switch($value){
case 'invoice':
$tmpInvoiceType[] = 'normal';
$invoceDo = true;
break;
case 'invoice_correct':
$invoceDo = true;
$tmpInvoiceType[] = 'correct';
break;
case 'recipe':
$receiptDo = true;
$tmpRecipeType[] = 'normal';
break;
case 'recipe_correct':
$receiptDo = true;
$tmpRecipeType[] = 'correct';
break;
}
}
if(count($tmpInvoiceType)>0){
$value = array_values ( $tmpInvoiceType );
$whereInvoice['ecminvoiceouts'][] = 'type IN ("' . implode('","',$value) . '")';
$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
}
if(count($tmpRecipeType)>0){
$value = array_values ( $tmpRecipeType );
$whereRecipe['ecmrecipes'][] = 'type IN ("' . implode('","',$value) . '")';
$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}
}else{
$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}
}else{
$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}
// Przetwarzanie danych
$data = array();
foreach($dataInvoice as $indeks => $invoice){
$data[$invoice['parent_id']]['name'] = '<a target="_blank" href="index.php?module=Accounts&return_module=Account&action=DetailView&parentTab=Kontakty&record=' . $invoice['parent_id'] . '">' . $invoice['parent_name'] . '</a>';
$data[$invoice['parent_id']]['total_netto'] += $invoice['total_netto'];
$data[$invoice['parent_id']]['price_purchase'] += $invoice['purchase_price'];
if($_REQUEST['to_xls']=='1'){
$data[$invoice['parent_id']]['name']= $invoice['parent_name'];
}
}
foreach($dataRecipe as $indeks => $invoice){
$data[$invoice['parent_id']]['name'] = '<a target="_blank" href="index.php?module=Accounts&return_module=Account&action=DetailView&parentTab=Kontakty&record=' . $invoice['parent_id'] . '">' . $invoice['parent_name'] . '</a>';
$data[$invoice['parent_id']]['total_netto'] += $invoice['total_netto'];
$data[$invoice['parent_id']]['price_purchase'] += $invoice['purchase_price'];
if($_REQUEST['to_xls']=='1'){
$data[$invoice['parent_id']]['name']= $invoice['parent_name'];
}
}
//
//Szykowanie wyświetlania
$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("APP_LIST_STRINGS", $app_list_strings);
$smarty->assign("DATA", $data);
$smarty->assign("TRADERS_LIST", $trader_array);
$smarty->assign("STOCK_LIST", $stock_array);
//Ustawiamy przeslane dane
//$date_from = $GLOBALS['timedate']->to_display_date($date_from);
//$date_to = $GLOBALS['timedate']->to_display_date($date_to);
$smarty->assign("date_from_value", $date_from );
$smarty->assign("date_to_value", $date_to );
$smarty->assign("TRADER_SELECTED", $_REQUEST['trader']);
$smarty->assign("account_invoice_type_dom", $app_list_strings['account_invoice_type_dom']);
if($_REQUEST['to_pdf']!='1'){
$smarty->assign("STOCK_SELECTED", $_REQUEST['stocks']);
$smarty->assign("PRODUCT_GROUP_SELECTED", $_REQUEST['product_group']);
$smarty->assign("DOCUMENT_SALES_SELECTED", $_REQUEST['document_sales_type']);
echo $smarty->display('modules/EcmReports/tpls/ReportSalesByContractor.tpl');
}else{
if($_REQUEST['to_xls']=='1'){
$header=array();
$header[]='nazwa';
$header[]='sprzedaż netto';
$header[]='koszt zakupu';
$header[]='dochód';
$filename='modules/Home/Files/raport_sprzedazy_wg_nabywcow_'.date('d_m-Y').'.csv';
$fp=fopen($filename,'w');
foreach ($header as $k=>$v){
$header[$k]=iconv('UTF-8','windows-1250',$header[$k]);
}
fwrite($fp, implode(";",$header).PHP_EOL);
foreach ($data as $key=>$val){
$line=array();
$line[]=preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['name'])));
$line[]=str_replace(".",",",$val['total_netto']);
$line[]=str_replace(".",",",$val['price_purchase']);
$line[]=str_replace(".",",",$val['total_netto']-$val['price_purchase']);
foreach ($line as $k=>$v){
$line[$k]=iconv('UTF-8','windows-1250',$line[$k]);;
}
fwrite($fp, implode(";",$line).PHP_EOL);
}
print $filename;
} else {
include_once ("include/MPDF57/mpdf.php");
include_once ("modules/EcmSysInfos/EcmSysInfo.php");
$smarty->assign("STOCK_SELECTED", $_REQUEST['stocks']);
$smarty->assign("PRODUCT_GROUP_SELECTED", $_REQUEST['product_group']);
$smarty->assign("DOCUMENT_SALES_SELECTED", $_REQUEST['document_sales_type']);
$EcmSysInfos = new EcmSysInfo();
$content = $smarty->fetch('modules/EcmReports/tpls/ReportSalesByContractorPDF.tpl');
$mPDF = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 10, 10, 5, 5 );
$mPDF->mirrorMargins = 1;
$mPDF->WriteHTML($content);
$dir = 'upload/' . $EcmSysInfos->getDatabaseName() . '/pdf/EcmReports/';
if(!is_dir($dir)){
mkdir($dir, '755', true);
}
$file_name = $dir . str_replace(".","",$date_from) . "_" . str_replace(".","",$date_to) ."_Raport_Sprzedazy_Podzial_Kontrahenci.pdf";
$mPDF->Output( $file_name, "F");
print $file_name;
}
}
function getFormatedDateForDB($data){
if(strpos($data,".")>0){
$split = explode (".",$data);
$return_data = $split[2] . "-" . $split[1] . "-" .$split['0'];
}
return $return_data;
}

View File

@@ -0,0 +1,42 @@
<?php
require_once 'ReportSalesByContractor.inc.php';
/*****************************************************/
/********************** SMARTY ***********************/
/*****************************************************/
$Calendar_daFormat = str_replace("d","%d",str_replace("m","%m",str_replace("Y","%Y",$GLOBALS['timedate']->get_date_format())));
// Default value from date input
$currentDate = $GLOBALS['timedate']->to_display_date($date_from);
$date_from = $GLOBALS['timedate']->to_display_date($date_from);
$date_to = $GLOBALS['timedate']->to_display_date($date_to);
// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty -> assign( "MOD", $mod_strings );
$smarty -> assign( "SUM", $sum);
$smarty -> assign( "ContractorData", $newArray);
$smarty -> assign( "date_from", $date_from );
$smarty -> assign( "date_to", $date_to );
$smarty -> assign("dateFormat", $Calendar_daFormat);
$smarty -> assign("searchByType", $searchByType);
$smarty -> assign( "USERS", $datausers);
$smarty -> assign( "selectedUser", $selectUser);
$smarty -> assign( "selectedPdfType", $selectPdfType);
$smarty -> assign( "source", $_GET['source']);
$smarty -> assign( "group_media_saturn_holding", $group_media_saturn_holding);
// Eksport do PDF
if( $_GET['toPDF'] == '1' ) {
$output = $smarty->fetch( 'modules/EcmReports/tpls/PDF/ReportSalesByContractor.tpl' );
include_once ("include/MPDF57/mpdf.php");
$p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 10, 10, 5, 5 );
$p->setTitle($mod_strings["LBL_SUBPANEL_TITLE"]);
$p->writeHTML( $output );
$p->Output ('RaportSprzedazyPoKontrahencie.pdf', 'I');
} else {
echo $smarty->display ( 'modules/EcmReports/tpls/ReportSalesByContractor2.tpl' );
}
?>

View File

@@ -0,0 +1,43 @@
<?php
$reportSales = 1;
require_once 'ReportSalesByContractor.inc';
/*****************************************************/
/********************** SMARTY ***********************/
/*****************************************************/
$Calendar_daFormat = str_replace("d","%d",str_replace("m","%m",str_replace("Y","%Y",$GLOBALS['timedate']->get_date_format())));
// Default value from date input
$currentDate = $GLOBALS['timedate']->to_display_date($date_from);
$date_from = $GLOBALS['timedate']->to_display_date($date_from);
$date_to = $GLOBALS['timedate']->to_display_date($date_to);
// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty -> assign( "MOD", $mod_strings );
$smarty -> assign( "SUM", $sum);
$smarty -> assign( "ContractorData", $newArray);
$smarty -> assign( "date_from", $date_from );
$smarty -> assign( "date_to", $date_to );
$smarty -> assign("dateFormat", $Calendar_daFormat);
$smarty -> assign("searchByType", $searchByType);
$smarty -> assign( "USERS", $datausers);
$smarty -> assign( "selectedUser", $selectUser);
$smarty -> assign( "selectedPdfType", $selectPdfType);
$smarty -> assign( "group_media_saturn_holding", $group_media_saturn_holding);
$smarty -> assign( "reportSales", $reportSales);
// Eksport do PDF
if( $_GET['toPDF'] == '1' ) {
$output = $smarty->fetch( 'modules/EcmReports/tpls/PDF/ReportSalesByContractor.tpl' );
include_once ("include/MPDF57/mpdf.php");
$p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 10, 10, 5, 5 );
$p->setTitle($mod_strings["LBL_SUBPANEL_TITLE"]);
$p->writeHTML( $output );
$p->Output ('RaportSprzedazyPoKontrahencie.pdf', 'I');
} else {
echo $smarty->display ( 'modules/EcmReports/tpls/ReportSalesByContractor2.tpl' );
}
?>

View File

@@ -0,0 +1,311 @@
<?php
global $mod_strings, $app_list_strings, $db;
// kontrahent
if(!$_REQUEST['date_from'])
$date_from = date("01.m.Y");
else
$date_from = $_REQUEST["date_from"];
if(!$_REQUEST['date_to'])
$date_to = date("d.m.Y");
else
$date_to = $_REQUEST["date_to"];
if(!class_exists('EcmInvoiceOut')){
include_once('modules/EcmInvoiceouts/EcmInvoiceout.php');
};
if(!class_exists('EcmReceipts')){
include_once('modules/EcmReceipts/EcmReceipt.php');
};
//get trader list
$query_trader = "select ecminvoiceouts.assigned_user_id AS user_id , concat(users.first_name, ' ', users.last_name) AS user_name FROM ecminvoiceouts, users WHERE ecminvoiceouts.deleted = 0 and ecminvoiceouts.canceled = 0 AND users.id = ecminvoiceouts.assigned_user_id group by user_id ORDER BY user_name";
$trader_result = $db->query($query_trader);
$trader_array = array(""=>"&nbsp;");
while($row = $db->fetchByAssoc($trader_result)){
$trader_array[$row['user_id']] = $row['user_name'];
}
//Get Stock List
$query_stock = "Select id, name from ecmstocks where deleted=0";
$stock_result = $db->query($query_stock);
$stock_array = array(""=>"");
while($row = $db->fetchByAssoc($stock_result)){
$stock_array[$row['id']] = $row['name'];
}
//Szykowanie zapytań
//Zakres dat
$whereInvoice['ecminvoiceouts'][] = 'register_date>="' . getFormatedDateForDB($date_from) . '"';
$whereInvoice['ecminvoiceouts'][] = 'register_date<="' . getFormatedDateForDB($date_to) . '"';
$whereRecipe['ecmrecipes'][] = 'register_date>="' . getFormatedDateForDB($date_from) . '"';
$whereRecipe['ecmrecipes'][] = 'register_date<="' . getFormatedDateForDB($date_to) . '"';
//Handlowiec
if($_REQUEST['trader'] != ""){
if($_REQUEST['trader'][0]==""){
unset($_REQUEST['trader'][0]);
}
if(count($_REQUEST['trader'])>0){
$whereInvoice['ecminvoiceouts'][] = 'assigned_user_id in ("' . implode('","',$_REQUEST['trader']). '")';
$whereRecipe['ecmrecipes'][] = 'assigned_user_id in ("' . implode('","',$_REQUEST['trader']). '")';
}
}
//Kontrahent
if($_REQUEST['account_id'] != ""){
$whereInvoice['ecminvoiceouts'][] = 'parent_id="' . $_REQUEST['account_id'] . '"';
$whereRecipe['ecmrecipes'][] = 'parent_id="' . $_REQUEST['account_id'] . '"';
}
//Magazyn
$stocks = $_REQUEST['stocks'];
if(count($stocks)>0){
if(in_array("",$stocks)){
$indeks = array_search("",$stocks);
unset($stocks[$indeks]);
}
if(count($stocks)>0){
$stocksList = array();
$value = array_values ( $stocks );
$whereInvoice['ecminvoiceouts'][] = 'stock_id IN ("' . implode('","',$value) . '")';
$whereRecipe['ecmrecipes'][] = 'stock_id IN ("' . implode('","',$value) . '")';
}
}
//Grupa
$product_group = $_REQUEST['product_group'];
if(count($product_group)>0){
if(in_array("",$product_group)){
$indeks = array_search("",$product_group);
unset($product_group[$indeks]);
}
if(count($product_group)>0){
$product_group_list = array();
$value = array_values ( $product_group );
$whereInvoice['ecmproducts'][] = 'ks_group IN ("' . implode('","',$value) . '")';
$whereRecipe['ecmproducts'][] = 'ks_group IN ("' . implode('","',$value) . '")';
}
}
// Typ PDF
$pdf_type = $_REQUEST['pdf_type'];
if(count($pdf_type)>0){
if(in_array("",$pdf_type)){
$indeks = array_search("",$pdf_type);
unset($pdf_type[$indeks]);
}
if(count($pdf_type)>0){
$product_group_list = array();
$value = array_values ( $pdf_type );
$whereInvoice['ecmproducts'][] = 'pdf_type IN ("' . implode('","',$value) . '")';
// $whereRecipe['ecmproducts'][] = 'pdf_type IN ("' . implode('","',$value) . '")';
}
}
//Typ dokumentu
$document_sales_type = $_REQUEST['document_sales_type'];
if(count($document_sales_type)>0){
if(in_array("",$document_sales_type)){
$indeks = array_search("",$document_sales_type);
unset($document_sales_type[$indeks]);
}
if(count($document_sales_type)>0){
$tmpInvoiceType = array();
$tmpRecipeType = array();
$receiptDo = false;
$invoceDo = true;
foreach($document_sales_type as $key => $value){
switch($value){
case 'invoice':
$tmpInvoiceType[] = 'normal';
$invoceDo = true;
break;
case 'invoice_correct':
$invoceDo = true;
$tmpInvoiceType[] = 'correct';
break;
case 'recipe':
$receiptDo = true;
$tmpRecipeType[] = 'normal';
break;
case 'recipe_correct':
$receiptDo = true;
$tmpRecipeType[] = 'correct';
break;
}
}
if(count($tmpInvoiceType)>0){
$value = array_values ( $tmpInvoiceType );
$whereInvoice['ecminvoiceouts'][] = 'type IN ("' . implode('","',$value) . '")';
$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
}
if(count($tmpRecipeType)>0){
$value = array_values ( $tmpRecipeType );
$whereRecipe['ecmrecipes'][] = 'type IN ("' . implode('","',$value) . '")';
$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}
}else{
$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}
}else{
$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}
// Przetwarzanie danych
$data = array();
foreach($dataInvoice as $indeks => $invoice){
if($invoice['document_type'] == 'EcmInvoiceOuts'){
$docname = 'Faktura';
}elseif($invoice['document_type'] == 'EcmReceipts'){
$docname .= 'Paragon';
}
if($invoice['type'] == 'correct'){
$docname .= ' Korekta';
}
$docname .= " " . $invoice['document_no'];
$data[$invoice['id']]['name'] = '<a target="_blank" href="index.php?module=' . $invoice['document_type'] . '&action=DetailView&parentTab=Sprzedaż&record=' . $invoice['id'] . '">' . $docname . '</a>';
$data[$invoice['id']]['register_date'] = getFormatedDateForView($invoice['register_date']);
$data[$invoice['id']]['total_netto'] += $invoice['total_netto']*($invoice['currency_value_nbp']!="" ? $invoice['currency_value_nbp'] : 1);
$data[$invoice['id']]['total_brutto'] += $invoice['total_brutto']*($invoice['currency_value_nbp']!="" ? $invoice['currency_value_nbp'] : 1);
foreach($invoice['position_list'] as $k => $v){
$data[$invoice['id']]['price_purchase'] += $v['position_total_price_purchase'];
}
$data[$invoice['id']]['parent_name'] = '<a target="_blank" href="index.php?module=Accounts&return_module=Account&action=DetailView&parentTab=Kontakty&record=' . $invoice['parent_id'] . '">' . $invoice['parent_name'] . '</a>';
if($_REQUEST['to_xls']=='1'){
$data[$invoice['id']]['parent_name']= $invoice['parent_name'];
$data[$invoice['id']]['name'] =$docname;
}
}
foreach($dataRecipe as $indeks => $invoice){
if($invoice['document_type'] == 'EcmInvoiceOuts'){
$docname = 'Faktura';
}elseif($invoice['document_type'] == 'EcmReceipts'){
$docname = 'Paragon';
}
if($invoice['type'] == 'correct'){
$docname .= ' Korekta';
}
//print_r($invoice);print_r('<br><br>');
//print_r($invoice['position_total_price_purchase']);;print_r('<br><br>');
$docname .= " " . $invoice['document_no'];
$data[$invoice['id']]['name'] = '<a target="_blank" href="index.php?module=' . $invoice['document_type']. '&action=DetailView&parentTab=Sprzedaż&record=' . $invoice['id'] . '">' . $docname . '</a>';
$data[$invoice['id']]['register_date'] = getFormatedDateForView($invoice['register_date']);
$data[$invoice['id']]['total_netto'] += $invoice['total_netto']*($invoice['currency_value_nbp']!="" ? $invoice['currency_value_nbp'] : 1);
$data[$invoice['id']]['total_brutto'] += $invoice['total_brutto']*($invoice['currency_value_nbp']!="" ? $invoice['currency_value_nbp'] : 1);
foreach($invoice['position_list'] as $k => $v){
$data[$invoice['id']]['price_purchase'] += $v['position_total_price_purchase'];
}
$data[$invoice['id']]['parent_name'] = '<a target="_blank" href="index.php?module=Accounts&return_module=Account&action=DetailView&parentTab=Kontakty&record=' . $invoice['parent_id'] . '">' . $invoice['parent_name'] . '</a>';
if($_REQUEST['to_xls']=='1'){
$data[$invoice['id']]['parent_name']= $invoice['parent_name'];
$data[$invoice['id']]['name'] =$docname;
}
}
//
//Szykowanie wyświetlania
$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("APP_LIST_STRINGS", $app_list_strings);
$smarty->assign("DATA", $data);
$smarty->assign("TRADERS_LIST", $trader_array);
$smarty->assign("STOCK_LIST", $stock_array);
//Ustawiamy przeslane dane
//$date_from = $GLOBALS['timedate']->to_display_date($date_from);
//$date_to = $GLOBALS['timedate']->to_display_date($date_to);
$smarty->assign("date_from_value", $date_from );
$smarty->assign("date_to_value", $date_to );
$smarty->assign("TRADER_SELECTED", $_REQUEST['trader']);
$smarty->assign("account_invoice_type_dom", $app_list_strings['account_invoice_type_dom']);
$smarty->assign("STOCK_SELECTED", $_REQUEST['stocks']);
$smarty->assign("PRODUCT_GROUP_SELECTED", $_REQUEST['product_group']);
$smarty->assign("DOCUMENT_SALES_SELECTED", $_REQUEST['document_sales_type']);
$smarty->assign("PDF_TYPE_SELECTED", $_REQUEST['pdf_type']);
$smarty->assign("ACCOUNT_ID", $_REQUEST['account_id']);
$smarty->assign("ACCOUNT_NAME", $_REQUEST['account_name']);
if($_REQUEST['to_pdf']!='1'){
echo $smarty->display('modules/EcmReports/tpls/ReportSalesByDocument.tpl');
}else{
if($_REQUEST['to_xls']=='1'){
$header=array();
$header[]='dokument';
$header[]='data dokumentu';
$header[]='kontrahent';
$header[]='sprzedaż netto';
$header[]='sprzedaż brutto';
$header[]='koszt zakupu';
$header[]='dochód';
$filename='modules/Home/Files/raport_sprzedazy_wartosciowy_'.date('d_m-Y').'.csv';
$fp=fopen($filename,'w');
foreach ($header as $k=>$v){
$header[$k]=iconv('UTF-8','windows-1250',$header[$k]);
}
fwrite($fp, implode(";",$header).PHP_EOL);
foreach ($data as $key=>$val){
$line=array();
$line[]=$val['name'];
$line[]=$val['register_date'];
$line[]=preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['parent_name'])));
$line[]=str_replace(".",",",$val['total_netto']);
$line[]=str_replace(".",",",$val['total_brutto']);
$line[]=str_replace(".",",",$val['price_purchase']);
$line[]=str_replace(".",",",$val['total_netto']-$val['price_purchase']);
foreach ($line as $k=>$v){
$line[$k]=iconv('UTF-8','windows-1250',$line[$k]);;
}
fwrite($fp, implode(";",$line).PHP_EOL);
}
print $filename;
} else {
include_once ("include/MPDF57/mpdf.php");
include_once ("modules/EcmSysInfos/EcmSysInfo.php");
$EcmSysInfos = new EcmSysInfo();
$content = $smarty->fetch('modules/EcmReports/tpls/ReportSalesByDocumentPDF.tpl');
$mPDF = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 10, 10, 5, 5 );
$mPDF->mirrorMargins = 1;
$mPDF->WriteHTML($content);
$dir = 'upload/' . $EcmSysInfos->getDatabaseName() . '/pdf/EcmReports/';
if(!is_dir($dir)){
mkdir($dir, '755', true);
}
$file_name = $dir . str_replace(".","",$date_from) . "_" . str_replace(".","",$date_to) ."_Raport_Sprzedazy_Raport_wartosciowy.pdf";
$mPDF->Output( $file_name, "F");
print $file_name;
}
}
function getFormatedDateForDB($data){
if(strpos($data,".")>0){
$split = explode (".",$data);
$return_data = $split[2] . "-" . $split[1] . "-" .$split['0'];
}
return $return_data;
}
function getFormatedDateForView($data){
if(strpos($data,"-")>0){
$split = explode ("-",$data);
$return_data = $split[2] . "." . $split[1] . "." .$split['0'];
}
return $return_data;
}

View File

@@ -0,0 +1,999 @@
<?php
//ini_set('display_errors', 1);
// ini_set('error_reporting', E_ALL);
// ini_set('display_startup_errors', 1);
global $mod_strings, $app_list_strings, $db;
$db = $GLOBALS['db'];
// Filters for query
// Array with months
$array_months = [
1 => 'Styczeń',
2 => 'Luty',
3 => 'Marzec',
4 => 'Kwiecień',
5 => 'Maj',
6 => 'Czerwiec',
7 => 'Lipec',
8 => 'Sierpień',
9 => 'Wrzesień',
10 => 'Październik',
11 => 'Listopad',
12 => 'Grudzizeń'
];
$whereFilter = "";
$whereFilterBranch2 = "";
$otherGroupFilter = "";
$relationsQuery = " FROM `ecminvoiceouts`
INNER JOIN `accounts` ON
(accounts.id = ecminvoiceouts.parent_id)
INNER JOIN `ecminvoiceoutitems` ON
(ecminvoiceoutitems.ecminvoiceout_id = ecminvoiceouts.id)
INNER JOIN `ecmproducts` ON
(ecmproducts.id = ecminvoiceoutitems.ecmproduct_id)
" /*. $relationsQueryReceipts*/ . "
";
$relationsQueryRec = " FROM `ecmreceipts`
INNER JOIN `accounts` ON
(accounts.id = ecmreceipts.parent_id)
INNER JOIN `ecmreceiptitems` ON
(ecmreceiptitems.ecmreceipt_id = ecmreceipts.id)
INNER JOIN `ecmproducts` ON
(ecmproducts.id = ecmreceiptitems.ecmproduct_id)
" /*. $relationsQueryReceipts*/ . "
";
$dataInvoice = EcmInvoiceOut::getInvoiceList();
$dataRecipe = EcmReceipt::getReceiptsList();
print_r($dataInvoice);
function get_items_fk( $request,$db,$whereFilter,$whereFilterBranch2,$otherGroupFilter,$relationsQuery){
// Years and months
$years_group = isset($request['years_group']) ? $request['years_group'] : [0];
$months_group = isset($request['months_group']) ?$request['months_group'] : [0];
$document_type=isset($request['document_sales_type']) ? $request['document_sales_type'] : ['invoice','invoice_correct','recipe','recipe_correct'];
if((count($years_group) > 0) AND (count($months_group) > 0)){
$_months_group = strlen($months_group[0]) == 1 ? '0'.$months_group[0] : $months_group[0];
$value = $years_group[0] . '-' . $_months_group;
$whereFilter .= ' AND ecminvoiceouts.register_date >= "' . $value . '" ';
}
//print_r($document_type);
// Types
$types_group = isset($request['types_group']) ? $request['types_group'] : [0];
if(count($types_group) > 0){
if(in_array("",$types_group)){
$index = array_search("",$types_group);
unset($types_group[$index]);
}
if(count($types_group) > 0){
$value = array_values ( $types_group );
//$whereFilter .= ' AND accounts.account_type IN ("' . implode('","',$value) . '") ';
}
}
// Group_ks/*
$product_group = isset($request['product_group']) ?$request['product_group'] : [0];
if(count($product_group) > 0){
if(in_array("",$product_group)){
$index = array_search("",$product_group);
unset($product_group[$index]);
}
if(count($product_group) > 0){
$value = array_values ( $product_group );
$whereFilterBranch2 = $whereFilter;
$otherGroupFilter .= $whereFilter;
//$whereFilter .= ' AND ecmproducts.ks_group IN ("' . implode('","',$value) . '") ';
//$whereFilterBranch2 .= ' AND ecmproducts.ks_group NOT IN ("' . implode('","',$value) . '")';
$otherGroupFilter .= $whereFilterBranch2;
}
}
// Other_group_ks
$other_group_ks_filter = isset($request['product_other_group']) ? $request['product_other_group'] : [0];
if(count($other_group_ks_filter) > 0){
if(in_array("",$other_group_ks_filter)){
$index = array_search("",$other_group_ks_filter);
unset($other_group_ks_filter[$index]);
}
if(count($other_group_ks_filter) > 0){
$value = array_values ( $other_group_ks_filter );
$whereFilterBranch2 .= ' AND ecmproducts.ks_group IN ("' . implode('","',$value) . '") ';
}
}
// Shop
$stocks = isset($request['stocks']) ? $request['stocks'] : [0];
if(count($stocks)>0){
if(in_array("",$stocks)){
$indeks = array_search("",$stocks);
unset($stocks[$indeks]);
}
if(count($stocks)>0){
$stocksList = array();
$value = array_values ( $stocks );
$whereFilter .= ' AND ecminvoiceouts.stock_id IN ("' . implode('","',$value) . '")';
$whereFilterBranch2 .= $whereFilter;
$otherGroupFilter .= $whereFilter;
}
}
// Added to query check deleted and canceled fields
if(in_array('invoice',$document_type)){
$document_types[]='normal';
}
if(in_array('invoice_correct',$document_type)){
$document_types[]='correct';
}
$whereFilter .= "
AND ecminvoiceouts.deleted=0
AND ecminvoiceouts.canceled=0
AND ecminvoiceouts.type in ('".implode("','",$document_types)."')
";
$relationsQueryReceipts = "
";
$total_netto_request = "
ROUND(SUM(
CASE
WHEN ecminvoiceouts.type = 'normal' THEN
ecminvoiceoutitems.total_netto *
CASE WHEN ecminvoiceouts.currency_value_nbp != '' THEN
ecminvoiceouts.currency_value_nbp
ELSE 1
END
ELSE
ecminvoiceoutitems.total_netto_corrected *
CASE WHEN ecminvoiceouts.currency_value_nbp != '' THEN
ecminvoiceouts.currency_value_nbp
ELSE 1
END
END
),2)
";
$pre_table_request = "
SELECT
COUNT(DISTINCT accounts.id) AS `accounts_count2`,
COUNT(ecminvoiceouts.id) AS `ecminvoiceouts_count2`,
MONTH(ecminvoiceouts.register_date) AS `ecminvoiceouts_month2`,
YEAR(ecminvoiceouts.register_date) AS `ecminvoiceouts_year2`,
accounts.account_type AS `accounts_type2`
" . $relationsQuery . "
" . $whereFilter . "
GROUP BY `ecminvoiceouts_year2`, `ecminvoiceouts_month2`, `accounts_type2`
-- ORDER BY `ecminvoiceouts_year2`, `ecminvoiceouts_month2`, `accounts_type2`
";
$pre_table_request_other_groups = "
SELECT
accounts.account_type AS `accounts_type3`,
ecmproducts.ks_group AS `ecmproducts_group_ks3`,
MONTH(ecminvoiceouts.register_date) AS `ecminvoiceouts_month3`,
YEAR(ecminvoiceouts.register_date) AS `ecminvoiceouts_year3`,
" . $total_netto_request . " AS `ecminvoiceouts_total_brutto3`
" . $relationsQuery . "
" . $whereFilterBranch2 . "
";
$pre_table_result_other_groups = $db->query($pre_table_request_other_groups);
while($row = $db->fetchByAssoc($pre_table_result_other_groups)) { $pre_table_result_other_groups_array[] = $row; }
//print_r($pre_table_result_other_groups_array);
// Generate table data
$table_request = "
SELECT
counter.`accounts_count2`,
counter.`ecminvoiceouts_count2`,
accounts.account_type AS `accounts_type`,
ecmproducts.ks_group AS `ecmproducts_group_ks`,
MONTH(ecminvoiceouts.register_date) AS `ecminvoiceouts_month`,
YEAR(ecminvoiceouts.register_date) AS `ecminvoiceouts_year`,
" . $total_netto_request . " AS `ecminvoiceouts_total_brutto`
" . $relationsQuery . "
" . $whereFilter . "
INNER JOIN (" . $pre_table_request . ") AS counter
ON (counter.ecminvoiceouts_year2 = YEAR(ecminvoiceouts.register_date))
AND (counter.ecminvoiceouts_month2 = MONTH(ecminvoiceouts.register_date))
AND (counter.accounts_type2 = accounts.account_type)
GROUP BY `ecminvoiceouts_year`, `ecminvoiceouts_month`, `accounts_type`, `ecmproducts_group_ks`
-- ORDER BY `ecminvoiceouts_year`, `ecminvoiceouts_month`, `accounts_type`, `ecmproducts_group_ks`
";
//print_r('<pre>');
//print_r($table_request);
$table_result = $db->query($table_request);
while($row = $db->fetchByAssoc($table_result)) { $table_result_array[] = $row; }
// Initial variable for generate array
// If table_result is not empty
if(!empty($table_result_array)):
// Genarate main array
foreach ($table_result_array as $table_key => $table) {
if(empty($pre_table_result_other_groups_array)) { $pre_table_result_other_groups_array = []; }
foreach ($pre_table_result_other_groups_array as $pre_table_key => $pre_table) {
$generate_table_array
[$table['ecminvoiceouts_year']]
[$table['ecminvoiceouts_month']]
[$table['accounts_type']]
['accounts_count'] = $table['accounts_count2'];
$generate_table_array
[$table['ecminvoiceouts_year']]
[$table['ecminvoiceouts_month']]
[$table['accounts_type']]
['documents_count'] = $table['ecminvoiceouts_count2'];
$generate_table_array
[$table['ecminvoiceouts_year']]
[$table['ecminvoiceouts_month']]
[$table['accounts_type']]
['accounts_type']
[$table['ecmproducts_group_ks']] = $table['ecminvoiceouts_total_brutto'];
if(!empty($pre_table_result_other_groups_array)) {
if(
$table['ecminvoiceouts_year'] == $pre_table['ecminvoiceouts_year3'] &&
$table['ecminvoiceouts_month'] == $pre_table['ecminvoiceouts_month3'] &&
$table['accounts_type'] == $pre_table['accounts_type3']
) {
$generate_table_array
[$table['ecminvoiceouts_year']]
[$table['ecminvoiceouts_month']]
[$table['accounts_type']]
['together'] = $pre_table['ecminvoiceouts_total_brutto3'];
}
}
}
}
endif;
if (isset($generate_table_array) && count($generate_table_array)>0){
return $generate_table_array;
}else{
return [];
}
}
//koniec fk
// poczatek paragony
function get_items_rec( $request,$db,$whereFilter,$whereFilterBranch2,$otherGroupFilter,$relationsQuery){
// Years and months
$years_group = isset($request['years_group']) ? $request['years_group'] : [0];
$months_group = isset($request['months_group']) ?$request['months_group'] : [0];
$document_type=isset($request['document_sales_type']) ? $request['document_sales_type'] : [0];
if((count($years_group) > 0) AND (count($months_group) > 0)){
$_months_group = strlen($months_group[0]) == 1 ? '0'.$months_group[0] : $months_group[0];
$value = $years_group[0] . '-' . $_months_group;
$whereFilter .= ' AND ecmreceipts.register_date >= "' . $value . '" ';
}
//print_r($document_type);
// Types
$types_group = isset($request['types_group']) ? $request['types_group'] : [0];
if(count($types_group) > 0){
if(in_array("",$types_group)){
$index = array_search("",$types_group);
unset($types_group[$index]);
}
if(count($types_group) > 0){
$value = array_values ( $types_group );
//$whereFilter .= ' AND accounts.account_type IN ("' . implode('","',$value) . '") ';
}
}
// Group_ks
$product_group = isset($request['product_group']) ?$request['product_group'] : [0];
if(count($product_group) > 0){
if(in_array("",$product_group)){
$index = array_search("",$product_group);
unset($product_group[$index]);
}
if(count($product_group) > 0){
$value = array_values ( $product_group );
$whereFilterBranch2 = $whereFilter;
$otherGroupFilter .= $whereFilter;
//$whereFilter .= ' AND ecmproducts.ks_group IN ("' . implode('","',$value) . '") ';
//$whereFilterBranch2 .= ' AND ecmproducts.ks_group NOT IN ("' . implode('","',$value) . '")';
$otherGroupFilter .= $whereFilterBranch2;
}
}
// Other_group_ks
$other_group_ks_filter = isset($request['product_other_group']) ? $request['product_other_group'] : [0];
if(count($other_group_ks_filter) > 0){
if(in_array("",$other_group_ks_filter)){
$index = array_search("",$other_group_ks_filter);
unset($other_group_ks_filter[$index]);
}
if(count($other_group_ks_filter) > 0){
$value = array_values ( $other_group_ks_filter );
//$whereFilterBranch2 .= ' AND ecmproducts.ks_group IN ("' . implode('","',$value) . '") ';
}
}
// Shop
$stocks = isset($request['stocks']) ? $request['stocks'] : [0];
if(count($stocks)>0){
if(in_array("",$stocks)){
$indeks = array_search("",$stocks);
unset($stocks[$indeks]);
}
if(count($stocks)>0){
$stocksList = array();
$value = array_values ( $stocks );
$whereFilter .= ' AND ecmreceipts.stock_id IN ("' . implode('","',$value) . '")';
$whereFilterBranch2 .= $whereFilter;
$otherGroupFilter .= $whereFilter;
}
}
// Added to query check deleted and canceled fields
if(in_array('recipe',$document_type)){
$document_types[]='normal';
}
if(in_array('recipe_correct',$document_type)){
$document_types[]='correct';
}
$whereFilter .= "
AND ecmreceipts.deleted=0
AND ecmreceipts.canceled=0
AND ecmreceipts.type in ('".implode("','",$document_types)."')
";
$relationsQueryReceipts = "
";
$total_netto_request = "
ROUND(SUM(
CASE
WHEN ecmreceipts.type = 'normal' THEN
ecmreceiptitems.total_netto *
CASE WHEN 0 THEN
1
ELSE 1
END
ELSE
ecmreceiptitems.total_netto_corrected *
CASE WHEN 0 THEN
1
ELSE 1
END
END
),2)
";
$pre_table_request = "
SELECT
COUNT(DISTINCT accounts.id) AS `accounts_count2`,
COUNT(ecmreceipts.id) AS `ecminvoiceouts_count2`,
MONTH(ecmreceipts.register_date) AS `ecminvoiceouts_month2`,
YEAR(ecmreceipts.register_date) AS `ecminvoiceouts_year2`,
accounts.account_type AS `accounts_type2`
" . $relationsQuery . "
" . $whereFilter . "
GROUP BY `ecminvoiceouts_year2`, `ecminvoiceouts_month2`, `accounts_type2`
-- ORDER BY `ecminvoiceouts_year2`, `ecminvoiceouts_month2`, `accounts_type2`
";
$pre_table_request_other_groups = "
SELECT
accounts.account_type AS `accounts_type3`,
ecmproducts.ks_group AS `ecmproducts_group_ks3`,
MONTH(ecmreceipts.register_date) AS `ecminvoiceouts_month3`,
YEAR(ecmreceipts.register_date) AS `ecminvoiceouts_year3`,
" . $total_netto_request . " AS `ecminvoiceouts_total_brutto3`
" . $relationsQuery . "
" . $whereFilterBranch2 . "
";
$pre_table_result_other_groups = $db->query($pre_table_request_other_groups);
while($row = $db->fetchByAssoc($pre_table_result_other_groups)) { $pre_table_result_other_groups_array[] = $row; }
//print_r($pre_table_result_other_groups_array);
// Generate table data
$table_request = "
SELECT
counter.`accounts_count2`,
counter.`ecminvoiceouts_count2`,
accounts.account_type AS `accounts_type`,
ecmproducts.ks_group AS `ecmproducts_group_ks`,
MONTH(ecmreceipts.register_date) AS `ecminvoiceouts_month`,
YEAR(ecmreceipts.register_date) AS `ecminvoiceouts_year`,
" . $total_netto_request . " AS `ecminvoiceouts_total_brutto`
" . $relationsQuery . "
" . $whereFilter . "
INNER JOIN (" . $pre_table_request . ") AS counter
ON (counter.ecminvoiceouts_year2 = YEAR(ecmreceipts.register_date))
AND (counter.ecminvoiceouts_month2 = MONTH(ecmreceipts.register_date))
AND (counter.accounts_type2 = accounts.account_type)
GROUP BY `ecminvoiceouts_year`, `ecminvoiceouts_month`, `accounts_type`, `ecmproducts_group_ks`
-- ORDER BY `ecminvoiceouts_year`, `ecminvoiceouts_month`, `accounts_type`, `ecmproducts_group_ks`
";
$table_result = $db->query($table_request);
while($row = $db->fetchByAssoc($table_result)) { $table_result_array[] = $row; }
// Initial variable for generate array
// If table_result is not empty
if(!empty($table_result_array)):
// Genarate main array
foreach ($table_result_array as $table_key => $table) {
if(empty($pre_table_result_other_groups_array)) { $pre_table_result_other_groups_array = []; }
foreach ($pre_table_result_other_groups_array as $pre_table_key => $pre_table) {
$generate_table_array
[$table['ecminvoiceouts_year']]
[$table['ecminvoiceouts_month']]
[$table['accounts_type']]
['accounts_count'] = $table['accounts_count2'];
$generate_table_array
[$table['ecminvoiceouts_year']]
[$table['ecminvoiceouts_month']]
[$table['accounts_type']]
['documents_count'] = $table['ecminvoiceouts_count2'];
$generate_table_array
[$table['ecminvoiceouts_year']]
[$table['ecminvoiceouts_month']]
[$table['accounts_type']]
['accounts_type']
[$table['ecmproducts_group_ks']] = $table['ecminvoiceouts_total_brutto'];
if(!empty($pre_table_result_other_groups_array)) {
if(
$table['ecminvoiceouts_year'] == $pre_table['ecminvoiceouts_year3'] &&
$table['ecminvoiceouts_month'] == $pre_table['ecminvoiceouts_month3'] &&
$table['accounts_type'] == $pre_table['accounts_type3']
) {
$generate_table_array
[$table['ecminvoiceouts_year']]
[$table['ecminvoiceouts_month']]
[$table['accounts_type']]
['together'] = $pre_table['ecminvoiceouts_total_brutto3'];
}
}
}
}
endif;
if (isset($generate_table_array) && count($generate_table_array)>0){
return $generate_table_array;
}else{
return [];
}
}
//koniec paragony
// Get all groups from ecmproducts table (with filter)
$group_ks = [];
$group_ks_result = $db->query("SELECT DISTINCT `ks_group` " . $relationsQuery . " " . $whereFilter . " ORDER BY `ks_group`");
while($row = $db->fetchByAssoc($group_ks_result)) { $group_ks[$row['ks_group']] = $app_list_strings['ecmproducts_group_ks_dom'][ $row['ks_group'] ]; }
// Get all groups from ecmproducts table (without filter)
$group_ks_without_filter = [];
$group_ks_result_without_filter = $db->query("SELECT DISTINCT `ks_group` " . $relationsQuery . " ORDER BY `ks_group`");
while($row = $db->fetchByAssoc($group_ks_result_without_filter)) { $group_ks_without_filter[$row['ks_group']] = $app_list_strings['ecmproducts_group_ks_dom'][ $row['ks_group'] ]; }
// Get groups that is not selected from ecmproducts table
$other_group_ks = [];
$other_group_ks_result = $db->query("SELECT DISTINCT `ks_group` " . $relationsQuery . " " . $otherGroupFilter . " ORDER BY `ks_group`");
while($row = $db->fetchByAssoc($other_group_ks_result)) { $other_group_ks[$row['ks_group']] = $app_list_strings['ecmproducts_group_ks_dom'][ $row['ks_group'] ]; }
// Get all types from accounts table (filter)
$types = [];
$types_result = $db->query("SELECT DISTINCT accounts.account_type " . $relationsQuery . " ORDER BY `account_type`");
while($row = $db->fetchByAssoc($types_result)) { $types[$row['account_type']] = $app_list_strings['account_type_dom'][ $row['account_type'] ]; }
//Get Stock List
$stock_array = array(""=>"");
$stock_request = $db->query("SELECT id, name FROM ecmstocks WHERE deleted=0");
while($row = $db->fetchByAssoc($stock_request)){ $stock_array[$row['id']] = $row['name']; }
// Get years from ecminvoiceouts table
$years = [];
$years_result = $db->query("SELECT DISTINCT YEAR(ecminvoiceouts.register_date) AS `years` " . $relationsQuery . " ORDER BY `years`");
while($row = $db->fetchByAssoc($years_result)) { $years[] = $row['years']; }
// Get months from ecminvoiceouts table
$months = [];
$months_result = $db->query("SELECT DISTINCT MONTH(ecminvoiceouts.register_date) AS `months` " . $relationsQuery . " ORDER BY `months`");
while($row = $db->fetchByAssoc($months_result)) { $months[$row['months']] = $row['months']; }
// Generate file pdf
function pdf($smarty) {
include_once ("include/MPDF60/mpdf60/mpdf.php");
include_once ("modules/EcmSysInfos/EcmSysInfo.php");
$EcmSysInfos = new EcmSysInfo();
if(!$_REQUEST['date_from']) {
$date_from = date("01.m.Y");
} else {
$date_from = $_REQUEST["date_from"];
}
if(!$_REQUEST['date_to']) {
$date_to = date("d.m.Y");
} else {
$date_to = $_REQUEST["date_to"];
}
$content = $smarty->fetch('modules/EcmReports/tpls/ReportSalesByGroupPDF.tpl');
$mPDF = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 10, 10, 5, 5 );
$mPDF->mirrorMargins = 1;
//print_r($content);
$mPDF->WriteHTML($content);
$dir = 'upload/' . $EcmSysInfos->getDatabaseName() . '/pdf/EcmReports/';
if(!is_dir($dir)){
mkdir($dir, '755', true);
}
$file_name = str_replace(".","",$date_from) . "_" . str_replace(".","",$date_to) ."_Raport_Sprzedazy_Po_Gropach.pdf";
$mPDF->Output( $file_name, "F");
print $file_name;
}
// Generate JSON-array for Chart
function chart_json($generate_table_array, $group_ks, $types,$req) {
$chart_column = !empty($_REQUEST['chart_column'][0]) ? $_REQUEST['chart_column'] : ["1efd09c99174463e7f3a81d80c4d6668"];
$group_ks_column = $chart_column[0];
if(!empty($_REQUEST['types_group'][0])) {
// Translate all index in text
foreach ($_REQUEST['types_group'] as $types_request_key => $type_request) {
$types_request[$types_request_key] = $types[$type_request];
}
} elseif(isset($types)) {
$types_request = $types;
} else {
$types_request[] = '';
};
$head[] = 'Data';
foreach ($types_request as $type_request) { $head[] = $type_request; }
$head[]='total';
// Add header to main array
// Generate array
$count=1;
$arr[0] = $head;
foreach ($generate_table_array as $year_key => $year) {
foreach ($year as $month_key => $month) {
$ccc=0;
$i=0;
foreach ($month as $type_key => $types_val) {
//print_r($type_key);print_r('<br><br>');
//print_r($types_val);print_r('<br><br>');
if($ccc == 0) {
$arr[$count][] = $year_key."-".$month_key; // date
$ccc++;
}
if($group_ks_column == 'accounts_count' ||$group_ks_column == 'documents_count') {
$arr[$count][] = (int)$types_val[$group_ks_column];
}
elseif($group_ks_column=='suma'){
if(in_array($type_key,$req)){
$arr[$count][]=$types_val['accounts_type']['total'];
}
//print_r($types_val);
}
else {
foreach ($types_val['accounts_type'] as $groups_key => $groups_val) {
$name=$types[$type_key];
$kx=array_search($name,$head);
if($type_key=='suma' || $type_key=='total'){
$kx=count($head)-1;
}
//var_dump($kx);
//print_r('<br><br>');
//var_dump($groups_val);print_r('<br><br>');
if($kx!=0){
if($groups_key == $group_ks_column ) {
$arr[$count][$kx] = (int)$groups_val;
}
}
}
}
}
$count++;
}
}
$header_count=0;
foreach($arr as $a_key => $a) {
$max=count($head);
for($i=0;$i<$max;$i++){
if(!isset($arr[$a_key][$i])){
$arr[$a_key][$i]=0;
}
}
//$arr[$a_key]
}
echo json_encode($arr);
//echo "<pre>";
//echo json_encode($arr);
}
// Genearte file xls
function xsl($group_ks, $array_months, $types, $generate_table_array) {
$filename='modules/Home/Files/raport_sprzedazy_w_groupach_'.date('d_m-Y').'.csv';
$fp = fopen($filename,'w');
$header = generate_header($group_ks);
$line = generate_line($group_ks, $array_months, $types, $generate_table_array);
fwrite($fp, implode(";", $header).PHP_EOL);
foreach ($line as $l) {
$l = coding($l);
fwrite($fp, implode(";", $l).PHP_EOL);
}
print $filename;
}
// Generate header for xls file
function generate_header($group_ks) {
$header = [];
$header[] = 'ROK';
$header[] = 'MIESIĄC';
$header[] = 'PROFIL GŁÓWNY';
$header[] = 'ILU ODBIORCÓW W LICZBACH';
$header[] = 'ILE DOKUMENTÓW';
foreach ($group_ks as $list_group_k) { $header[] = $list_group_k; }
return $header;
}
// Genearte body for xls file
function generate_line($group_ks, $array_months, $types, $generate_table_array) {
$line = [];
foreach ($generate_table_array as $year_key => $year) {
foreach ($year as $month_key => $month) {
foreach ($month as $type_key => $type) {
$line[$year_key."_".$month_key."_".$type_key]['ecminvoiceouts_year'] = $year_key;
$line[$year_key."_".$month_key."_".$type_key]['ecminvoiceouts_month'] = $array_months[$month_key];
$line[$year_key."_".$month_key."_".$type_key]['accounts_type'] = $types[$type_key];
$line[$year_key."_".$month_key."_".$type_key]['accounts_count'] = $type['accounts_count'];
$line[$year_key."_".$month_key."_".$type_key]['documents_count'] = $type['documents_count'];
foreach ($group_ks as $groups_key => $groups) {
$count=0;
foreach ($type['accounts_type'] as $group_key => $group) {
if($groups_key == $group_key) {
$count=1;
$line[$year_key."_".$month_key."_".$type_key][$group_key] = $group;
}
}
if($count == 0) {
$line[$year_key."_".$month_key."_".$type_key][$groups_key] = '';
}
}
}
}
}
return $line;
}
function coding_pl($variable) {
return preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/", ' ', preg_replace("/\r\n|\r|\n/", ' ', html_entity_decode($variable)));
}
// UTF-8 -> Windows-1250
function coding($data) {
foreach ($data as $k=>$v){
$data[$k]=iconv('UTF-8', 'windows-1250', $data[$k]);;
}
return $data;
}
$generate_table_array=[];
$document_type=isset($_REQUEST['document_sales_type']) ? $_REQUEST['document_sales_type'] : ['invoice','invoice_correct','recipe','recipe_correct'];
if(count($_REQUEST)>2){
if(in_array('invoice',$document_type) ||in_array('invoice_correct',$document_type) ){
$generate_table_array_fk=get_items_fk($_REQUEST,$db,$whereFilter,$whereFilterBranch2,$otherGroupFilter,$relationsQuery);
}
if(in_array('recipe',$document_type) ||in_array('recipe_correct',$document_type) ){
$generate_table_array_rec=get_items_rec($_REQUEST,$db,$whereFilter,$whereFilterBranch2,$otherGroupFilter,$relationsQueryRec);
}
//print_r($generate_table_array_fk);
if(!isset($generate_table_array_fk) || count($generate_table_array_fk)==0){
$generate_table_array=$generate_table_array_rec;
}elseif(!isset($generate_table_array_rec) || count($generate_table_array_rec)==0){
$generate_table_array=$generate_table_array_fk;
}else{
$generate_table_array=$generate_table_array_fk;
foreach ($generate_table_array_rec as $key =>$value){
if(isset($generate_table_array[$key])){
foreach($value as $miech =>$reszta){
if(isset($generate_table_array[$key][$miech])){
foreach($reszta as $kont =>$data){
if(isset($generate_table_array[$key][$miech][$kont])){
$generate_table_array[$key][$miech][$kont]['accounts_count']+=$data['accounts_count'];
$generate_table_array[$key][$miech][$kont]['documents_count']+=$data['documents_count'];
foreach($data['accounts_type'] as $grupa =>$ilosc){
if(isset($generate_table_array[$key][$miech][$kont]['accounts_type'][$grupa])){
$generate_table_array[$key][$miech][$kont]['accounts_type'][$grupa]+=$ilosc;
}
}
}
}
}
}
}
}//koniec foreacha glownego
}// koniec elsa
}
//dodawanie sumy na koncu
//print_r($_REQUEST['types_group_sum']);
foreach($generate_table_array as $rok=>$data_rok){
foreach($data_rok as $miech=>$data_miech ){
foreach($data_miech as $typ_gs => $data_type_gs){
$total_sum_group=0;
//print_r($data_type_gs);print_r('<br><br>');
if(!in_array($typ_gs,$_REQUEST['types_group'])){
if(!isset($generate_table_array[$rok][$miech]['suma'])){
$generate_table_array[$rok][$miech][suma] = array();
}
$generate_table_array[$rok][$miech]['suma']['accounts_count']+=$data_type_gs['accounts_count'];
$generate_table_array[$rok][$miech]['suma']['documents_count']+=$data_type_gs['documents_count'];
}
foreach($data_type_gs['accounts_type'] as $sum_k => $sum_data){
// sumowanie w kolumnach
if(!in_array($typ_gs,$_REQUEST['types_group'])){
$generate_table_array[$rok][$miech]['suma']['accounts_type'][$sum_k]+=$sum_data;
}
}
}
}
}//koniec glownego foreacha
foreach($generate_table_array as $rok=>$data_rok){
//sumowanie w wierszach
foreach($data_rok as $miech=>$data_miech ){
foreach($data_miech as $typ_gs => $data_type_gs){
foreach($data_type_gs['accounts_type'] as $sum_k => $sum_data){
if(!in_array($sum_k,$_REQUEST['product_group'])){
if(!isset($generate_table_array[$rok][$miech][$typ_gs]['accounts_type']['total'])){
$generate_table_array[$rok][$miech][$typ_gs]['accounts_type']['total'] = 0;
}
$generate_table_array[$rok][$miech][$typ_gs]['accounts_type']['total']+=$sum_data;
}
}
}
}
}//koniec glownego foreacha
$smarty = new Sugar_Smarty ();
// Variables for Smarty (tpl)
$smarty->assign("MOD", $mod_strings);
$smarty->assign("APP_LIST_STRINGS", $app_list_strings);
$smarty->assign("table_array", $generate_table_array);
//print_r($generate_table_array);
$req=$_REQUEST['types_group'];
$req[]='suma';
$req_prod=$_REQUEST['product_group'];
$req_prod[]='total';
$smarty->assign("list_types", $types);
$smarty->assign("list_group_ks", $group_ks);
$smarty->assign("list_group_ks_without_filter", $group_ks_without_filter);
$smarty->assign("list_other_group_ks", $other_group_ks);
$smarty->assign('types_group_req',$req);
$smarty->assign('types_prod_req',$req_prod);
$smarty->assign("list_years", $years);
$smarty->assign("list_months", $months);
$smarty->assign("months", $array_months);
$smarty->assign("stock_array", $stock_array);
$_REQUEST['to_xls'] = isset($_REQUEST['to_xls']) ? $_REQUEST['to_xls'] : null;
$_REQUEST['to_json'] = isset($_REQUEST['to_json']) ? $_REQUEST['to_json'] : null;
$_REQUEST['to_pdf_gen'] = isset($_REQUEST['to_pdf_gen']) ? $_REQUEST['to_pdf_gen'] : null;
$_REQUEST['to_chart'] = isset($_REQUEST['to_chart']) ? $_REQUEST['to_chart'] : null;
// All pages
if($_REQUEST['to_xls'] == '1') { xsl($group_ks, $array_months, $types, $generate_table_array); }
elseif($_REQUEST['to_pdf_gen'] == '1') { pdf($smarty); }
elseif($_REQUEST['to_json'] == '1') {
//print_r($generate_table_array);
chart_json($generate_table_array, $group_ks, $types,$req); }
elseif($_REQUEST['to_chart'] == '1') { echo $smarty->display('modules/EcmReports/tpls/ReportSalesByGroupChart.tpl'); }
else { echo $smarty->display('modules/EcmReports/tpls/ReportSalesByGroup.tpl'); }

View File

@@ -0,0 +1,381 @@
<?php
global $mod_strings, $app_list_strings, $db;
if(!$_REQUEST['date_from'])
$date_from = date("01.m.Y");
else
$date_from = $_REQUEST["date_from"];
if(!$_REQUEST['date_to'])
$date_to = date("d.m.Y");
else
$date_to = $_REQUEST["date_to"];
if(!class_exists('EcmInvoiceOut')){
include_once('modules/EcmInvoiceouts/EcmInvoiceout.php');
};
if(!class_exists('EcmReceipts')){
include_once('modules/EcmReceipts/EcmReceipt.php');
};
//get trader list
$query_trader = "select ecminvoiceouts.assigned_user_id AS user_id , concat(users.first_name, ' ', users.last_name) AS user_name FROM ecminvoiceouts, users WHERE ecminvoiceouts.deleted = 0 and ecminvoiceouts.canceled = 0 AND users.id = ecminvoiceouts.assigned_user_id group by user_id ORDER BY user_name";
$trader_result = $db->query($query_trader);
$trader_array = array(""=>"&nbsp;");
while($row = $db->fetchByAssoc($trader_result)){
$trader_array[$row['user_id']] = $row['user_name'];
}
//Get Stock List
$query_stock = "Select id, name from ecmstocks where deleted=0";
$stock_result = $db->query($query_stock);
$stock_array = array(""=>"");
while($row = $db->fetchByAssoc($stock_result)){
$stock_array[$row['id']] = $row['name'];
}
$query_stock = "Select account_type from accounts where deleted=0 group by account_type";
$stock_result = $db->query($query_stock);
$account_array = array(""=>"");
while($row = $db->fetchByAssoc($stock_result)){
$account_array[$row['account_type']] =$app_list_strings['account_type_dom'][$row['account_type']];
}
//Szykowanie zapytań
//Zakres dat
$whereInvoice['ecminvoiceouts'][] = 'register_date>="' . getFormatedDateForDB($date_from) . '"';
$whereInvoice['ecminvoiceouts'][] = 'register_date<="' . getFormatedDateForDB($date_to) . '"';
$whereRecipe['ecmrecipes'][] = 'register_date>="' . getFormatedDateForDB($date_from) . '"';
$whereRecipe['ecmrecipes'][] = 'register_date<="' . getFormatedDateForDB($date_to) . '"';
//Handlowiec
if($_REQUEST['trader'] != ""){
if($_REQUEST['trader'][0]==""){
unset($_REQUEST['trader'][0]);
}
if(count($_REQUEST['trader'])>0){
$whereInvoice['ecminvoiceouts'][] = 'assigned_user_id in ("' . implode('","',$_REQUEST['trader']). '")';
$whereRecipe['ecmrecipes'][] = 'assigned_user_id in ("' . implode('","',$_REQUEST['trader']). '")';
}
}
//Kontrahent
if($_REQUEST['account_id'] != ""){
$whereInvoice['ecminvoiceouts'][] = 'parent_id="' . $_REQUEST['account_id'] . '"';
$whereRecipe['ecmrecipes'][] = 'parent_id="' . $_REQUEST['account_id'] . '"';
}
//Magazyn
$stocks = $_REQUEST['stocks'];
if(count($stocks)>0){
if(in_array("",$stocks)){
$indeks = array_search("",$stocks);
unset($stocks[$indeks]);
}
if(count($stocks)>0){
$stocksList = array();
$value = array_values ( $stocks );
$whereInvoice['ecminvoiceouts'][] = 'stock_id IN ("' . implode('","',$value) . '")';
$whereRecipe['ecmrecipes'][] = 'stock_id IN ("' . implode('","',$value) . '")';
}
}
$accounts = $_REQUEST['account_type'];
if(count($accounts)>0){
if(in_array("",$accounts)){
$indeks = array_search("",$accounts);
unset($accounts[$indeks]);
}
if(count($accounts)>0){
$accountsList = array();
$value = array_values ( $accounts );
$whereInvoice['accounts'][] = 'accounts.account_type IN ("' . implode('","',$value) . '")';
}
}
//Grupa
$product_group = $_REQUEST['product_group'];
if(count($product_group)>0){
if(in_array("",$product_group)){
$indeks = array_search("",$product_group);
unset($product_group[$indeks]);
}
if(count($product_group)>0){
$product_group_list = array();
$value = array_values ( $product_group );
$whereInvoice['ecmproducts'][] = 'ks_group IN ("' . implode('","',$value) . '")';
$whereRecipe['ecmproducts'][] = 'ks_group IN ("' . implode('","',$value) . '")';
}
}
$product_group_2 = $_REQUEST['product_group_2'];
if(count($product_group_2)>0){
if(in_array("",$product_group_2)){
$indeks = array_search("",$product_group_2);
unset($product_group_2[$indeks]);
}
if(count($product_group_2)>0){
$product_group_list = array();
$value = array_values ( $product_group_2 );
$whereInvoice['ecmproducts'][] = 'ks_group2 IN ("' . implode('","',$value) . '")';
$whereRecipe['ecmproducts'][] = 'ks_group2 IN ("' . implode('","',$value) . '")';
}
}
//Typ dokumentu
$document_sales_type = $_REQUEST['document_sales_type'];
if(count($document_sales_type)>0){
if(in_array("",$document_sales_type)){
$indeks = array_search("",$document_sales_type);
unset($document_sales_type[$indeks]);
}
if(count($document_sales_type)>0){
$tmpInvoiceType = array();
$tmpRecipeType = array();
$receiptDo = false;
$invoceDo = true;
foreach($document_sales_type as $key => $value){
switch($value){
case 'invoice':
$tmpInvoiceType[] = 'normal';
$invoceDo = true;
break;
case 'invoice_correct':
$invoceDo = true;
$tmpInvoiceType[] = 'correct';
break;
case 'recipe':
$receiptDo = true;
$tmpRecipeType[] = 'normal';
break;
case 'recipe_correct':
$receiptDo = true;
$tmpRecipeType[] = 'correct';
break;
}
}
if(count($tmpInvoiceType)>0){
$value = array_values ( $tmpInvoiceType );
$whereInvoice['ecminvoiceouts'][] = 'type IN ("' . implode('","',$value) . '")';
$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
}
if(count($tmpRecipeType)>0){
$value = array_values ( $tmpRecipeType );
$whereRecipe['ecmrecipes'][] = 'type IN ("' . implode('","',$value) . '")';
$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}
}else{
$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}
}else{
$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}
// Przetwarzanie danych
$data = array();
$total=0;
$total2=0;
$total3=0;
foreach($dataInvoice as $indeks => $invoice){
foreach($invoice['position_list'] as $position => $item){
$data[$item['product_id']]['code'] = '<a target="_blank" href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '">' . $item['position_code'] . '</a>';
$data[$item['product_id']]['index'] = $item['position_code'] ;
$data[$item['product_id']]['nazwa'] = $item['position_name'];
$data[$item['product_id']]['name'] = '<a target="_blank" href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '"> ' . $item['position_name'] . '</a>';
$data[$item['product_id']]['total_netto'] += $item['position_total_netto'];
$data[$item['product_id']]['price_purchase'] += $item['position_total_price_purchase'];
$data[$item['product_id']]['quantity'] += $item['position_quantity'];
$data[$item['product_id']]['jm_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$item['position_unit_id']];
$data[$item['product_id']]['jm_name'] = $item['position_unit_name'];
if($_REQUEST['to_xls']=='1'){
$data[$item['product_id']]['name'] =$item['position_code'] . ' ' . $item['position_name'];
}
$total3+=$item['position_quantity'];
$total+=$item['position_total_netto'];
$total2+=$item['position_total_price_purchase'];
}
}
foreach($dataRecipe as $indeks => $invoice){
foreach($invoice['position_list'] as $position => $item){
$data[$item['product_id']]['code'] = '<a target="_blank" href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '">' . $item['position_code'] . '</a>';
$data[$item['product_id']]['index'] = $item['position_code'] ;
$data[$item['product_id']]['nazwa'] = $item['position_name'];
$data[$item['product_id']]['name'] = '<a target="_blank" href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '"> ' . $item['position_name'] . '</a>';
$data[$item['product_id']]['total_netto'] += $item['position_total_netto'];
$data[$item['product_id']]['price_purchase'] += $item['position_total_price_purchase'];
$data[$item['product_id']]['quantity'] += $item['position_quantity'];
$data[$item['product_id']]['jm_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$item['position_unit_id']];
$data[$item['product_id']]['jm_name'] = $item['position_unit_name'];
if($_REQUEST['to_xls']=='1'){
$data[$item['product_id']]['name'] =$item['position_code'] . ' ' . $item['position_name'];
}
$total3+=$item['position_quantity'];
$total+=$item['position_total_netto'];
$total2+=$item['position_total_price_purchase'];
}
}
//var_dump($data);
//
//Szykowanie wyświetlania
$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("APP_LIST_STRINGS", $app_list_strings);
$sort=$_REQUEST['sort'];
if(count($sort)>0){
foreach($sort as $key=>$val){
switch (strtolower( $key)) {
case 'indeks':
if($val=='ASC'){
usort($data, 'compare_lastname');
}else{
usort($data, 'compare_lastname_desc');
}
break;
case 'nazwa':
if($val=='ASC'){
usort($data, 'compare_nazwa');
}else{
usort($data, 'compare_nazwa_desc');
}
break;
default:
usort($data, 'compare_lastname');
}
}
}
$smarty->assign("DATA", $data);
$smarty->assign("TRADERS_LIST", $trader_array);
$smarty->assign("STOCK_LIST", $stock_array);
$smarty->assign("ACCOUNT_LIST", $account_array);
$smarty->assign("TOTAL", $total);
$smarty->assign("TOTAL2", $total2);
$smarty->assign("TOTAL3", $total3);
//Ustawiamy przeslane dane
//$date_from = $GLOBALS['timedate']->to_display_date($date_from);
//$date_to = $GLOBALS['timedate']->to_display_date($date_to);
$smarty->assign("date_from_value", $date_from );
$smarty->assign("date_to_value", $date_to );
$smarty->assign("TRADER_SELECTED", $_REQUEST['trader']);
$smarty->assign("ACCOUNT_ID", $_REQUEST['account_id']);
$smarty->assign("ACCOUNT_NAME", $_REQUEST['account_name']);
if($_REQUEST['to_pdf']!='1'){
$smarty->assign("STOCK_SELECTED", $_REQUEST['stocks']);
$smarty->assign("ACCOUNT_SELECTED", $_REQUEST['account_type']);
$smarty->assign("PRODUCT_GROUP_SELECTED", $_REQUEST['product_group']);
$smarty->assign("PRODUCT_GROUP_SELECTED_2", $_REQUEST['product_group_2']);
$smarty->assign("DOCUMENT_SALES_SELECTED", $_REQUEST['document_sales_type']);
echo $smarty->display('modules/EcmReports/tpls/ReportSalesByProduct.tpl');
}else{
if($_REQUEST['to_xls']=='1'){
$header=array();
$header[]='index';
$header[]='nazwa';
$header[]='ilość';
$header[]='jm';
$header[]='sprzedaż netto';
$header[]='koszt zakupu';
$header[]='dochód';
$filename='modules/Home/Files/raport_sprzedazy_ilosciowy_'.date('d_m_Y').'.csv';
$fp=fopen($filename,'w');
foreach ($header as $k=>$v){
$header[$k]=iconv('UTF-8','windows-1250',$header[$k]);
}
fwrite($fp, implode(";",$header).PHP_EOL);
foreach ($data as $key=>$val){
$line=array();
$line[]=html_entity_decode($val['index']);
$line[]=preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['name'])));
$line[]=str_replace(".",",",$val['quantity']);
$line[]=$val['jm_name'];
$line[]=str_replace(".",",",$val['total_netto']);
$line[]=str_replace(".",",",$val['price_purchase']);
$line[]=str_replace(".",",",$val['total_netto']-$val['price_purchase']);
foreach ($line as $k=>$v){
$line[$k]=iconv('UTF-8','windows-1250',$line[$k]);;
}
fwrite($fp, implode(";",$line).PHP_EOL);
}
print $filename;
} else {
include_once ("include/MPDF57/mpdf.php");
include_once ("modules/EcmSysInfos/EcmSysInfo.php");
$smarty->assign("STOCK_SELECTED", $stocks);
$smarty->assign("PRODUCT_GROUP_SELECTED", $product_group);
$smarty->assign("DOCUMENT_SALES_SELECTED", $document_sales_type);
$EcmSysInfo = new EcmSysInfo();
$smarty->assign("EcmSysInfo", $EcmSysInfo);
//echo $EcmSysInfo->getName();
$content = $smarty->fetch('modules/EcmReports/tpls/ReportSalesByProductPDF.tpl');
$mPDF = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 10, 10, 5, 5 );
$mPDF->mirrorMargins = 1;
$mPDF->WriteHTML($content);
$dir = 'upload/' . $EcmSysInfo->getDatabaseName() . '/pdf/EcmReports/';
if(!is_dir($dir)){
mkdir($dir, '755', true);
}
$file_name = $dir . str_replace(".","",$date_from) . "_" . str_replace(".","",$date_to) ."_Raport_Sprzedazy_Ilosciowy.pdf";
$mPDF->Output( $file_name, "F");
print $file_name;
}
}
function getFormatedDateForDB($data){
if(strpos($data,".")>0){
$split = explode (".",$data);
$return_data = $split[2] . "-" . $split[1] . "-" .$split['0'];
}
return $return_data;
}
function compare_lastname($a, $b)
{
return strnatcmp($a['index'], $b['index']);
}
function compare_lastname_desc($a, $b)
{
return strnatcmp($b['index'], $a['index']);
}
function compare_nazwa($a, $b)
{
return strnatcmp($a['nazwa'], $b['nazwa']);
}
function compare_nazwa_desc($a, $b)
{
return strnatcmp($b['nazwa'], $a['nazwa']);
}

View File

@@ -0,0 +1,123 @@
<?php
global $mod_strings;
if ($_REQUEST ['date_from'] == "") {
$_REQUEST ['date_from'] = date ( "d.m.Y" );
$date_from = $_REQUEST ['date_from'];
} else {
$date_from = $_REQUEST ['date_from'];
}
if ($_REQUEST ['date_to'] == "") {
$_REQUEST ['date_to'] = date ( "t.m.Y" );
$date_to = $_REQUEST ['date_to'];
} else {
$date_to = $_REQUEST ['date_to'];
}
if(isset($_REQUEST['submit'])){
$db=$GLOBALS['db'];
$query="
SELECT
d.id,
d.document_no,
d.register_date,
d.parent_id,
d.currency_id,
IF(d.currency_id != 'PLN',
d.total_netto * d.currency_value_nbp,
d.total_netto) AS total_netto,
d.parent_name,
IF(d.type = 'normal',
'Normalny',
'Korekta') AS type,
IF(d.currency_id != 'PLN',
d.total_vat * d.currency_value_nbp,
d.total_vat) AS total_vat,
IF(d.currency_id != 'PLN',
d.total_brutto * d.currency_value_nbp,
d.total_brutto) AS total_brutto,
SUM(IF(p.group_ks = 1,
IF(d.currency_id != 'PLN',
if(d.type='normal',i.total_netto,i.total_netto_corrected) * d.currency_value_nbp,
if(d.type='normal',i.total_netto,i.total_netto_corrected)),
0)) AS 'TH',
SUM(IF(p.group_ks = 2, IF(d.currency_id != 'PLN',
if(d.type='normal',i.total_netto,i.total_netto_corrected) * d.currency_value_nbp,
if(d.type='normal',i.total_netto,i.total_netto_corrected)), 0)) AS 'WG',
SUM(IF(p.group_ks = 3, IF(d.currency_id != 'PLN',
if(d.type='normal',i.total_netto,i.total_netto_corrected) * d.currency_value_nbp,
if(d.type='normal',i.total_netto,i.total_netto_corrected)), 0)) AS 'S',
SUM(IF(p.group_ks = 4, IF(d.currency_id != 'PLN',
if(d.type='normal',i.total_netto,i.total_netto_corrected) * d.currency_value_nbp,
if(d.type='normal',i.total_netto,i.total_netto_corrected)), 0)) AS 'T',
(SUM(IF(p.group_ks = 1,
IF(d.currency_id != 'PLN',
if(d.type='normal',i.total_netto,i.total_netto_corrected) * d.currency_value_nbp,
if(d.type='normal',i.total_netto,i.total_netto_corrected)),
0)) +
SUM(IF(p.group_ks = 2, IF(d.currency_id != 'PLN',
if(d.type='normal',i.total_netto,i.total_netto_corrected) * d.currency_value_nbp,
if(d.type='normal',i.total_netto,i.total_netto_corrected)), 0))+
SUM(IF(p.group_ks = 3, IF(d.currency_id != 'PLN',
if(d.type='normal',i.total_netto,i.total_netto_corrected) * d.currency_value_nbp,
if(d.type='normal',i.total_netto,i.total_netto_corrected)), 0)) +
SUM(IF(p.group_ks = 4, IF(d.currency_id != 'PLN',
if(d.type='normal',i.total_netto,i.total_netto_corrected) * d.currency_value_nbp,
if(d.type='normal',i.total_netto,i.total_netto_corrected)), 0)) ) as razem
FROM
ecminvoiceoutitems i
INNER JOIN
ecminvoiceouts d ON d.id = i.ecminvoiceout_id
INNER JOIN
ecmproducts p ON p.id = i.ecmproduct_id
WHERE
d.register_date >= '".date("Y-m-d",strtotime($date_from))."'
AND d.register_date <= '".date("Y-m-d",strtotime($date_to))."'
AND d.deleted = 0
AND d.canceled = 0
GROUP BY d.id
";
$totals=[];
$res=$db->query($query);
$data=[];
while($dane=$db->fetchByAssoc($res)){
$data[]=$dane;
$totals['total_netto']=$totals['total_netto']+$dane['total_netto'];
$totals['total_vat']=$totals['total_vat']+$dane['total_vat'];
$totals['total_brutto']=$totals['total_brutto']+$dane['total_brutto'];
$totals['TH']=$totals['TH']+$dane['TH'];
$totals['WG']=$totals['WG']+$dane['WG'];
$totals['S']=$totals['S']+$dane['S'];
$totals['T']=$totals['T']+$dane['T'];
}
}
$smarty = new Sugar_Smarty ();
$smarty->assign ( "date_from", $date_from);
$smarty->assign ( "date_to", $date_to);
$smarty->assign ( "totals", $totals);
$smarty->assign ( "DATA", $data );
$smarty->assign ( "dateFormat", "%d.%m.%Y" );
if($_REQUEST['to_pdf']==1){
include_once ("include/MPDF57/mpdf.php");
$p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 5, 5, 5, 5 );
$content= $smarty->fetch ( 'modules/EcmReports/tpls/PDF/ReportSalesByProdutGroups.html');
$p->WriteHTML ( $content );
//echo $content;
// draw PDF
$p->Output ();
} else {
echo $smarty->display ( 'modules/EcmReports/tpls/ReportSalesByProdutGroups.html' );
}
?>

View File

@@ -0,0 +1,466 @@
<?php
/*
* author: Michał Zieliński, mz@bim-it.pl
* created: 12.08.2015
* last modified date: 10.09.2015 by MZ
*/
global $mod_strings;
$process = false;
if ($_REQUEST['process'] == "1") $process = true;
$db = $GLOBALS['db'];
//create search form
$ss = new Sugar_Smarty ();
$ss->assign("MOD", $mod_strings);
//group accounts
if ($_REQUEST['group_accounts'] == "on") {
$group_accounts = true;
$ss->assign("GROUP_ACCOUNTS", "1");
}
//get Stocks
$stocks = "";
if ($_REQUEST['stocks']) $stocks = $_REQUEST['stocks'];
$s_res = $db->query("SELECT id, name FROM ecmstocks WHERE deleted='0' ORDER BY name");
$stocks_tpl = '<select multiple id="stocks" name="stocks[]">';
$s_stocks = "";
while ($s_row = $db->fetchByAssoc($s_res)) {
$stocks_tpl .= '<option value="'.$s_row['id'].'"';
if ($stocks=="" || in_array($s_row['id'], $stocks)) {
$stocks_tpl .= " selected ";
$s_stocks.= $s_row['name'].", ";
}
$stocks_tpl .= '>'.$s_row['name'].'</option>';
}
$stocks_tpl .= '</select>';
$s_stocks = substr($s_stocks,0,-2);
if (is_array($stocks) && sizeof($stocks) == $s_res->num_rows)
$s_stocks = "Wszystkie";
$ss->assign("STOCKS", $stocks_tpl);
//document types
$types_def = array (
'FV' => 'Faktura',
'FVKOR' => 'Faktura korygująca',
//'REC' => 'Paragon',
//'RECKOR' => 'Korekta paragonu',
);
$types = "";
if ($_REQUEST['types']) $types = $_REQUEST['types'];
$s_types = "";
$types_tpl = '<select multiple id="types" name="types[]">';
foreach ($types_def as $k=>$v) {
$types_tpl .= '<option value="'.$k.'"';
if ($types == "" || in_array($k, $types)) {
$types_tpl .= ' selected';
$s_types .= $v.", ";
}
$types_tpl .= '>'.$v.'</option>';
}
$types_tpl .= '</select>';
$s_types = substr($s_types, 0, -2);
if (is_array($types) && sizeof($types) == sizeof($types_def))
$s_types = "Wszystkie";
$ss->assign("TYPES", $types_tpl);
//document kinds
$kinds_def = array (
'K' => 'Kraj',
'U' => 'Unia',
'E' => 'Eksport',
);
$kinds = "";
if ($_REQUEST['kinds']) $kinds = $_REQUEST['kinds'];
$s_kinds = "";
$kinds_tpl = '<select multiple id="kinds" name="kinds[]">';
foreach ($kinds_def as $k=>$v) {
$kinds_tpl .= '<option value="'.$k.'"';
if ($kinds == "" || in_array($k, $kinds)) {
$kinds_tpl .= ' selected';
$s_kinds.=$v.", ";
}
$kinds_tpl .= '>'.$v.'</option>';
}
$kinds_tpl .= '</select>';
$s_kinds = substr($s_kinds,0,-2);
if (is_array($kinds) && sizeof($kinds) == sizeof($kinds_def))
$s_kinds = "Wszystkie";
$ss->assign("KINDS", $kinds_tpl);
//document categories
$categories = "";
if ($_REQUEST['categories']) $categories = $_REQUEST['categories'];
$s_categories = "";
global $app_list_strings;
$z=$GLOBALS['db']->query('select id,name from ecminvoicecategories');
$categories_def=array();
while($cat=$GLOBALS['db']->fetchByAssoc($z)){
$categories_def[$cat['id']]=$cat['name'];
}
//$categories_def = $app_list_strings['ecminvoiceouts_category_dom'];
if ($_REQUEST['categories']) $categories = $_REQUEST['categories'];
$categories_tpl = '<select multiple id="categories" name="categories[]">';
$categories_tpl.='<option value="all" selected></option>';
foreach ($categories_def as $k=>$v) {
$categories_tpl .= '<option value="'.$k.'"';
if ($categories == "" || in_array($k, $categories)) {
//$categories_tpl .= ' selected';
$s_categories.= $v.", ";
}
$categories_tpl .= '>'.$v.'</option>';
}
$categories_tpl .= '</select>';
$s_categories = substr($s_categories,0,-2);
if (is_array($categories) && sizeof($categories) == sizeof($categories_def)) {
$s_categories = "Wszystkie";
}
$ss->assign("CATEGORIES", $categories_tpl);
//dates
if ($_REQUEST['date_from'])
$date_from = $_REQUEST['date_from'];
else {
$date_from = new DateTime("first day of last month");
$date_from = $date_from->format('d.m.Y');
}
$date_from_db = implode('-', array_reverse(explode('.', $date_from)));
$ss->assign("DATE_FROM", $date_from);
if ($_REQUEST['date_to'])
$date_to = $_REQUEST['date_to'];
else {
$date_to = new DateTime("last day of last month");
$date_to = $date_to->format('d.m.Y');
}
$date_to_db = implode('-', array_reverse(explode('.', $date_to)));
$ss->assign("DATE_TO", $date_to);
if (!$process == true) {
$ss->display ( 'modules/EcmReports/tpls/ReportSalesVatSales.tpl' );
return;
}
//Do your job!
$main_query = "SELECT id, total_netto, total_brutto, total_vat, vats_summary, purchase_price FROM ecminvoiceouts WHERE deleted='0' AND canceled='0'";
$main_query.= "AND register_date >= '$date_from_db' AND register_date <= '$date_to_db' ";
if (in_array("FV", $types) && !in_array("FVKOR", $types))
$main_query .= "AND type='normal' ";
if (in_array("FVKOR", $types) && ! in_array("FV", $types))
$main_query .= "AND type='correct' ";
if (is_array($stocks))
$main_query .= " AND stock_id IN ('".implode("','", $stocks)."') ";
if($_REQUEST['categories'][0]=='all'){
$s_categories = "Wszystkie";
} else {
if (is_array($categories))
$main_query .= " AND (category IN ('".implode("','", $categories)."') OR category IS NULL)";
}
if (is_array($kinds))
$main_query .= " AND pdf_type IN ('".implode("','", $kinds)."') ";
$main_query .= " ORDER BY register_date, date_entered";
//echo $main_query; die();
//echo $main_query;
$inv_res = $db->query($main_query);
//get vats names
$main_query = str_replace(", total_netto, total_brutto, total_vat, vats_summary, purchase_price", "", $main_query); //leave only id field
$vats_query = "SELECT distinct ii.ecmvat_name, v.value FROM ecminvoiceoutitems AS ii
INNER JOIN ecmvats as v
ON v.id = ii.ecmvat_id
WHERE ecminvoiceout_id IN ($main_query) order by ecmvat_value";
$v_res = $db->query($vats_query);
$vats = array();
$vatsCount = 0;
while ($v_row = $db->fetchByAssoc($v_res)) {
//check if value is 0
if ($v_row['value'] == 0) {
$vats[strtoupper($v_row['ecmvat_name'])] = 1; //var is 0 - we didn't have to draw column
$vatsCount++;
} else {
$vats[strtoupper($v_row['ecmvat_name'])] = 2;
$vatsCount+=2;
}
}
$data = array();
$c = 1; //counter
while ($row = $db->fetchByAssoc($inv_res)) {
$tmp = array();
$tmp['lp'] = $c; $c++;
$inv = new EcmInvoiceOut();
$inv->retrieve($row['id']);
$tmp['document_no'] = $inv->document_no;
if($inv->type=='correct'){
$tmp['document_no'] = 'KF '.$inv->document_no;
} else {
$tmp['document_no'] = 'FV '.$inv->document_no;
}
$tmp['register_date'] = $inv->register_date;
//$pi = $inv->parent_nip.", ".$inv->parent_name.", ".$inv->parent_address_street.", ".$inv->parent_address_postalcode.", ".$inv->parent_address_city;
$pi = $inv->parent_nip;
$a = new Account();
$a->retrieve($inv->parent_id);
$pi.= ', '.$a->ks_account;
if (strlen($pi.", ".$inv->parent_name) <= 80){
$pi.=", ".$inv->parent_name;
} else {
$pos=strpos($inv->parent_name," ");
if($pos !== false){
$inv->parent_name=substr($inv->parent_name, 0,$pos).('...');
}
$pi.=", ".$inv->parent_name;
}
if (strlen($pi.", ".$inv->parent_address_street) <= 80){
$pi.=", ".$inv->parent_address_street;
}
if (strlen($pi.", ".$inv->parent_address_postalcode) <= 80)
$pi.=", ".$inv->parent_address_postalcode;
if (strlen($pi.", ".$inv->parent_address_city) <= 80)
$pi.=", ".$inv->parent_address_city;
$tmp['parent_info'] = $pi;
$a = new Account();
$a->retrieve($inv->parent_id);
$tmp['parent_index'] = $a->index_dbf;
$tmp['parent_id'] = $a->id;
unset($a);
if ($inv->currency_id == 'PLN') $currency = 1; else $currency = $inv->currency_value_nbp;
$tmp['netto'] = round($row['total_netto'] * $currency,2);
$tmp['brutto'] = round($row['total_brutto'] * $currency,2);
$tmp['vat'] = round($row['total_vat'] * $currency,2);
$tmp['type']=$inv->type;
if($inv->type=='correct'){
$tmp['purchase'] = -1*$row['purchase_price'];
} else {
$tmp['purchase'] = $row['purchase_price'];
}
//prepare vats
$vat_tmp = array();
$v_tmp = explode(",", $row['vats_summary']);
$v_tmp = array_slice($v_tmp, 0, -1); //remove last empty element
foreach ($v_tmp as $val) {
$vv_tmp = explode(":", $val);
$vvv_tmp = array();
$vvv_tmp[] = $vv_tmp[1];
$vvv_tmp[] = $vv_tmp[2];
$vat_tmp[strtoupper($vv_tmp[0])] = $vvv_tmp;
unset($vvv_tmp);
unset($vv_tmp);
}
unset($v_tmp);
$inv_vat = array();
foreach ($vats as $k => $v) {
$tmp_vat = array();
if (is_array($vat_tmp[$k])) {
$tmp_vat[] = round($vat_tmp[$k][0]*$currency,2);
$tmp_vat[] = round($vat_tmp[$k][1]*$currency,2);
} else {
$tmp_vat[] = 0;
$tmp_vat[] =0;
}
$inv_vat[$k] = $tmp_vat;
unset($tmp_vat);
}
$tmp['vats'] = $inv_vat;
unset($inv_vat);
unset($inv);
$data[] = $tmp;
unset($tmp);
}
if ($group_accounts == true) {
usort($data, "cmp");
//creaate Accounts summary
$tmp_data = array();
$summary = array();
$sum = array();
$sum_vat = array();
for ($i = 0; $i < sizeof($data); $i++) {
$row = $data[$i];
$row['lp'] = $i+1;
$tmp_data[] = $row;
if (array_key_exists("total_netto",$sum))
$sum['total_netto'] += $row['netto']; else $sum['total_netto'] = $row['netto'];
if (array_key_exists("total_brutto",$sum))
$sum['total_brutto'] += $row['brutto']; else $sum['total_brutto'] = $row['brutto'];
if (array_key_exists("total_vat",$sum))
$sum['total_vat'] += $row['vat']; else $sum['total_vat'] = $row['vat'];
if (array_key_exists("total_purchase",$sum))
$sum['total_purchase'] += $row['purchase']; else $sum['total_purchase'] = $row['purchase'];
foreach ($row['vats'] as $k=>$v) {
if (!array_key_exists($k,$sum_vat)) {
$sum_vat[$k][0] = 0;
$sum_vat[$k][1] = 0;
}
$sum_vat[$k][0] += $v[0];
$sum_vat[$k][1] += $v[1];
}
if ($data[$i]['parent_id'] != $data[$i+1]['parent_id'] || $i == sizeof($data)) {
//insert summary row
$sum['is_summary'] = 1;
$sum['index'] = $row['parent_index'];
$sum['parent_info'] = 'Podsumowanie dla kontrahenta';
$sum['vats'] = $sum_vat;
$tmp_data[] = $sum;
unset($sum); $sum = array();
unset($sum_vat); $sum_vat = array();
}
}
$data = $tmp_data;
}
$datas=$data;
$rop = 28; // rows on page
$nop = ceil(sizeof($data)/$rop); // number of pages
$pages_data = array_chunk($data, $rop);
$pages = array();
unset($data);
$prev_page = array();
$c = 1; //counter
foreach ($pages_data as $data) {
$tmp = array();
$tmp['site_netto'] = 0; $tmp['site_brutto'] = 0; $tmp['site_vat'] = 0; $tmp['site_purchase'] = 0;
$tmp['moved_netto'] = 0; $tmp['moved_brutto'] = 0; $tmp['moved_vat'] = 0; $tmp['moved_purchase'] = 0;
//prepare vats array
$site_vats = array();
$moved_vats = array();
$total_vats = array();
foreach ($vats as $k => $v) {
$site_vats[$k][0] = 0;
$site_vats[$k][1] = 0;
$moved_vats[$k][0] = 0;
$moved_vats[$k][1] = 0;
$total_vats[$k][0] = 0;
$total_vats[$k][1] = 0;
}
foreach ($data as $i) {
$tmp['site_netto'] += $i['netto'];
$tmp['site_brutto'] += $i['brutto'];
$tmp['site_vat'] += $i['vat'];
$tmp['site_purchase'] += $i['purchase'];
foreach ($i['vats'] as $k => $v) {
$site_vats[$k][0] += $v[0];
$site_vats[$k][1] += $v[1];
}
}
if ($c!=1) { //not first page
$tmp['moved_netto'] = $prev_page['total_netto'];
$tmp['moved_brutto'] = $prev_page['total_brutto'];
$tmp['moved_vat'] = $prev_page['total_vat'];
$tmp['moved_purchase'] = $prev_page['total_purchase'];
foreach ($vats as $k=>$v) {
$moved_vats[$k][0] += $prev_page['total_vats'][$k][0];
$moved_vats[$k][1] += $prev_page['total_vats'][$k][1];
}
}
$tmp['total_netto'] = $tmp['site_netto'] + $tmp['moved_netto'];
$tmp['total_brutto'] = $tmp['site_brutto'] + $tmp['moved_brutto'];
$tmp['total_vat'] = $tmp['site_vat'] + $tmp['moved_vat'];
$tmp['total_purchase'] = $tmp['site_purchase'] + $tmp['moved_purchase'];
foreach ($vats as $k=>$v) {
$total_vats[$k][0] += $site_vats[$k][0] + $moved_vats[$k][0];
$total_vats[$k][1] += $site_vats[$k][1] + $moved_vats[$k][1];
}
//insert page data
$tmp['rows'] = $data;
$tmp['page_no'] = $c;
$tmp['site_vats'] = $site_vats;
$tmp['moved_vats'] = $moved_vats;
$tmp['total_vats'] = $total_vats;
$pages[] = $tmp;
$prev_page = $tmp;
$c++;
}
//create document and show it
$ss_pdf = new Sugar_Smarty();
$ss_pdf->assign("PAGES", $pages);
$ss_pdf->assign("VATS", $vats);
$ss_pdf->assign("vatsCount", $vatsCount);
//header stuff
$cur_date = new DateTime("now");
$cur_date = $cur_date->format('d.m.Y H:m:s');
$ss_pdf->assign("CUR_DATE", $cur_date);
$ss_pdf->assign("DATE_FROM", $date_from);
$ss_pdf->assign("DATE_TO", $date_to);
$ss_pdf->assign("S_STOCK", $s_stocks);
$ss_pdf->assign("S_KIND", $s_kinds);
$ss_pdf->assign("S_CATEGORY", $s_categories);
$ss_pdf->assign("S_TYPE", $s_types);
if($_REQUEST['to_xls']==1){
$header=array();
$header[]='nr dok.';
$header[]='data wystawienia';
$header[]='odbiorca - nip,nazwa,adres';
$header[]='sprzedaż brutto';
$header[]='sprzedaż netto';
foreach ($vats as $val){
$header[]='netto '.$val;
$header[]='vat '.$val;
}
$header[]='vat razem';
$header[]='koszt';
$filename='modules/Home/Files/raport_sprzedazy_vat_'.date('d_m-Y').'.csv';
$fp=fopen($filename,'w');
foreach ($header as $k=>$v){
$header[$k]=iconv('UTF-8','windows-1250',$header[$k]);
}
fwrite($fp, implode(";",$header).PHP_EOL);
foreach ($pages[0]['rows'] as $key=>$val){
$line=array();
$line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['document_no']))).'"""';
$line[]=$val['register_date'];
$line[]=preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['parent_info'])));
$line[]=str_replace(".",",",$val['brutto']);
$line[]=str_replace(".",",",$val['netto']);
foreach ($val['vats'] as $vi){
$line[]=str_replace(".",",",$vi[0]);
$line[]=str_replace(".",",",$vi[1]);
}
$line[]=str_replace(".",",",$val['vat']);
$line[]=str_replace(".",",",$val['purchase']);
foreach ($line as $k=>$v){
$line[$k]=iconv('UTF-8','windows-1250',$line[$k]);;
}
fwrite($fp, implode(";",$line).PHP_EOL);
}
header("Location: ". $filename);
}else {
include_once ("modules/EcmSysInfos/EcmSysInfo.php");
$EcmSysInfo = new EcmSysInfo();
$ss_pdf->assign("COMPANY_NAME", $EcmSysInfo->getName());
$content = $ss_pdf->fetch ( 'modules/EcmReports/tpls/ReportSalesVatSalesPDF.tpl' );
include_once ("include/MPDF57/mpdf.php");
$p = new mPDF ( '', 'A4', null, 'helvetica', 5, 5, 33, 5, 5, 5 );
$p->writeHTML ($content) ;
$p->setTitle ( "Rejestr sprzedaży VAT" );
$p->output("rej.pdf", "I");
}
//helper
function cmp($a, $b) {
if ($a['parent_info'] == $b['parent_info']) {
return ( $a['register_date'] > $b['register_date'] ) ? 1 : -1;
}
return ( $a['parent_info'] > $b['parent_info'] ) ? 1 : -1;
}

View File

@@ -0,0 +1,533 @@
<?php
ini_set('memory_limit', '-1');
ini_set('max_execution_time', '-1');
if (!defined('sugarEntry') || !sugarEntry)
die('Not A Valid Entry Point');
function getStocksList() {
$db = $GLOBALS['db'];
$queryStocks = "SELECT id, name FROM ecmstocks WHERE deleted= 0";
$rowsStocks = $db->query($queryStocks);
$stocks = array();
while ($rowStocks = $db->fetchByAssoc($rowsStocks)) {
$stocks [$rowStocks ["id"]] = $rowStocks ["name"];
}
return $stocks;
}
function getStockIndexList() {
$db = $GLOBALS['db'];
$queryStockIndex = "SELECT id, name FROM ecmproductstockindexs;";
$rowsStockIndex = $db->query($queryStockIndex);
$StockIndexList = array();
while ($rowStocksIndex = $db->fetchByAssoc($rowsStockIndex)) {
$StockIndexList [$rowStocksIndex ["id"]] = $rowStocksIndex ["name"];
}
return $StockIndexList;
}
function getKartotekaMaterialowaQuery($unknow) {
if (!isset($unknow) || count($unknow) == 0 || (in_array('', $unknow))) {
} else {
if (in_array('NULL', $unknow) && count($unknow) == 1) {
$query .= " AND doc.ecmproductstockindex_id IS NULL ";
} else if (in_array('NULL', $unknow) && count($unknow) > 1) {
$queryUnknow = " (";
foreach ($unknow as $key => $value) {
if ($value != 'NULL') {
$queryUnknow .= "'" . $value . "',";
}
}
$queryUnknow = rtrim($queryUnknow, ",");
$queryUnknow .= ") ";
$query .= " AND (doc.ecmproductstockindex_id IS NULL OR doc.ecmproductstockindex_id IN " . $queryUnknow . ") ";
} else {
$queryUnknow = " (";
foreach ($unknow as $key => $value) {
$queryUnknow .= "'" . $value . "',";
}
$queryUnknow = rtrim($queryUnknow, ",");
$queryUnknow .= ") ";
$query .= " AND doc.ecmproductstockindex_id IN " . $queryUnknow . " ";
}
}
return $query;
}
// Tworzy kawałek zapytania dla magazynów
// np: ('magazyn1','magazyn2',...)
function getStockQuery($stockSelected) {
if (isset($stockSelected) && count($stockSelected) > 0) {
$queryStockSelected = " (";
foreach ($stockSelected as $key => $value) {
$queryStockSelected .= "'" . $value . "',";
}
$queryStockSelected = rtrim($queryStockSelected, ",");
$queryStockSelected .= ") ";
} else {
$stockList = getStocksList();
$queryStockSelected = " (";
foreach ($stockList as $key => $value) {
$queryStockSelected .= "'" . $key . "',";
}
$queryStockSelected = rtrim($queryStockSelected, ",");
$queryStockSelected .= ") ";
}
return $queryStockSelected;
}
function getDataRwPwKs($documentsSelected, $stockSelected, $date_from, $date_to, $stockIndexSelected) {
if (!isset($documentsSelected) && isset($stockSelected) && isset($date_from) && isset($date_to)) {
return null;
}
$db = $GLOBALS['db'];
global $app_list_strings;
$documentsList = array(// dokumenty
'EcmStockDocInsideOuts' => 'RW',
'EcmStockDocInsideIns' => 'PW',
'EcmStockDocMoves' => 'MM',
'EcmStockDocCorrects' => 'KS',
'EcmStockDocIns' => 'PZ',
'EcmStockDocOuts' => 'WZ',
'EcmInvoiceOuts' => "FK",
'EcmReceipts' => 'Paragon'
);
$query = "SELECT "
. "doc.id AS docid, "
. "doc.ecmproductstockindex_name AS docstockindex, "
. "doc.name AS docname, "
. "DATE_FORMAT(doc.register_date,'%d.%m.%Y') AS docregister_date, "
. "doc.document_no AS docdocument_no, "
. "doc.stock_id AS docstock_id, "
. "o.type AS otype, "
. "o.quantity AS oquantity, "
. "o.price AS oprice, "
. "o.product_id AS oproduct_id, "
. "o.product_name AS oproduct_name, "
. "o.product_code as oproduct_code, "
. "p.unit_id as punit_id "
. "FROM "
. "ecmstockoperations o, "
. "ecmproducts p, "
. "" . strtolower($documentsSelected) . " doc "
. "WHERE o.parent_id = doc.id "
. "AND p.id = o.product_id "
. "AND doc.deleted=0 "
. "AND o.deleted=0 "
. "AND doc.stock_id IN " . getStockQuery($stockSelected) . " "
. "AND doc.register_date >='" . $date_from . "' "
. "AND doc.register_date <= '" . $date_to . "'";
$query .= getKartotekaMaterialowaQuery($stockIndexSelected);
$query .= " ORDER BY doc.register_date, o.counter, o.product_code, o.product_name, doc.name";
$resultRows = $db->query($query);
$stockList = getStocksList();
while ($row = $db->fetchByAssoc($resultRows)) {
if($documentsSelected=='EcmStockDocCorrects'){
$c = new EcmStockDocCorrect();
$c->retrieve($row['docid']);
if($c->type=='6ed5b076-ddd1-9809-b236-54e5b2bcbd97'){
if($row['otype']==0){
$data['doc'][$row['docid']]['wartosc'] += $row['oquantity'] * $row['oprice'];
$data['prod'][$row['oproduct_id']]['wartosc'] += $row['oquantity'] * $row['oprice'];
} else {
$data['doc'][$row['docid']]['wartosc'] -= $row['oquantity'] * $row['oprice'];
$data['prod'][$row['oproduct_id']]['wartosc'] -= $row['oquantity'] * $row['oprice'];
$data['prod'][$row['oproduct_id']]['ilosc'] += $row['oquantity'];
}
} else {
$data['doc'][$row['docid']]['wartosc'] += $row['oquantity'] * $row['oprice'];
$data['prod'][$row['oproduct_id']]['wartosc'] += $row['oquantity'] * $row['oprice'];
$data['prod'][$row['oproduct_id']]['ilosc'] += $row['oquantity'];
}
unset($c);
} else {
$data['doc'][$row['docid']]['wartosc'] += $row['oquantity'] * $row['oprice'];
$data['prod'][$row['oproduct_id']]['wartosc'] += $row['oquantity'] * $row['oprice'];
$data['prod'][$row['oproduct_id']]['ilosc'] += $row['oquantity'];
}
$data['prod'][$row['oproduct_id']]['kod'] = $row['oproduct_code'];
$data['prod'][$row['oproduct_id']]['nazwa'] = $row['oproduct_name'];
$data['prod'][$row['oproduct_id']]['id'] = $row['oproduct_id'];
$data['prod'][$row['oproduct_id']]['data'] = $row['docregister_date'];
$data['prod'][$row['oproduct_id']]['numer'] = $row['docdocument_no'];
$data['prod'][$row['oproduct_id']]['kartoteka'] = $row['docstockindex'];
$data['prod'][$row['oproduct_id']]['jm'] = $app_list_strings['ecmproducts_unit_dom'][$row['punit_id']];
$data['doc'][$row['docid']]['magazyn'] = $stockList[$row['docstock_id']];
$data['doc'][$row['docid']]['nazwa'] = $row['docname'];
$data['doc'][$row['docid']]['otyp'] = $row['otype'];
$data['doc'][$row['docid']]['typ'] = $documentsList[$documentsSelected];
$data['doc'][$row['docid']]['id'] = $row['docid'];
$data['doc'][$row['docid']]['data'] = $row['docregister_date'];
$data['doc'][$row['docid']]['numer'] = $row['docdocument_no'];
$data['doc'][$row['docid']]['kartoteka'] = $row['docstockindex'];
}
return $data;
}
function getDataMm($documentsSelected, $stockSelected, $date_from, $date_to, $mmSelected) {
if (!isset($documentsSelected) && isset($stockSelected) && isset($date_from) && isset($date_to)) {
return null;
}
$db = $GLOBALS['db'];
global $app_list_strings;
$documentsList = array(// dokumenty
'EcmStockDocInsideOuts' => 'RW',
'EcmStockDocInsideIns' => 'PW',
'EcmStockDocMoves' => 'MM',
'EcmStockDocCorrects' => 'KS',
'EcmStockDocIns' => 'PZ',
'EcmStockDocOuts' => 'WZ',
'EcmInvoiceOuts' => "FK",
'EcmReceipts' => 'Paragon'
);
$query = "SELECT "
. "doc.id AS docid, "
. "doc.ecmproductstockindex_name AS docstockindex, "
. "doc.name AS docname, "
. "DATE_FORMAT(doc.register_date,'%d.%m.%Y') AS docregister_date, "
. "doc.document_no AS docdocument_no, "
. "doc.stock_in_id AS docstock_in_id,"
. "doc.stock_out_id AS docstock_id,"
. "o.type AS otype, "
. "o.quantity AS oquantity, "
. "o.price AS oprice, "
. "o.product_id AS oproduct_id, "
. "o.product_name AS oproduct_name, "
. "o.product_code as oproduct_code, "
. "p.unit_id as punit_id "
. "FROM "
. "ecmstockoperations o, "
. "ecmproducts p, "
. "" . strtolower($documentsSelected) . " doc "
. "WHERE o.parent_id = doc.id "
. "AND p.id = o.product_id "
. "AND doc.deleted=0 "
. "AND o.deleted=0 "
. "AND doc.stock_out_id IN " . getStockQuery($stockSelected) . " "
. "AND doc.stock_in_id IN " . getStockQuery($mmSelected) . " "
. "AND doc.register_date >='" . $date_from . "' "
. "AND doc.register_date <= '" . $date_to . "'"
. "AND o.type=0 "
. "ORDER BY doc.register_date, o.counter, o.product_code, o.product_name, doc.name ";
$resultRows = $db->query($query);
$stockList = getStocksList();
while ($row = $db->fetchByAssoc($resultRows)) {
$data['doc'][$row['docid']]['wartosc'] += $row['oquantity'] * $row['oprice'];
$data['prod'][$row['oproduct_id']]['wartosc'] += $row['oquantity'] * $row['oprice'];
$data['prod'][$row['oproduct_id']]['ilosc'] += $row['oquantity'];
$data['prod'][$row['oproduct_id']]['kod'] = $row['oproduct_code'];
$data['prod'][$row['oproduct_id']]['nazwa'] = $row['oproduct_name'];
$data['prod'][$row['oproduct_id']]['id'] = $row['oproduct_id'];
$data['prod'][$row['oproduct_id']]['data'] = $row['docregister_date'];
$data['prod'][$row['oproduct_id']]['numer'] = $row['docdocument_no'];
$data['prod'][$row['oproduct_id']]['kartoteka'] = $row['docstockindex'];
$data['prod'][$row['oproduct_id']]['jm'] = $app_list_strings['ecmproducts_unit_dom'][$row['punit_id']];
$data['doc'][$row['docid']]['magazyn'] = $stockList[$row['docstock_id']];
$data['doc'][$row['docid']]['magazynIn'] = $stockList[$row['docstock_in_id']];
$data['doc'][$row['docid']]['nazwa'] = $row['docname'];
$data['doc'][$row['docid']]['typ'] = $documentsList[$documentsSelected];
$data['doc'][$row['docid']]['id'] = $row['docid'];
$data['doc'][$row['docid']]['data'] = $row['docregister_date'];
$data['doc'][$row['docid']]['numer'] = $row['docdocument_no'];
$data['doc'][$row['docid']]['kartoteka'] = $row['docstockindex'];
}
return $data;
}
function getDataPzWzFk($documentsSelected, $stockSelected, $date_from, $date_to, $accountId, $accountName) {
//var_dump(!isset($documentsSelected) && !isset($stockSelected) && !isset($date_from) && !isset($date_to));
if (!isset($documentsSelected) && !isset($stockSelected) && !isset($date_from) && !isset($date_to)) {
return null;
}
$db = $GLOBALS['db'];
global $app_list_strings;
$documentsList = array(// dokumenty
'EcmStockDocInsideOuts' => 'RW',
'EcmStockDocInsideIns' => 'PW',
'EcmStockDocMoves' => 'MM',
'EcmStockDocCorrects' => 'KS',
'EcmStockDocIns' => 'PZ',
'EcmStockDocOuts' => 'WZ',
'EcmInvoiceOuts' => "FK",
'EcmReceipts' => 'Paragon'
);
$query = "SELECT "
. "doc.id AS docid, "
. "doc.name AS docname, "
. "DATE_FORMAT(doc.register_date,'%d.%m.%Y') AS docregister_date, "
. "doc.document_no AS docdocument_no, "
. "doc.stock_id AS docstock_id, "
. "o.type AS otype, "
. "o.quantity AS oquantity, "
. "o.price AS oprice, "
. "o.product_id AS oproduct_id, "
. "o.product_name AS oproduct_name, "
. "o.product_code as oproduct_code, "
. "doc.parent_id as docparent_id, "
. "doc.parent_name as docparent_name, ";
if($documentsSelected == 'EcmStockDocOuts'){
$query .= "doc.category as doccategory, ";
}
$query .= "p.unit_id as punit_id "
. "FROM "
. "ecmstockoperations o, "
. "ecmproducts p, "
. "" . strtolower($documentsSelected) . " doc "
. "WHERE o.parent_id = doc.id "
. "AND p.id = o.product_id "
. "AND doc.deleted=0 "
. "AND o.deleted=0 ";
if($documentsSelected=='EcmInvoiceOuts'){
$query .= " AND doc.canceled=0 ";
}
if (isset($accountId) && strlen($accountId) > 0) {
$query .= "AND doc.parent_id='" . $accountId . "' ";
}
$query.= "AND doc.stock_id IN " . getStockQuery($stockSelected) . " "
. "AND doc.register_date >='" . $date_from . "' "
. "AND doc.register_date <= '" . $date_to . "'";
if($documentsSelected == 'EcmStockDocOuts' && $_REQUEST['wz_category'] != ""){
$query.= " AND doc.category = '" . $_REQUEST['wz_category'] . "' ";
}
$query .= " ORDER BY doc.register_date, o.counter, o.product_code, o.product_name, doc.name";
$resultRows = $db->query($query);
$stockList = getStocksList();
while ($row = $db->fetchByAssoc($resultRows)) {
$data['prod'][$row['oproduct_id']]['kod'] = $row['oproduct_code'];
$data['prod'][$row['oproduct_id']]['nazwa'] = $row['oproduct_name'];
$data['prod'][$row['oproduct_id']]['id'] = $row['oproduct_id'];
$data['prod'][$row['oproduct_id']]['data'] = $row['docregister_date'];
$data['prod'][$row['oproduct_id']]['otype'] = $row['otype'];
$data['prod'][$row['oproduct_id']]['numer'] = $row['docdocument_no'];
$data['prod'][$row['oproduct_id']]['jm'] = $app_list_strings['ecmproducts_unit_dom'][$row['punit_id']];
$data['doc'][$row['docid']]['magazyn'] = $stockList[$row['docstock_id']];
$data['doc'][$row['docid']]['accountId'] = $row['docparent_id'];
$data['doc'][$row['docid']]['accountNazwa'] = $row['docparent_name'];
$data['doc'][$row['docid']]['nazwa'] = $row['docname'];
$data['doc'][$row['docid']]['typ'] = $documentsList[$documentsSelected];
$data['doc'][$row['docid']]['id'] = $row['docid'];
$data['doc'][$row['docid']]['doccategory'] = $app_list_strings['ecmstockdocouts_category_list'][$row['doccategory']];
$data['doc'][$row['docid']]['data'] = $row['docregister_date'];
$data['doc'][$row['docid']]['numer'] = $row['docdocument_no'];
if ($documentsSelected == 'EcmInvoiceOuts' && $row['otype'] == '0') {
$data['doc'][$row['docid']]['wartosc'] -= $row['oquantity'] * $row['oprice'];
$data['prod'][$row['oproduct_id']]['wartosc'] -= $row['oquantity'] * $row['oprice'];
$data['doc'][$row['docid']]['typ'] = 'KF';
$data['prod'][$row['oproduct_id']]['ilosc'] -= $row['oquantity'];
} else {
$data['prod'][$row['oproduct_id']]['ilosc'] += $row['oquantity'];
$data['doc'][$row['docid']]['wartosc'] += $row['oquantity'] * $row['oprice'];
$data['prod'][$row['oproduct_id']]['wartosc'] += $row['oquantity'] * $row['oprice'];
}
}
return $data;
}
//
// ***************************************************************************
//Pobieranie danych z filtrowania
if ($_REQUEST['date_from'] == '') {
$_REQUEST['date_from'] = date('01.m.Y');
} else {
$date_from = date('Y-m-d', strtotime($_REQUEST['date_from']));
}
if ($_REQUEST['date_to'] == '') {
$_REQUEST['date_to'] = date('t.m.Y');
} else {
$date_to = date('Y-m-d', strtotime($_REQUEST['date_to']));
}
$stockSelected = $_REQUEST['stockSelected'];
$documentsSelected = $_REQUEST['documentsSelected'];
$stockIndexSelected = $_REQUEST['stockIndexSelected'];
$viewSelected = $_REQUEST['viewSelected'];
$mmSelected = $_REQUEST['mmSelected'];
$accountId = $_REQUEST['accountId'];
$accountName = $_REQUEST['accountName'];
//Przygotowywanie innych potrzebnych zmiennych
$data = array();
$datatmp = array();
$db = $GLOBALS['db'];
global $mod_strings, $app_list_strings;
$stockList = getStocksList(); // magazyny
$stockIndexList = getStockIndexList(); //Kartoteki Materialowe
$documentsList = array(// dokumenty
'EcmStockDocInsideOuts' => 'RW',
'EcmStockDocInsideIns' => 'PW',
'EcmStockDocMoves' => 'MM',
'EcmStockDocCorrects' => 'KS',
'EcmStockDocIns' => 'PZ',
'EcmStockDocOuts' => 'WZ',
'EcmInvoiceOuts' => "FK",
'EcmReceipts' => 'Paragon'
);
$viewList = array(//Lista widokow
'documents' => 'Dokumenty',
'positions' => 'Pozycje',
);
//Pobieranie i przetwarzanie danych
if ($documentsSelected == 'EcmStockDocInsideOuts' || $documentsSelected == 'EcmStockDocInsideIns' || $documentsSelected == 'EcmStockDocCorrects') {
$data = getDataRwPwKs($documentsSelected, $stockSelected, $date_from, $date_to, $stockIndexSelected);
} elseif ($documentsSelected == 'EcmStockDocMoves') {
$data = getDataMm($documentsSelected, $stockSelected, $date_from, $date_to, $mmSelected);
} elseif ($documentsSelected == 'EcmStockDocIns' || $documentsSelected == 'EcmStockDocOuts' || $documentsSelected == 'EcmInvoiceOuts' || $documentsSelected == 'EcmReceipts') {
$data = getDataPzWzFk($documentsSelected, $stockSelected, $date_from, $date_to, $accountId, $accountName);
}
$kategorie_wz[""] = "";
foreach($app_list_strings['ecmstockdocouts_category_list'] as $k => $v){
$kategorie_wz[$k] = $v;
}
// create & execute smarty
$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("APP_LIST_STRINGS", $app_list_strings);
$smarty->assign("DATA", $data);
$smarty->assign("kategorie_wz", $kategorie_wz);
$smarty->assign("wz_category_selected", $_REQUEST['wz_category']);
$smarty->assign("stocksList", $stockList);
$smarty->assign("stockSelected", $stockSelected);
$smarty->assign("documentList", $documentsList);
$smarty->assign("documentSelected", $documentsSelected);
$smarty->assign("stockIndexList", $stockIndexList);
$smarty->assign("stockIndexSelected", $stockIndexSelected);
$smarty->assign("viewList", $viewList);
$smarty->assign("viewSelected", $viewSelected);
$smarty->assign("date_from", $_REQUEST['date_from']);
$smarty->assign("date_to", $_REQUEST['date_to']);
$smarty->assign("aktualnaData", date("d.m.Y"));
$smarty->assign("mmSelected", $mmSelected);
$smarty->assign("accountId", $accountId);
$smarty->assign("accountName", htmlentities($accountName));
// Eksport do PDF
if ($_REQUEST['toPDF'] == '1') {
if ($_REQUEST['to_xls'] == '1') {
$header=array();
$header[]='numer dokumentu';
$header[]='data';
$header[]='kontrahent';
$header[]='opis';
$header[]='wartość';
$header[]='magazyn';
$filename='modules/Home/Files/obroty_wg_magazynu_'.date('d_m-Y').'.csv';
$fp=fopen($filename,'w');
foreach ($header as $k=>$v){
$header[$k]=iconv('UTF-8','windows-1250',$header[$k]);
}
fwrite($fp, implode(";",$header).PHP_EOL);
foreach ($data['doc'] as $key=>$val){
$line=array();
$line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['typ'].' '.$val['numer']))).'"""';
$line[]=$val['data'];
$line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['accountNazwa']))).'"""';
$line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['nazwa']))).'"""';
$line[]=str_replace(".",",",$val['wartosc']);
$line[]=preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['magazyn'])));
foreach ($line as $k=>$v){
$line[$k]=iconv('UTF-8','windows-1250',$line[$k]);;
}
fwrite($fp, implode(";",$line).PHP_EOL);
}
header("Location: ". $filename);
} else {
if ($documentsSelected == 'EcmStockDocInsideOuts' || $documentsSelected == 'EcmStockDocInsideIns' || $documentsSelected == 'EcmStockDocCorrects') {
$txt = 'Kartoteka materiałowa: ';
if (isset($stockIndexSelected)) {
if (count($stockIndexSelected) == count($stockIndexList) + 1) {
$txt .= 'Wszystkie';
} else {
foreach ($stockIndexSelected as $key => $value) {
if ($value == 'NULL') {
$txt .= 'Bez kartoteki materiaĹowej ,';
} else {
$txt .= $stockIndexList[$value] . ' ,';
}
}
}
} else {
$txt .= 'Wszystkie';
}
$txt = rtrim($txt, ",");
} elseif ($documentsSelected == 'EcmStockDocMoves') {
$txt = 'Do magazynu: ';
if (isset($mmSelected)) {
if (count($mmSelected) == count($stockList)) {
$txt .= 'Wszystkie';
} else {
foreach ($mmSelected as $key => $value) {
$txt .= $stockList[$value] . ' ,';
}
}
} else {
$txt .= 'Wszystkie';
}
$txt = rtrim($txt, ",");
} elseif ($documentsSelected == 'EcmStockDocIns' || $documentsSelected == 'EcmStockDocOuts' || $documentsSelected == 'EcmInvoiceOuts' || $documentsSelected == 'EcmReceipts') {
if (isset($accountName) && strlen($accountName) > 1) {
$txt = 'Kontrahent: ' . $accountName;
} else {
$txt = 'Kontrahent: Wszyscy';
}
}
include_once ("modules/EcmSysInfos/EcmSysInfo.php");
$EcmSysInfo = new EcmSysInfo();
$smarty->assign("nazwaFirmy", $EcmSysInfo->getName());
$output = $smarty->fetch('modules/EcmReports/tpls/ReportStockDocMovesPDF.tpl');
include_once ("include/MPDF57/mpdf.php");
unset($smarty);
$p = new mPDF('', 'A4', null, 'helvetica', 10, 10, 26, 10, 5, 5);
$p->setFooter('{PAGENO}');
$p->setHTMLHeader('<div style="text-align: left; border-bottom: 1px solid #000000; font-weight: bold; font-size: 10pt;">
<table>
<tr>
<td style="font-weight: bold; font-size: 9pt;">Obroty wg dokumentów ' . $documentsList[$documentsSelected] . '</td>
</tr>
<tr>
<td style="font-weight: bold; font-size: 9pt;">' . $EcmSysInfo->getName() . '</td>
</tr>
<tr>
<td style="font-weight: bold; font-size: 9pt;">Data wygenerowania: ' . date("d.m.Y") . ' Okres: ' . $_REQUEST['date_from'] . ' do ' . $_REQUEST['date_to'] . '</td>
</tr>
<tr>
<td style="font-weight: bold; font-size: 9pt;">' . $txt . ' </td>
</tr>
</table>
</div>');
$p->writeHTML($output);
$p->Output("ObrotWgDokumentow_" . $documentsList[$documentsSelected] . "_" . $_REQUEST['date_from'] . "-" . $_REQUEST['date_to'].".pdf", "I");
}
} else {
$smarty->display('modules/EcmReports/tpls/ReportStockDocMoves.tpl');
}
?>

View File

@@ -0,0 +1,406 @@
<?php
// partie
include 'EcmConfig.php';
ini_set('memory_limit', '-1');
ini_set('max_execution_time', '-1');
if (!defined('sugarEntry') || !sugarEntry)
die('Not A Valid Entry Point');
$db = $GLOBALS['db'];
global $app_list_strings;
$doc_name = array(
'EcmStockDocInsideIns' => 'PW',
'EcmStockDocMoves' => 'MM',
'EcmStockDocCorrects' => 'KS',
'EcmStockDocIns' => 'PZ'
);
/*
* Magazyny
*/
$datastocks = array();
$users = array();
$queryStocks = "SELECT
name,
id
FROM ecmstocks
where deleted= 0";
$rowsStocks = $db->query($queryStocks);
$s = array();
while ($rowStocks = $db->fetchByAssoc($rowsStocks)) {
$stocks["name"] = $rowStocks["name"];
$stocks["id"] = $rowStocks["id"];
$datastocks[] = $stocks;
$s[$stocks["id"]]['name'] = $stocks["name"];
}
if ($_GET['date_from'] == '') {
$_GET['date_from'] = date('01.m.Y');
} else {
$date_from = date('Y-m-d 00:00:01', strtotime($_GET['date_from']));
}
if ($_GET['date_to'] == '') {
$_GET['date_to'] = date('t.m.Y');
} else {
$date_to = date('Y-m-d 23:59:59', strtotime($_GET['date_to']));
}
/*
* Dodatkowe parametry do zapytania
*/
if ($_GET['selectStock'] != "")
$add_where .= " and stock_id = '" . $_GET["selectStock"] . "' ";
$hideEmpty=false;
if ($_GET['selectProductActive'] == "1") {
$hideEmpty=true;
}
$_GET['selectShowEmpty'] = 1;
$r1 = $db->query("select id,name,code,unit_id from ecmproducts " . $where . " order by name asc");
$docs = array();
$i = 0;
$skip = array();
$total_quantity_old = 0;
$total_value_old = 0;
if($_GET['submit']=='Wykonaj'){
while ($tmp2 = $db->fetchByAssoc($r1)) {
$r = $db->query("select * from ecmstockoperations where
product_id='" . $tmp2['id'] . "'
" . $add_where . "
and in_id is null and type=0 and date_entered <='" . $date_from . "'");
$l = 0;
$i = $tmp2['id'];
if ($r->num_rows > 0) {
$docs[$i]['unit_id'] = $app_list_strings['ecmproducts_unit_dom'][$tmp2['unit_id']];
$docs[$i]['product_id'] = $tmp2['id'];
$docs[$i]['product_name'] = $tmp2['name'];
$docs[$i]['product_code'] = $tmp2['code'];
$docs[$i]['total_quantity_old'] = 0;
$docs[$i]['total_price_old'] = 0;
} else {
$skip[$tmp2['id']]['start'] = 1;
}
while ($tmp = $db->fetchByAssoc($r)) {
$ii = $db->query("select * from ecmstockoperations where in_id='" . $tmp['id'] . "' and type=1 and date_entered <='" . $date_from . "'");
if ($ii->num_rows > 0) {
// licz ilość dla użytych
$quantity_tmp = $tmp['quantity'];
while ($tmp2 = $db->fetchByAssoc($ii)) {
$quantity_tmp -= $tmp2['quantity'];
}
if ($quantity_tmp == 0) {
$db->query("update ecmstockoperations set used=1 where id='" . $tmp['id'] . "'");
continue;
}
$doc['quantity'] = $quantity_tmp;
$doc['parent_name'] = $tmp['parent_name'];
$doc['part_no'] = $tmp['part_no'];
$doc['price'] = $tmp['price'];
$doc['parent_type'] = $doc_name[$tmp['parent_type']];
$doc['parent_type2'] = $tmp['parent_type'];
$doc['parent_id'] = $tmp['parent_id'];
$doc['product_id'] = $tmp2['id'];
// $doc['date_entered'] = $n->register_date;
$doc['position_value'] = $doc['quantity'] * $tmp['price'];
$total_quantity_old += $doc['quantity'];
$total_value_old += round($doc['quantity'] * $tmp['price'], 2);
//$docs[$i-1]['add'][] = $doc;
$docs[$i]['total_price_old'] += ($doc['quantity'] * $tmp['price']);
$docs[$i]['total_quantity_old'] += ($doc['quantity']);
} else {
// dla całych
$doc['quantity'] = $tmp['quantity'];
$doc['parent_name'] = $tmp['parent_name'];
$doc['price'] = $tmp['price'];
$doc['part_no'] = $tmp['part_no'];
$doc['parent_type'] = $doc_name[$tmp['parent_type']];
$doc['parent_id'] = $tmp['parent_id'];
// $doc['date_entered'] = $n->register_date;
$doc['product_id'] = $tmp2['id'];
$doc['position_value'] = $doc['quantity'] * $tmp['price'];
$total_quantity_old += $doc['quantity'];
$total_value_old += round($doc['quantity'] * $tmp['price'], 2);
// $docs[$i-1]['add'][] = $doc;
$docs[$i]['total_price_old'] += ($doc['quantity'] * $tmp['price']);
$docs[$i]['total_quantity_old'] += ($doc['quantity']);
}
if ($r->num_rows > 1) {
$docs[$i]['price'] = $docs[$i]['total_price_old'] / $docs[$i]['total_quantity_old'];
$docs[$i]['parent_name'] = '';
$docs[$i]['parent_type'] = '';
}
if ($r->num_rows < 2) {
$docs[$i]['price'] = $tmp['price'];
$doc[$i]['part_no'] = $tmp['part_no'];
$docs[$i]['parent_id'] = $tmp['parent_id'];
$docs[$i]['parent_name'] = $tmp['parent_name'];
// $docs[$i-1]['date_entered'] = $n->register_date;
$docs[$i]['parent_type'] = $doc_name[$tmp['parent_type']];
} else {
$docs[$i]['price'] = $docs[$i]['total_price_old'] / $docs[$i]['total_quantity_old'];
$docs[$i]['parent_name'] = '';
$docs[$i]['parent_type'] = '';
}
}
if( $docs[$i]['total_quantity_old']==0){
$unset[$i]['unset_start'] = true;
}
}
$r1 = $db->query("select id,name,code,unit_id from ecmproducts " . $where . " order by name asc");
$i = 0;
$total_quantity_now = 0;
$total_value_now = 0;
while ($tmp2 = $db->fetchByAssoc($r1)) {
$r = $db->query("select * from ecmstockoperations where
product_id='" . $tmp2['id'] . "'
" . $add_where . "
and in_id is null and type=0 and date_entered <'" . $date_to . "'");
$i = $tmp2['id'];
$l = 0;
if ($r->num_rows > 0) {
$docs[$i]['unit_id'] = $app_list_strings['ecmproducts_unit_dom'][$tmp2['unit_id']];
$docs[$i]['product_id'] = $tmp2['id'];
$docs[$i]['product_name'] = $tmp2['name'];
$docs[$i]['product_code'] = $tmp2['code'];
$docs[$i]['total_quantity_now'] = 0;
$docs[$i]['total_price_now'] = 0;
} else {
$skip[$tmp2['id']]['mid'] = 1;
}
while ($tmp = $db->fetchByAssoc($r)) {
$ii = $db->query("select * from ecmstockoperations where in_id='" . $tmp['id'] . "' and type=1 and date_entered <'" . $date_to . "'");
if ($ii->num_rows > 0) {
// licz ilość dla użytych
$quantity_tmp = $tmp['quantity'];
while ($tmp2 = $db->fetchByAssoc($ii)) {
$quantity_tmp -= $tmp2['quantity'];
}
if ($quantity_tmp == 0) {
$db->query("update ecmstockoperations set used=1 where id='" . $tmp['id'] . "'");
continue;
}
$doc['quantity'] = $quantity_tmp;
$doc['parent_name'] = $tmp['parent_name'];
$doc['part_no'] = $tmp['part_no'];
$doc['price'] = $tmp['price'];
$doc['parent_type'] = $doc_name[$tmp['parent_type']];
$doc['parent_type2'] = $tmp['parent_type'];
$doc['parent_id'] = $tmp['parent_id'];
$doc['product_id'] = $tmp2['id'];
// $doc['date_entered'] = $n->register_date;
$doc['position_value'] = $doc['quantity'] * $tmp['price'];
$total_quantity_now += $doc['quantity'];
$total_value_now += round($doc['quantity'] * $tmp['price'], 2);
//$docs[$i-1]['add'][] = $doc;
$docs[$i]['total_price_now'] += ($doc['quantity'] * $tmp['price']);
$docs[$i]['total_quantity_now'] += ($doc['quantity']);
} else {
// dla całych
$doc['quantity'] = $tmp['quantity'];
$doc['parent_name'] = $tmp['parent_name'];
$doc['price'] = $tmp['price'];
$doc['part_no'] = $tmp['part_no'];
$doc['parent_type'] = $doc_name[$tmp['parent_type']];
$doc['parent_id'] = $tmp['parent_id'];
// $doc['date_entered'] = $n->register_date;
$doc['product_id'] = $tmp2['id'];
$doc['position_value'] = $doc['quantity'] * $tmp['price'];
$total_quantity_now += $doc['quantity'];
$total_value_now += round($doc['quantity'] * $tmp['price'], 2);
// $docs[$i-1]['add'][] = $doc;
$docs[$i]['total_price_now'] += ($doc['quantity'] * $tmp['price']);
$docs[$i]['total_quantity_now'] += ($doc['quantity']);
}
if ($r->num_rows > 1) {
$docs[$i]['price'] = $docs[$i]['total_price_now'] / $docs[$i]['total_quantity_now'];
$docs[$i]['parent_name'] = '';
$docs[$i]['parent_type'] = '';
}
if ($r->num_rows < 2) {
$docs[$i]['price'] = $tmp['price'];
$doc[$i]['part_no'] = $tmp['part_no'];
$docs[$i]['parent_id'] = $tmp['parent_id'];
$docs[$i]['parent_name'] = $tmp['parent_name'];
// $docs[$i-1]['date_entered'] = $n->register_date;
$docs[$i]['parent_type'] = $doc_name[$tmp['parent_type']];
} else {
$docs[$i]['price'] = $docs[$i]['total_price_now'] / $docs[$i]['total_quantity_now'];
$docs[$i]['parent_name'] = '';
$docs[$i]['parent_type'] = '';
}
}
if( $docs[$i]['total_quantity_now']==0){
$unset[$i]['unset_end'] = true;
}
}
$r1 = $db->query("select id,name,code,unit_id from ecmproducts " . $where . " order by name asc");
$i = 0;
$przychod_w = 0;
$przychod_q = 0;
$rozchod_q = 0;
$rozchod_w = 0;
while ($tmp2 = $db->fetchByAssoc($r1)) {
$r = $db->query("select * from ecmstockoperations where
product_id='" . $tmp2['id'] . "'
" . $add_where . "
and in_id is null and type=0 and date_entered <'" . $date_to . "' and date_entered >='" . $date_from . "'");
$i = $tmp2['id'];
$l = 0;
if ($r->num_rows > 0) {
$docs[$i]['rozchod_q'] = 0;
$docs[$i]['rozchod_w'] = 0;
$docs[$i]['przychod_q'] = 0;
$docs[$i]['przychod_w'] = 0;
} else {
$skip[$tmp2['id']]['end'] = 1;
}
while ($tmp = $db->fetchByAssoc($r)) {
$module=substr($tmp['parent_type'], 0, -1);
$doc = new $module();
$doc->retrieve($tmp['parent_id']);
if($doc->type=='correct'){
$docs[$i]['rozchod_w'] += (-1*$tmp['quantity'] * $tmp['price']);
$docs[$i]['rozchod_q'] += ($tmp['quantity']*-1);
$rozchod_w += ($tmp['quantity'] * $tmp['price']*-1);
$rozchod_q += ($tmp['quantity']*-1);
} else {
$docs[$i]['przychod_w'] += ($tmp['quantity'] * $tmp['price']);
$docs[$i]['przychod_q'] += ($tmp['quantity']);
$przychod_w += ($tmp['quantity'] * $tmp['price']);
;
$przychod_q += ($tmp['quantity']);
}
}
$ii = $db->query("select * from ecmstockoperations where product_id='" . $tmp2['id'] . "' and type=1 and date_entered <'" . $date_to . "' " . $add_where . " and date_entered >='" . $date_from . "'");
if ($ii->num_rows > 0) {
// licz ilość dla użytych
$quantity_tmp = $tmp['quantity'];
while ($tmp3 = $db->fetchByAssoc($ii)) {
$docs[$i]['rozchod_w'] += ($tmp3['quantity'] * $tmp3['price']);
$docs[$i]['rozchod_q'] += ($tmp3['quantity']);
$rozchod_w += ($tmp3['quantity'] * $tmp3['price']);
$rozchod_q += ($tmp3['quantity']);
}
}
$docs[$i]['unit_id'] = $app_list_strings['ecmproducts_unit_dom'][$tmp2['unit_id']];
$docs[$i]['unit_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$tmp2['unit_id']];
$docs[$i]['product_id'] = $tmp2['id'];
$docs[$i]['product_name'] = $tmp2['name'];
$docs[$i]['product_code'] = $tmp2['code'];
if( $docs[$i]['rozchod_w']==0 && $docs[$i]['przychod_w']==0){
$unset[$i]['unset_mid'] = true;
if($hideEmpty==true){
if($unset[$i]['unset_mid']==true && $unset[$i]['unset_end']==true && $unset[$i]['unset_start']==true){
unset($docs[$i]);
}
}
}
}
foreach ($skip as $key => $id) {
if ($skip[$key]['end'] == 1 && $skip[$key]['mid'] == 1 && $skip[$key]['start'] == 1) {
unset($docs[$key]);
}
}
}
// create & execute smarty
$smarty = new Sugar_Smarty();
global $mod_strings;
$smarty->assign("MOD", $mod_strings);
$smarty->assign("DATA", $docs);
$smarty->assign("date_from", $_GET['date_from']);
$smarty->assign("date_to", $_GET['date_to']);
$smarty->assign("TOTAL_VALUE_OLD", $total_value_old);
$smarty->assign("TOTAL_QUANTITY_OLD", $total_quantity_old);
$smarty->assign("TOTAL_VALUE_NOW", $total_value_now);
$smarty->assign("TOTAL_QUANTITY_NOW", $total_quantity_now);
$smarty->assign("rozchod_w", $rozchod_w);
$smarty->assign("rozchod_q", $rozchod_q);
$smarty->assign("przychod_w", $przychod_w);
$smarty->assign("przychod_q", $przychod_q);
$smarty->assign("CONSIGNMENTS", $EcmConfig['consignments']);
$smarty->assign("STOCKS", $datastocks);
$smarty->assign("selectStock", $_GET["selectStock"]);
$smarty->assign("selectProductActive", $_GET["selectProductActive"]);
$smarty->assign("selectProductEol", $_GET["selectProductEol"]);
$smarty->assign("selectShowEmpty", $_GET["selectShowEmpty"]);
// Eksport do PDF
if ($_GET['toPDF'] == '1') {
$output = $smarty->fetch('modules/EcmReports/tpls/PDF/ReportStockNewDoc.tpl');
include_once("include/MPDF57/mpdf.php");
unset($smarty);
if( $_GET ["selectStock"]!=''){
$s = new EcmStock();
$s->retrieve($_GET ["selectStock"]);
$magazyn_nazwa = $s->name;
}else{
$magazyn_nazwa = 'Wszystkie';
}
$p = new mPDF('', 'A4', null, 'helvetica', 5, 5, 23, 5, 5, 5);
$p->setFooter('Strona {PAGENO} z {nbpg}');
$EcmSysInfos = new EcmSysInfo();
$p->SetHTMLHeader('<p style="text-align:left;font-size: 10px;">' . $EcmSysInfos->getName() . '<br>
Raport magazynowy - Stany magazynowe za okres ' . $_GET['date_from'] . ' - ' . $_GET['date_to'] . '<br>Data wydruku: ' . date("d.m.Y") . '<br>Magazyn: ' . $magazyn_nazwa . '</p>');
//$p->setTitle($mod_strings["LBL_REPORT_STOCKS_DOCS"]);
//echo $output;
$p->writeHTML($output);
$p->Output();
} else {
$smarty->display('modules/EcmReports/tpls/ReportStockNewDoc.tpl');
}
?>

View File

@@ -0,0 +1,233 @@
<?php
global $mod_strings, $app_list_strings, $db;
// partie
$EcmConfig = array (
'consignments' => true,
'consignments_label1' => 'Nr',
);
ini_set('memory_limit','-1');
ini_set('max_execution_time','-1');
$doc_name=array('EcmStockDocInsideIns'=>'PW','EcmStockDocMoves'=>'MM','EcmStockDocCorrects'=>'KS','EcmStockDocIns'=>'PZ');
/*
* Magazyny
*/
$datastocks = array ();
$users = array ();
$queryStocks = "SELECT
name,
id
FROM ecmstocks
where deleted= 0";
$rowsStocks = $db->query ( $queryStocks );
while ( $rowStocks = $db->fetchByAssoc ( $rowsStocks ) ) {
$stocks ["name"] = $rowStocks ["name"];
$stocks ["id"] = $rowStocks ["id"];
$datastocks [] = $stocks;
}
/*
* Dodatkowe parametry do zapytania
*/
if ($_GET ['selectStock'] != "") {
$add_where = " and stock_id = '" . $_GET ["selectStock"] . "' ";
}
$where='WHERE 1=1 ';
if ($_GET ['selectProductActive'] != ""){
$where.=" AND product_active = '" . $_GET ["selectProductActive"] . "' ";
}
if ($_GET ['productCode'] != ""){
$where.=" AND code LIKE '" . $_GET ["productCode"] . "' ";
}
$_GET['selectShowEmpty']=1;
$r1 = $db->query("select id,name,code,unit_id from ecmproducts ".$where." order by name asc");
$docs = array();
$i=0;
$total_quantity=0;
$total_value=0;
while ($tmp2 = $db->fetchByAssoc($r1)) {
$r = $db->query("select * from ecmstockoperations where product_id='" . $tmp2['id'] . "' ".$add_where." and in_id is null and used=0 and type=0 order by counter asc");
$l = 0;
if ($r->num_rows > 0) {
$docs[$i]['unit_id'] = $app_list_strings['ecmproducts_unit_dom'][$tmp2['unit_id']];
$docs[$i]['unit_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$tmp2['unit_id']];
$docs[$i]['product_id'] = $tmp2['id'];
$docs[$i]['product_name'] = $tmp2['name'];
$docs[$i]['product_code'] = $tmp2['code'];
$docs[$i]['total_quantity'] = 0;
$docs[$i]['total_price'] = 0;
$i++;
}
while ($tmp = $db->fetchByAssoc($r)) {
$ii = $db->query( "select * from ecmstockoperations where in_id='" . $tmp['id'] ."' and type=1");
if ($ii->num_rows > 0) {
// licz ilość dla użytych
$quantity_tmp = $tmp['quantity'];
while ($tmp2 = $db->fetchByAssoc($ii)) {
$quantity_tmp -= $tmp2['quantity'];
}
if($quantity_tmp==0){
$db->query("update ecmstockoperations set used=1 where id='".$tmp['id']."'");
continue;
}
$doc['quantity'] = $quantity_tmp;
$doc['parent_name'] = $tmp['parent_name'];
$doc['part_no'] = $tmp['part_no'];
$doc['price'] = $tmp['price'];
$doc['parent_type'] = $doc_name[$tmp['parent_type']];
$doc['parent_type2'] = $tmp['parent_type'];
$doc['parent_id'] = $tmp['parent_id'];
$doc['product_id'] = $tmp['id'];
$doc['date_entered'] = $tmp['date_entered'];
$doc['position_value'] = $doc['quantity']*$tmp['price'];
$total_quantity+=$doc['quantity'];
$total_value+=round($doc['quantity']*$tmp['price'],2);
$docs[$i-1]['add'][] = $doc;
$docs[$i-1]['total_price']+=($doc['quantity']*$tmp['price'] );
$docs[$i-1]['part_no'] =$tmp['part_no'];
$docs[$i-1]['total_quantity']+=($doc['quantity']);
} else {
// dla całych
$doc['quantity'] = $tmp['quantity'];
$doc['parent_name'] = $tmp['parent_name'];
$doc['price'] = $tmp['price'];
$doc['part_no'] = $tmp['part_no'];
$doc['parent_type'] = $doc_name[$tmp['parent_type']];
$doc['parent_id'] = $tmp['parent_id'];
$doc['date_entered'] = $tmp['date_entered'];
$doc['product_id'] = $tmp2['id'];
$doc['position_value'] = $doc['quantity']*$tmp['price'];
$total_quantity+=$doc['quantity'];
$total_value+=round($doc['quantity']*$tmp['price'],2);
$docs[$i-1]['add'][] = $doc;
$docs[$i-1]['total_price']+=($doc['quantity']*$tmp['price'] );
$docs[$i-1]['total_quantity']+=($doc['quantity']);
$docs[$i-1]['part_no'] =$tmp['part_no'];
}
if ($r->num_rows > 1) {
$docs[$i-1]['price']='';
$docs[$i-1]['parent_name']='';
$doc[$i-1]['part_no'] = $tmp['part_no'];
$docs[$i-1]['parent_type']='';
} if ($r->num_rows < 2 ){
$docs[$i-1]['price']=$tmp['price'];
$doc[$i-1]['part_no'] = $tmp['part_no'];
$docs[$i-1]['parent_id'] = $tmp['parent_id'];
$docs[$i-1]['parent_name']=$tmp['parent_name'];
$docs[$i-1]['date_entered'] = $tmp['date_entered'];
$docs[$i-1]['parent_type'] = $doc_name[$tmp['parent_type']];
}else {
$docs[$i-1]['price']='';
$docs[$i-1]['parent_name']='';
$docs[$i-1]['parent_type']='';
}
}
if( $docs[$i-1]['total_quantity']==0 && $_GET['selectShowEmpty']!='')unset($docs[$i-1]);
}
// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty->assign ( "MOD", $mod_strings );
$smarty->assign ( "DATA", $docs );
$smarty->assign ( "TOTAL_VALUE", $total_value );
$smarty->assign ( "TOTAL_QUANTITY", $total_quantity );
$smarty->assign ( "CONSIGNMENTS",$EcmConfig['consignments']);
$smarty->assign ( "STOCKS", $datastocks );
if($_REQUEST['data']=='')$_REQUEST['data'] =date('d.m.Y');
$smarty->assign ( "date", $_REQUEST['data'] );
$smarty->assign ( "selectStock", $_GET ["selectStock"]);
$smarty->assign ( "selectProductActive", $_GET ["selectProductActive"] );
$smarty->assign ( "selectProductEol", $_GET ["selectProductEol"] );
$smarty->assign ( "selectShowEmpty", $_GET ["selectShowEmpty"] );
$smarty->assign ( "productCode", $_GET ["productCode"] );
// Eksport do PDF
if( $_GET['toPDF'] == '1' ) {
if( $_GET['to_xls'] == '1' ) {
$header=array();
$header[]='indeks';
$header[]='nazwa';
$header[]='dokument';
$header[]='ilosc';
$header[]='cena';
$header[]='suma';
$filename='modules/Home/Files/raport_stanow_magazynowych_'.date('d_m-Y').'.csv';
$fp=fopen($filename,'w');
foreach ($header as $k=>$v){
$header[$k]=iconv('UTF-8','windows-1250',$header[$k]);
}
fwrite($fp, implode(";",$header).PHP_EOL);
foreach ($docs as $key=>$val){
$line=array();
$line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['product_code']))).'"""';
$line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['product_name']))).'"""';
$line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['parent_type'].' '.$val['parent_name']))).'"""';
$line[]=str_replace(".",",",$val['total_quantity']);
$line[]=str_replace(".",",",$val['price']);
$line[]=str_replace(".",",",$val['total_price']);
foreach ($line as $k=>$v){
$line[$k]=iconv('UTF-8','windows-1250',$line[$k]);;
}
fwrite($fp, implode(";",$line).PHP_EOL);
if(count($val['add'])>1){
foreach($val['add'] as $k2=>$v2){
$line=array();
$line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['product_code']))).'"""';
$line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['product_name']))).'"""';
$line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['parent_type'].' '.$v2['parent_name']))).'"""';
$line[]=str_replace(".",",",$v2['quantity']);
$line[]=str_replace(".",",",$v2['price']);
$line[]=str_replace(".",",",$v2['position_price']);
foreach ($line as $k=>$v){
$line[$k]=iconv('UTF-8','windows-1250',$line[$k]);
}
fwrite($fp, implode(";",$line).PHP_EOL);
}
}
}
header("Location: ". $filename);
} else {
$output = $smarty->fetch( 'modules/EcmReports/tpls/PDF/ReportStocksDoc.tpl' );
include_once ("include/MPDF57/mpdf.php");
unset($smarty);
$p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 25, 10, 5, 5 );
$p->setFooter('Strona {PAGENO} z {nbpg}');
if( $_GET ["selectStock"]!=''){
$s = new EcmStock();
$s->retrieve($_GET ["selectStock"]);
$dopisek = $s->name;
}else{
$dopisek = 'Wszystkie';
}
$EcmSysInfos = new EcmSysInfo();
$p->SetHTMLHeader('<p style="text-align:left;font-size: 10px;">' . $EcmSysInfos->getName() . '<br>
Raport Magazynowy - Stany magazynowe<br>Data wydruku: '.date("d.m.Y",strtotime($_REQUEST['data'])).'<br>Magazyn: ' . $dopisek .'</p>');
//$p->setTitle($mod_strings["LBL_REPORT_STOCKS_DOCS"]);
//echo $output;
$p->writeHTML( $output );
$p->Output ();
}
} else {
$smarty->display ( 'modules/EcmReports/tpls/ReportStocksDoc.tpl' );
}
?>

View File

@@ -0,0 +1,240 @@
<?php
if (! defined ( 'sugarEntry' ) || ! sugarEntry)
die ( 'Not A Valid Entry Point' );
/**
* ********************* PREPARE ********************
*/
global $app_list_strings;
global $current_user;
$db = $GLOBALS ['db'];
$data = array ();
$date_from = date("Y-01-01");
$date_to = date("Y-m-01");
$query = "";
$selectedColumns = array();
$suma = array();
$mons = array( 1 => "Styczeń",
2 => "Luty",
3 => "Marzec",
4 => "Kwiecień",
5 => "Maj",
6 => "Czerwiec",
7 => "Lipiec",
8 => "Sierpień",
9 => "Wrzesień",
10 => "Październik",
11 => "Listopad",
12 => "Grudzień");
// Pobieranie danych z formularza
if(!$_GET['date_from']){
$date_from = date("Y-01-01");
}else{
$date_from = $_GET['date_from'];
$tmp = date_parse_from_format("d.m.Y", $_GET['date_from']);
$date_from = date($tmp['year']."-".$tmp['month']."-01");
}
if(!$_GET['date_to']){
$date_to = date("Y-m-d");
}else{
$date_to = $_GET['date_to'];
}
//formatowanie daty
$Calendar_daFormat = str_replace("d","%d",str_replace("m","%m",str_replace("Y","%Y",$GLOBALS['timedate']->get_date_format())));
$date_from = $GLOBALS['timedate']->to_display_date($date_from);
$date_to = $GLOBALS['timedate']->to_display_date($date_to);
$selectedColumns = json_decode($current_user->getPreference('ecmreports_reportvalue_column'));
//Sprawdzanie jakie kolumny ma zaznaczone uzytkownik i zapisywanie do bazy w razie zmian
if($_GET['selectedColumns']==NULL){
//Jeśli nic nie bylo przeslane z formularza i nie bylo nic w bazie
//tworzy nowa tablice z zaznaczonymi wszystkimi kolumnami
if($selectedColumns==NULL){
$selectedColumns = array();
foreach($app_list_strings['document_category_dom'] as $key=> $value){
$selectedColumns[] = $key;
}
// i ja zapisuje
$current_user->setPreference('ecmreports_reportvalue_column', json_encode($selectedColumns));
}
}else{
// Jeśli było coś przesłane przez formularz i nie bylo nic w bazie
// to zapisuje przeslane kolumny
if($selectedColumns==NULL){
$current_user->setPreference('ecmreports_reportvalue_column', json_encode($_GET['selectedColumns']));
}else{
// Jesli bylo cos przeslane przez formularz i bylo cos w bazie
// sprawdza czy tablice sie roznia elementami - jak tak to zapisuje zmiany do bazy
// i ustawia nowe kolumny
if(count($_GET['selectedColumns'])!=count($selectedColumns)){
if(count($_GET['selectedColumns'])!=0){
$current_user->setPreference('ecmreports_reportvalue_column', json_encode($_GET['selectedColumns']));
$selectedColumns = $_GET['selectedColumns'];
}
}
// Jak nic sie nie zmienilo to nic nie robi bo po co
}
}
/**
* ************* GET DATA FROM DB********************
*/
//Wybieranie zaznaczonych kolumn
$querycategory="";
foreach($selectedColumns as $value){
$querycategory = $querycategory . "'" . $value ."',";
}
$querycategory = rtrim($querycategory, ',');
$tmp = date_parse_from_format("d.m.Y", $date_to);
$date_finish_m = $tmp['month'];
$date_finish_y = $tmp['year'];
$date_finish_d = $tmp['day'];
$tmp = date_parse_from_format("d.m.Y", $date_from);
$date_f_month = $tmp['month']-1;
$date_f_year = $tmp['year'];
$date_f = "01.". $date_f_month . "." . $date_f_year;
$date_t_year = $date_f_year;
$data[$date_f_year] = array();
do{
$date_f_month++;
if($date_f_month == 13){
$date_f_month = 1;
$date_f_year++;
$data[$date_f_year] = array();
}
$date_f = "01.". $date_f_month . "." . $date_f_year;
$date_t_month = $date_f_month + 1;
if($date_t_month == 13){
$date_t_month = 1;
$date_t_year++;
}
if($date_f_year == $date_finish_y && $date_f_month == $date_finish_m){
$date_t_month = $date_finish_m;
$date_t_year = $date_finish_y;
$date_t_day = $date_finish_d;
}else{
$date_t_day = "01";
}
$date_t = $date_t_day .".". $date_t_month . "." . $date_t_year;
// inicjalizacja danych
$querydatefrom = "STR_TO_DATE('".$date_f."','%d.%m.%Y') ";
$querydateto = "STR_TO_DATE('".$date_t."','%d.%m.%Y') ";
$query = "SELECT
category_id,
ROUND(SUM(ifnull(value,'0,00')),2) as value
FROM
documents
WHERE
deleted=0 AND
category_id IN (".$querycategory.") AND
date_entered >= " . $querydatefrom . " AND
date_entered <= " . $querydateto . "
group by category_id";
$rows = $db->query ( $query );
$data[$date_f_year][$mons[$date_f_month]] = array();
if($rows->num_rows == 0){
// Jeśli baza nie zwróci żadnych rekordów to ustawia puste pola
foreach($selectedColumns as $wartosc){
$data[$date_f_year][$mons[$date_f_month]][] = '0,00';
}
// Dodatkowa kolumna na sumę
$data[$date_f_year][$mons[$date_f_month]][] = '0,00';
}else{
$tmp2 = array();
$sumka = 0;
// Rekordy z bazy danych wpisujemy do tymczasowej tabeli by móc wstawić dane w odpowiednie miejsce
while ( $r = $db->fetchByAssoc ( $rows ) ) {
$row = array ();
$row['category_id'] = $r['category_id'];
$row['value'] = number_format($r['value'], 2, ",", ".");
$sumka +=$r['value'];
$tmp2[] = $row;
}
// tutaj wstawiamy w odpowiednie miejsce
foreach($selectedColumns as $wartosc){
$sprawdzamy = false;
foreach($tmp2 as $cos){
if($wartosc==$cos['category_id']){
$sprawdzamy = true;
$data[$date_f_year][$mons[$date_f_month]][] = $cos['value'];
}
}
if(!$sprawdzamy){
$data[$date_f_year][$mons[$date_f_month]][] = '0,00';
}
}
// dodajemy ostatni wiersz sumy
$data[$date_f_year][$mons[$date_f_month]][]=number_format($sumka, 2, ",", ".");
}
}while(!($date_f_year == $date_finish_y && $date_f_month == $date_finish_m && $date_t_day == $date_finish_d));
//Pobieranie sumy dla każdego typu
$query = "SELECT
category_id,
ROUND(SUM(ifnull(value,'0,00')),2) as value
FROM
documents
WHERE
deleted=0 AND
category_id IN (".$querycategory.") AND
date_entered >= STR_TO_DATE('".$date_from."','%d.%m.%Y') AND
date_entered <= STR_TO_DATE('".$date_to."','%d.%m.%Y')
group by category_id";
$rows = $db->query ( $query );
if($rows->num_rows == 0){
// Jeśli baza nie zwróci żadnych rekordów to ustawia puste pola
foreach($selectedColumns as $wartosc){
$suma[] = '0,00';
}
// Dodatkowa kolumna na sumę
$suma[] = '0,00';
}else{
$tmp2 = array();
$sumka = 0;
// Rekordy z bazy danych wpisujemy do tymczasowej tabeli by móc wstawić dane w odpowiednie miejsce
while ( $r = $db->fetchByAssoc ( $rows ) ) {
$row = array ();
$row['category_id'] = $r['category_id'];
$row['value'] = number_format($r['value'], 2, ",", ".");
$sumka +=$r['value'];
$tmp2[] = $row;
}
// tutaj wstawiamy w odpowiednie miejsce
foreach($selectedColumns as $wartosc){
$sprawdzamy = false;
foreach($tmp2 as $cos){
if($wartosc==$cos['category_id']){
$sprawdzamy = true;
$suma[] = $cos['value'];
}
}
if(!$sprawdzamy){
$suma[] = '0,00';
}
}
// dodajemy ostatni wiersz sumy
$suma[]=number_format($sumka, 2, ",", ".");
}
/**
* ******************** SMARTY **********************
*/
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty -> assign('MOD', $mod_strings);
$smarty -> assign('data', $data);
$smarty -> assign('date_from', $date_from);
$smarty -> assign('suma', $suma);
$smarty -> assign('date_to', $date_to );
$smarty -> assign('dateFormat', $Calendar_daFormat);
$smarty -> assign('selectedColumns', $selectedColumns);
$smarty -> assign('category', $app_list_strings['document_category_dom']);
echo $smarty->display ( 'modules/EcmReports/tpls/ReportValue.tpl' );
?>

View File

@@ -0,0 +1,17 @@
<?php
/*
ini_set('display_errors',1);
error_reporting(E_ALL);
*/
include_once 'modules/EcmReports/RewizorGT/Dokument.php';
include_once 'modules/EcmReports/RewizorGT/Kontrahent.php';
include_once 'modules/EcmReports/RewizorGT/Pozycja.php';
include_once 'modules/EcmReports/RewizorGT/InvoiceCreator.php';
include_once 'modules/EcmReports/RewizorGT/AmazonInvoiceCreator.php';
include_once 'modules/EcmReports/RewizorGT/PurchaseCreator.php';
include_once 'modules/EcmReports/RewizorGT/PzCreator.php';
include_once 'modules/EcmReports/RewizorGT/RwCreator.php';
include_once 'modules/EcmReports/RewizorGT/WzCreator.php';
include_once 'modules/EcmReports/RewizorGT/PwCreator.php';
include_once 'modules/EcmReports/RewizorGT/ObjectLoader.php';
?>

View File

@@ -0,0 +1,168 @@
<?php
class AmazonInvoiceCreator{
private $db;
public $kontrahenci;
private $date_from;
private $date_to;
public function __construct($date){
$this->db=$GLOBALS['db'];
$date = new DateTime($date);
$this->date_from = $date->format("Y-m-01");
$this->date_to=$date->format("Y-m-t");
$this->kontrahenci=[];
}
public function getInvoices(){
global $app_list_strings;
$query="select * from amazon_invoices where register_date >='".$this->date_from."' and register_date <='".$this->date_to."' order by register_date ASC LIMIT 0,1";
$rs = $this->db->query($query);
$documents=array();
while($dane = $this->db->fetchByAssoc($rs)){
$dokument = new Dokument();
$kontrahent = new Kontrahent();
$dokument->typ_dokumentu=(string)'FS';
$dokument->status_dokumentu=1;
$dokument->status_rejestracji_fiskalnej=0;
$dokument->numer_dokumentu=0;
$dokument->numer_dokumentu_dostawcy=$dane['document_no'];
$dokument->rozszerzenie_numeru=(string)"FS"; // ??
$dokument->pelny_numer_dokumentu=$dane['document_no']; // OK
$dokument->numer_dokumentu_korygowanego=null;
$dokument->data_wystawienia_korekty=null;
$letters = substr($dane['parent_nip'],0,2); // OK
if(ctype_alpha ($letters)){
$rest = substr($dane['parent_nip'],2);
$dane['parent_nip']=$letters.' '.$rest;
}
$dokument->numer_zamowienia=$dane['order_no']; // OK
$dokument->magazyn_docelowy=null;
$kontrahent->typ_kontrahenta=(float)0;
$kontrahent->kod_identyfikacyjny=(string)''; // ??? Imię+Nazwisko ??
$kontrahent->nazwa_skrocona=mb_substr($dane['parent_name'],0,40,'UTF-8'); // ??!!
$kontrahent->nazwa_pelna=str_replace("\r\n","",$dane['parent_name']); // ??!!
$kontrahent->miasto=$dane['parent_address_city']; // OK
$kontrahent->kod_pocztowy=mb_substr($dane['parent_address_postalcode'],0,6,'UTF-8'); // OK
$kontrahent->ulica_i_adres=$dane['parent_address_street']; // ?????
$kontrahent->nip=$dane['parent_nip']; // OK
if($dane['parent_address_country_code']=='PL'){ // TYLKO UNIA????
$kontrahent->czy_unijny=0;
} else {
$kontrahent->czy_unijny=1;
}
$this->kontrahenci[]=$kontrahent;
$dokument->kod_identyfikacyjny_kontrahenta=mb_substr($dane['parent_name'],0,40,'UTF-8');
$dokument->nazwa_skrocona=mb_substr($dane['parent_name'],0,40,'UTF-8');
$dokument->nazwa_pelna=str_replace("\r\n","",$dane['parent_name']);
$dokument->miasto=$dane['parent_address_city']; //OK
$dokument->kod_pocztowy=mb_substr($dane['parent_address_postalcode'],0,6,'UTF-8'); //OK
$dokument->ulica_i_numer=$dane['parent_address_street']; // ?????
$dokument->nip=$dane['parent_nip']; // OK
$dokument->kategoria="Sprzedaż";
$dokument->podtytul=null;
$dokument->data_wystawienia=date("Ymd000000",strtotime($dane['register_date'])); // OK
$dokument->data_sprzedazy=date("Ymd000000",strtotime($dane['sell_date'])); // OK
$dokument->data_otrzymania=date("Ymd000000",strtotime($dane['register_date'])); // OK
$dokument->czy_dokumenty_wystawian_wg_ceny_netto=0;
$dokument->wartosc_netto=(float)$dane['total_netto']; // OK
$dokument->wartosc_vat=(float)$dane['total_vat'];
$dokument->wartosc_brutto=(float)$dane['total_brutto']; // OK
$dokument->koszt=(float)$dane['purchase_price']; // niepotrzebne
//$dokument->rabat_format_platnosci=$app_list_strings['payment_method'][$dane['payment_method']]; // KONIECZNE??
//$dokument->rabat_termin_platnosci=date("Ymd000000",strtotime($dane['payment_date'])); // J/W
$dokument->kwota_zaplacona_przy_odbiorze=(float)$dane['paid_val']; // CHYBA 0
$dokument->wartosc_do_zaplaty=(float)round($dane['total_brutto'],2); // OK
$dokument->zaokraglenie_wartosci_do_zaplaty=0;
$dokument->zaokraglenie_wartosci_vat=0;
$dokument->automatyczne_zaokgraglanie=0;
$dokument->statusy_rozszerzone_i_specjalne=0;
$u = new User();
$u->retrieve($dane['assigned_user_id']);
$dokument->nazwisko_i_imie_wystawcy=$u->full_name; // nie potrzebne
if($dane['currency_id']=="PLN"){
$dokument->waluta='PLN';
} else {
$cur = new Currency();
$cur->retrieve($dane['currency_id']);
$dokument->waluta=$cur->name;
$dokument->kurs_waluty=(float)$dane['currency_value_nbp']; // POBIERAMY Z NBP ?? REWIZOR SAM UZUPEŁNI??
}
$dokument->uwagi=null;
$dokument->import_dokumentu=0;
// czy będą inne niz unia ?
if($dane['pdf_type']=='K'){
$dokument->rodzaj_transakcji=0;
} else {
if($dane['pdf_type']=='U'){
$dokument->rodzaj_transakcji=2;
} else {
$dokument->rodzaj_transakcji=1;
}
}
$dokument->panstwo_kontrahenta=$a->billing_address_country; // tutaj państwo konsumpcji
if($a->invoice_type=='U'){
$dokument->prefix_panstwa_ue=mb_substr($a->to_vatid,0,2,'UTF-8');
$dokument->czy_kontrahent_unijny=1;
}
$dokument->setPozycjeObiekt($this->getDocumentPositions($dane['id'],$dokument));
$documents[]=$dokument;
}
print_r(count($documents));
return $documents;
}
public function getDocumentPositions($id,&$doc){
$query="select * from amazon_invoices_products where amazon_invoice_id='".$id."'";
$rr=$this->db->query($query);
$pozycje=[];
while($dane=$this->db->fetchByAssoc($rr)){
$pozycja = new Pozycja;
$pozycja->symbol_stawki_vat = str_replace(".00","",$dane ['ecmvat_value']);
$pozycja->wysokosc_stawki_vat_w_procentach = floatval ($dane ['ecmvat_value'] . '.00');
$pozycja->wartosc_netto = floatval($dane ['total_netto']);
$pozycja->wartosc_vat = floatval($dane ['total_vat']);
$pozycja->wartosc_brutto = floatval($dane ['total_netto'])+floatval($dane ['total_vat']);
$pozycja->wartosc_nabycia = round ( $dane ['price_purchase'] * $dane ['quantity'], 2 ); // ?????
$pozycje[$dane ['ecmvat_value']]=$pozycja;
}
$pozycja->wartosc_brutto=round((($pozycja->wartosc_netto*$pozycja->wysokosc_stawki_vat_w_procentach)/100)+$pozycja->wartosc_netto,2);
$pozycja->wartosc_vat=round((($pozycja->wartosc_netto*$pozycja->wysokosc_stawki_vat_w_procentach)/100),2);
$doc->pozycje=count($pozycja);
return $pozycje;
}
}
?>

View File

@@ -0,0 +1,123 @@
<?php
class Dokument{
public $typ_dokumentu;
public $status_dokumentu;
public $status_rejestracji_fiskalnej;
public $numer_dokumentu;
public $numer_dokumentu_dostawcy;
public $rozszerzenie_numeru;
public $pelny_numer_dokumentu;
public $numer_dokumentu_korygowanego;
public $data_wystawienia_korekty;
public $numer_zamowienia;
public $magazyn_docelowy;
/*
* Kontrahent
*/
public $kod_identyfikacyjny_kontrahenta;
public $nazwa_skrocona;
public $nazwa_pelna;
public $miasto;
public $kod_pocztowy;
public $ulica_i_numer;
public $nip;
/*
* Kategoria dokumentu
*/
public $kategoria;
public $podtytul;
/*
* Miejsce i data
*/
public $miejsce_wystawienia='Obrowo';
public $data_wystawienia;
public $data_sprzedazy;
public $data_otrzymania;
/*
* Pozycje
*/
public $pozycje;
public $pozycjeObiekt;
/*
* Cena na dokumencie
*/
public $czy_dokumenty_wystawian_wg_ceny_netto;
public $aktywna_cena;
/*
* Wartość i koszt dokumentu
*/
public $wartosc_netto;
public $wartosc_vat;
public $wartosc_brutto;
public $koszt;
/*
* Rabat i forma płatności
*/
public $rabat_nazwa;
public $rabat_procent;
public $rabat_format_platnosci;
public $rabat_termin_platnosci;
/*
* Kwoty na dokumencie;
*/
public $kwota_zaplacona_przy_odbiorze;
public $wartosc_do_zaplaty;
/*
* Zaokrąglenie i przeliczenia
*/
public $zaokraglenie_wartosci_do_zaplaty;
public $zaokraglenie_wartosci_vat;
public $automatyczne_zaokgraglanie;
public $statusy_rozszerzone_i_specjalne;
/*
* Osoby
*/
public $nazwisko_i_imie_wystawcy;
public $nazwisko_i_imie_odbiorcy;
public $podstawa_wydania_dokumentu;
/*
* Opakowanie
*/
public $wartosc_wydanych_opakowan;
public $wartosc_zwroconych_opakowan;
/*
* Waluta dokumentu
*/
public $waluta;
public $kurs_waluty;
/*
* Inne parametry
*/
public $uwagi;
public $komentarze;
public $podtytul_dokumentu;
public $nie_uzywane;
public $import_dokumentu;
public $dokument_eksportowy;
public $rodzaj_transakcji;
/*
* Płatnosc karta
*/
public $platnosc_karta_nazwa;
public $platnosc_karta_kwota;
public $platnosc_kredytowa_nazwa;
public $platnosc_kredytowa_kwota;
/*
* Inne dane
*/
public $panstwo_kontrahenta;
public $prefix_panstwa_ue;
public $czy_kontrahent_unijny;
public function getPozycjeObiekt(){
return $this->pozycjeObiekt;
}
public function setPozycjeObiekt($pozycje){
$this->pozycjeObiekt=$pozycje;
}
}
?>

View File

@@ -0,0 +1,198 @@
<?php
class InvoiceCreator{
private $db;
public $kontrahenci;
public function __construct($date){
$this->db=$GLOBALS['db'];
$date = new DateTime($date);
$this->date_from = $date->format("Y-m-01");
$this->date_to=$date->format("Y-m-t");
$this->kontrahenci=[];
}
public function getInvoices(){
$query="select * from ecminvoiceouts where deleted=0 and canceled=0 and register_date >='".$this->date_from."' and register_date <='".$this->date_to."' order by document_no ASC";
$rs = $this->db->query($query);
global $app_list_strings;
$documents=array();
while($dane = $this->db->fetchByAssoc($rs)){
$dokument = new Dokument();
$kontrahent = new Kontrahent();
if($dane['type']=='correct'){
$dokument->typ_dokumentu=(string)'KFS';
} else {
$dokument->typ_dokumentu=(string)'FS';
}
$dokument->status_dokumentu=($dane['canceled']==true? 2 :1);
$dokument->status_rejestracji_fiskalnej=0;
$dokument->numer_dokumentu=0;
$dokument->numer_dokumentu_dostawcy=$dane['document_no'];
$dokument->rozszerzenie_numeru=(string)"FS";
$dokument->pelny_numer_dokumentu=$dane['document_no'];
if($dane['type']=='correct'){
$ii = new EcmInvoiceOut();
$ii->retrieve($dane['ecminvoiceout_id']);
$dokument->numer_dokumentu_korygowanego=$ii->document_no;
$dokument->data_wystawienia_korekty=date("Ymd000000",strtotime($dane['register_date']));
$dokument->wartosc_wydanych_opakowan=0;
$dokument->wartosc_zwroconych_opakowan=0;
if($dokument->numer_dokumentu_korygowanego==""){
$dokument->numer_dokumentu_korygowanego='Korekta zbiorcza';
}
} else {
$dokument->numer_dokumentu_korygowanego=null;
$dokument->data_wystawienia_korekty=null;
}
$letters = substr($dane['parent_nip'],0,2);
if(ctype_alpha ($letters)){
$rest = substr($dane['parent_nip'],2);
$dane['parent_nip']=$letters.' '.$rest;
}
$dokument->numer_zamowienia=$dane['order_no'];
$dokument->magazyn_docelowy=null;
$a = new Account();
$a->retrieve($dane['parent_id']);
$a->name=str_replace("\r\n","",$a->name);
$kontrahent->typ_kontrahenta=(float)0;
$kontrahent->kod_identyfikacyjny=$a->index_dbf;
$kontrahent->nazwa_skrocona=mb_substr($dane['parent_name'],0,40,'UTF-8');
$kontrahent->nazwa_pelna=str_replace("\r\n","",$dane['parent_name']);
$kontrahent->miasto=$dane['parent_address_city'];
$kontrahent->kod_pocztowy=mb_substr($dane['parent_address_postalcode'],0,6,'UTF-8');
$kontrahent->ulica_i_adres=$dane['parent_address_street'];
$kontrahent->nip=$dane['parent_nip'];
if($a->invoice_type=='U'){
$kontrahent->prefix=mb_substr($a->to_vatid,0,2,'UTF-8');
$kontrahent->czy_unijny=1;
} else {
$kontrahent->czy_unijny=0;
}
$this->kontrahenci[$a->id]=$kontrahent;
$dokument->kod_identyfikacyjny_kontrahenta=$a->index_dbf;
$dokument->nazwa_skrocona=mb_substr($dane['parent_name'],0,40,'UTF-8');
$dokument->nazwa_pelna=str_replace("\r\n","",$dane['parent_name']);
$dokument->miasto=$dane['parent_address_city'];
$dokument->kod_pocztowy=mb_substr($dane['parent_address_postalcode'],0,6,'UTF-8');
$dokument->ulica_i_numer=$dane['parent_address_street'];
$dokument->nip=$dane['parent_nip'];
$dokument->kategoria="Sprzedaż";
$dokument->podtytul=null;
$dokument->data_wystawienia=date("Ymd000000",strtotime($dane['register_date']));
$dokument->data_sprzedazy=date("Ymd000000",strtotime($dane['sell_date']));
$dokument->data_otrzymania=date("Ymd000000",strtotime($dane['register_date']));
$dokument->czy_dokumenty_wystawian_wg_ceny_netto=0;
$dokument->wartosc_netto=(float)$dane['total_netto'];
$dokument->wartosc_vat=(float)$dane['total_vat'];
$dokument->wartosc_brutto=(float)$dane['total_brutto'];
$dokument->koszt=(float)$dane['purchase_price'];
$dokument->rabat_format_platnosci=$app_list_strings['payment_method'][$dane['payment_method']];
$dokument->rabat_termin_platnosci=date("Ymd000000",strtotime($dane['payment_date']));
$dokument->kwota_zaplacona_przy_odbiorze=(float)$dane['paid_val'];
$dokument->wartosc_do_zaplaty=(float)round($dane['total_brutto'],2);
$dokument->zaokraglenie_wartosci_do_zaplaty=0;
$dokument->zaokraglenie_wartosci_vat=0;
$dokument->automatyczne_zaokgraglanie=0;
$dokument->statusy_rozszerzone_i_specjalne=0;
$u = new User();
$u->retrieve($dane['assigned_user_id']);
$dokument->nazwisko_i_imie_wystawcy=$u->full_name;
if($dane['currency_id']=="PLN"){
$dokument->waluta='PLN';
} else {
$cur = new Currency();
$cur->retrieve($dane['currency_id']);
$dokument->waluta=$cur->name;
$dokument->kurs_waluty=(float)$dane['currency_value_nbp'];
}
$dokument->uwagi=str_replace("\r\n","",$dane['pdf_text']);
$dokument->import_dokumentu=0;
if($dane['pdf_type']=='K'){
$dokument->rodzaj_transakcji=0;
} else {
if($dane['pdf_type']=='U'){
$dokument->rodzaj_transakcji=2;
} else {
$dokument->rodzaj_transakcji=1;
}
}
$dokument->panstwo_kontrahenta=$a->billing_address_country;
if($a->invoice_type=='U'){
$dokument->prefix_panstwa_ue=mb_substr($a->to_vatid,0,2,'UTF-8');
$dokument->czy_kontrahent_unijny=1;
}
$dokument->setPozycjeObiekt($this->getDocumentPositions($dane['id'],$dokument));
$documents[]=$dokument;
}
return $documents;
}
public function getDocumentPositions($id,&$doc){
$query="select * from ecminvoiceoutitems where ecminvoiceout_id='".$id."' and deleted=0";
$rr=$this->db->query($query);
$pozycje=[];
while($dane=$this->db->fetchByAssoc($rr)){
if($pozycje[$dane ['ecmvat_value']]!=""){
$obiekt = $pozycje[$dane ['ecmvat_value']];
if ($doc->typ_dokumentu!= 'FS') {
$obiekt->wartosc_netto+= $dane ['total_netto_corrected'];
$obiekt->wartosc_vat+= $dane ['total_vat_corrected'];
$obiekt->wartosc_brutto+= $dane ['total_brutto_corrected'];
} else {
$obiekt->wartosc_netto+= $dane ['total_netto'];
$obiekt->wartosc_vat+= $dane ['total_vat'];
$obiekt->wartosc_brutto+= floatval($dane ['total_netto'])+floatval($dane ['total_vat']);
}
$obiekt->wartosc_nabycia+= round ( $dane ['price_purchase'] * $dane ['quantity'], 2 );
$pozycje[$dane ['ecmvat_value']]=$obiekt;
} else {
$pozycja = new Pozycja;
$pozycja->symbol_stawki_vat = str_replace(".00","",$dane ['ecmvat_value']);
$pozycja->wysokosc_stawki_vat_w_procentach = floatval ($dane ['ecmvat_value'] . '.00');
if ($doc->typ_dokumentu!= 'FS') {
$pozycja->wartosc_netto =floatval($dane ['total_netto_corrected']);
$pozycja->wartosc_vat = floatval($dane ['total_vat_corrected']);
$pozycja->wartosc_brutto =floatval($dane ['total_brutto_corrected']);
} else {
$pozycja->wartosc_netto = floatval($dane ['total_netto']);
$pozycja->wartosc_vat = floatval($dane ['total_vat']);
$pozycja->wartosc_brutto = floatval($dane ['total_netto'])+floatval($dane ['total_vat']);
}
$pozycja->wartosc_nabycia = round ( $dane ['price_purchase'] * $dane ['quantity'], 2 );
$pozycje[$dane ['ecmvat_value']]=$pozycja;
}
}
$pozycja->wartosc_brutto=round((($pozycja->wartosc_netto*$pozycja->wysokosc_stawki_vat_w_procentach)/100)+$pozycja->wartosc_netto,2);
$pozycja->wartosc_vat=round((($pozycja->wartosc_netto*$pozycja->wysokosc_stawki_vat_w_procentach)/100),2);
$doc->pozycje=count($pozycja);
return $pozycje;
}
}
?>

View File

@@ -0,0 +1,34 @@
<?php
class Kontrahent{
public $typ_kontrahenta;
public $kod_identyfikacyjny;
public $nazwa_skrocona;
public $nazwa_pelna;
public $miasto;
public $kod_pocztowy;
public $ulica_i_adres;
public $nip;
public $regon;
public $telefon;
public $faks;
public $email;
public $www;
public $nazwisko_imie;
public $analityka_dostawcy;
public $analityka_odbiorcy;
public $pole_uzytkownika_1;
public $pole_uzytkownika_2;
public $pole_uzytkownika_3;
public $pole_uzytkownika_4;
public $pole_uzytkownika_5;
public $pole_uzytkownika_6;
public $pole_uzytkownika_7;
public $pole_uzytkownika_8;
public $nazwa_banku;
public $numer_banku;
public $panstwo_kontrahenta;
public $prefix;
public $czy_unijny;
}
?>

View File

@@ -0,0 +1,191 @@
<?php
if ($_REQUEST ['date']) {
$date = $_REQUEST ['date'];
} else {
$date = new DateTime ();
$date->modify ( "-1 month" );
$date = $date->format ( "01.m.Y" );
}
$dokumenty = $_REQUEST['documents'];
if ($_REQUEST ['date'] != "") {
$array=[];
foreach ($dokumenty as $dokument){
echo $dokument;
if($dokument=='afs'){
$invoiceCreator = new AmazonInvoiceCreator ( $_REQUEST ['date'] );
$array2 = $invoiceCreator->getInvoices ();
$array = array_merge ( $array, $array2 );
}
if($dokument=='fs'){
$invoiceCreator = new InvoiceCreator ( $_REQUEST ['date'] );
$array2 = $invoiceCreator->getInvoices ();
$array = array_merge ( $array, $array2 );
}
if($dokument=='fz-all'){
$purchaseCreator = new PurchaseCreator ( $_REQUEST ['date'] );
$array2 = $purchaseCreator->getPurchases ("all");
$array = array_merge ( $array, $array2 );
}
if($dokument=='fz-new'){
$purchaseCreator = new PurchaseCreator ( $_REQUEST ['date'] );
$array2 = $purchaseCreator->getPurchases ("new");
$array = array_merge ( $array, $array2 );
}
if($dokument=='pz'){
$purchaseCreator = new PzCreator ( $_REQUEST ['date'] );
$array2 = $purchaseCreator->getDocuments();
$array = array_merge ( $array, $array2 );
}
if($dokument=='wz'){
$purchaseCreator = new WzCreator ( $_REQUEST ['date'] );
$array2 = $purchaseCreator->getDocuments();
$array = array_merge ( $array, $array2 );
}
if($dokument=='rw'){
$purchaseCreator = new RwCreator ( $_REQUEST ['date'] );
$array2 = $purchaseCreator->getDocuments();
$array = array_merge ( $array, $array2 );
}
if($dokument=='pw'){
$purchaseCreator = new PwCreator ( $_REQUEST ['date'] );
$array2 = $purchaseCreator->getDocuments();
$array = array_merge ( $array, $array2 );
}
if($dokument=='mm'){
$purchaseCreator = new MmCreator ( $_REQUEST ['date'] );
$array2 = $purchaseCreator->getDocuments();
$array = array_merge ( $array, $array2 );
}
}
/*
echo '<pre>';
print_r($array);
echo '</pre>';
die();
*/
$delimiter = ',';
unlink( 'eksport.epp');
if (count ( $array ) > 0) {
$fp = fopen ( 'eksport.epp', 'w' );
fwriteEncoding ( $fp, "[INFO]\r\n" );
fwriteEncoding ( $fp, '"1.05.4",0,1250,"Subiekt GT","GT","SubTest","Firma przykładowa systemu InsERT GT","Wrocław","54-445","Bławatkowa 25/3","111-111-11-11","MAG","Główny","Magazyn główny",,1,20170101000000,20170331000000,"Kowalski Jan",20170804155934,"Polska","PL",,0' . "\r\n\r\n" );
foreach ( $array as $element ) {
fwriteEncoding ( $fp, "[NAGLOWEK]\r\n" );
$arrayElement = ( array ) $element;
unset ( $arrayElement ['pozycjeObiekt'] );
fwriteArray ( $fp, $arrayElement, $delimiter );
fwriteEncoding ( $fp, "\r\n" );
$pozycje = $element->getPozycjeObiekt ();
if (count ( $pozycje ) > 0) {
fwriteEncoding ( $fp, "[ZAWARTOSC]\r\n" );
foreach ( $pozycje as $pozycja ) {
fwriteArray ( $fp, ( array ) $pozycja, $delimiter );
}
fwriteEncoding ( $fp, "\r\n" );
} else {
fwriteEncoding ( $fp, "[ZAWARTOSC]\r\n" );
fwriteEncoding ( $fp, "\r\n" );
}
}
fwriteEncoding ( $fp, "[NAGLOWEK]\r\n" );
fwriteEncoding ( $fp, "\"KONTRAHENCI\"\r\n\r\n" );
fwriteEncoding ( $fp, "[ZAWARTOSC]\r\n" );
foreach ( $invoiceCreator->kontrahenci as $pozycja ) {
fwriteArray ( $fp, ( array ) $pozycja, $delimiter );
}
/*
foreach ( $purchaseCreator->kontrahenci as $pozycja ) {
fwriteArray ( $fp, ( array ) $pozycja, $delimiter );
}*/
fwriteEncoding ( $fp, "\r\n" );
}
$quoted = sprintf('"%s"', addcslashes(basename('eksport.epp'), '"\\'));
$size = filesize('eksport.epp');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $quoted);
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size);
ob_clean();
flush();
readfile('eksport.epp'); //Absolute URL
exit();
} else {
$smarty = new Sugar_Smarty ();
$smarty->assign ( 'dateFormat', $Calendar_daFormat = str_replace ( "d", "%d", str_replace ( "m", "%m", str_replace ( "Y", "%Y", $GLOBALS ['timedate']->get_date_format () ) ) ) );
$smarty->assign ( "date", $date );
echo $smarty->fetch ( "modules/EcmReports/RewizorGT/form.tpl.html" );
}
function fwriteEncoding($fp,$text){
//cp1250
return fwrite($fp, iconv('UTF-8//TRANSLIT',"Windows-1250//TRANSLIT",$text));
}
function fwriteArray($fp, $array, $delimiter) {
$string = "";
$i = 0;
$len = count ( $array );
foreach ( $array as $key => $value ) {
if ($i == $len - 1) {
$string .= addEnclosure ( $value ) . "\r\n";
} else {
$string .= addEnclosure ( $value ) . $delimiter;
}
// …
$i ++;
}
fwriteEncoding ( $fp, $string );
}
function addEnclosure($value) {
if (is_string ( $value )) {
return '"' . $value . '"';
} else {
return $value;
}
}
?>

View File

@@ -0,0 +1,38 @@
<?php
class Pozycja{
public $symbol_stawki_vat;
public $wysokosc_stawki_vat_w_procentach;
public $wartosc_netto;
public $wartosc_vat;
public $wartosc_brutto;
public $wartosc_netto_ogolna_koncowa=0;
public $wartosc_vat_ogolna_koncowa=0;
public $wartosc_brutto_ogolna_koncowa=0;
public $wartosc_netto_poprzednich_zaliczek=0;
public $wartosc_vat_poprzednich_zaliczek=0;
public $wartosc_brutto_poprzednich_zaliczek=0;
public $wartosc_netto_w_pln_poprzednich_zaliczek=0;
public $wartosc_vat_w_pln_poprzednich_zaliczek=0;
public $wartosc_brutto_w_pln_poprzednich_zaliczek=0;
public $wartosc_netto_marzy=0;
public $wartosc_vat_marzy=0;
public $wartosc_brutto_marzy=0;
public $wartosc_nabycia;
public function dupa(){
$pozycja->symbol_stawki_vat = $dane ['ecmvat_value'];
$pozycja->wysokosc_stawki_vat_w_procentach = $dane ['ecmvat_value'] . '.00';
if ($dokument->numer_dokumentu_korygowanego != '') {
$pozycja->wartosc_netto = $dane ['total_netto_corrected'];
$pozycja->wartosc_vat = $dane ['total_vat_corrected'];
$pozycja->wartosc_brutto = $dane ['total_brutto_corrected'];
} else {
$pozycja->wartosc_netto = $dane ['total_netto'];
$pozycja->wartosc_vat = $dane ['total_vat'];
$pozycja->wartosc_brutto = $dane ['total_brutto'];
}
$pozycja->wartosc_nabycia = round ( $dane ['price_purchase'] * $dane ['quantity'], 2 );
}
}
?>

View File

@@ -0,0 +1,190 @@
<?php
class PurchaseCreator{
private $db;
public $kontrahenci;
public function __construct($date){
$this->db=$GLOBALS['db'];
$date = new DateTime($date);
$this->date_from = $date->format("Y-m-01");
$this->date_to=$date->format("Y-m-t");
$this->kontrahenci=[];
}
public function getPurchases($type){
$query="select * from documents where document_date>='" . $this->date_from . "' and document_date<='" . $this->date_to . "' and category_id in ('invoice','compain_note','return_note') and deleted=0";
if ($type == "new") {
$query .= " and exported = 0";
}
$rs = $this->db->query($query);
global $app_list_strings;
$documents=array();
while($dane = $this->db->fetchByAssoc($rs)){
$dokument = new Dokument();
$kontrahent = new Kontrahent();
if($dane['corrected_document_name']!=""){
$dokument->typ_dokumentu=(string)'KFZ';
} else {
$dokument->typ_dokumentu=(string)'FZ';
}
$dokument->status_dokumentu=1;
$dokument->status_rejestracji_fiskalnej=0;
$dokument->numer_dokumentu=0;
$dokument->numer_dokumentu_dostawcy=str_replace("Faktura VAT nr ","",$dane['document_name']);
$dokument->rozszerzenie_numeru=(string)"FZ";
$dokument->pelny_numer_dokumentu=str_replace("Faktura VAT nr ","",$dane['document_name']);
if($dane['corrected_document_name']!=""){
$dokument->numer_dokumentu_korygowanego=$dane['corrected_document_name'];
$dokument->data_wystawienia_korekty=date("Ymd000000",strtotime($dane['document_date']));
} else {
$dokument->numer_dokumentu_korygowanego=null;
$dokument->data_wystawienia_korekty=null;
}
$dokument->numer_zamowienia=null;
$dokument->magazyn_docelowy=null;
$value = new Document();
$value->retrieve($dane['id']);
$relations=$value->getParentList(true);
$a = new Account ();
$a->retrieve ( $relations[0]['parent_id']);
$a->name=str_replace("\r\n","",$a->name);
$dokument->kod_identyfikacyjny_kontrahenta=$a->index_dbf;
$dokument->nazwa_skrocona=mb_substr($a->name,0,40,'UTF-8');
$dokument->nazwa_pelna=str_replace("\r\n","",$a->name);
$dokument->miasto=$a->billing_address_city;
$dokument->kod_pocztowy=$a->billing_address_postalcode;
$dokument->ulica_i_numer=$a->billing_address_street;
$dokument->nip=$a->to_vatid;
$dokument->kategoria=null;
$dokument->podtytul=null;
$kontrahent->typ_kontrahenta=(float)0;
$kontrahent->kod_identyfikacyjny=$a->index_dbf;
$kontrahent->nazwa_skrocona=mb_substr($a->name,0,40,'UTF-8');
$kontrahent->nazwa_pelna=str_replace("\r\n","",$a->name);
$kontrahent->miasto=$a->billing_address_city;
$kontrahent->kod_pocztowy=$a-billing_address_postalcode;
$kontrahent->ulica_i_adres=$a->billing_address_street;
$kontrahent->nip=$a->to_vatid;
if($a->invoice_type=='U'){
$kontrahent->prefix=mb_substr($a->to_vatid,0,2,'UTF-8');
$kontrahent->czy_unijny=1;
} else {
$kontrahent->czy_unijny=0;
}
$this->kontrahenci[$a->id]=$kontrahent;
$dokument->data_wystawienia=date("Ymd000000",strtotime($dane['document_date']));
$dokument->data_sprzedazy=date("Ymd000000",strtotime($dane['document_date']));
$dokument->data_otrzymania=date("Ymd000000",strtotime($dane['document_date']));
$sumQuery=$this->db->query("select ROUND(sum(netto),2) AS total_netto,ROUND(sum(vat),2) AS total_vat,ROUND(sum(vat+netto),2) AS total_brutto from documents_vat WHERE document_id='".$dane['id']."' and netto!='NaN' and vat!='NaN' and netto!=0 and deleted=0");
$sumRes=$this->db->fetchByAssoc($sumQuery);
$dokument->czy_dokumenty_wystawian_wg_ceny_netto=0;
$dokument->wartosc_netto=(float)$sumRes['total_netto'];
$dokument->wartosc_vat=(float)$sumRes['total_vat'];
$dokument->wartosc_brutto=(float)$sumRes['total_brutto'];
$dokument->koszt=(float)$dane['value'];
if($dane['payment_date']!=""){
$dokument->rabat_format_platnosci='przelew';
$dokument->rabat_termin_platnosci=date("Ymd000000",strtotime($dane['payment_date']));
} else {
$dokument->rabat_format_platnosci='gotówka';
$dokument->rabat_termin_platnosci=date("Ymd000000",strtotime($dane['document_date']));
}
if($dane['left_paid']!=0){
$dokument->kwota_zaplacona_przy_odbiorze=(float)$dane['left_paid'];;
$dokument->wartosc_do_zaplaty=(float)round($dane['value'],2);
} else {
$dokument->kwota_zaplacona_przy_odbiorze=(float)$dane['value'];
$dokument->wartosc_do_zaplaty=(float)$dane['value'];
}
$dokument->zaokraglenie_wartosci_do_zaplaty=0;
$dokument->zaokraglenie_wartosci_vat=0;
$dokument->automatyczne_zaokgraglanie=0;
$dokument->statusy_rozszerzone_i_specjalne=0;
$u = new User();
$u->retrieve($dane['assigned_user_id']);
$dokument->nazwisko_i_imie_wystawcy=$u->full_name;
if($dane['currency_id']=="PLN"){
$dokument->waluta='PLN';
} else {
$cur = new Currency();
$cur->retrieve($dane['currency_id']);
$dokument->waluta=$cur->name;
$dokument->kurs_waluty=(float)$dane['currency_value'];
}
$dokument->uwagi=null;
$dokument->import_dokumentu=0;
if($dane['document_type']=='k'){
$dokument->rodzaj_transakcji=0;
} else {
if($dane['document_type']=='u'){
$dokument->rodzaj_transakcji=2;
} else {
$dokument->rodzaj_transakcji=1;
}
}
$dokument->panstwo_kontrahenta=$a->billing_address_country;
if($a->invoice_type=='U'){
$dokument->prefix_panstwa_ue=mb_substr($a->to_vatid,0,2,'UTF-8');
$dokument->czy_kontrahent_unijny=1;
}
$dokument->setPozycjeObiekt($this->getDocumentPositions($dane['id'],$dokument));
$documents[]=$dokument;
$query="update documents set exported = 1 where id='".$dane['id']."'";
$this->db->query($query);
}
return $documents;
}
public function getDocumentPositions($id,&$doc){
$query="select * from documents_vat WHERE document_id='".$id."' and netto!='NaN' and vat!='NaN' and netto!=0 and deleted=0";
$rr=$this->db->query($query);
$pozycje=[];
while($dane=$this->db->fetchByAssoc($rr)){
$pozycja = new Pozycja;
$pozycja->symbol_stawki_vat = $dane ['vat_id'];
$pozycja->wysokosc_stawki_vat_w_procentach = floatval($dane ['vat_id'] . '.00');
if ($doc->numer_dokumentu_korygowanego != '') {
$pozycja->wartosc_netto =(float)$dane ['netto'];
$pozycja->wartosc_vat =(float)$dane ['vat'];
$pozycja->wartosc_brutto = (float)round( $dane ['netto']+ $dane ['vat'],2);
} else {
$pozycja->wartosc_netto =(float)$dane ['netto'];
$pozycja->wartosc_vat =(float)$dane ['vat'];
$pozycja->wartosc_brutto = (float)round( $dane ['netto']+ $dane ['vat'],2);
}
$pozycja->wartosc_nabycia =(float)round( $dane ['netto']+ $dane ['vat'],2);
$pozycje[]=$pozycja;
}
$doc->pozycje=count($pozycja);
return $pozycje;
}
}
?>

View File

@@ -0,0 +1,164 @@
<?php
class PwCreator{
private $db;
public $kontrahenci;
public function __construct($date){
$this->db=$GLOBALS['db'];
$date = new DateTime($date);
$this->date_from = $date->format("Y-m-01");
$this->date_to=$date->format("Y-m-t");
$this->kontrahenci=[];
}
public function getDocuments(){
$query="select * from ecmstockdocinsideins where deleted=0 and register_date >='".$this->date_from."' and register_date <='".$this->date_to."' order by document_no ASC";
$rs = $this->db->query($query);
global $app_list_strings;
$documents=array();
while($dane = $this->db->fetchByAssoc($rs)){
$dokument = new Dokument();
$kontrahent = new Kontrahent();
$dokument->typ_dokumentu=(string)'PW';
$dokument->status_dokumentu=1;
$dokument->status_rejestracji_fiskalnej=0;
$dokument->numer_dokumentu=0;
$dokument->numer_dokumentu_dostawcy=$dane['document_no'];
$dokument->rozszerzenie_numeru=(string)"PW";
$dokument->pelny_numer_dokumentu=$dane['document_no'];
$dokument->numer_dokumentu_korygowanego=null;
$dokument->data_wystawienia_korekty=null;
$dane['parent_nip']=$kontrahent->to_vatid;
$letters = substr($dane['parent_nip'],0,2);
if(ctype_alpha ($letters)){
$rest = substr($dane['parent_nip'],2);
$dane['parent_nip']=$letters.' '.$rest;
}
$dokument->numer_zamowienia="";
$dokument->magazyn_docelowy=null;
$a = new Account();
$a->retrieve($dane['parent_id']);
$a->name=str_replace("\r\n","",$a->name);
$kontrahent->typ_kontrahenta=(float)0;
$kontrahent->kod_identyfikacyjny=$a->number;
$kontrahent->nazwa_skrocona=mb_substr($dane['parent_name'],0,40,'UTF-8');
$kontrahent->nazwa_pelna=str_replace("\r\n","",$dane['parent_name']);
$kontrahent->miasto=$dane['parent_address_city'];
$kontrahent->kod_pocztowy=$a->billing_address_postalcode;
$kontrahent->ulica_i_adres=$dane['parent_address_street'];
$kontrahent->nip=$dane['parent_nip'];
if($a->invoice_type=='U'){
$kontrahent->prefix=mb_substr($a->to_vatid,0,2,'UTF-8');
$kontrahent->czy_unijny=1;
} else {
$kontrahent->czy_unijny=0;
}
$this->kontrahenci[$a->id]=$kontrahent;
$dokument->kod_identyfikacyjny_kontrahenta=$a->number;
$dokument->nazwa_skrocona=mb_substr($dane['parent_name'],0,40,'UTF-8');
$dokument->nazwa_pelna=str_replace("\r\n","",$dane['parent_name']);
$dokument->miasto=$dane['parent_address_city'];
$dokument->kod_pocztowy=$a->billing_address_postalcode;
$dokument->ulica_i_numer=$dane['parent_address_street'];
$dokument->nip=$dane['parent_nip'];
$dokument->kategoria="Magazyn";
$dokument->podtytul='Dokument magazynowy';
$dokument->data_wystawienia=date("Ymd000000",strtotime($dane['register_date']));
$dokument->data_sprzedazy=date("Ymd000000",strtotime($dane['register_date']));
$dokument->data_otrzymania=date("Ymd000000",strtotime($dane['register_date']));
$dokument->czy_dokumenty_wystawian_wg_ceny_netto=0;
$dokument->wartosc_netto=(float)$dane['total'];
$dokument->wartosc_vat=(float)$dane['total_vat'];
$dokument->wartosc_brutto=(float)$dane['total'];
$dokument->koszt=(float)$dane['total'];
$dokument->rabat_format_platnosci=$app_list_strings['payment_method'][$dane['payment_method']];
$dokument->rabat_termin_platnosci=date("Ymd000000",strtotime($dane['payment_date']));
$dokument->kwota_zaplacona_przy_odbiorze=(float)0;
$dokument->wartosc_do_zaplaty=(float)0;
$dokument->zaokraglenie_wartosci_do_zaplaty=0;
$dokument->zaokraglenie_wartosci_vat=0;
$dokument->automatyczne_zaokgraglanie=0;
$dokument->statusy_rozszerzone_i_specjalne=0;
$u = new User();
$u->retrieve($dane['assigned_user_id']);
$dokument->nazwisko_i_imie_wystawcy=$u->full_name;
$dokument->waluta='PLN';
$dokument->uwagi=str_replace("\r\n","",$dane['pdf_text']);
$dokument->import_dokumentu=0;
$dokument->rodzaj_transakcji=0;
//$dokument->panstwo_kontrahenta=$a->billing_address_country;
//$dokument->setPozycjeObiekt($this->getDocumentPositions($dane['id'],$dokument));
$documents[]=$dokument;
}
return $documents;
}
public function getDocumentPositions($id,&$doc){
$query="select * from ecminvoiceoutitems where ecminvoiceout_id='".$id."' and deleted=0";
$rr=$this->db->query($query);
$pozycje=[];
while($dane=$this->db->fetchByAssoc($rr)){
if($pozycje[$dane ['ecmvat_value']]!=""){
$obiekt = $pozycje[$dane ['ecmvat_value']];
if ($doc->typ_dokumentu!= 'FS') {
$obiekt->wartosc_netto+= $dane ['total_netto_corrected'];
$obiekt->wartosc_vat+= $dane ['total_vat_corrected'];
$obiekt->wartosc_brutto+= $dane ['total_brutto_corrected'];
} else {
$obiekt->wartosc_netto+= $dane ['total_netto'];
$obiekt->wartosc_vat+= $dane ['total_vat'];
$obiekt->wartosc_brutto+= $dane ['total_brutto'];
}
$obiekt->wartosc_nabycia+= round ( $dane ['price_purchase'] * $dane ['quantity'], 2 );
$pozycje[$dane ['ecmvat_value']]=$obiekt;
} else {
$pozycja = new Pozycja;
$pozycja->symbol_stawki_vat = $dane ['ecmvat_value'];
$pozycja->wysokosc_stawki_vat_w_procentach = floatval ($dane ['ecmvat_value'] . '.00');
if ($doc->typ_dokumentu!= 'FS') {
$pozycja->wartosc_netto =floatval($dane ['total_netto_corrected']);
$pozycja->wartosc_vat = floatval($dane ['total_vat_corrected']);
$pozycja->wartosc_brutto =floatval($dane ['total_brutto_corrected']);
} else {
$pozycja->wartosc_netto = floatval($dane ['total_netto']);
$pozycja->wartosc_vat = floatval($dane ['total_vat']);
$pozycja->wartosc_brutto = floatval($dane ['total_brutto']);
}
$pozycja->wartosc_nabycia = round ( $dane ['price_purchase'] * $dane ['quantity'], 2 );
$pozycje[$dane ['ecmvat_value']]=$pozycja;
}
}
$doc->pozycje=count($pozycja);
return $pozycje;
}
}
?>

View File

@@ -0,0 +1,165 @@
<?php
class PzCreator{
private $db;
public $kontrahenci;
public function __construct($date){
$this->db=$GLOBALS['db'];
$date = new DateTime($date);
$this->date_from = $date->format("Y-m-01");
$this->date_to=$date->format("Y-m-t");
$this->kontrahenci=[];
}
public function getDocuments(){
$query="select * from ecmstockdocins where deleted=0 and register_date >='".$this->date_from."' and register_date <='".$this->date_to."' order by document_no ASC";
$rs = $this->db->query($query);
global $app_list_strings;
$documents=array();
while($dane = $this->db->fetchByAssoc($rs)){
$dokument = new Dokument();
$kontrahent = new Kontrahent();
$dokument->typ_dokumentu=(string)'PZ';
$dokument->status_dokumentu=1;
$dokument->status_rejestracji_fiskalnej=0;
$dokument->numer_dokumentu=0;
$dokument->numer_dokumentu_dostawcy=$dane['document_no'];
$dokument->rozszerzenie_numeru=(string)"PZ";
$dokument->pelny_numer_dokumentu=$dane['document_no'];
$dokument->numer_dokumentu_korygowanego=null;
$dokument->data_wystawienia_korekty=null;
$dane['parent_nip']=$kontrahent->to_vatid;
$letters = substr($dane['parent_nip'],0,2);
if(ctype_alpha ($letters)){
$rest = substr($dane['parent_nip'],2);
$dane['parent_nip']=$letters.' '.$rest;
}
$dokument->numer_zamowienia="";
$dokument->magazyn_docelowy=null;
$a = new Account();
$a->retrieve($dane['parent_id']);
$a->name=str_replace("\r\n","",$a->name);
$dane['parent_name']=str_replace("\r\n","",$dane['parent_name']);
$kontrahent->typ_kontrahenta=(float)0;
$kontrahent->kod_identyfikacyjny=$a->number;
$kontrahent->nazwa_skrocona=mb_substr($dane['parent_name'],0,40,'UTF-8');
$kontrahent->nazwa_pelna=str_replace("\r\n","",$dane['parent_name']);
$kontrahent->miasto=$dane['parent_address_city'];
$kontrahent->kod_pocztowy=$a->billing_address_postalcode;
$kontrahent->ulica_i_adres=str_replace("\n","",str_replace("\r\n","",$dane['parent_address_street']));
$kontrahent->nip=$dane['parent_nip'];
if($a->invoice_type=='U'){
$kontrahent->prefix=mb_substr($a->to_vatid,0,2,'UTF-8');
$kontrahent->czy_unijny=1;
} else {
$kontrahent->czy_unijny=0;
}
$this->kontrahenci[$a->id]=$kontrahent;
$dokument->kod_identyfikacyjny_kontrahenta=$a->number;
$dokument->nazwa_skrocona=mb_substr($dane['parent_name'],0,40,'UTF-8');
$dokument->nazwa_pelna=str_replace("\r\n","",$dane['parent_name']);
$dokument->miasto=$dane['parent_address_city'];
$dokument->kod_pocztowy=$a->billing_address_postalcode;
$dokument->ulica_i_numer=str_replace("\n","",str_replace("\r\n","",$dane['parent_address_street']));
$dokument->nip=$dane['parent_nip'];
$dokument->kategoria="Magazyn";
$dokument->podtytul='Dokument magazynowy';
$dokument->data_wystawienia=date("Ymd000000",strtotime($dane['register_date']));
$dokument->data_sprzedazy=date("Ymd000000",strtotime($dane['data_fk']));
$dokument->data_otrzymania=date("Ymd000000",strtotime($dane['register_date']));
$dokument->czy_dokumenty_wystawian_wg_ceny_netto=0;
$dokument->wartosc_netto=(float)$dane['total'];
$dokument->wartosc_vat=(float)0;
$dokument->wartosc_brutto=(float)$dane['total'];
$dokument->koszt=(float)$dane['total'];
$dokument->rabat_format_platnosci=$app_list_strings['payment_method'][$dane['payment_method']];
$dokument->rabat_termin_platnosci=date("Ymd000000",strtotime($dane['payment_date']));
$dokument->kwota_zaplacona_przy_odbiorze=(float)0;
$dokument->wartosc_do_zaplaty=(float)0;
$dokument->zaokraglenie_wartosci_do_zaplaty=0;
$dokument->zaokraglenie_wartosci_vat=0;
$dokument->automatyczne_zaokgraglanie=0;
$dokument->statusy_rozszerzone_i_specjalne=0;
$u = new User();
$u->retrieve($dane['assigned_user_id']);
$dokument->nazwisko_i_imie_wystawcy=$u->full_name;
$dokument->waluta='PLN';
$dokument->uwagi=str_replace("\r\n","",$dane['pdf_text']);
$dokument->import_dokumentu=0;
$dokument->rodzaj_transakcji=0;
//$dokument->panstwo_kontrahenta=$a->billing_address_country;
//$dokument->setPozycjeObiekt($this->getDocumentPositions($dane['id'],$dokument));
$documents[]=$dokument;
}
return $documents;
}
public function getDocumentPositions($id,&$doc){
$query="select * from ecminvoiceoutitems where ecminvoiceout_id='".$id."' and deleted=0";
$rr=$this->db->query($query);
$pozycje=[];
while($dane=$this->db->fetchByAssoc($rr)){
if($pozycje[$dane ['ecmvat_value']]!=""){
$obiekt = $pozycje[$dane ['ecmvat_value']];
if ($doc->typ_dokumentu!= 'FS') {
$obiekt->wartosc_netto+= $dane ['total_netto_corrected'];
$obiekt->wartosc_vat+= $dane ['total_vat_corrected'];
$obiekt->wartosc_brutto+= $dane ['total_brutto_corrected'];
} else {
$obiekt->wartosc_netto+= $dane ['total_netto'];
$obiekt->wartosc_vat+= $dane ['total_vat'];
$obiekt->wartosc_brutto+= $dane ['total_brutto'];
}
$obiekt->wartosc_nabycia+= round ( $dane ['price_purchase'] * $dane ['quantity'], 2 );
$pozycje[$dane ['ecmvat_value']]=$obiekt;
} else {
$pozycja = new Pozycja;
$pozycja->symbol_stawki_vat = $dane ['ecmvat_value'];
$pozycja->wysokosc_stawki_vat_w_procentach = floatval ($dane ['ecmvat_value'] . '.00');
if ($doc->typ_dokumentu!= 'FS') {
$pozycja->wartosc_netto =floatval($dane ['total_netto_corrected']);
$pozycja->wartosc_vat = floatval($dane ['total_vat_corrected']);
$pozycja->wartosc_brutto =floatval($dane ['total_brutto_corrected']);
} else {
$pozycja->wartosc_netto = floatval($dane ['total_netto']);
$pozycja->wartosc_vat = floatval($dane ['total_vat']);
$pozycja->wartosc_brutto = floatval($dane ['total_brutto']);
}
$pozycja->wartosc_nabycia = round ( $dane ['price_purchase'] * $dane ['quantity'], 2 );
$pozycje[$dane ['ecmvat_value']]=$pozycja;
}
}
$doc->pozycje=count($pozycja);
return $pozycje;
}
}
?>

View File

@@ -0,0 +1,164 @@
<?php
class RwCreator{
private $db;
public $kontrahenci;
public function __construct($date){
$this->db=$GLOBALS['db'];
$date = new DateTime($date);
$this->date_from = $date->format("Y-m-01");
$this->date_to=$date->format("Y-m-t");
$this->kontrahenci=[];
}
public function getDocuments(){
$query="select * from ecmstockdocinsideouts where deleted=0 and register_date >='".$this->date_from."' and register_date <='".$this->date_to."' order by document_no ASC";
$rs = $this->db->query($query);
global $app_list_strings;
$documents=array();
while($dane = $this->db->fetchByAssoc($rs)){
$dokument = new Dokument();
$kontrahent = new Kontrahent();
$dokument->typ_dokumentu=(string)'RW';
$dokument->status_dokumentu=1;
$dokument->status_rejestracji_fiskalnej=0;
$dokument->numer_dokumentu=0;
$dokument->numer_dokumentu_dostawcy=$dane['document_no'];
$dokument->rozszerzenie_numeru=(string)"RW";
$dokument->pelny_numer_dokumentu=$dane['document_no'];
$dokument->numer_dokumentu_korygowanego=null;
$dokument->data_wystawienia_korekty=null;
$dane['parent_nip']=$kontrahent->to_vatid;
$letters = substr($dane['parent_nip'],0,2);
if(ctype_alpha ($letters)){
$rest = substr($dane['parent_nip'],2);
$dane['parent_nip']=$letters.' '.$rest;
}
$dokument->numer_zamowienia="";
$dokument->magazyn_docelowy=null;
$a = new Account();
$a->retrieve($dane['parent_id']);
$a->name=str_replace("\r\n","",$a->name);
$kontrahent->typ_kontrahenta=(float)0;
$kontrahent->kod_identyfikacyjny=$a->number;
$kontrahent->nazwa_skrocona=mb_substr($dane['parent_name'],0,40,'UTF-8');
$kontrahent->nazwa_pelna=str_replace("\r\n","",$dane['parent_name']);
$kontrahent->miasto=$dane['parent_address_city'];
$kontrahent->kod_pocztowy=$a->billing_address_postalcode;
$kontrahent->ulica_i_adres=$dane['parent_address_street'];
$kontrahent->nip=$dane['parent_nip'];
if($a->invoice_type=='U'){
$kontrahent->prefix=mb_substr($a->to_vatid,0,2,'UTF-8');
$kontrahent->czy_unijny=1;
} else {
$kontrahent->czy_unijny=0;
}
$this->kontrahenci[$a->id]=$kontrahent;
$dokument->kod_identyfikacyjny_kontrahenta=$a->number;
$dokument->nazwa_skrocona=mb_substr($dane['parent_name'],0,40,'UTF-8');
$dokument->nazwa_pelna=str_replace("\r\n","",$dane['parent_name']);
$dokument->miasto=$dane['parent_address_city'];
$dokument->kod_pocztowy=$a->billing_address_postalcode;
$dokument->ulica_i_numer=$dane['parent_address_street'];
$dokument->nip=$dane['parent_nip'];
$dokument->kategoria="Magazyn";
$dokument->podtytul='Dokument magazynowy';
$dokument->data_wystawienia=date("Ymd000000",strtotime($dane['register_date']));
$dokument->data_sprzedazy=date("Ymd000000",strtotime($dane['register_date']));
$dokument->data_otrzymania=date("Ymd000000",strtotime($dane['register_date']));
$dokument->czy_dokumenty_wystawian_wg_ceny_netto=0;
$dokument->wartosc_netto=(float)$dane['total'];
$dokument->wartosc_vat=(float)$dane['total_vat'];
$dokument->wartosc_brutto=(float)$dane['total'];
$dokument->koszt=(float)$dane['total'];
$dokument->rabat_format_platnosci=$app_list_strings['payment_method'][$dane['payment_method']];
$dokument->rabat_termin_platnosci=date("Ymd000000",strtotime($dane['payment_date']));
$dokument->kwota_zaplacona_przy_odbiorze=(float)0;
$dokument->wartosc_do_zaplaty=(float)0;
$dokument->zaokraglenie_wartosci_do_zaplaty=0;
$dokument->zaokraglenie_wartosci_vat=0;
$dokument->automatyczne_zaokgraglanie=0;
$dokument->statusy_rozszerzone_i_specjalne=0;
$u = new User();
$u->retrieve($dane['assigned_user_id']);
$dokument->nazwisko_i_imie_wystawcy=$u->full_name;
$dokument->waluta='PLN';
$dokument->uwagi=str_replace("\r\n","",$dane['pdf_text']);
$dokument->import_dokumentu=0;
$dokument->rodzaj_transakcji=0;
//$dokument->panstwo_kontrahenta=$a->billing_address_country;
//$dokument->setPozycjeObiekt($this->getDocumentPositions($dane['id'],$dokument));
$documents[]=$dokument;
}
return $documents;
}
public function getDocumentPositions($id,&$doc){
$query="select * from ecminvoiceoutitems where ecminvoiceout_id='".$id."' and deleted=0";
$rr=$this->db->query($query);
$pozycje=[];
while($dane=$this->db->fetchByAssoc($rr)){
if($pozycje[$dane ['ecmvat_value']]!=""){
$obiekt = $pozycje[$dane ['ecmvat_value']];
if ($doc->typ_dokumentu!= 'FS') {
$obiekt->wartosc_netto+= $dane ['total_netto_corrected'];
$obiekt->wartosc_vat+= $dane ['total_vat_corrected'];
$obiekt->wartosc_brutto+= $dane ['total_brutto_corrected'];
} else {
$obiekt->wartosc_netto+= $dane ['total_netto'];
$obiekt->wartosc_vat+= $dane ['total_vat'];
$obiekt->wartosc_brutto+= $dane ['total_brutto'];
}
$obiekt->wartosc_nabycia+= round ( $dane ['price_purchase'] * $dane ['quantity'], 2 );
$pozycje[$dane ['ecmvat_value']]=$obiekt;
} else {
$pozycja = new Pozycja;
$pozycja->symbol_stawki_vat = $dane ['ecmvat_value'];
$pozycja->wysokosc_stawki_vat_w_procentach = floatval ($dane ['ecmvat_value'] . '.00');
if ($doc->typ_dokumentu!= 'FS') {
$pozycja->wartosc_netto =floatval($dane ['total_netto_corrected']);
$pozycja->wartosc_vat = floatval($dane ['total_vat_corrected']);
$pozycja->wartosc_brutto =floatval($dane ['total_brutto_corrected']);
} else {
$pozycja->wartosc_netto = floatval($dane ['total_netto']);
$pozycja->wartosc_vat = floatval($dane ['total_vat']);
$pozycja->wartosc_brutto = floatval($dane ['total_brutto']);
}
$pozycja->wartosc_nabycia = round ( $dane ['price_purchase'] * $dane ['quantity'], 2 );
$pozycje[$dane ['ecmvat_value']]=$pozycja;
}
}
$doc->pozycje=count($pozycja);
return $pozycje;
}
}
?>

View File

@@ -0,0 +1,172 @@
<?php
class WzCreator{
private $db;
public $kontrahenci;
public function __construct($date){
$this->db=$GLOBALS['db'];
$date = new DateTime($date);
$this->date_from = $date->format("Y-m-01");
$this->date_to=$date->format("Y-m-t");
$this->kontrahenci=[];
}
public function getDocuments(){
$query="select * from ecmstockdocouts where deleted=0 and register_date >='".$this->date_from."' and register_date <='".$this->date_to."' order by document_no ASC";
$rs = $this->db->query($query);
global $app_list_strings;
$documents=array();
while($dane = $this->db->fetchByAssoc($rs)){
$dokument = new Dokument();
$kontrahent = new Kontrahent();
$dokument->typ_dokumentu=(string)'WZ';
$dokument->status_dokumentu=1;
$dokument->status_rejestracji_fiskalnej=0;
$dokument->numer_dokumentu=0;
$dokument->numer_dokumentu_dostawcy=$dane['document_no'];
$dokument->rozszerzenie_numeru=(string)"WZ";
$dokument->pelny_numer_dokumentu=$dane['document_no'];
$dokument->numer_dokumentu_korygowanego=null;
$dokument->data_wystawienia_korekty=null;
$dane['parent_nip']=$kontrahent->to_vatid;
$letters = substr($dane['parent_nip'],0,2);
if(ctype_alpha ($letters)){
$rest = substr($dane['parent_nip'],2);
$dane['parent_nip']=$letters.' '.$rest;
}
$dokument->numer_zamowienia="";
$dokument->magazyn_docelowy=null;
$a = new Account();
$a->retrieve($dane['parent_id']);
$a->name=str_replace("\r\n","",$a->name);
$dane['parent_name']=str_replace("\r\n","",$dane['parent_name']);
$kontrahent->typ_kontrahenta=(float)0;
$kontrahent->kod_identyfikacyjny=$a->number;
$kontrahent->nazwa_skrocona=mb_substr($dane['parent_name'],0,40,'UTF-8');
$kontrahent->nazwa_pelna=str_replace("\r\n","",$dane['parent_name']);
$kontrahent->miasto=$dane['parent_address_city'];
$kontrahent->kod_pocztowy=$a->billing_address_postalcode;
$kontrahent->ulica_i_adres=str_replace("\n"," ",str_replace("\r\n"," ",$dane['parent_address_street']));
$kontrahent->nip=$dane['parent_nip'];
if($a->invoice_type=='U'){
$kontrahent->prefix=mb_substr($a->to_vatid,0,2,'UTF-8');
$kontrahent->czy_unijny=1;
} else {
$kontrahent->czy_unijny=0;
}
$this->kontrahenci[$a->id]=$kontrahent;
$dokument->kod_identyfikacyjny_kontrahenta=$a->number;
$dokument->nazwa_skrocona=mb_substr($dane['parent_name'],0,40,'UTF-8');
$dokument->nazwa_pelna=str_replace("\r\n","",$dane['parent_name']);
$dokument->miasto=$dane['parent_address_city'];
$dokument->kod_pocztowy=$a->billing_address_postalcode;
$dokument->ulica_i_numer=$a->billing_address_street;
$dokument->nip=$dane['parent_nip'];
$dokument->kategoria="Magazyn";
$dokument->podtytul='Dokument magazynowy';
$dokument->data_wystawienia=date("Ymd000000",strtotime($dane['register_date']));
$dokument->data_sprzedazy=date("Ymd000000",strtotime($dane['register_date']));
$dokument->data_otrzymania=date("Ymd000000",strtotime($dane['register_date']));
$dokument->czy_dokumenty_wystawian_wg_ceny_netto=0;
$query2="select round(sum(quantity*price),2) as total from ecmstockoperations where parent_id='".$dane['id']."' and deleted=0";
$zz=$this->db->query($query2);
$dane22 = $this->db->fetchByAssoc($zz);
$dokument->wartosc_netto=(float)$dane22['total'];
$dokument->wartosc_vat=(float)0;
$dokument->wartosc_brutto=(float)$dane22['total'];
$dokument->koszt=(float)$dane22['total'];
$dokument->rabat_format_platnosci=$app_list_strings['payment_method'][$dane['payment_method']];
$dokument->rabat_termin_platnosci=date("Ymd000000",strtotime($dane['payment_date']));
$dokument->kwota_zaplacona_przy_odbiorze=(float)0;
$dokument->wartosc_do_zaplaty=(float)0;
$dokument->zaokraglenie_wartosci_do_zaplaty=0;
$dokument->zaokraglenie_wartosci_vat=0;
$dokument->automatyczne_zaokgraglanie=0;
$dokument->statusy_rozszerzone_i_specjalne=0;
$u = new User();
$u->retrieve($dane['assigned_user_id']);
$dokument->nazwisko_i_imie_wystawcy=$u->full_name;
$dokument->waluta='PLN';
$dokument->uwagi=str_replace("\r\n","",$dane['pdf_text']);
$dokument->import_dokumentu=0;
$dokument->rodzaj_transakcji=0;
//$dokument->panstwo_kontrahenta=$a->billing_address_country;
//$dokument->setPozycjeObiekt($this->getDocumentPositions($dane['id'],$dokument));
$documents[]=$dokument;
}
return $documents;
}
public function getDocumentPositions($id,&$doc){
$query="select * from ecminvoiceoutitems where ecminvoiceout_id='".$id."' and deleted=0";
$rr=$this->db->query($query);
$pozycje=[];
while($dane=$this->db->fetchByAssoc($rr)){
if($pozycje[$dane ['ecmvat_value']]!=""){
$obiekt = $pozycje[$dane ['ecmvat_value']];
if ($doc->typ_dokumentu!= 'FS') {
$obiekt->wartosc_netto+= $dane ['total_netto_corrected'];
$obiekt->wartosc_vat+= $dane ['total_vat_corrected'];
$obiekt->wartosc_brutto+= $dane ['total_brutto_corrected'];
} else {
$obiekt->wartosc_netto+= $dane ['total_netto'];
$obiekt->wartosc_vat+= $dane ['total_vat'];
$obiekt->wartosc_brutto+= $dane ['total_brutto'];
}
$obiekt->wartosc_nabycia+= round ( $dane ['price_purchase'] * $dane ['quantity'], 2 );
$pozycje[$dane ['ecmvat_value']]=$obiekt;
} else {
$pozycja = new Pozycja;
$pozycja->symbol_stawki_vat = $dane ['ecmvat_value'];
$pozycja->wysokosc_stawki_vat_w_procentach = floatval ($dane ['ecmvat_value'] . '.00');
if ($doc->typ_dokumentu!= 'FS') {
$pozycja->wartosc_netto =floatval($dane ['total_netto_corrected']);
$pozycja->wartosc_vat = floatval($dane ['total_vat_corrected']);
$pozycja->wartosc_brutto =floatval($dane ['total_brutto_corrected']);
} else {
$pozycja->wartosc_netto = floatval($dane ['total_netto']);
$pozycja->wartosc_vat = floatval($dane ['total_vat']);
$pozycja->wartosc_brutto = floatval($dane ['total_brutto']);
}
$pozycja->wartosc_nabycia = round ( $dane ['price_purchase'] * $dane ['quantity'], 2 );
$pozycje[$dane ['ecmvat_value']]=$pozycja;
}
}
$doc->pozycje=count($pozycja);
return $pozycje;
}
}
?>

View File

@@ -0,0 +1,65 @@
<?php
$db=$GLOBALS['db'];
if(isset($_REQUEST['date_from'])){
$from = new DateTime($_REQUEST['date_from']);
} else {
$from = new DateTime(date("01.m.Y"));
}
if(isset($_REQUEST['date_to'])){
$to = new DateTime($_REQUEST['date_to']);
} else {
$to = new DateTime(date("t.m.Y"));
}
$executed=0;
if(isset($_REQUEST['submit'])){
$query="select * from send_report where send_date>='".$from->format('Y-m-d')."' and send_date<='".$to->format('Y-m-d')."'";
if($_REQUEST['number']!=''){
$query.=" and number='".$_REQUEST["number"]."'";
}
if($_REQUEST['account_id']!=''){
$query.=" and parent_id='".$_REQUEST["account_id"]."'";
}
if($_REQUEST['empty']!=''){
$query.=" and number!=''";
}
$zap=$db->query($query);
if($zap->num_rows>0){
$no=1;
while($row=$db->fetchByAssoc($zap)){
$query2="select * from send_report_items where send_report_id='".$row['id']."' order by payment_date desc";
$zap2=$db->query($query2);
$no2=1;
while($row2=$db->fetchByAssoc($zap2)){
$row2['no']=$no2;
$no2++;
$row['records'][]=$row2;
}
$row['no']=$no;
$p = new Account();
$p->retrieve_by_string_fields (array('index_dbf'=>$row['parent_id']));
$row['parent_name']=$p->name;
$data[]=$row;
$no++;
unset($p);
}
} else {
$data=null;
}
$executed=1;
}
$smarty = new Sugar_Smarty ();
$smarty->assign("data", $data);
$smarty->assign("empty", $_REQUEST['empty']);
$smarty->assign("executed", $executed);
$smarty->assign("MOD", $mod_strings);
$smarty->assign("date_from_value", $from->format('d.m.Y'));
$smarty->assign("date_to_value", $to->format('d.m.Y'));
$output = $smarty->fetch('modules/EcmReports/tpls/RaportSMS.tpl');
echo $output;
?>

View File

@@ -0,0 +1,73 @@
<?php
/**
* Klasa pobiera informacje o wЕaЕcicielu faktury
* @author Krzysztof Raciniewski
*
*/
class Account {
/**
* Pobera wszystkie pozycje faktury o unikalnym ID
*
* @param $id -
* unikalny ID faktury
*/
public static function getByAccountId($id) {
$db = $GLOBALS ['db'];
$query = "SELECT * FROM accounts WHERE id='$id'";
$result = $db->query ( $query );
return $result->fetch_assoc();
}
/**
* Metoda stworzy strukturД™ tablicy:
* .
* .
* |
* |
* +----- Kontrahent1 --------------------------+ Dokument1 ------------------> Wpisy na fakturze
* | |
* | |
* | |
* | +-------------------+ Dokument2 ------------------> Wpisy na fakturze
* |
* |
* |
* +----- Kontrahent2 --------------------------+ Kategoria ------------------> Wpisy na fakturze
* . |
* . |
* . |
* +-------------------+ Kategoria2 ------------------> Wpisy na fakturze
*
*
*
*
* Na podstawie tablicy z dokumentami( takД… tablicД™ zwraca metoda getBetweenDate w klasie Invoice i Receipt )
* */
public static function getAccountsFromInvoicesArray($invoices) {
$accounts = array();
foreach( $invoices as $invoice ){
$accounts[$invoice["parent_name"]]["invoices"][] = $invoice;
}
return $accounts;
}
/**
* Zwraca w formie tablicy wszystkie wiersze odpowiedzi na zapytanie
* @param $result
* @return multitype:
*/
public static function getAllFromResult( $result ) {
$itemsArray = array();
while($row = $result->fetch_assoc()){
array_push($itemsArray, $row);
}
return $itemsArray;
}
}
?>

View File

@@ -0,0 +1,183 @@
<?php
include ("class.PurchaseInvoiceItems.php");
/**
* Klasa reprezentujпїЅca fakturпїЅ
*
* @author Kate
*
*/
class Invoice {
/**
* Pobiera jeden dokument o unikalnym identyfikatorze ID
*
* @param $id -
* identyfikator faktury
*/
public static function getById($id) {
$db = $GLOBALS ['db'];
$query = "SELECT * FROM documents d LEFT OUTER JOIN documents_vat dv on d.id= dv.document_id WHERE d.id='$id'";
$result = $db->query ( $query );
$invoiceData = $result->fetch_assoc ();
$invoiceData ["items"] = PurchaseInvoiceItems::getByInvoiceId ( $id );
$invoiceData ["account"] = Account::getByInvoiceId ( $id );
return $invoiceData;
}
/**
* Pobiera wszystkie dokumenty z podanego przedziaпїЅu dat
*
* @param $date_from -
* data od( w formacie YYYY-mm-dd )
* @param $date_to -
* data do( w formacie YYYY-mm-dd )
* @param $type -
* typ faktury(normal/correct)
*/
public static function getBetweenDate($date_from, $date_to, $category, $contractorId) {
$db = $GLOBALS ['db'];
$query = "SELECT * FROM documents
WHERE register_date >= '$date_from'
AND register_date <='$date_to'
AND register_date IS NOT NULL
AND register_date >= STR_TO_DATE('01.01.1990', '%d.%m.%Y')
AND register_date <= STR_TO_DATE('01.01.2515', '%d.%m.%Y')
AND deleted=0
AND canceled=0
AND sdocument_number IS NOT NULL
";
if (! empty ( $contractorId )) {
$query .= " AND parent_id = '" . $contractorId . "'";
}
if( count( $category ) != 0 && $category[0] != "%" ) {
for( $i = 0; $i < count($category); $i++ ) {
if( $i == 0) {
$query .= " AND category = '".$category[$i]."'";
} else {
$query .= " OR category = '".$category[$i]."'";
}
}
}
$query .= " ORDER BY rgister_date asc";
$result = $db->query ( $query );
$invoicesArray = array ();
while ( $invoiceData = $result->fetch_assoc () ) {
// Formatowanie dat zgodnie z datД… systemowД…
$date = new DateTime ( $invoiceData ["register_date"] );
$invoiceData ["register_date"] = $date->format ( 'd.m.Y' );
$date = new DateTime ( $invoiceData ["document_date"] );
$invoiceData ["document_date"] = $date->format ( 'd.m.Y' );
$invoiceData ["items"] = PurchaseInvoiceItems::getByInvoiceId ( $invoiceData ["id"] );
$invoiceData ["account"] = Account::getByAccountId ( $invoiceData ["parent_id"] );
// MnoЕјД™ odpowiednie sumy przez currency_value
Invoice::multiplyValuesByCurrencyValue ( $invoiceData );
// Obliczam wysokoЕД‡ VAT i sumД™ netto
$invoiceData ["netto0"] = Invoice::getNetto ( $invoiceData ["vats_summary"], "0%", $invoiceData["currency_value"]);
$invoiceData ["netto7"] = Invoice::getNetto ( $invoiceData ["vats_summary"], "7%", $invoiceData["currency_value"]);
$invoiceData ["netto8"] = Invoice::getNetto ( $invoiceData ["vats_summary"], "8%", $invoiceData["currency_value"]);
$invoiceData ["netto22"] = Invoice::getNetto ( $invoiceData ["vats_summary"], "22%", $invoiceData["currency_value"]);
$invoiceData ["netto23"] = Invoice::getNetto ( $invoiceData ["vats_summary"], "23%", $invoiceData["currency_value"]);
$invoiceData ["vat0"] = Invoice::getVat ( $invoiceData ["vats_summary"], "0%", $invoiceData["currency_value"]);
$invoiceData ["vat7"] = Invoice::getVat ( $invoiceData ["vats_summary"], "7%", $invoiceData["currency_value"]);
$invoiceData ["vat8"] = Invoice::getVat ( $invoiceData ["vats_summary"], "8%", $invoiceData["currency_value"]);
$invoiceData ["vat22"] = Invoice::getVat ( $invoiceData ["vats_summary"], "22%", $invoiceData["currency_value"]);
$invoiceData ["vat23"] = Invoice::getVat ( $invoiceData ["vats_summary"], "23%", $invoiceData["currency_value"]);
// JeЕјeli koszt wЕasny na fakturze nie istnieje albo nulem
if ($invoiceData ["purchase_price"] == NULL || $invoiceData ["purchase_price"] == "") {
$invoiceData ["purchase_price"] = 0.00;
}
// Wyliczam marЕјД™ dla faktury
// if ($type != "correct") {
// $invoiceData ["marginInPercent"] = ($invoiceData ['total_netto'] - $invoiceData ['purchase_price']) / ($invoiceData ['total_netto']) * 100;
// $invoiceData ["margin"] = $invoiceData ['total_netto'] - $invoiceData ['purchase_price'];
// } else {
// $invoiceData ["marginInPercent"] = 0;
// $invoiceData ["margin"] = 0;
// }
array_push ( $invoicesArray, $invoiceData );
}
return $invoicesArray;
}
/**
* Funkcja mnoЕјy wszystkie sumy przez currency_value o ile currency_value nie jest 0
*
* @param $data -
* tablica danych przekazana jako referencja
*/
public static function multiplyValuesByCurrencyValue(&$data) {
// JeЕјeli kurs walutowy nie jest zerem ani pustym polem wtedy naleЕјy przemnoЕјyД‡ wszystkie wartoЕci
// bo wszystko musi byД‡ w zЕotГіwkach
if( $data["currency_value"] != NULL && $data["currency_value"] != 0 && $data["currency_value"] != '') {
$data["total_netto"] *= $data["currency_value"];
$data["total_brutto"] *= $data["currency_value"];
$data["purchase_price"] *= $data["currency_value"];
$data["margin"] *= $data["currency_value"];
}
}
/**
* Funkcja wyciД…ga netto z bazy( w bazie zapisane jest to w formacie: 23%:2000.00:460.00:2460.00 )
* @param unknown $formatted_string
* @param unknown $param_vat
* @param unknown $currency_value
* @return Ambigous <NULL, unknown>
*/
public static function getNetto($formatted_string, $param_vat, $currency_value) {
$return = NULL;
$vats = explode( ";" , $formatted_string);
foreach( $vats as $vat ) {
$split_values = explode( ":" , $vat );
if( $split_values[0] == $param_vat ) {
// Ceny na itemach wymagajД… przemnoЕјenia przez kurs walutowy
($currency_value == NULL || $currency_value == "") ? $currency_value = 1 : $currency_value = $currency_value;
$return = $split_values[1] * $currency_value;
}
}
return $return;
}
/**
* Funkcja wyciД…ga vat z bazy( w bazie zapisane jest to w formacie: 23%:2000.00:460.00:2460.00 )
* @param unknown $formatted_string
* @param unknown $param_vat
* @param unknown $currency_value
* @return Ambigous <NULL, unknown>
*/
public static function getVat($formatted_string, $param_vat, $currency_value) {
$return = NULL;
$vats = explode( ";" , $formatted_string);
foreach( $vats as $vat ) {
$split_values = explode( ":" , $vat );
if( $split_values[0] == $param_vat ) {
// Ceny na itemach wymagajД… przemnoЕјenia przez kurs walutowy
($currency_value == NULL || $currency_value == "") ? $currency_value = 1 : $currency_value = $currency_value;
$return = $split_values[2] * $currency_value;
}
}
return $return;
}
}
?>

View File

@@ -0,0 +1,36 @@
<?php
include ("class.Account.php");
include ("class.PurchaseInvoice.php");
/**
* Klasa statyczna odpowiedzialna za wyciД…ganie z bazy
* informacji zwiД…zanych z fakturami
* @author Kate
*/
class PurchaseInvoice {
/**
* Metoda pobiera fakturД™ o odpowiednim ID w formie tabeli
* zwraca wszystkie moЕјliwe pola z bazy danych
* @param $id - Identyfikator faktury
*/
public static function getInvoiceById( $id ) {
return PurchaseInvoice::getById( $id );
}
/**
* Zwraca listпїЅ faktur, ktГіre byЕy dodane w podanym zakresie dat
* @param $date_from - data startowa
* @param $date_to - data koЕ„cowa
* @param $type - typ faktury(normal/correct)
*/
public static function getInvoicesBetweenDates( $date_from, $date_to, $category, $contractorId ) {
return PurchaseInvoice::getBetweenDate( $date_from, $date_to, $category, $contractorId );
}
// public static function getReceiptsBetweenDates( $date_from, $date_to, $type = "%", $contractorId ) {
// return Receipt::getBetweenDate( $date_from, $date_to, $type, $contractorId );
// }
}
?>

View File

@@ -0,0 +1,41 @@
<?php
/**
*
* @author: Katarzyna Zdunek
**/
class PurchaseInvoiceItems{
/**
* Pobiera wszystkie faktury wchodzД…ce do firmy
* @param id- unikalny id faktury wchodzacej
*
**/
public static function getByInvoiceId($id)
{
$db = $GLOBALS['db'];
$query = "SELECT * FROM Documents WHERE parent_id'=$id'
AND parent_type= 'Accounts'
AND (category_id= 'invoice_costs'
OR category_id= 'invoice_goods')";
$result = $db->query($query);
return BuyerItems::getAllFromResult ($result);
}
/**
* Zwrocenie w tablicy wszystkich wynikпїЅw zapytania
*
* @param $result wiersze w postaci tablicy
*/
public static function getAllFromResult ($result){
$itemsArray= Array();
while ( $row = $result->fetch_assoc () ) {
array_push ( $itemsArray, $row );
}
return $itemsArray;
}
}
?>

View File

@@ -0,0 +1,26 @@
<?php
$db=$GLOBALS['db'];
$query="select * from documents where deleted=0 and id in (
'19364fc3-5fd9-9d17-ffa0-59f6d8bc3915','62e151e9-54cf-61be-1f2d-59f82790820e','9d6f2bee-b5d3-868f-e3eb-59f83348f5a9','ad1f0ab1-01f1-4e04-3e61-59f83c9d8447','4bd5e5bb-1e5e-1a6c-b551-59fc6820fe9f','3942df38-d3bd-f9f2-18f8-59fc6b3b19e4','9c235679-9e89-0c91-6ce5-59fc6eece324','7f39f001-ee33-bec8-697e-5a0423dd1aed','5d996a63-5c3c-6558-77d6-5a0425342b50','55187e64-ac7e-a6b4-f34d-5a042683de3d','6ed6d21b-b049-b029-a4f2-5a0457ded787','29fc0d3e-126d-85c1-50a8-5a04573c6107','1a83bd68-02dc-8f20-369b-5a045ce8ac6d','840117b2-a716-a232-835b-5a0476f9bf86','4782399d-4b0d-ab20-f054-5a047761a98c','6b816cad-b719-f2a9-484d-5a0958b6bde4','72b679c7-7cb5-7a07-29c6-5a095b7f5f8b','a9ea59ed-238b-2615-1cb4-5a095c7fb64d','6591f357-4aef-b31d-91c3-5a095d11918a','be60cc51-aa9c-5b19-afa3-5a095e59064b','c485807f-5b34-b953-4ab4-5a0985c6375e','de9b50b7-b6be-b733-2428-5a0985c31ce1','102a666d-1aa3-009f-3e36-5a098d72853f','98bf097c-c289-40f3-7618-5a098e671f67','1f3e2dc3-e1bd-c350-5af9-5a0997681451','d9172527-4f39-3fab-aee2-5a09ad167a00','6bb37d48-affe-9d1b-24d4-5a09ad43f78d','823c3bab-076c-29ea-dc8d-5a09ae6b194a','39839f82-218a-65ec-9271-5a0aaf6e9fb5','40052dd3-ba0b-e5db-6f3c-5a0c2f200cfb','8e1a1fef-7d88-8cc4-68bb-5a0c31785d3b','753858e3-98f8-2733-5273-5a0c36a75a59','28d8b053-d51c-28fc-7788-5a0c4afb40fb','a1a5b4f3-da46-fe1b-3857-5a0c4bb7a18c','af8c94bd-f8fd-92f0-258f-5a0c4c10b3de','8da61669-dd7e-a4af-3137-5a0c4da7c055','aeb50f43-d779-40d1-ab79-5a0c4e311f22','ed3432e2-0a95-9ef3-0a1a-5a0c4f809617','658ea5a2-7724-3613-3f3d-5a0c530ce8c6','9e356463-6663-a112-bb88-5a0c543d71ff','76a19282-18ba-784d-ce9d-5a0c5487b939','5cfce300-888f-1dcf-b4e6-5a0c5557702e','bb9670fa-343d-89cf-e32a-5a0c569adc92','6f5c84cb-170b-0c75-271e-5a0c58a3f4df','916201ad-f63b-184b-4505-5a0c5989b951','a89a3fd6-a21e-ea78-73be-5a0e89580de8','ba707651-e92a-b33c-af61-5a0e8a24d580','7c2e6fb1-ea5c-12c8-2689-5a0e8b4302b0','780696bf-e905-ea28-6706-5a0e8bb48c63','400ee2a6-6671-8e8e-8c5e-5a0e8b169298','118cb4a0-da73-fca1-c2f0-5a0edad76741','2e6c0419-c7cf-e221-ec3e-5a12b81377a7','2971901e-0638-d91e-2ee3-5a12ba61a827','53ad6b01-f7c9-574a-9ef0-5a12bb156b21','453f8ea5-7d50-1f59-d6da-5a12c1c64c21','25f866e8-064f-d87a-957f-5a12c3b945e4','1e897c70-679b-e279-2964-5a14283de6bc','f124c106-7993-2bfd-83f5-5a14294bdc30','e9c881f7-7a82-daf4-2c0e-5a142ad834ab','c57e5d43-8620-e21a-4e3e-5a142b06609c','b4f291c8-de81-9874-0e20-5a142c9224f0','b9662eed-cf5c-4fe9-803b-5a142db0db9b','2a1ae135-0382-5928-f875-5a142dd587e4','cd46d422-1025-1826-2aa3-5a142efb16b9','b8e8810d-fddc-5428-03c7-5a142f600471','22d7ebc6-0261-b86f-3d49-5a1430c711c9','b4cea0b8-10bc-64cc-8033-5a14319c1431','11f13984-f0a7-4b75-532e-5a1432f1dd2d','133ca176-1cca-7ac2-ba45-5a14338c79fe','90eda7b3-3e61-019b-f72c-5a16aed798be','4fc53939-03a6-98fd-cfe7-5a16c32423b4','201bf67b-241e-3e30-56b9-5a1c15dfe9a7','ca700903-94a2-a1db-4965-5a1c16e2d46c','483397b3-afbf-e216-0601-5a1c17eecbb1','a0d29ec3-52bf-944c-c2f9-5a1c18f93bea','e00b1813-2583-74eb-9e5b-5a1c187adb93','af00031b-2298-5045-e28f-5a1c19db12bb','8d706207-3208-99c7-97f3-5a1c1a6301a8','dec290a0-a0ae-93e4-c8f8-5a1c1b9cbfa1','9a658b9c-b71c-a9d5-b432-5a1c1b822420','7529710a-82ae-61bc-417a-5a1c1d943809','c25b11fe-c9c2-23fc-393a-5a1c1ecf06f0','ca3af0d3-8b99-5f6d-fd6e-5a1c1ee34f6a','46429fb6-c42a-d18d-01af-5a1d2c0656b5','da5ce0ed-b579-4419-1e0a-5a1d32ad1ab0','19470e0c-e836-9167-64c0-5a1d33d0d15c','29259349-158d-5de5-73b5-5a1d35de4859','9a0c0aba-f353-7526-3ff5-5a1d36c7a80d','9d2f4644-660a-b6c3-4c8b-5a1e4ed0d917','cae7914e-00c8-8199-9703-5a1e696d95d1','2a6ddea1-aa88-f97a-68af-5a1fdf13ecf4','8ad19f30-29e8-0042-c005-5a269b56cee6','f3a1ce2a-6eb0-a168-cf0c-5a269c68823c','e7ead284-12ff-ec3c-96ef-5a269ee1ff53','a0b2e1ba-82f3-083f-3f63-5a269f353153','61d2a334-d01a-2eb5-01fc-5a26a020a12a','337c4f0d-3304-f5ae-d0f3-5a26a10e4db2','d1bd84ba-16e2-95da-bd21-5a26a1d96c38','3733e0e3-fe5f-77bd-f984-5a26a27dc340','bfc4e719-62a6-907e-32b2-5a26a374b451','4314f6bb-6aa2-8344-7435-5a26a44511ca','c7a69474-435d-6ab2-3111-5a26a5c1a078','cd6750fc-a69a-de89-7467-5a26a7b1c652','97068d10-d1df-fdb6-87b4-5a26a81cfddd','4cbc7c42-9347-023a-bfdb-5a26f3df34aa','ccab5a70-8969-502f-881a-5a26f4a50abf','1c809a72-bfc7-f5ce-677e-5a26f54d2aa0','a5bb6b02-e9b8-a6d7-97b4-5a2704034d6a','c50d87b8-bd88-1d0b-e96f-5a27b3cb796b','d2a60f60-2d14-5d6c-2b6d-5a27b4facd49','28dc33d4-2f74-ca4f-06ba-5a27b84aadb7','4aaaad40-b9cb-da5b-6e39-5a27bbad0d9f','8d8ff628-f188-91b7-cc1f-5a27bc747f30','53e7ce4d-035d-dbdd-41b3-5a28f6b12ef0'
)";
$res= $db->query($query);
echo 'a';
while($dane = $db->fetchByAssoc($res)){
$value = new Document();
$value->retrieve($dane['id']);
$relations=$value->getParentList(true);
$a = new Account ();
$a->retrieve ( $relations[0]['parent_id']);
if(!$a->id){
$query2="INSERT INTO `documents_accounts` (`id`,`document_id`,`parent_id`,`date_entered`,`parent_type`,`deleted`,`date_modified`) VALUES ('".create_guid()."','".$value->id."','f084e64a-4e63-a3d1-6417-58cbf730df3f','2017-12-06','Account','0','2017-12-06')";
$db->query($query2);
}
}
?>

View File

@@ -0,0 +1,17 @@
<?php
include_once ("include/MPDF57/mpdf.php");
$smarty = new Sugar_Smarty ();
$content = $smarty->fetch('modules/EcmReports/tpls/pdf_content_header.tpl');
$content .= 'test<table id="myTable" class="tablesorter">' .$_REQUEST['dataTable'] . '</table>';
$content .= $smarty->fetch('modules/EcmReports/tpls/pdf_content_footer.tpl');
$mpdf = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 10, 10, 5, 5 );
$mpdf->mirrorMargins = 1;
$mpdf->WriteHTML($content);
$dir = 'upload/' . $current_user->id . '/';
if(!is_dir($dir)){
mkdir($dir, '755', true);
}
$mpdf->Output ($dir.'Raport.pdf', 'F');
print $dir.'Raport.pdf';

488
modules/EcmReports/ewkaCSV.php Executable file
View File

@@ -0,0 +1,488 @@
<form action="index.php">
<input type='hidden' name='module' value='EcmReports'>
<input type='hidden' name='action' value='ewkaCSV'>
<table>
<tr>
<td>
Data od:
</td>
<td>
<input autocomplete="off" type="text" name="date_start" id="date_start" value="<?php echo ''.($_REQUEST['date_start']!='' ? $_REQUEST['date_start'] : date('01.m.Y')).'' ?>" title="" tabindex="105" size="10" maxlength="10"> (dd.mm.yyyy)
</td>
<td>
<img border="0" src="themes/Sugar5/images/jscalendar.gif?s=bed8cd35065048ceebdc639ebe305e2c&amp;c=1" alt="Wprowadź datę" id="date_start_trigger" align="absmiddle">
<script type="text/javascript">
Calendar.setup ({
inputField : "date_start",
daFormat : "%d.%m.%Y %H:%M",
button : "date_start_trigger",
singleClick : true,
dateStr : "05.01.2016",
step : 1,
weekNumbers:false
}
);
</script>
</td>
</tr>
<tr>
<td>
Data do:
</td>
<td>
<input autocomplete="off" type="text" name="date_end" id="date_end" value="<?php echo ''.($_REQUEST['date_end']!='' ? $_REQUEST['date_end'] : date('t.m.Y')).'' ?>" title="" tabindex="105" size="10" maxlength="10"> (dd.mm.yyyy)
</td>
<td>
<img border="0" src="themes/Sugar5/images/jscalendar.gif?s=bed8cd35065048ceebdc639ebe305e2c&amp;c=1" alt="Wprowadź datę" id="date_end_trigger" align="absmiddle">
<script type="text/javascript">
Calendar.setup ({
inputField : "date_end",
daFormat : "%d.%m.%Y %H:%M",
button : "date_end_trigger",
singleClick : true,
dateStr : "05.01.2016",
step : 1,
weekNumbers:false
}
);
</script>
</td>
</tr>
</table>
<br><input type="submit" value="Generuj" name="submit">
</form>
<?php
global $current_user;
class raportTxT {
public $fileName;
private $db;
private $fp;
private $separator;
private $nl;
private $header;
private $to_write;
private $docTypes;
private $dateFrom;
private $dateTo;
private $stockList;
function __construct($fileName, $separator, $nl,$date_start,$date_end) {
$this->fileName = $fileName;
$this->separator = $separator;
$this->nl = $nl;
$this->db = $GLOBALS['db'];
$this->getStockList();
$this->documentTypes();
$this->setDateFrom(date('Y-m-d',strtotime($date_start)));
$this->setDateTo(date('Y-m-d',strtotime($date_end)));
$this->drawHeader();
$this->openFile();
$this->writeLine();
$this->createFileContent();
}
function getStockList() {
$res = $this->db->query('SELECT id, name, no,production FROM ecmstocks order by no');
$this->stockList = array();
while ($dane = $this->db->fetchByAssoc($res)) {
$this->stockList[$dane['id']] = $dane;
}
}
function getStockNumber($stockId) {
$EcmSysInfo = new EcmSysInfo();
if($EcmSysInfo->getDatabaseName() == 'preDb_5d9477918f845c6fdc25532d415f9e73'){
return 'MG_' . $this->stockList[$stockId]['production'];
} else {
return 'MG_' . $this->stockList[$stockId]['no'];
}
}
function setDateFrom($data = NULL) {
if (isset($data) && strlen($data) > 8) {
try {
$this->dateFrom = new DateTime($data);
} catch (Exception $e) {
$this->dateFrom = NULL;
}
} else {
$this->dateFrom = NULL;
}
}
function setDateTo($data = NULL) {
if (isset($data) && strlen($data) > 8) {
try {
$this->dateTo = new DateTime($data);
} catch (Exception $e) {
$this->dateTo = NULL;
}
} else {
$this->dateTo = NULL;
}
}
function getQueryWhere() {
$check = false;
$whereQuery = '';
if (isset($this->dateFrom) && is_a($this->dateFrom, 'DateTime')) {
if (!$check) {
$check = true;
$whereQuery = " WHERE ";
}
$whereQuery .= " register_date >= '" . $this->dateFrom->format("Y-m-d") ."' ";
}
if (isset($this->dateTo) && is_a($this->dateTo, 'DateTime')) {
if (!$check) {
$check = true;
$whereQuery = " WHERE ";
}
$whereQuery .= " AND register_date <= '" . $this->dateTo->format("Y-m-d") . "' ";
}
$whereQuery.='and deleted=0 and canceled=0 ';
if ($check) {
return $whereQuery;
} else {
return '';
}
}
function openFile() {
unlink($this->fileName);
$this->fp = fopen($this->fileName, 'w+');
}
function documentTypes() {
$tmp = array();
$tmp[] = 'EcmStockDocIn';
$tmp[] = 'EcmStockDocOut';
$tmp[] = 'EcmInvoiceOut';
$tmp[] = 'EcmStockDocInsideIn';
$tmp[] = 'EcmStockDocInsideOut';
$tmp[] = 'EcmStockDocCorrect';
$tmp[] = 'EcmStockDocMove';
$this->docTypes = $tmp;
unset($tmp);
}
function createFileContent() {
foreach ($this->docTypes as $key => $val) {
$callMe = 'Get' . $val;
$this->$callMe($val);
}
}
function GetEcmInvoiceOut($mod) {
// echo 'wywoluje?';
// echo '<br>';
// echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
// echo '<br>';
$zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
// echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
while ($dane = $this->db->fetchByAssoc($zap)) {
// echo "<pre>";
$tmp = array();
if ($dane['type'] == 'normal') {
$tmp[] = 'FK';
} else {
$tmp[] = 'KF';
}
$tmp[] = $dane['document_no'];
$tmp[] = $dane['register_date'];
$tmp[] = $dane['purchase_price'];
$tmp[] = $dane['total_netto'];
$tmp[] = $dane['total_vat'];
$tmp[] = $dane['total_brutto'];
$tmp[] = $dane['pdf_type'];
$tmp[] = $this->getStockNumber($dane['stock_id']);
$tmp[] = $this->getStockNumber($dane['stock_id']);
$a = new Account();
$a->retrieve($dane['parent_id']);
$tmp[] = $a->ks_account;
$tmp[] = $a->index_dbf;
$tmp[] = $dane['payment_date_days'];
$zap2 = $this->db->query("select name from ecminvoicecategories where id='".$dane['category']."'");
$dane2 = $this->db->fetchByAssoc($zap2);
$tmp[] = $dane2['name'];
$tmp[]= $dane['currency_value_nbp'];
$tmp[] = '';
unset($a);
$this->to_write = implode($this->separator, $tmp) . ';';
unset($tmp);
$this->writeLine();
}
}
function GetEcmStockDocOut($mod) {
// echo 'wywoluje?';
// echo '<br>';
// echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
// echo '<br>';
global $app_list_strings;
$zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
while ($dane = $this->db->fetchByAssoc($zap)) {
$purchasePrice = 0;
$purchasePriceResult = $this->db->query("Select quantity*price as suma from ecmstockdocoutitems WHERE ecmstockdocout_id='" . $dane['id'] . "'");
while ($danepurchase = $this->db->fetchByAssoc($purchasePriceResult)) {
$purchasePrice += $danepurchase['suma'];
}
$tmp = array();
$tmp[] = 'WZ';
$tmp[] = $dane['document_no'];
$tmp[] = $dane['register_date'];
$tmp[] = $purchasePrice;
$tmp[] = $dane['total_netto'];
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = $this->getStockNumber($dane['stock_id']);
$tmp[] = $this->getStockNumber($dane['stock_id']);
$a = new Account();
$a->retrieve($dane['parent_id']);
$tmp[] = $a->ks_account;
$tmp[] = $a->index_dbf;
$tmp[] = '';
$tmp[] = $app_list_strings['ecmstockdocouts_category_list'][$dane['category']];
$tmp[] = '';
$tmp[] = '';
unset($a);
$this->to_write = implode($this->separator, $tmp) . ';';
unset($tmp);
$this->writeLine();
}
}
function GetEcmStockDocIn($mod) {
// echo 'wywoluje?';
// echo '<br>';
// echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
// echo '<br>';
$zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
while ($dane = $this->db->fetchByAssoc($zap)) {
$tmp = array();
$tmp[] = 'PZ';
$tmp[] = $dane['document_no'];
$tmp[] = $dane['register_date'];
$tmp[] = $dane['total_netto'];
$tmp[] = $dane['total_netto'];
$tmp[] = '';
$tmp[] = '';
$tmp[] = $dane['kind'];
$tmp[] = $this->getStockNumber($dane['stock_id']);
$tmp[] = $this->getStockNumber($dane['stock_id']);
$a = new Account();
$a->retrieve($dane['parent_id']);
$tmp[] = $a->ks_account;
$tmp[] = $a->index_dbf;
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
unset($a);
$this->to_write = implode($this->separator, $tmp) . ';';
unset($tmp);
$this->writeLine();
}
}
function GetEcmStockDocInsideIn($mod) {
// echo 'wywoluje?';
// echo '<br>';
// echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
// echo '<br>';
$zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
while ($dane = $this->db->fetchByAssoc($zap)) {
$tmp = array();
$tmp[] = 'PW';
$tmp[] = $dane['document_no'];
$tmp[] = $dane['register_date'];
$tmp[] = $dane['total'];
$tmp[] = $dane['total'];
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = $this->getStockNumber($dane['stock_id']);
$tmp[] = $this->getStockNumber($dane['stock_id']);
$a = new Account();
$a->retrieve($dane['parent_id']);
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$kar= new EcmProductStockIndex();
$kar->retrieve($dane['ecmproductstockindex_id']);
$tmp[] = $kar->name;
unset($a);
unset($kar);
$this->to_write = implode($this->separator, $tmp) . ';';
unset($tmp);
$this->writeLine();
}
}
function GetEcmStockDocInsideOut($mod) {
// echo 'wywoluje?';
// echo '<br>';
// echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
// echo '<br>';
$zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
while ($dane = $this->db->fetchByAssoc($zap)) {
$tmp = array();
$tmp[] = 'RW';
$tmp[] = $dane['document_no'];
$tmp[] = $dane['register_date'];
$tmp[] = $dane['total'];
$tmp[] = $dane['total'];
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = $this->getStockNumber($dane['stock_id']);
$tmp[] = $this->getStockNumber($dane['stock_id']);
$a = new Account();
$a->retrieve($dane['parent_id']);
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$kar= new EcmProductStockIndex();
$kar->retrieve($dane['ecmproductstockindex_id']);
$tmp[] = $kar->name;
unset($a);
unset($kar);
$this->to_write = implode($this->separator, $tmp) . ';';
unset($tmp);
$this->writeLine();
}
}
function GetEcmStockDocCorrect($mod) {
// echo 'wywoluje?';
// echo '<br>';
// echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
// echo '<br>';
$zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
while ($dane = $this->db->fetchByAssoc($zap)) {
$tmp = array();
$tmp[] = 'KS';
$tmp[] = $dane['document_no'];
$tmp[] = $dane['register_date'];
$tmp[] = $dane['total'];
$tmp[] = $dane['total'];
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = $this->getStockNumber($dane['stock_id']);
$tmp[] = $this->getStockNumber($dane['stock_id']);
$a = new Account();
$a->retrieve($dane['parent_id']);
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$kar= new EcmProductStockIndex();
$kar->retrieve($dane['ecmproductstockindex_id']);
$tmp[] = $kar->name;
unset($a);
unset($kar);
$this->to_write = implode($this->separator, $tmp) . ';';
unset($tmp);
$this->writeLine();
}
}
function GetEcmStockDocMove($mod) {
// echo 'wywoluje?';
// echo '<br>';
// echo "select * from " . strtolower($mod) . "s " . $this->getQueryWhere();
// echo '<br>';
$zap = $this->db->query("select * from " . strtolower($mod) . "s " . $this->getQueryWhere());
while ($dane = $this->db->fetchByAssoc($zap)) {
$tmp = array();
$tmp[] = 'MM';
$tmp[] = $dane['document_no'];
$tmp[] = $dane['register_date'];
$tmp[] = $dane['total'];
$tmp[] = $dane['total'];
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = $this->getStockNumber($dane['stock_out_id']);
$tmp[] = $this->getStockNumber($dane['stock_in_id']);
$a = new Account();
$a->retrieve($dane['parent_id']);
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$tmp[] = '';
$kar= new EcmProductStockIndex();
$kar->retrieve($dane['ecmproductstockindex_id']);
$tmp[] = $kar->name;
unset($a);
unset($kar);
$this->to_write = implode($this->separator, $tmp) . ';';
unset($tmp);
$this->writeLine();
}
}
function closeFile() {
fclose($this->fp);
}
function drawHeader() {
$tmp = array();
$tmp[] = 'SYMBOL DOK';
$tmp[] = 'NR DOK';
$tmp[] = 'DATA DOK';
$tmp[] = 'WART MAG';
$tmp[] = 'WART NET';
$tmp[] = 'WART VAT';
$tmp[] = 'WART B';
$tmp[] = 'RODZAJ';
$tmp[] = 'MAG ZR';
$tmp[] = 'MAG DOC';
$tmp[] = 'KONTO KS';
$tmp[] = 'INDEKS';
$tmp[] = 'DNI_PLATNOSCI';
$tmp[] = 'KATEGORIA';
$tmp[] = 'KURS VAL';
$tmp[] = 'KARTOTEKA';
$this->to_write = implode($this->separator, $tmp) . ';';
unset($tmp);
}
function writeLine() {
fwrite($this->fp, iconv("UTF-8","CP852",$this->to_write . $this->nl));
}
}
if($_REQUEST['submit']!=''){
$name='evka.csv';
$c = new raportTXT($name, ';', PHP_EOL,$_REQUEST['date_start'],$_REQUEST['date_end']);
$file=$name;
header("Location: ".$name);
}
?>

View File

@@ -0,0 +1,50 @@
<?php
include_once 'modules/EcmReports/RaportMSH/FileHandler.php';
include_once 'modules/EcmReports/RaportMSH/XlsReader.php';
include_once 'modules/EcmReports/RaportMSH/Order.php';
include_once 'modules/EcmReports/RaportMSH/ProductFactory.php';
$uploaded=0;
if(isset($_POST["submit"])) {
$fileHandler = new FileHandler();
if($fileHandler->uploadFile()){
$xlsReader = new XlsReader($fileHandler->target_file);
$productFactory = new ProductFactory($xlsReader->getArray(),$_REQUEST['date'],$fileHandler);
$productFactory->createProducts();
$uploaded=1;
} else {
$uploaded=2;
}
} else {
if($_REQUEST['delete']!=""){
$query="delete from orders where file_id='".$_REQUEST['delete']."'";
$res=$GLOBALS['db']->query($query);
}
$query="select file_id,file_name,user_id,file_date from orders group by file_id";
$res=$GLOBALS['db']->query($query);
$files = [];
while($dane=$GLOBALS['db']->fetchByAssoc($res)){
$user = new User();
$user->retrieve($dane['user_id']);
$dane['user_name']=$user->full_name;
$files[]=$dane;
}
}
$date = new DateTime ();
$date->modify ( "-1 month" );
$smarty = new Sugar_Smarty ();
$smarty->assign ( 'MOD', $mod_strings );
$smarty->assign ( 'files', $files );
$smarty->assign ( 'uploaded', $uploaded);
$smarty->assign ( 'count', ProductFactory::getObjectCount());
$smarty->assign ( 'date', $date->format ( "01.m.Y" ) );
echo $smarty->fetch ( "modules/EcmReports/RaportMSH/tpl/FileUpload.html" );
?>

1
modules/EcmReports/index.php Executable file
View File

@@ -0,0 +1 @@
<?php include_once("modules/EcmReports/ReportSales.php");?>

View File

@@ -0,0 +1,184 @@
<?php
if (! defined ( 'sugarEntry' ) || ! sugarEntry)
die ( 'Not A Valid Entry Point' );
/*
* kasjer
*/
$user=array();
$r=$GLOBALS['db']->query("select u.first_name,u.last_name,u.id from users as u join ecmcashs_ecmkpkw as rel on rel.user_id=u.id group by u.id");
while($dn = $GLOBALS['db']->fetchByAssoc($r))
$user[]=$dn;
/**
* pobiera imie i nazwisko wybranego kasjera
*
*/
$us=new User;
$us->retrieve($_GET['kasjer']);
/**
* EcmNewKpkws report DATE format
*/
require_once('include/utils.php');
global $db,$app_strings;
$stop = new DateTime('NOW');
$start = new DateTime(date('01.m.Y'));
$currentTo = @$_GET['date_to'] ? : $stop->format('t.m.Y');
$currentFrom = @$_GET['date_from'] ? : $start->format('01.m.Y');
$Calendar_daFormat = str_replace("d","%d",str_replace("m","%m",str_replace("Y","%Y",$GLOBALS['timedate']->get_date_format())));
/*
* generate query
*
*/
$additionalWhereConditions = array(
'\'' . $start->format('Y-m-01') . '\'',
'\'' . $stop->format('Y-m-t') . '\'',
);
if($from = @$_GET['date_from']) {
$fromDate = new DateTime($from);
$additionalWhereConditions[0] = '\'' . $fromDate->format('Y-m-d') . '\'';
}
if($to = @$_GET['date_to']) {
$toDate = new DateTime($to);
$additionalWhereConditions[1] = '\'' . $toDate->format('Y-m-d') . '\'';
}
if($_GET['ecmcash_id']!=''){
$additionalWhereConditions[2]='cash_id=\'' . $_GET['ecmcash_id'] . '\'';
}
if($_GET['kasjer']!=''){
$kasjer=" and `created_by`='".$_GET['kasjer']."'";
}
$additionalWhere = '`date_entered` BETWEEN ' . implode(' AND ', $additionalWhereConditions)." ".$kasjer;
$query = '
SELECT
`description`,`description`,`amount`,`document_no`,
`parent_address_street`,`parent_address_city`,`parent_address_postalcode`,
`parent_address_country`,`parent_contact_name`,`parent_contact_title`,
`date_entered`,`type_id`,`parent_name`
FROM `ecmnewkpkws`
WHERE
' . (additionalWhere ? ($additionalWhere) : '') . '
ORDER BY
`date_entered` ASC;
';
$result = $db->query($query);
$query_bo = "SELECT SUM(IF(type_id = 0, amount, -amount)) AS `sum` FROM `ecmnewkpkws` WHERE `date_entered` < ".$additionalWhereConditions[0]." ".$kasjer;
$result_bo = $db->query($query_bo);
if($row_bo = $db->fetchByAssoc($db->query($query_bo)))
{
$bo = $row_bo["sum"];
}
$date=array();
$i=1;
while($row = $db->fetchByAssoc($result)){
$row['type_id']==0 ? $date['in']+=$row['amount'] : $date['out']+=$row['amount'];
$i%2 ? $row['class']='even' : $row['class']='odd';
$row['number']=$i;
$date[]=$row;
$i++;
}
// create & execute smarty
$smarty = new Sugar_Smarty ();
global $mod_strings;
$smarty->assign ( "MOD", $mod_strings );
$smarty->assign ( "DATA", $date );
$smarty->assign ( "CASH_BEFORE", $bo );
$smarty->assign ( "CASH_NOW",(($bo+$date['in'])-$date['out']));
$smarty->assign ( "STOCKS", $datastocks );
$smarty->assign ( "PARAMS", $_GET);
$smarty->assign ( "USER_NAME",$us->full_name);
$smarty->assign ( "USERS", $user);
$smarty->assign ( "currentTo", $currentTo);
$smarty->assign ( "currentFrom", $currentFrom);
$smarty -> assign("dateFormat", $Calendar_daFormat);
if( $_GET['toPDF'] == '1' ) {
if( $_GET['to_xls'] == '1' ) {
$header=array();
$header[]='numer dokumentu';
$header[]='data';
$header[]='tytuł';
$header[]='kontrahent';
$header[]='przychód';
$header[]='rozchód';
$filename='modules/Home/Files/raport_kasowy_'.date('d_m-Y').'.csv';
$fp=fopen($filename,'w');
foreach ($header as $k=>$v){
$header[$k]=iconv('UTF-8','windows-1250',$header[$k]);
}
fwrite($fp, implode(";",$header).PHP_EOL);
foreach ($date as $key=>$val){
if($val['type_id']!=''){
$line=array();
$line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['document_no']))).'"""';
$line[]=$val['date_entered'];
$line[]='"=""'.preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['description']))).'"""';
$line[]=preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['parent_name'])));
if($poz.type_id==0){
$line[]=str_replace(".",",",$val['amount']);
$line[]=str_replace(".",",",$val['wartosc']);
} else {
$line[]=str_replace(".",",",$val['wartosc']);
$line[]=str_replace(".",",",$val['amount']);
}
foreach ($line as $k=>$v){
$line[$k]=iconv('UTF-8','windows-1250',$line[$k]);;
}
fwrite($fp, implode(";",$line).PHP_EOL);
}
}
header("Location: ". $filename);
} else {
$output = $smarty->fetch( 'modules/EcmReports/tpls/PDF/kpkwReport.tpl' );
include_once ("include/MPDF57/mpdf.php");
unset($smarty);
$p = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 26, 10, 5, 5 );
$p->setFooter('Strona {PAGENO} z {nbpg}');
$kasa=$_GET['cash_name']!='' ? '<br>Kasa: '.$_GET['cash_name'] : '';
$usr=$_GET['kasjer']!='' ? '<br>Kasjer: '.$us->full_name : '';
$p->SetHTMLHeader('<p style="text-align:left;font-size: 10px;">Saas SystemS Sp. z o.o.<br>
Raport kasowy<br>Raport od '.date('d.m.Y',strtotime($currentFrom)).' do '.date('d.m.Y',strtotime($currentTo)).' <br>Data wydruku: '.date("d.m.Y").' '.$kasa.' '.$usr.'</p>');
//$p->setTitle($mod_strings["LBL_REPORT_STOCKS_DOCS"]);
//echo $output;
$p->writeHTML( $output );
$p->Output ();
}
} else {
$smarty->display ( 'modules/EcmReports/tpls/kpkwReport.tpl' );
}
?>

View File

@@ -0,0 +1,84 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*********************************************************************************
* Description: Defines the English language pack for the base application.
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
* Contributor(s): ______________________________________..
********************************************************************************/
$mod_strings = array (
'LBL_REPORT_STOCKS' => 'Stock States Report',
'LBL_STOCK' => 'Stock',
'LBL_PRODUCT_ACTIVE' => 'Product Active',
'LBL_YES' => 'Yes',
'LBL_NO' => 'No',
'LBL_ASSIGNED_TO_ID' => 'Assigned To',
'LBL_VALUE' => 'Value',
'LBL_MODULE_NAME' => 'Sales Report',
'LBL_MODULE_TITLE' => 'Sales Report: Home',
'LBL_MODULE_ID' => 'Sales Report',
'LBL_SEARCH_FORM_TITLE' => 'Sales Report Search',
'LBL_LIST_FORM_TITLE' => 'Sales Report List',
'LBL_NEW_FORM_TITLE' => 'New Sales Report',
'LBL_SUBJECT' => 'Subject:',
'LBL_ECMREPORT' => 'Sales Report:',
'LBL_ECMREPORT_SUBJECT' => 'Sales Report Subject:',
'LBL_LIST_SUBJECT' => 'Name',
'LBL_LIST_LAST_MODIFIED' => 'Last Modified',
'LNK_NEW_ECMREPORT' => 'Create Sales Report',
'LNK_ECMREPORT_LIST' => 'Sales Report',
'ERR_DELETE_RECORD' => 'You must specify a record number in order to delete the vat.',
'LBL_LIST_MY_ECMREPORTS' => 'My Assigned Sales Report',
'LBL_CREATED_BY' => 'Created by:',
'LBL_DATE_CREATED' => 'Create Date:',
'LBL_MODIFIED_BY' => 'Last Modified by:',
'LBL_DATE_LAST_MODIFIED' => 'Modify Date:',
'LBL_DEFAULT_SUBPANEL_TITLE' => 'Sales Report',
'LBL_SYSTEM_ID' => 'System ID',
'LBL_LIST_ASSIGNED_TO_NAME' => 'Assigned User',
'LBL_LIST_VALUE' => 'Value',
'LBL_ASSIGNED_TO_NAME' => 'Assigned to',
);
?>

View File

@@ -0,0 +1,79 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*********************************************************************************
* Description: Defines the English language pack for the base application.
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
* All Rights Reserved.
* Contributor(s): ______________________________________..
********************************************************************************/
$mod_strings = array (
'LBL_ASSIGNED_TO_ID' => 'Assigned To',
'LBL_VALUE' => 'Value',
'LBL_MODULE_NAME' => 'Vat',
'LBL_MODULE_TITLE' => 'Vat: Home',
'LBL_MODULE_ID' => 'Vat',
'LBL_SEARCH_FORM_TITLE' => 'Vat Search',
'LBL_LIST_FORM_TITLE' => 'Vat List',
'LBL_NEW_FORM_TITLE' => 'New Vat',
'LBL_SUBJECT' => 'Subject:',
'LBL_ECMREPORT' => 'Vat:',
'LBL_ECMREPORT_SUBJECT' => 'Vat Subject:',
'LBL_LIST_SUBJECT' => 'Name',
'LBL_LIST_LAST_MODIFIED' => 'Last Modified',
'LNK_NEW_ECMREPORT' => 'Create Vat',
'LNK_ECMREPORT_LIST' => 'Vat',
'ERR_DELETE_RECORD' => 'You must specify a record number in order to delete the vat.',
'LBL_LIST_MY_ECMREPORTS' => 'My Assigned Vat',
'LBL_CREATED_BY' => 'Created by:',
'LBL_DATE_CREATED' => 'Create Date:',
'LBL_MODIFIED_BY' => 'Last Modified by:',
'LBL_DATE_LAST_MODIFIED' => 'Modify Date:',
'LBL_DEFAULT_SUBPANEL_TITLE' => 'Vat',
'LBL_SYSTEM_ID' => 'System ID',
'LBL_LIST_ASSIGNED_TO_NAME' => 'Assigned User',
'LBL_LIST_VALUE' => 'Value',
'LBL_ASSIGNED_TO_NAME' => 'Assigned to',
);
?>

View File

@@ -0,0 +1,258 @@
<?php
$mod_strings = array (
'LBL_MODULE_NAME' => 'Raporty',
'LBL_MODULE_TITLE' => 'Raporty: Strona Główna',
'LBL_MODULE_ID' => 'Raporty',
'LBL_REPORT_SALES_BY_PRODUCT' => 'Raport Sprzedaży - Ilościowy',
'LBL_REPORT_SALES_BY_CONTRACTOR' => 'Raport Sprzedaży - Według Nabywców',
'LBL_REPORT_SALES_BY_DOCUMENT' => 'Raport Sprzedaży - Raport wartościowy',
'LBL_REPORT_SALES_BY_GROUP' => 'Raport sprzedaż w grupach',
'LBL_REPORT_SALES_ANALIS_PRODUCT' => 'Raport Sprzedaży - Analiza czasowa',
'LBL_REPORT_SALES_VAT_SALES' => 'Raport Sprzedaży - Rejestr sprzedaży VAT',
'LBL_REPORT_SALES_ANALYSIS_ECMQUOTE' => 'Raport Sprzedaży - Skuteczność ofert',
'LBL_REPORT_STOCKS_STOCK_STATE' => 'Raport Magazynowy - Stany magazynowe',
'LBL_REPORT_BUY_ANALIS_PRODUCT'=>'Raport zakupu - Analiza czasowa',
'LBL_DATE_FROM' => 'Data od',
'LBL_DATE_TO' => 'Data do',
'LBL_EXECUTE' => 'Wykonaj',
'LBL_CLEAR' => 'Wyczyść',
'LBL_PDF' => 'PDF',
'LBL_SALES_BRUTTO' => 'Sprzedaż brutto',
'LBL_DOCUMENT' => 'Dokument',
'LBL_DOCUMENT_SALES_TYPE' => 'Typ dokumentu',
'DOCUMENT_SALES_LIST' => array(
'' => '',
'invoice' => 'Faktura',
'invoice_correct' =>'Faktura korekta',
'recipe' => 'Paragon',
'recipe_correct' => 'Paragon korekta',
),
'LBL_PRODUCT_GROUP' => 'Grupa',
'LBL_PRODUCT_GROUP_2' => 'Grupa 2',
'TIP_MULTIPLE' => 'By zaznaczyć/odznaczyć kilka opcji wciśnij CTRL i kliknij na porządane elementy',
'LBL_TRADER' => 'Handlowiec',
'LBL_STOCK' => 'Magazyn',
'TIP_CHOOSE_TRADER' => 'Wybierz Sprzedawcę',
'TIP_CHOOSE_ACCOUNT' => 'Wybierz Kontrahenta',
'LBL_PRODUCTS_CATEGORY' => 'Kategoria produktowa',
'LBL_PRODUCT' => 'Produkt',
'LBL_CONTRACTOR' => 'Kontrahent',
'LBL_NETTO' => 'Netto',
'LBL_BRUTTO' => 'Brutto',
'LBL_PURCHASE' => 'Zakup',
'LBL_INCOME' => 'Dochód',
'LBL_OVERHEAD' => 'Narzut',
'LBL_NAME' => 'Nazwa',
'LBL_SUMMARY' => 'Suma',
'LBL_QUANTITY' => 'Ilość',
'LBL_JM' => 'jm',
'LBL_SALES_NETTO' => 'Sprzedaż Netto',
'LBL_COST_PURCHASE' => 'Koszt Zakupu',
'LBL_INCOME_OVERHEAD' => 'Dochód (Narzut)',
'LBL_YES' => 'Tak',
'LBL_NO' => 'Nie',
'LBL_PRODUCT_ACTIVE' => 'Produkt aktywny',
'LBL_INDEX' => 'Indeks',
'LBL_PRICE' => 'Cena',
'LBL_CONSIGNMENTS'=>'Partia',
'LBL_DOCUMENT_DATE' => 'Data dokumentu',
'LBL_DOCUMENT_TYPE' => 'Rodzaj dokumentu',
'LBL_REPORT_ACCEPTANCE' => 'Raport akceptacji',
'LBL_REPORT_ACCEPTANCE_DOCNAME' => 'Nazwa dokumentu',
'LBL_REPORT_ACCEPTANCE_ACCOUNT' => 'Przywiązane do',
'LBL_REPORT_ACCEPTANCE_CATEGORY' => 'Kategoria',
'LBL_REPORT_ACCEPTANCE_DES' => 'Opis',
'LBL_REPORT_ACCEPTANCE_NAME' => 'Nazwa uzytkownika',
'LBL_REPORT_ACCEPTANCE_DOCDATE' => 'Data dokumentu',
// kpkw report
// RAPORT && PDF
'LBL_NUMBER_LP' => 'Lp',
'LBL_DOCUMENT_NO' => 'Nr dokumentu',
'LBL_CREATE_LAB' => 'Data wyst.',
'LBL_TITLE' => 'Tytuł',
'LBL_PARENT_NAME' => 'Kontrahent',
'LBL_AMOUNT_PLUS' => 'Przychód',
'LBL_AMOUNT_MINUS' => 'Rozchód',
'LBL_VALUE' => 'Suma',
'LBL_VALUE_BEFORE' => 'Stan kasy poprzednio',
'LBL_VALUE_TOTAL' => 'Stan kasy obecny',
'LBL_RAPORT_TITLE' => 'Zestawienie KPKW',
'LBL_RAPORT_TITLE2' => 'RAPORT KASOWY',
'LBL_RAPORT_LABEL' => 'Raport kasowy',
'LBL_TIME' => 'okres',
'LBL_TIME2' => 'Okres',
'LBL_CASH' => 'kasa',
'LBL_CURRENCY_PDF' => 'waluta',
'LBL_CURRENCY_PDF2' => 'Waluta',
'LBL_CASH_USER' => 'kasjer',
'LBL_DATE_START' => 'Od',
'LBL_DATE_END' => 'Do',
'LBL_CASH2' => 'Kasa',
'LBL_CASH_USER2' => 'Kasjer',
'LBL_SUBMIT' => 'Wykonaj',
'LBL_SELECT' => 'Wybierz',
'LBL_ALL' => 'Wszyscy',
'LBL_PRINT_PDF' => 'Drukuj PDF',
'LBL_SALE_DATE' => 'Data sprz.',
'LBL_CONTRACTOR_NIP' => 'Nip odbiorcy',
'LBL_ADDRESS' => 'Adres',
'LBL_GROSS_SALES' => 'Sprz. brutto',
'LBL_NET_SALES' => 'Sprz. netto',
'LBL_VAT' => 'Vat',
'LBL_SUM_VAT' => 'Vat razem',
'LBL_VAT_SALES_REGISTER' => "Rejestr sprzedaży VAT",
'LBL_COST_OF' => "Koszt własny",
'LBL_VALUE_NETTO' => 'Wartość netto',
'LBL_VALUE_BRUTTO' => 'Wartość brutto',
'LBL_ACTION_CODE' => 'Indeks czynności',
'LBL_PRODUCT_CODE' => 'Indeks produktu',
'LBL_ACTION' => 'Czynności',
'LBL_REPORT_STOCKS' => 'Raport stanów magazynowych',
'LBL_REPORT_ACCEPTANCE' => 'Raport akceptacji',
'LBL_STOCK' => 'Magazyn',
'LBL_DATE_FROM' => 'Data od',
'LBL_DATE_TO' => 'Data do',
'LBL_PRODUCTS_CATEGORY' => 'Grupa towarów',
'LBL_PRODUCT' => 'Produkt',
'LBL_WORKER_NAME' => 'Pracownik',
'LBL_COLUMNS_SHOW' => 'Kolumny do wyświetlenia:',
'LBL_YEAR_MONTH' => 'Rok / Miesiąc',
'LBL_SUM' => 'Suma',
'LBL_SUM_NETTO' => 'Suma netto',
'LBL_SUM_BRUTTO' => 'Suma brutto',
'LBL_PRODUCT_ACTIVE' => 'Produkt aktywny',
'LBL_YES' => 'Tak',
'LBL_SEARCH' => 'Wyszukiwanie',
'LBL_NO' => 'Nie',
'LBL_CONSIGNMENTS'=>"Partia",
'LBL_REPORT_ACCEPTANCE_DOCNAME' => 'Nazwa dokumentu',
'LBL_REPORT_ACCEPTANCE_ACCOUNT' => 'Przywiązane do',
'LBL_REPORT_ACCEPTANCE_CATEGORY' => 'Kategoria',
'LBL_REPORT_ACCEPTANCE_DES' => 'Opis',
'LBL_REPORT_ACCEPTANCE_NAME' => 'Nazwa uzytkownika',
'LBL_REPORT_ACCEPTANCE_DOCDATE' => 'Data dokumentu',
'LBL_REPORT_VALUE_NAME' => 'Raport wartości',
'LBL_REPORT_ECMWORKCARDS' => 'Raport kart pracy',
'LBL_REPORT_STOCKS_DOCS' => 'Raport stanów magazynowych po dokumentach',
'LBL_ASSIGNED_TO_ID' => 'Przypisane Do',
'LBL_VALUE' => 'Wartość',
'LBL_MODULE_NAME' => 'Raport Sprzedaży',
'LBL_MODULE_TITLE' => 'Raport Sprzedaży: STrona Główna',
'LBL_MODULE_ID' => 'Raport Sprzedaży',
'LBL_SEARCH_FORM_TITLE' => 'Raport Sprzedaży Wyszukiwanie',
'LBL_LIST_FORM_TITLE' => 'Lista',
'LBL_NEW_FORM_TITLE' => 'Nowa Stawka Vat',
'LBL_SUBJECT' => 'Tytuł:',
'LBL_ECMREPORT' => 'Raport Sprzedaży:',
'LBL_ECMREPORT_SUBJECT' => 'Nazwa Raport Sprzedaży:',
'LBL_LIST_SUBJECT' => 'Nazwa',
'LBL_LIST_LAST_MODIFIED' => 'Ostatnia Modyfikacja',
'LNK_NEW_ECMREPORT' => 'Utwórz Stawkę Vat',
'LNK_ECMREPORT_LIST' => 'Raport Sprzedaży',
'ERR_DELETE_RECORD' => 'Podaj numer rekordu aby usunąć stawkę vat.',
'LBL_LIST_MY_ECMREPORTS' => 'Moje Przypisane Raport Sprzedaży',
'LBL_CREATED_BY' => 'Utworzone Przez:',
'LBL_DATE_CREATED' => 'Data Utworzenia:',
'LBL_MODIFIED_BY' => 'Ostatnio Modyfikowane Przez:',
'LBL_DATE_LAST_MODIFIED' => 'Data Modyfikacji:',
'LBL_DEFAULT_SUBPANEL_TITLE' => 'Raport Sprzedaży',
'LBL_SYSTEM_ID' => 'System ID',
'LBL_LIST_ASSIGNED_TO_NAME' => 'Przypisany Użytkownik',
'LBL_LIST_VALUE' => 'Wartość',
'LBL_ASSIGNED_TO_NAME' => 'Przypisane Do',
'LBL_EMPTY_STATES' => 'Pokaż puste',
'LBL_PRICE' => 'Cena',
'LBL_REPORT' => 'Raport: ',
'LBL_SUBPANEL_TITLE' => 'Raport wartościowy',
'LBL_CONTRACTOR' => 'Kontrahent',
'LBL_INVOICE_NUMBER' => 'Numer dok.',
'LBL_TYPE' => 'Typ',
'LBL_REGISTER_DATE' => 'Data rejestracji',
'LBL_NET_VALUE' => 'Wartość netto',
'LBL_GROSS_VALUE' => 'Wartość brutto',
'LBL_COST' => 'Koszt',
'LBL_MARGIN' => 'Marża',
'LBL_PDF_TYPE' => 'Rodzaj',
'LBL_PDF_TYPE_NORMAL' => 'Normalna',
'LBL_PDF_TYPE_CORRECT' => 'Korekta',
'LBL_PDF_TYPE_K' => 'Kraj',
'LBL_PDF_TYPE_U' => 'Unia',
'LBL_PDF_TYPE_E' => 'Eksport',
'LBL_DOC_NUMBER' => 'Nr Dokumentu',
'LBL_INDEX' => 'Indeks',
'LBL_ALL_STOCKS' => 'Wszystkie',
'LBL_SEARCH' => 'Szukaj',
'LBL_EXECUTE' => 'Wykonaj',
'LBL_CLEAR' => 'Wyczyść',
'LBL_PRODUCTS' => 'Produkty',
'LBL_SOLD_AMOUNT' => 'Sprzedana ilość',
'LBL_QUANTITY' => 'Ilość',
'LBL_VALUE_SALES' => 'Wartość sprzedaży',
'LBL_AVERAGE_PRICE' => 'Średnia cena',
'LBL_RAPORT_SALES' => 'Raport sprzedaży',
'LBL_GORUP_BY' => 'Grupuj po',
'LBL_STOCK_STATES' => 'Stan magazynu',
'LBL_STOCK_VALUE' => 'Wartość magazynu',
'LBL_RAPORT_SALES_BY_CONTRACTOR' => 'Raport sprzedaży po kontrahencie',
'BTN_EXCEL_EXPORT' => 'Excel',
'BTN_PDF_EXPORT' => 'PDF',
'BTN_SHOW_GROUP_DIVISION' => 'Pokaż kategorie produktowe',
'BTN_SHOW_VAT_DIVISION' => 'Pokaż kolumny z Vat',
'LBL_VALUE_REGISTER' => 'Rejestr wartościowy',
'LBL_VAT_A' => '0%',
'LBL_VAT_B' => '22%',
'LBL_VAT_C' => '23%',
// kpkw report
// RAPORT && PDF
'LBL_NUMBER_LP' => 'Lp',
'LBL_DOCUMENT_NO' => 'Nr dokumentu',
'LBL_CREATE_LAB' => 'Data wyst.',
'LBL_TITLE' => 'Tytuł',
'LBL_PARENT_NAME' => 'Kontrahent',
'LBL_AMOUNT_PLUS' => 'Przychód',
'LBL_AMOUNT_MINUS' => 'Rozchód',
'LBL_VALUE' => 'Suma',
'LBL_VALUE_BEFORE' => 'Stan kasy poprzednio',
'LBL_VALUE_TOTAL' => 'Stan kasy obecny',
'LBL_RAPORT_TITLE' => 'Zestawienie KPKW',
'LBL_RAPORT_TITLE2' => 'RAPORT KASOWY',
'LBL_RAPORT_LABEL' => 'Raport kasowy',
'LBL_TIME' => 'okres',
'LBL_TIME2' => 'Okres',
'LBL_CASH' => 'kasa',
'LBL_CURRENCY_PDF' => 'waluta',
'LBL_CURRENCY_PDF2' => 'Waluta',
'LBL_CASH_USER' => 'kasjer',
'LBL_DATE_START' => 'Od',
'LBL_DATE_END' => 'Do',
'LBL_CASH2' => 'Kasa',
'LBL_CASH_USER2' => 'Kasjer',
'LBL_SUBMIT' => 'Wykonaj',
'LBL_SELECT' => 'Wybierz',
'LBL_ALL' => 'Wszyscy',
'LBL_PRINT_PDF' => 'Drukuj PDF',
'LBL_SALE_DATE' => 'Data sprz.',
'LBL_CONTRACTOR_NIP' => 'Nip odbiorcy',
'LBL_ADDRESS' => 'Adres',
'LBL_GROSS_SALES' => 'Sprz. brutto',
'LBL_NET_SALES' => 'Sprz. netto',
'LBL_VAT' => 'Vat',
'LBL_SUM_VAT' => 'Vat razem',
'LBL_VAT_SALES_REGISTER' => "Rejestr sprzedaży VAT",
'LBL_COST_OF' => "Koszt własny",
// AGREEMENTS
'LBL_REPORT_AGREEMENT' => 'Raport należności' ,
'LBL_DOCUMENT_DATE' => 'Data',
'LBL_REPORT_ACCOUNT'=> 'Kontrahent',
'LBL_REPORT_POSTALCODE'=>'Kod pocztowy',
'LBL_REPORT_CITY'=>'Miasto',
'LBL_REPORT_RECEIVE_REGISTER' => 'Rejestr zakupu',
'LBL_SALES_NIP'=> 'NIP',
'LBL_BUYER_VALUE_BRUTTO'=> 'wart brutto',
'LBL_BUYER_VALUE_NETTO'=> 'Netto',
'LBL_PAGE_SUM'=> 'Suma strony',
'LBL_TRANSFER_SUM'=> 'Suma z przeniesienia'
);
?>

View File

@@ -0,0 +1,44 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
$searchFields['EcmReports'] =
array (
'name' => array( 'query_type'=>'default'),
'value' => array( 'query_type'=>'default'),
'current_user_only'=> array('query_type'=>'default','db_field'=>array('assigned_user_id'),'my_items'=>true),
'assigned_user_id'=> array('query_type'=>'default'),
);
?>

View File

@@ -0,0 +1,64 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
*********************************************************************************/
require_once('include/utils.php');
function additionalDetailsEcmReport($fields) {
static $mod_strings;
global $app_strings;
if(empty($mod_strings)) {
global $current_language;
$mod_strings = return_module_language($current_language, 'EcmReports');
}
$overlib_string = '';
if(!empty($fields['DATE_ENTERED']))
$overlib_string .= '<b>'. $app_strings['LBL_DATE_ENTERED'] . '</b> ' . $fields['DATE_ENTERED'] . '<br>';
if(!empty($fields['NAME']))
$overlib_string .= '<b>'. $mod_strings['LBL_NAME'] . '</b> ' . $fields['NAME'] . '<br>';
return array('fieldToAddTo' => 'NAME',
'string' => $overlib_string,
'editLink' => "index.php?action=EditView&module=EcmReports&return_module=EcmReports&record={$fields['ID']}",
'viewLink' => "index.php?action=DetailView&module=EcmReports&return_module=EcmReports&record={$fields['ID']}");
}
?>

View File

@@ -0,0 +1,67 @@
<?php
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
$viewdefs['EcmReports']['DetailView'] = array(
'templateMeta'=>array(
'form'=>array(
'buttons'=>array(
'EDIT',
'DUPLICATE',
'DELETE',
)
),
'maxColumns'=>'2',
'widths'=>array(
array(
'label'=>'10',
'field' =>'30'
),
array(
'label'=>'10',
'field'=>'30'
)
),
),
'panels'=>array(
array(
'name',
'assigned_user_name',
),
array(
'value',
),
)
);
?>

View File

@@ -0,0 +1,52 @@
<?php
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
$viewdefs['EcmReports']['EditView'] = array(
'templateMeta'=>array(
'form' => array('buttons'=>array('SAVE', 'CANCEL')),
'maxColumns'=>'2',
'widths'=>array(
array('label'=>'10','field'=>'30'),
array('label'=>'10','field'=>'30'),
),
),
'panels'=>array(
'default'=>array(
array('name','assigned_user_name'),
array('value'),
),
),
);
?>

View File

@@ -0,0 +1,56 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/**
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
*/
$listViewDefs['EcmReports'] = array(
'NAME' => array(
'width' => '32',
'label' => 'LBL_LIST_SUBJECT',
'default' => true,
'link' => true),
'VALUE' => array(
'width' => '10',
'label' => 'LBL_LIST_VALUE',
'default' => true),
'ASSIGNED_USER_NAME' => array(
'width' => '9',
'label' => 'LBL_LIST_ASSIGNED_USER',
'default' => true)
);
?>

View File

@@ -0,0 +1,50 @@
<?php
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*
* Created on Jun 1, 2007
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
$metafiles['EcmReports'] = array(
'detailviewdefs' => 'modules/EcmReports/metadata/detailviewdefs.php',
'editviewdefs' => 'modules/EcmReports/metadata/editviewdefs.php',
'listviewdefs' => 'modules/EcmReports/metadata/listviewdefs.php',
'searchdefs' => 'modules/EcmReports/metadata/searchdefs.php',
'popupdefs' => 'modules/EcmReports/metadata/popupdefs.php',
'searchfields' => 'modules/EcmReports/metadata/SearchFields.php',
);
?>

View File

@@ -0,0 +1,67 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
$popupMeta = array('moduleMain' => 'EcmReport',
'varName' => 'ECMREPORT',
'orderBy' => 'ecmreports.name',
'whereClauses' =>
array('name' => 'ecmreports.name'),
'listviewdefs' => array(
'NAME' => array(
'width' => '32',
'label' => 'LBL_LIST_SUBJECT',
'default' => true,
'link' => true),
'VALUE' => array(
'width' => '10',
'label' => 'LBL_LIST_VALUE',
'default' => true),
'ASSIGNED_USER_NAME' => array(
'width' => '9',
'label' => 'LBL_LIST_ASSIGNED_USER',
'default' => true)
),
'searchdefs' => array(
'name',
'value',
array('name' => 'assigned_user_id', 'type' => 'enum', 'label' => 'LBL_ASSIGNED_TO', 'function' => array('name' => 'get_user_array', 'params' => array(false))),
)
);
?>

View File

@@ -0,0 +1,59 @@
<?php
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
/*
* Created on May 29, 2007
*
* To change the template for this generated file go to
* Window - Preferences - PHPeclipse - PHP - Code Templates
*/
$searchdefs['EcmReports'] = array(
'templateMeta' => array(
'maxColumns' => '3',
'widths' => array('label' => '10', 'field' => '30'),
),
'layout' => array(
'basic_search' => array(
'name',
array('name'=>'current_user_only', 'label'=>'LBL_CURRENT_USER_FILTER', 'type'=>'bool'),
),
'advanced_search' => array(
'name',
'value',
array('name' => 'assigned_user_id', 'type' => 'enum', 'label' => 'LBL_ASSIGNED_TO', 'function' => array('name' => 'get_user_array', 'params' => array(false))),
),
),
);
?>

View File

@@ -0,0 +1,71 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
*********************************************************************************/
$viewdefs['EcmReports']['SideQuickCreate'] = array(
'templateMeta' => array('form'=>array('buttons'=>array('SAVE'),
'button_location'=>'bottom',
'headerTpl'=>'include/EditView/header.tpl',
'footerTpl'=>'include/EditView/footer.tpl',
),
'maxColumns' => '1',
'panelClass'=>'none',
'labelsOnTop'=>true,
'widths' => array(
array('label' => '10', 'field' => '30'),
),
),
'panels' =>array (
'DEFAULT' =>
array (
array (
array('name'=>'name', 'displayParams'=>array('size'=>20, 'required'=>true)),
),
array(
array('name'=>'value', 'displayParams'=>array('size'=>20)),
),
array (
array('name'=>'assigned_user_name', 'displayParams'=>array('required'=>true, 'size'=>11, 'selectOnly'=>true)),
),
),
)
);
?>

View File

@@ -0,0 +1,65 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/**
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
*/
$GLOBALS['studioDefs']['EcmReports'] = array(
'LBL_DETAILVIEW'=>array(
'template'=>'xtpl',
'template_file'=>'modules/EcmReports/DetailView.html',
'php_file'=>'modules/EcmReports/DetailView.php',
'type'=>'DetailView',
),
'LBL_EDITVIEW'=>array(
'template'=>'xtpl',
'template_file'=>'modules/EcmReports/EditView.html',
'php_file'=>'modules/EcmReports/EditView.php',
'type'=>'EditView',
),
'LBL_LISTVIEW'=>array(
'template'=>'listview',
'meta_file'=>'modules/EcmReports/listviewdefs.php',
'type'=>'ListView',
),
'LBL_SEARCHFORM'=>array(
'template'=>'xtpl',
'template_file'=>'modules/EcmReports/SearchForm.html',
'php_file'=>'modules/EcmReports/ListView.php',
'type'=>'SearchForm',
),
);

View File

@@ -0,0 +1,42 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/**
* Layout definition for EcmReports
*
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
*/
$layout_defs['EcmReports']['subpanel_setup'] = array(
);
?>

View File

@@ -0,0 +1,91 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/**
* Subpanel Layout definition for EcmReports
*
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
*/
$subpanel_layout = array(
'top_buttons' => array(
array('widget_class' => 'SubPanelTopCreateButton'),
array('widget_class' => 'SubPanelTopSelectButton', 'popup_module' => 'EcmReports'),
),
'where' => '',
'list_fields' => array(
'ecmreport_number'=>array(
'vname' => 'LBL_LIST_NUMBER',
'width' => '5%',
),
'name'=>array(
'vname' => 'LBL_LIST_SUBJECT',
'widget_class' => 'SubPanelDetailViewLink',
'width' => '50%',
),
'status'=>array(
'vname' => 'LBL_LIST_STATUS',
'width' => '15%',
),
'type'=>array(
'vname' => 'LBL_LIST_TYPE',
'width' => '15%',
),
'priority'=>array(
'vname' => 'LBL_LIST_PRIORITY',
'width' => '11%',
),
'assigned_user_name' => array (
'name' => 'assigned_user_name',
'vname' => 'LBL_LIST_ASSIGNED_TO_NAME',
),
'edit_button'=>array(
'widget_class' => 'SubPanelEditButton',
'module' => 'EcmReports',
'width' => '4%',
),
'remove_button'=>array(
'widget_class' => 'SubPanelRemoveButton',
'module' => 'EcmReports',
'width' => '5%',
),
),
);
?>

View File

@@ -0,0 +1,383 @@
<?php
global $mod_strings, $app_list_strings, $db;
if(!$_REQUEST['date_from'])
$date_from = date("01.m.Y");
else
$date_from = $_REQUEST["date_from"];
if(!$_REQUEST['date_to'])
$date_to = date("d.m.Y");
else
$date_to = $_REQUEST["date_to"];
if(!class_exists('EcmInvoiceOut')){
include_once('modules/EcmInvoiceouts/EcmInvoiceout.php');
};
if(!class_exists('EcmReceipts')){
include_once('modules/EcmReceipts/EcmReceipt.php');
};
if(!class_exists('EcmStockDocIn')){
include_once('modules/EcmStockDocIns/EcmStockDocIn.php');
};
//get trader list
$query_trader = "select ecminvoiceouts.assigned_user_id AS user_id , concat(users.first_name, ' ', users.last_name) AS user_name FROM ecminvoiceouts, users WHERE ecminvoiceouts.deleted = 0 and ecminvoiceouts.canceled = 0 AND users.id = ecminvoiceouts.assigned_user_id group by user_id ORDER BY user_name";
//$query_trader = "select ecmstockdockins.assigned_user_id AS user_id , concat(users.first_name, ' ', users.last_name) AS user_name FROM ecmstockdockins, users WHERE ecmstockdockins.deleted = 0 and ecmstockdockins.canceled = 0 AND users.id = ecmstockdockins.assigned_user_id group by user_id ORDER BY user_name";
$trader_result = $db->query($query_trader);
$trader_array = array(""=>"&nbsp;");
while($row = $db->fetchByAssoc($trader_result)){
$trader_array[$row['user_id']] = $row['user_name'];
}
//Get Stock List
if($_REQUEST['product_category_id'] != ""){
$product_category = $_REQUEST['product_category_id'];
}
$query_stock = "Select id, name from ecmstocks where deleted=0";
$stock_result = $db->query($query_stock);
$stock_array = array(""=>"");
while($row = $db->fetchByAssoc($stock_result)){
$stock_array[$row['id']] = $row['name'];
}
$query_stock = "Select account_type from accounts where deleted=0 group by account_type";
$stock_result = $db->query($query_stock);
$account_array = array(""=>"");
while($row = $db->fetchByAssoc($stock_result)){
$account_array[$row['account_type']] =$app_list_strings['account_type_dom'][$row['account_type']];
}
//Szykowanie zapytań
//Zakres dat
$whereInvoice['ecminvoiceouts'][] = 'register_date>="' . getFormatedDateForDB($date_from) . '"';
$whereInvoice['ecminvoiceouts'][] = 'register_date<="' . getFormatedDateForDB($date_to) . '"';
$whereRecipe['ecmrecipes'][] = 'register_date>="' . getFormatedDateForDB($date_from) . '"';
$whereRecipe['ecmrecipes'][] = 'register_date<="' . getFormatedDateForDB($date_to) . '"';
//Handlowiec
if($_REQUEST['trader'] != ""){
if($_REQUEST['trader'][0]==""){
unset($_REQUEST['trader'][0]);
}
if(count($_REQUEST['trader'])>0){
$whereInvoice['ecminvoiceouts'][] = 'assigned_user_id in ("' . implode('","',$_REQUEST['trader']). '")';
$whereRecipe['ecmrecipes'][] = 'assigned_user_id in ("' . implode('","',$_REQUEST['trader']). '")';
}
}
//Kontrahent
if($_REQUEST['account_id'] != ""){
$whereInvoice['ecminvoiceouts'][] = 'parent_id="' . $_REQUEST['account_id'] . '"';
$whereRecipe['ecmrecipes'][] = 'parent_id="' . $_REQUEST['account_id'] . '"';
}
//Magazyn
$stocks = $_REQUEST['stocks'];
if(count($stocks)>0){
if(in_array("",$stocks)){
$indeks = array_search("",$stocks);
unset($stocks[$indeks]);
}
if(count($stocks)>0){
$stocksList = array();
$value = array_values ( $stocks );
$whereInvoice['ecminvoiceouts'][] = 'stock_id IN ("' . implode('","',$value) . '")';
$whereRecipe['ecmrecipes'][] = 'stock_id IN ("' . implode('","',$value) . '")';
}
}
$accounts = $_REQUEST['account_type'];
if(count($accounts)>0){
if(in_array("",$accounts)){
$indeks = array_search("",$accounts);
unset($accounts[$indeks]);
}
if(count($accounts)>0){
$accountsList = array();
$value = array_values ( $accounts );
$whereInvoice['accounts'][] = 'accounts.account_type IN ("' . implode('","',$value) . '")';
}
}
//Grupa
$product_group = $_REQUEST['product_group'];
if(count($product_group)>0){
if(in_array("",$product_group)){
$indeks = array_search("",$product_group);
unset($product_group[$indeks]);
}
if(count($product_group)>0){
$product_group_list = array();
$value = array_values ( $product_group );
$whereInvoice['ecmproducts'][] = 'ks_group IN ("' . implode('","',$value) . '")';
$whereRecipe['ecmproducts'][] = 'ks_group IN ("' . implode('","',$value) . '")';
}
}
$product_group_2 = $_REQUEST['product_group_2'];
if(count($product_group_2)>0){
if(in_array("",$product_group_2)){
$indeks = array_search("",$product_group_2);
unset($product_group_2[$indeks]);
}
if(count($product_group_2)>0){
$product_group_list = array();
$value = array_values ( $product_group_2 );
$whereInvoice['ecmproducts'][] = 'ks_group2 IN ("' . implode('","',$value) . '")';
$whereRecipe['ecmproducts'][] = 'ks_group2 IN ("' . implode('","',$value) . '")';
}
}
//Typ dokumentu
$document_sales_type = $_REQUEST['document_sales_type'];
if(count($document_sales_type)>0){
if(in_array("",$document_sales_type)){
$indeks = array_search("",$document_sales_type);
unset($document_sales_type[$indeks]);
}
if(count($document_sales_type)>0){
$tmpInvoiceType = array();
$tmpRecipeType = array();
$receiptDo = false;
$invoceDo = true;
if(count($tmpRecipeType)>0){
$value = array_values ( $tmpRecipeType );
//var_dump($where);
$dataRecipe = EcmStockDocIn::getReceiptsList($whereRecipe,$product_category);
}
}else{
//$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
var_dump($where);
$dataRecipe = EcmStockDocIn::getReceiptsList($whereRecipe,$product_category);
}
}else{
//$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
$dataRecipe = EcmStockDocIn::getReceiptsList($whereRecipe,$product_category);
}
// Przetwarzanie danych
$data = array();
$total=0;
$total2=0;
$total3=0;
foreach($dataInvoice as $indeks => $invoice){
foreach($invoice['position_list'] as $position => $item){
$data[$item['product_id']]['code'] = '<a target="_blank" href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '">' . $item['position_code'] . '</a>';
$data[$item['product_id']]['index'] = $item['position_code'] ;
$data[$item['product_id']]['nazwa'] = $item['position_name'];
$data[$item['product_id']]['position_weight'] = $item['position_weight'];
$data[$item['product_id']]['position_total_weight'] += $item['position_total_weight'];
$data[$item['product_id']]['name'] = '<a target="_blank" href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '"> ' . $item['position_name'] . '</a>';
$data[$item['product_id']]['total_netto'] += $item['position_total_netto'];
$data[$item['product_id']]['price_purchase'] += $item['position_total_price_purchase'];
$data[$item['product_id']]['quantity'] += $item['position_quantity'];
$data[$item['product_id']]['jm_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$item['position_unit_id']];
$data[$item['product_id']]['jm_name'] = $item['position_unit_name'];
if($_REQUEST['to_xls']=='1'){
$data[$item['product_id']]['name'] =$item['position_code'] . ' ' . $item['position_name'];
}
$total3+=$item['position_quantity'];
$total+=$item['position_total_netto'];
$total2+=$item['position_total_price_purchase'];
}
}
$total4=0;
foreach($dataRecipe as $indeks => $invoice){
foreach($invoice['position_list'] as $position => $item){
$data[$item['product_id']]['code'] = '<a target="_blank" href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '">' . $item['position_code'] . '</a>';
$data[$item['product_id']]['index'] = $item['position_code'] ;
$data[$item['product_id']]['nazwa'] = $item['position_name'];
$data[$item['product_id']]['position_weight'] = $item['position_weight'];
$data[$item['product_id']]['position_total_weight'] += $item['position_total_weight'];
$data[$item['product_id']]['name'] = '<a target="_blank" href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '"> ' . $item['position_name'] . '</a>';
$data[$item['product_id']]['total_netto'] += $item['position_total_netto'];
$data[$item['product_id']]['price_purchase'] += $item['position_total_price_purchase'];
$data[$item['product_id']]['quantity'] += $item['position_quantity'];
$data[$item['product_id']]['jm_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$item['position_unit_id']];
$data[$item['product_id']]['jm_name'] = $item['position_unit_name'];
if($_REQUEST['to_xls']=='1'){
$data[$item['product_id']]['name'] =$item['position_code'] . ' ' . $item['position_name'];
}
$total3+=$item['position_quantity'];
$total+=$item['position_total_netto'];
$total2+=$item['position_total_price_purchase'];
$total4+=$item['position_total_weight'];
}
}
//var_dump($data);
//
//Szykowanie wyświetlania
$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("APP_LIST_STRINGS", $app_list_strings);
$sort=$_REQUEST['sort'];
if(count($sort)>0){
foreach($sort as $key=>$val){
switch (strtolower( $key)) {
case 'indeks':
if($val=='ASC'){
usort($data, 'compare_lastname');
}else{
usort($data, 'compare_lastname_desc');
}
break;
case 'nazwa':
if($val=='ASC'){
usort($data, 'compare_nazwa');
}else{
usort($data, 'compare_nazwa_desc');
}
break;
default:
usort($data, 'compare_lastname');
}
}
}
$smarty->assign("DATA", $data);
$smarty->assign("TRADERS_LIST", $trader_array);
$smarty->assign("STOCK_LIST", $stock_array);
$smarty->assign("ACCOUNT_LIST", $account_array);
$smarty->assign("TOTAL", $total);
$smarty->assign("TOTAL2", $total2);
$smarty->assign("TOTAL3", $total3);
//Ustawiamy przeslane dane
//$date_from = $GLOBALS['timedate']->to_display_date($date_from);
//$date_to = $GLOBALS['timedate']->to_display_date($date_to);
$smarty->assign("date_from_value", $date_from );
$smarty->assign("date_to_value", $date_to );
$smarty->assign("TRADER_SELECTED", $_REQUEST['trader']);
$smarty->assign("ACCOUNT_ID", $_REQUEST['account_id']);
$smarty->assign("ACCOUNT_NAME", $_REQUEST['account_name']);
$smarty->assign("PRODUCT_CATEGORY_ID", $_REQUEST['product_category_id']);
$smarty->assign("PRODUCT_CATEGORY_NAME", $_REQUEST['product_category_name']);
if($_REQUEST['to_pdf']!='1'){
$smarty->assign("STOCK_SELECTED", $_REQUEST['stocks']);
$smarty->assign("ACCOUNT_SELECTED", $_REQUEST['account_type']);
$smarty->assign("PRODUCT_GROUP_SELECTED", $_REQUEST['product_group']);
$smarty->assign("PRODUCT_GROUP_SELECTED_2", $_REQUEST['product_group_2']);
$smarty->assign("DOCUMENT_SALES_SELECTED", $_REQUEST['document_sales_type']);
echo $smarty->display('modules/EcmReports/tpls/mzVatPurchases.tpl');
}else{
if($_REQUEST['to_xls']=='1'){
$header=array();
$header[]='index';
$header[]='nazwa';
$header[]='ilość';
$header[]='jm';
$header[]='zakup netto';
// $header[]='koszt zakupu';
//$header[]='dochód';
$filename='modules/Home/Files/raport_zakupu_ilosciowy_'.date('d_m_Y').'.csv';
$fp=fopen($filename,'w');
foreach ($header as $k=>$v){
$header[$k]=iconv('UTF-8','windows-1250',$header[$k]);
}
fwrite($fp, implode(";",$header).PHP_EOL);
foreach ($data as $key=>$val){
$line=array();
$line[]=html_entity_decode($val['index']);
$line[]=preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['name'])));
$line[]=str_replace(".",",",$val['quantity']);
$line[]=$val['jm_name'];
$line[]=str_replace(".",",",$val['total_netto']);
// $line[]=str_replace(".",",",$val['price_purchase']);
//$line[]=str_replace(".",",",$val['total_netto']-$val['price_purchase']);
foreach ($line as $k=>$v){
$line[$k]=iconv('UTF-8','windows-1250',$line[$k]);;
}
fwrite($fp, implode(";",$line).PHP_EOL);
}
print $filename;
} else {
include_once ("include/MPDF57/mpdf.php");
include_once ("modules/EcmSysInfos/EcmSysInfo.php");
$smarty->assign("STOCK_SELECTED", $stocks);
$smarty->assign("PRODUCT_GROUP_SELECTED", $product_group);
$smarty->assign("DOCUMENT_SALES_SELECTED", $document_sales_type);
$EcmSysInfo = new EcmSysInfo();
$smarty->assign("EcmSysInfo", $EcmSysInfo);
//echo $EcmSysInfo->getName();
$content = $smarty->fetch('modules/EcmReports/tpls/mzVatPurchaesPDF.tpl');
$mPDF = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 10, 10, 5, 5 );
$mPDF->mirrorMargins = 1;
$mPDF->WriteHTML($content);
$dir = 'upload/' . $EcmSysInfo->getDatabaseName() . '/pdf/EcmReports/';
if(!is_dir($dir)){
mkdir($dir, '755', true);
}
$file_name = $dir . str_replace(".","",$date_from) . "_" . str_replace(".","",$date_to) ."_Raport_zakupu_Ilosciowy.pdf";
$mPDF->Output( $file_name, "F");
print $file_name;
}
}
function getFormatedDateForDB($data){
if(strpos($data,".")>0){
$split = explode (".",$data);
$return_data = $split[2] . "-" . $split[1] . "-" .$split['0'];
}
return $return_data;
}
function compare_lastname($a, $b)
{
return strnatcmp($a['index'], $b['index']);
}
function compare_lastname_desc($a, $b)
{
return strnatcmp($b['index'], $a['index']);
}
function compare_nazwa($a, $b)
{
return strnatcmp($a['nazwa'], $b['nazwa']);
}
function compare_nazwa_desc($a, $b)
{
return strnatcmp($b['nazwa'], $a['nazwa']);
}

View File

@@ -0,0 +1,236 @@
<?php
require_once 'modules/EcmReports/optima/OptimaXML.php';
class ExportOptima {
private $date_from;
private $date_to;
private $db;
private $optimaXML;
private $XMLObject;
public function __construct($date, OptimaXML $optimaXML) {
$date = new DateTime ( $date );
$this->date_from = $date->format ( "Y-m-01" );
$this->date_to = $date->format ( "Y-m-t" );
$this->db = $GLOBALS ['db'];
$this->optimaXML = $optimaXML;
}
public function loadXmlObject() {
$this->optimaXML->generateStartXMl ()->loadXml ();
}
public function addInvoiceDocuments() {
global $app_list_strings;
$this->getInvoicesObject ();
$payment_methods = $app_list_strings ['payment_method_dom'];
$fpn = new SimpleXMLElement ( '<REJESTRY_SPRZEDAZY_VAT></REJESTRY_SPRZEDAZY_VAT>' );
$fpn->addChild ( 'WERSJA', OptimaXMLConstant::WERSJA );
$fpn->addChild ( 'BAZA_ZRD_ID', OptimaXMLConstant::BAZA_ZRD_ID );
$fpn->addChild ( 'BAZA_DOC_ID', OptimaXMLConstant::BAZA_DOC_ID );
foreach ( $this->getInvoicesObject () as $value ) {
$fpn = $this->addInvoiceDocument ( $value, $fpn );
}
$this->xml_adopt ( $this->optimaXML->basicXML, $fpn );
echo $this->optimaXML->basicXML->asXML ();
}
public function addInvoiceDocument($value, $fpn) {
$header = new SimpleXMLElement ( '<REJESTR_SPRZEDAZY_VAT></REJESTR_SPRZEDAZY_VAT>' );
$fpe = $header->addChild ( 'REJESTR_SPRZEDAZY_VAT' );
$this->addIfNotEmpty ( $fpe, 'ID_ZRODLA', $value->id );
$this->addIfNotEmpty ( $fpe, 'MODUL', 'HANDEL' );
$this->addIfNotEmpty ( $fpe, 'REJESTR', 'REJESTR SPRZEDAŻY VAT' );
$this->addIfNotEmpty ( $fpe, 'DATA_WYSTAWIENIA', date ( "Y-m-d", strtotime ( $value->register_date ) ) );
$this->addIfNotEmpty ( $fpe, 'DATA_SPRZEDAZY', date ( "Y-m-d", strtotime ( $value->sell_date ) ) );
$this->addIfNotEmpty ( $fpe, 'TERMIN', date ( "Y-m-d", strtotime ( $value->payment_date ) ) );
$this->addIfNotEmpty ( $fpe, 'DATA_DATAOBOWIAZKUPODATKOWEGO', date ( "Y-m-d", strtotime ( $value->register_date ) ) );
$this->addIfNotEmpty ( $fpe, 'DATA_DATAPRAWAODLICZENIA', date ( "Y-m-d", strtotime ( $value->register_date ) ) );
$this->addIfNotEmpty ( $fpe, 'NUMER', $value->document_no );
$this->addIfNotEmpty ( $fpe, 'KOREKTA', ($value->type == 'normal' ? 'Nie' : 'Tak') );
if ($value->type == 'correct') {
$cor = new EcmInvoiceOut ();
$cor->retrieve ( $value->ecminvoiceout_id );
$this->addIfNotEmpty ( $fpe, 'KOREKTA_NUMER', $cor->document_no );
}
$this->addIfNotEmpty ( $fpe, 'WEWNETRZNA', 'Nie' );
$this->addIfNotEmpty ( $fpe, 'METODA_KASOWA', 'Nie' );
$this->addIfNotEmpty ( $fpe, 'FISKALNA', 'Nie' );
$this->addIfNotEmpty ( $fpe, 'DETALICZNA', 'Nie' );
if ($value->pdf_type == 'K') {
$dek_7 = date ( "Y-m", strtotime ( $value->register_date ) );
$dek_ue = "Nie";
$export = 'nie';
} else if ($value->pdf_type == 'U') {
$dek_7 = "";
$dek_ue = 'Tak';
$export = 'wewnątrzunijny';
} else if ($value->pdf_type == 'E') {
$export = 'tak';
$dek_7 = date ( "Y-m", strtotime ( $value->register_date ) );
$dek_ue = 'Nie';
}
$this->addIfNotEmpty ( $fpe, 'EKSPORT', $export );
$acc = new Account ();
$acc->retrieve ( $value->parent_id );
$this->addIfNotEmpty ( $fpe, 'FINALNY', ($acc->natural_person ? 'Tak' : 'Nie') );
$this->addIfNotEmpty ( $fpe, 'PODATNIK_CZYNNY', ($acc->vat_payer ? 'Tak' : 'Nie') );
$this->addIfNotEmpty ( $fpe, 'TYP_PODMIOTU', 'kontrahent' );
$this->addIfNotEmpty ( $fpe, 'PODMIOT', $acc->index_dbf );
$this->addIfNotEmpty ( $fpe, 'PODMIOT_ID', $acc->id );
$this->addIfNotEmpty ( $fpe, 'PODMIOT_NIP', $acc->to_vatid );
$acc_name = $acc->name;
if (strlen ( $acc_name ) > 50) {
$this->addIfNotEmpty ( $fpe, 'NAZWA1', substr ( $acc_name, 0, 50 ) );
if (strlen ( $acc_name ) > 100) {
$this->addIfNotEmpty ( $fpe, 'NAZWA2', substr ( $acc_name, 50, 50 ) );
$this->addIfNotEmpty ( $fpe, 'NAZWA3', substr ( $acc_name, 100 ) );
} else {
$this->addIfNotEmpty ( $fpe, 'NAZWA2', substr ( $acc_name, 50 ) );
}
} else {
$this->addIfNotEmpty ( $fpe, 'NAZWA1', $acc_name );
}
if ($acc->invoice_type == "K") {
$this->addIfNotEmpty ( $fpe, 'NIP_KRAJ', 'PL' );
} else {
$this->addIfNotEmpty ( $fpe, 'NIP_KRAJ', substr ( $acc->to_vatid, 0, 2 ) );
}
$this->addIfNotEmpty ( $fpe, 'NIP', $acc->to_vatid );
preg_match ( '/^([^\d]*[^\d\s]) *(\d.*)$/', $acc->register_address_street, $matches );
$this->addIfNotEmpty ( $fpe, 'KRAJ', $acc->register_address_country );
$this->addIfNotEmpty ( $fpe, 'WOJEWÓDZTWO', $acc->register_address_state );
// $fpe->addChild('POWIAT',$acc->to_vatid);
$this->addIfNotEmpty ( $fpe, 'GMINA', $acc->register_address_ecmcommune_name );
$this->addIfNotEmpty ( $fpe, 'ULICA', $matches [1] );
$numbers = $this->findHomeAndLocale ( $matches [2] );
$this->addIfNotEmpty ( $fpe, 'NR_DOMU', $numbers [0] );
$this->addIfNotEmpty ( $fpe, 'NR_LOKALU', $numbers [1] );
$this->addIfNotEmpty ( $fpe, 'MIASTO', $acc->register_address_city );
$this->addIfNotEmpty ( $fpe, 'KOD_POCZTOWY', $acc->register_address_postalcode );
$this->addIfNotEmpty ( $fpe, 'DEKLARACJA_VAT7', $dek_7 );
$this->addIfNotEmpty ( $fpe, 'DEKLARACJA_VATUE', $dek_ue );
if ($value->currency_id==null) {
$cur = new Currency ();
$cur->retrieve ( $value->currency_id );
$date = $this->getCurrencyDate ( $value->currency_table, $cur->id );
$this->addIfNotEmpty ( $fpe, 'WALUTA', $cur->name );
$this->addIfNotEmpty ( $fpe, 'KURS_WALUTY', '--' . $value->currency_value_nbp );
$this->addIfNotEmpty ( $fpe, 'DATA_KURSU', date ( "Y-m-d", strtotime ( $date ) ) );
$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ILE', $value->currency_value_nbp );
$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ZA_ILE', $value->currency_value_nbp );
$this->addIfNotEmpty ( $fpe, 'KURS_DO_KSIEGOWANIA', 'Nie' );
} else {
$this->addIfNotEmpty ( $fpe, 'WALUTA', 'PLN' );
$this->addIfNotEmpty ( $fpe, 'KURS_WALUTY', 'Nie' );
$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ILE', '1' );
$this->addIfNotEmpty ( $fpe, 'NOTOWANIE_WALUTY_ZA_ILE', '1' );
$this->addIfNotEmpty ( $fpe, 'KURS_DO_KSIEGOWANIA', "Nie" );
}
$this->addIfNotEmpty ( $fpe, 'PLATNOSC_VAT_W_PLN', "Tak" );
$this->addIfNotEmpty ( $fpe, 'JPK_FA', "Tak" );
$this->addIfNotEmpty ( $fpe, 'DEKLARACJA_VAT27', "Nie" );
$this->addIfNotEmpty ( $fpe, 'WARTOSC_ZAKUPU', $value->purchase_price );
$this->addInvoicePositions ( $fpe, $value );
$this->xml_adopt ( $fpn, $fpe );
return $fpn;
}
public function addInvoicePositions($node, $object) {
$pozycje = $node->addChild ( 'POZYCJE' );
$positions = $object->getPositionList ( true );
global $app_list_strings;
foreach ( $positions as $position ) {
$header = new SimpleXMLElement ( '<POZYCJA></POZYCJA>' );
$fpe = $header->addChild ( 'POZYCJA' );
$fpe->addChild ( 'STAWKA_VAT', $position ['ecmvat_name'] );
$fpe->addChild ( 'STATUS_VAT', 'opodatkowana' );
$fpe->addChild ( 'NETTO', $position ['total_netto'] );
$fpe->addChild ( 'VAT', $position ['total_vat'] );
if ($value->currency_id == null) {
$fpe->addChild ( 'NETTO_SYS', round ( $position ['total_netto'] * $object->currency_value_nbp, 2 ) );
$fpe->addChild ( 'VAT_SYS', round ( $position ['total_vat'] * $object->currency_value_nbp, 2 ) );
$fpe->addChild ( 'NETTO_SYS2', round ( $position ['total_netto'] * $object->currency_value_nbp, 2 ) );
$fpe->addChild ( 'VAT_SYS2', round ( $position ['total_vat'] * $object->currency_value_nbp, 2 ) );
}
$fpe->addChild ( 'RODZAJ_SPRZEDAZY',$app_list_strings['ecmproducts_group_ks_dom'][$position['product_ks_group']] );
$fpe->addChild ( 'UWZ_W_PROPORCJI','TAK' );
$this->xml_adopt ( $pozycje, $fpe );
}
}
public function getCurrencyDate($nbp, $cur_id) {
$res = $this->db->query ( "select date from currency_nbp_archive where currency_id='" . $cur_id . "' and nbp_table_name='" . $nbp . "'" );
$dane = $this->db->fetchByAssoc ( $res );
return $dane ['date'];
}
public function addIfNotEmpty(&$object, $key, $value) {
if ($value) {
if ($value != "") {
$object->addChild ( $key, $value );
}
}
}
public function findHomeAndLocale($numbers) {
$numbers = str_replace ( " ", "", $numbers );
$pos = strpos ( $numbers, '/' );
if ($pos !== false) {
return implode ( '/', $numbers );
}
return [ ];
}
public function xml_adopt($root, $new) {
$node = $root->addChild ( $new->getName (), ( string ) $new );
foreach ( $new->attributes () as $attr => $value ) {
$node->addAttribute ( $attr, $value );
}
foreach ( $new->children () as $ch ) {
self::xml_adopt ( $node, $ch );
}
}
public function getInvoicesObject() {
$invoices = new EcmInvoiceOut ();
$invoices = $invoices->get_full_list ( null, "register_date>='" . $this->date_from . "' and register_date<='" . $this->date_to . "'" );
return $invoices;
}
}
$exportOptima = new ExportOptima ( '04.08.2017', new OptimaXML () );
$exportOptima->loadXmlObject ();
$exportOptima->addInvoiceDocuments ();
?>

View File

@@ -0,0 +1,43 @@
<?php
require_once 'modules/EcmReports/optima/OptimaXMLConstant.php';
class OptimaXML{
private $sugarSmarty;
public $basicXML;
private $content;
private $dom;
public function __construct(){
$this->sugarSmarty= new Sugar_Smarty();
$this->dom= new DOMDocument;
}
public function generateStartXMl(){
$this->sugarSmarty->assign("WERSJA",OptimaXMLConstant::WERSJA);
$this->sugarSmarty->assign("BAZA_ZRD_ID",OptimaXMLConstant::BAZA_ZRD_ID);
$this->sugarSmarty->assign("BAZA_DOC_ID",OptimaXMLConstant::BAZA_DOC_ID);
$this->content=$this->sugarSmarty->fetch(OptimaXMLConstant::FILE_PATH);
return $this;
}
public function loadXml(){
$this->dom->loadXML($this->content);
$this->basicXML=simplexml_import_dom($this->dom);
return $this;
}
public function getXmlNode(){
return $this->basicXML;
}
}

View File

@@ -0,0 +1,9 @@
<?php
class OptimaXMLConstant{
const WERSJA = '2.00';
const BAZA_ZRD_ID='SPR';
const BAZA_DOC_ID='KSI';
const FILE_PATH='modules/EcmReports/tpls/test_2.xml.html';
}

View File

@@ -0,0 +1,36 @@
<?php
if (isset ( $_REQUEST ['date_from'] )) {
$date_from = date ( 'Y-m-d', strtotime ( $_REQUEST ['date_from'] ) );
} else {
$date_from = date ( "01.m.Y" );
}
$data = array ();
if (isset ( $_REQUEST ['date_to'] )) {
$date_to = date ( 'Y-m-d', strtotime ( $_REQUEST ['date_to'] ) );
} else {
$date_to = date ( "t.m.Y" );
}
$fired=false;
if (isset ( $_REQUEST ['process'] )) {
$db = $GLOBALS ['db'];
$query = "select p.pkwiu,o.parent_name,o.parent_id,sum(case o.type when 'normal' then i.quantity when 'correct' then i.quantity_corrected end) as sum from ecminvoiceoutitems i
inner join ecminvoiceouts o on i.ecminvoiceout_id=o.id
inner join ecmproducts p on p.id=i.ecmproduct_id
where o.deleted=0 and o.canceled!=1 and o.register_date >='" . $date_from . "' and o.register_date<='" . $date_to . "'
group by p.pkwiu,o.parent_id";
$res = $db->query ( $query );
while ( $dat = $db->fetchByAssoc ( $res ) ) {
$data [] = $dat;
}
$fired=true;
}
$smarty = new Sugar_Smarty ();
$smarty->assign ( "data", $data );
$smarty->assign ( "fired", $fired );
$smarty->assign ( 'date_from', date ( 'd.m.Y', strtotime ($date_from ) ) );
$smarty->assign ( 'date_to', date ( 'd.m.Y', strtotime ($date_to ) ) );
echo $smarty->fetch ( 'modules/EcmReports/tpls/pkwiu.tpl' );
?>

View File

@@ -0,0 +1,101 @@
<?php
include_once ("include/MPDF57/mpdf.php");
global $app_list_strings;
$p2=new mPDF('','A4', null, 'helvetica', 10,10,10,10,0,0);
$i=0;
$j=0;
$db = $GLOBALS ['db'];
$data = array ();
//var_dump($_POST);
foreach ($_POST as $klucz => $wartosc){
if($pos !== false){
if($j%4==0){
$p2->AddPage();
}
$j++;
$tytul = "";
$opis = "";
$query = "SELECT
d.document_date as docdate,
d.document_name as docname,
DATE_FORMAT(DATE(d.date_entered), '%d-%m-%Y') as docdateentered,
d.category_id as doccategory,
d.description as docdes,
ifnull(d.value,0) as docwartosc,
u.first_name as username,
u.last_name as userlastname
FROM
documents d
left join users u on u.id = d.created_by
left join accounts a on d.parent_id = a.id
WHERE
d.id = '".$wartosc. "' AND d.deleted = 0";
/**
* ************* GET DATA FROM DB********************
*/
echo $query;
die();
$rows = $db->query ( $query );
while ( $r = $db->fetchByAssoc ( $rows ) ) {
if($r['docname']!=NULL)
$tytul = $tytul. "Nazwa dokumentu: ".$r['docname']."<br>";
if($r['docdateentered']!=NULL)
$tytul = $tytul."Data wprowadzenia: ".$r['docdateentered']."<br>";
if($r['docdate']!=NULL)
$tytul = $tytul."Data dokumentu: ".$r['docdate']."<br>";
if($r ['doccategory']!=NULL)
$tytul = $tytul."Kategoria: ".$app_list_strings['document_category_dom'][$r ['doccategory']]."<br>";
if($r['docwartosc']!=NULL)
$tytul = $tytul."Wartość: ".number_format($r['docwartosc'], 2, ",", ".")."<br>";
if($r['username']!=NULL && $r['userlastname']!=NULL)
$tytul = $tytul."Wprowadził: ".$r['username']." ".$r['userlastname']."<br>";
if($r['docdes']!=NULL)
$tytul = $tytul."Opis dokumentu: ".$r['docdes']."<br>";
// Wczytywanie raportów
$queryraport = "
SELECT
CONCAT(u.first_name, ' ', u.last_name) AS name,
d.accepted AS accepted,
d.accepted_description AS accepteddes
FROM
documents_user d
left join users u on u.id = d.user_id
WHERE
d.document_id = '".$wartosc."'";
$tmp = $db->query ( $queryraport );
if($tmp->num_rows == 0){
$opisy = "";
}else{
$opisy = "<table style='border: 1px solid black; padding: 3px;'>
<tr>
<th style='border: 1px solid black; padding: 3px;'>Użytkownik</th>
<th style='border: 1px solid black; padding: 3px;'>Status</th>
<th style='border: 1px solid black; padding: 3px;'>Opis</th>
</tr>";
while($tmp2 = $db->fetchByAssoc($tmp)){
$opisy = $opisy . "<tr>";
$opisy = $opisy ."<td style='border: 1px solid black; padding: 3px;'>".$tmp2['name']."</td>";
if($tmp2['accepted']==0){
$opisy = $opisy ."<td style='border: 1px solid black; padding: 3px;'>Oczekuje</td>";
}elseif($tmp2['accepted']==1){
$opisy = $opisy ."<td style='border: 1px solid black; padding: 3px;'>Zaakceptowano</td>";
}elseif($tmp2['accepted']==2){
$opisy = $opisy ."<td style='border: 1px solid black; padding: 3px;'>Odrzucono</td>";
}
$opisy = $opisy ."<td style='border: 1px solid black; padding: 3px;'>".str_replace("XVZC","<br>",$tmp2['accepteddes'])."</td>";
$opisy = $opisy ."</tr>";
};
$opisy = $opisy . "</table>";
}
}
$p2->WriteHTML($tytul . $opisy . "<hr>");
}
$i++;
}
var_dump($opisy);
echo $tytul . $opisy ;
//$p2->Output ();
?>

View File

@@ -0,0 +1,97 @@
<?php
include_once ("include/MPDF57/mpdf.php");
global $app_list_strings;
$p2=new mPDF('','A4', null, 'helvetica', 10,10,10,10,0,0);
$i=0;
$j=0;
$db = $GLOBALS ['db'];
$data = array ();
//var_dump($_POST);
foreach ($_POST as $klucz => $wartosc){
$pos = strpos($klucz, 'box_');
if($pos !== false){
if($j%4==0){
$p2->AddPage();
}
$j++;
$tytul = "";
$opis = "";
$query = "SELECT
d.document_date as docdate,
d.document_name as docname,
DATE_FORMAT(DATE(d.date_entered), '%d-%m-%Y') as docdateentered,
d.category_id as doccategory,
d.description as docdes,
ifnull(d.value,0) as docwartosc,
u.first_name as username,
u.last_name as userlastname
FROM
documents d
left join users u on u.id = d.created_by
left join accounts a on d.parent_id = a.id
WHERE
d.id = '".$wartosc. "' AND d.deleted = 0";
/**
* ************* GET DATA FROM DB********************
*/
$rows = $db->query ( $query );
while ( $r = $db->fetchByAssoc ( $rows ) ) {
if($r['docname']!=NULL)
$tytul = $tytul. "Nazwa dokumentu: ".$r['docname']."<br>";
if($r['docdateentered']!=NULL)
$tytul = $tytul."Data wprowadzenia: ".$r['docdateentered']."<br>";
if($r['docdate']!=NULL)
$tytul = $tytul."Data dokumentu: ".$r['docdate']."<br>";
if($r ['doccategory']!=NULL)
$tytul = $tytul."Kategoria: ".$app_list_strings['document_category_dom'][$r ['doccategory']]."<br>";
if($r['docwartosc']!=NULL)
$tytul = $tytul."Wartość: ".number_format($r['docwartosc'], 2, ",", ".")."<br>";
if($r['username']!=NULL && $r['userlastname']!=NULL)
$tytul = $tytul."Wprowadził: ".$r['username']." ".$r['userlastname']."<br>";
if($r['docdes']!=NULL)
$tytul = $tytul."Opis dokumentu: ".$r['docdes']."<br>";
// Wczytywanie raportów
$queryraport = "
SELECT
CONCAT(u.first_name, ' ', u.last_name) AS name,
d.accepted AS accepted,
d.accepted_description AS accepteddes
FROM
documents_user d
left join users u on u.id = d.user_id
WHERE
d.document_id = '".$wartosc."'";
$tmp = $db->query ( $queryraport );
if($tmp->num_rows == 0){
$opisy = "";
}else{
$opisy = "<table style='border: 1px solid black; padding: 3px;'>
<tr>
<th style='border: 1px solid black; padding: 3px;'>Użytkownik</th>
<th style='border: 1px solid black; padding: 3px;'>Status</th>
<th style='border: 1px solid black; padding: 3px;'>Opis</th>
</tr>";
while($tmp2 = $db->fetchByAssoc($tmp)){
$opisy = $opisy . "<tr>";
$opisy = $opisy ."<td style='border: 1px solid black; padding: 3px;'>".$tmp2['name']."</td>";
if($tmp2['accepted']==0){
$opisy = $opisy ."<td style='border: 1px solid black; padding: 3px;'>Oczekuje</td>";
}elseif($tmp2['accepted']==1){
$opisy = $opisy ."<td style='border: 1px solid black; padding: 3px;'>Zaakceptowano</td>";
}elseif($tmp2['accepted']==2){
$opisy = $opisy ."<td style='border: 1px solid black; padding: 3px;'>Odrzucono</td>";
}
$opisy = $opisy ."<td style='border: 1px solid black; padding: 3px;'>".str_replace("XVZC","<br>",$tmp2['accepteddes'])."</td>";
$opisy = $opisy ."</tr>";
};
$opisy = $opisy . "</table>";
}
}
$p2->WriteHTML($tytul . $opisy . "<hr>");
}
$i++;
}
$p2->Output ();
?>

304
modules/EcmReports/tt.php Normal file
View File

@@ -0,0 +1,304 @@
<?php
global $mod_strings, $app_list_strings, $db;
if(!$_REQUEST['date_from'])
$date_from = date("01.m.Y");
else
$date_from = $_REQUEST["date_from"];
if(!$_REQUEST['date_to'])
$date_to = date("d.m.Y");
else
$date_to = $_REQUEST["date_to"];
if(!class_exists('EcmInvoiceOut')){
include_once('modules/EcmInvoiceouts/EcmInvoiceout.php');
};
if(!class_exists('EcmReceipts')){
include_once('modules/EcmReceipts/EcmReceipt.php');
};
//get trader list
$query_trader = "select ecminvoiceouts.assigned_user_id AS user_id , concat(users.first_name, ' ', users.last_name) AS user_name FROM ecminvoiceouts, users WHERE ecminvoiceouts.deleted = 0 and ecminvoiceouts.canceled = 0 AND users.id = ecminvoiceouts.assigned_user_id group by user_id ORDER BY user_name";
$trader_result = $db->query($query_trader);
$trader_array = array(""=>"");
while($row = $db->fetchByAssoc($trader_result)){
$trader_array[$row['user_id']] = $row['user_name'];
}
//Get Stock List
$query_stock = "Select id, name from ecmstocks where deleted=0";
$stock_result = $db->query($query_stock);
$stock_array = array(""=>"");
while($row = $db->fetchByAssoc($stock_result)){
$stock_array[$row['id']] = $row['name'];
}
$query_stock = "Select account_type from accounts where deleted=0 group by account_type";
$stock_result = $db->query($query_stock);
$account_array = array(""=>"");
while($row = $db->fetchByAssoc($stock_result)){
$account_array[$row['account_type']] =$app_list_strings['account_type_dom'][$row['account_type']];
}
//Szykowanie zapytań
//Zakres dat
$whereInvoice['ecminvoiceouts'][] = 'register_date>="' . getFormatedDateForDB($date_from) . '"';
$whereInvoice['ecminvoiceouts'][] = 'register_date<="' . getFormatedDateForDB($date_to) . '"';
$whereRecipe['ecmrecipes'][] = 'register_date>="' . getFormatedDateForDB($date_from) . '"';
$whereRecipe['ecmrecipes'][] = 'register_date<="' . getFormatedDateForDB($date_to) . '"';
//Handlowiec
if($_REQUEST['trader'] != ""){
$whereInvoice['ecminvoiceouts'][] = 'assigned_user_id="' . $_REQUEST['trader'] . '"';
$whereRecipe['ecmrecipes'][] = 'assigned_user_id="' . $_REQUEST['trader'] . '"';
}
//Kontrahent
if($_REQUEST['account_id'] != ""){
$whereInvoice['ecminvoiceouts'][] = 'parent_id="' . $_REQUEST['account_id'] . '"';
$whereRecipe['ecmrecipes'][] = 'parent_id="' . $_REQUEST['account_id'] . '"';
}
//Magazyn
$stocks = $_REQUEST['stocks'];
if(count($stocks)>0){
if(in_array("",$stocks)){
$indeks = array_search("",$stocks);
unset($stocks[$indeks]);
}
if(count($stocks)>0){
$stocksList = array();
$value = array_values ( $stocks );
$whereInvoice['ecminvoiceouts'][] = 'stock_id IN ("' . implode('","',$value) . '")';
$whereRecipe['ecmrecipes'][] = 'stock_id IN ("' . implode('","',$value) . '")';
}
}
$accounts = $_REQUEST['account_type'];
if(count($accounts)>0){
if(in_array("",$accounts)){
$indeks = array_search("",$accounts);
unset($accounts[$indeks]);
}
if(count($accounts)>0){
$accountsList = array();
$value = array_values ( $accounts );
$whereInvoice['accounts'][] = 'accounts.account_type IN ("' . implode('","',$value) . '")';
}
}
//Grupa
$product_group = $_REQUEST['product_group'];
if(count($product_group)>0){
if(in_array("",$product_group)){
$indeks = array_search("",$product_group);
unset($product_group[$indeks]);
}
if(count($product_group)>0){
$product_group_list = array();
$value = array_values ( $product_group );
$whereInvoice['ecmproducts'][] = 'ks_group IN ("' . implode('","',$value) . '")';
$whereRecipe['ecmproducts'][] = 'ks_group IN ("' . implode('","',$value) . '")';
}
}
//Typ dokumentu
$document_sales_type = $_REQUEST['document_sales_type'];
if(count($document_sales_type)>0){
if(in_array("",$document_sales_type)){
$indeks = array_search("",$document_sales_type);
unset($document_sales_type[$indeks]);
}
if(count($document_sales_type)>0){
$tmpInvoiceType = array();
$tmpRecipeType = array();
$receiptDo = false;
$invoceDo = true;
foreach($document_sales_type as $key => $value){
switch($value){
case 'invoice':
$tmpInvoiceType[] = 'normal';
$invoceDo = true;
break;
case 'invoice_correct':
$invoceDo = true;
$tmpInvoiceType[] = 'correct';
break;
case 'recipe':
$receiptDo = true;
$tmpRecipeType[] = 'normal';
break;
case 'recipe_correct':
$receiptDo = true;
$tmpRecipeType[] = 'correct';
break;
}
}
if(count($tmpInvoiceType)>0){
$value = array_values ( $tmpInvoiceType );
$whereInvoice['ecminvoiceouts'][] = 'type IN ("' . implode('","',$value) . '")';
$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
}
if(count($tmpRecipeType)>0){
$value = array_values ( $tmpRecipeType );
$whereRecipe['ecmrecipes'][] = 'type IN ("' . implode('","',$value) . '")';
$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}
}else{
$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}
}else{
$dataInvoice = EcmInvoiceOut::getInvoiceList($whereInvoice);
$dataRecipe = EcmReceipt::getReceiptsList($whereRecipe);
}
// Przetwarzanie danych
$data = array();
$total=0;
$total2=0;
$total4=0;
foreach($dataInvoice as $indeks => $invoice){
$total2+=$invoice['total_netto'];
$total3=0;
foreach($invoice['position_list'] as $position => $item){
$data[$item['product_id']]['code'] = '<a target="_blank" href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '">' . $item['position_code'] . '</a>';
$data[$item['product_id']]['name'] = '<a target="_blank" href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '">' . $item['position_code'] . ' ' . $item['position_name'] . '</a>';
$data[$item['product_id']]['total_netto'] += $item['position_total_netto'];
$data[$item['product_id']]['price_purchase'] += $item['position_total_price_purchase'];
$data[$item['product_id']]['quantity'] += $item['position_quantity'];
$data[$item['product_id']]['jm_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$item['position_unit_id']];
$data[$item['product_id']]['jm_name'] = $item['position_unit_name'];
if($_REQUEST['to_xls']=='1'){
$data[$item['product_id']]['name'] =$item['position_code'] . ' ' . $item['position_name'];
}
$total+=round($item['position_total_netto'],2);
$total3+=$item['position_total_netto'];
}
echo $invoice['total_netto'].' '.$total3.' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; '.$total.' '.$total2.' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; '.$invoice['id'].'<br>';
if(round($total3,2)!=round($invoice['total_netto'],2)){
echo 'tu!';
}
}
echo $total.' '.$total2;
foreach($dataRecipe as $indeks => $invoice){
foreach($invoice['position_list'] as $position => $item){
$data[$item['product_id']]['name'] = '<a target="_blank" href="index.php?module=EcmProducts&return_module=EcmProducts&action=DetailView&parentTab=Produkty&record=' . $item['product_id'] . '">'. $item['position_code'] . ' ' . $item['position_name'] . '</a>';
$data[$item['product_id']]['total_netto'] += $item['position_total_netto'];
$data[$item['product_id']]['price_purchase'] += $item['position_total_price_purchase'];
$data[$item['product_id']]['quantity'] += $item['position_quantity'];
$data[$item['product_id']]['jm_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$item['position_unit_id']];
$data[$item['product_id']]['jm_name'] = $item['position_unit_name'];
if($_REQUEST['to_xls']=='1'){
$data[$item['product_id']]['name'] =$item['position_code'] . ' ' . $item['position_name'];
}
$total+=$item['position_total_netto'];
$total2+=$item['position_total_price_purchase'];
}
}
//var_dump($data);
//
//Szykowanie wyświetlania
$smarty = new Sugar_Smarty ();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("APP_LIST_STRINGS", $app_list_strings);
$smarty->assign("DATA", $data);
$smarty->assign("TRADERS_LIST", $trader_array);
$smarty->assign("STOCK_LIST", $stock_array);
$smarty->assign("ACCOUNT_LIST", $account_array);
$smarty->assign("TOTAL", $total);
$smarty->assign("TOTAL2", $total2);
//Ustawiamy przeslane dane
//$date_from = $GLOBALS['timedate']->to_display_date($date_from);
//$date_to = $GLOBALS['timedate']->to_display_date($date_to);
$smarty->assign("date_from_value", $date_from );
$smarty->assign("date_to_value", $date_to );
$smarty->assign("TRADER_SELECTED", $_REQUEST['trader']);
$smarty->assign("ACCOUNT_ID", $_REQUEST['account_id']);
$smarty->assign("ACCOUNT_NAME", $_REQUEST['account_name']);
if($_REQUEST['to_pdf']!='1'){
$smarty->assign("STOCK_SELECTED", $_REQUEST['stocks']);
$smarty->assign("ACCOUNT_SELECTED", $_REQUEST['account_type']);
$smarty->assign("PRODUCT_GROUP_SELECTED", $_REQUEST['product_group']);
$smarty->assign("DOCUMENT_SALES_SELECTED", $_REQUEST['document_sales_type']);
echo $smarty->display('modules/EcmReports/tpls/ReportSalesByProduct.tpl');
}else{
if($_REQUEST['to_xls']=='1'){
$header=array();
$header[]='nazwa';
$header[]='ilość';
$header[]='jm';
$header[]='sprzedaż netto';
$header[]='koszt zakupu';
$header[]='dochód';
$filename='modules/Home/Files/raport_sprzedazy_ilosciowy_'.date('d_m_Y').'.csv';
$fp=fopen($filename,'w');
foreach ($header as $k=>$v){
$header[$k]=iconv('UTF-8','windows-1250',$header[$k]);
}
fwrite($fp, implode(";",$header).PHP_EOL);
foreach ($data as $key=>$val){
$line=array();
$line[]=preg_replace("/[^A-ZłŁąĄęĘżŻ,:.źŹ%ćĆńŃśŚóÓa-z0-9\-\/]/",' ',preg_replace("/\r\n|\r|\n/",' ',html_entity_decode($val['name'])));
$line[]=str_replace(".",",",$val['quantity']);
$line[]=$val['jm_name'];
$line[]=str_replace(".",",",$val['total_netto']);
$line[]=str_replace(".",",",$val['price_purchase']);
$line[]=str_replace(".",",",$val['total_netto']-$val['price_purchase']);
foreach ($line as $k=>$v){
$line[$k]=iconv('UTF-8','windows-1250',$line[$k]);;
}
fwrite($fp, implode(";",$line).PHP_EOL);
}
print $filename;
} else {
include_once ("include/MPDF57/mpdf.php");
include_once ("modules/EcmSysInfos/EcmSysInfo.php");
$smarty->assign("STOCK_SELECTED", $stocks);
$smarty->assign("PRODUCT_GROUP_SELECTED", $product_group);
$smarty->assign("DOCUMENT_SALES_SELECTED", $document_sales_type);
$EcmSysInfo = new EcmSysInfo();
$smarty->assign("EcmSysInfo", $EcmSysInfo);
//echo $EcmSysInfo->getName();
$content = $smarty->fetch('modules/EcmReports/tpls/ReportSalesByProductPDF.tpl');
$mPDF = new mPDF ( '', 'A4', null, 'helvetica', 10, 10, 10, 10, 5, 5 );
$mPDF->mirrorMargins = 1;
$mPDF->WriteHTML($content);
$dir = 'upload/' . $EcmSysInfo->getDatabaseName() . '/pdf/EcmReports/';
if(!is_dir($dir)){
mkdir($dir, '755', true);
}
$file_name = $dir . str_replace(".","",$date_from) . "_" . str_replace(".","",$date_to) ."_Raport_Sprzedazy_Ilosciowy.pdf";
$mPDF->Output( $file_name, "F");
print $file_name;
}
}
function getFormatedDateForDB($data){
if(strpos($data,".")>0){
$split = explode (".",$data);
$return_data = $split[2] . "-" . $split[1] . "-" .$split['0'];
}
return $return_data;
}

88
modules/EcmReports/vardefs.php Executable file
View File

@@ -0,0 +1,88 @@
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
$dictionary['EcmReport']=array(
'table'=>'ecmreports',
'audited'=>false,
'comment'=>'EcmReports',
'duplicate_merge'=>true ,
'unified_search'=>true,
'fields'=>array(
'name'=>array(
'name'=>'name',
'vname'=>'LBL_NAME',
'type'=>'varchar',
'len'=>'255',
),
),
'indices'=>array(
array('name'=>'idx_ecmreport_id_del','type'=>'index','fields'=>array('id','deleted')),
array('name'=>'idx_ecmreport_assigned_del','type'=>'index','fields'=>array( 'deleted', 'assigned_user_id')),
),
'relationships'=>array(
'ecmreports_assigned_user'=>array(
'lhs_module'=>'Users',
'lhs_table'=>'users',
'lhs_key'=>'id',
'rhs_module'=>'EcmReports',
'rhs_table'=>'ecmreports',
'rhs_key'=>'assigned_user_id',
'relationship_type'=>'one-to-many'
),
'ecmreports_modified_user'=>array(
'lhs_module'=>'Users',
'lhs_table'=>'users',
'lhs_key'=>'id',
'rhs_module'=>'EcmReports',
'rhs_table'=>'ecmreports',
'rhs_key'=>'modified_user_id',
'relationship_type'=>'one-to-many'
),
'ecmreports_created_by'=>array(
'lhs_module'=>'Users',
'lhs_table'=>'users',
'lhs_key'=>'id',
'rhs_module'=>'EcmReports',
'rhs_table'=>'ecmreports',
'rhs_key'=>'created_by',
'relationship_type'=>'one-to-many'
)
),
'optimistic_locking'=>true,
);
require_once('include/SugarObjects/VardefManager.php');
VardefManager::createVardef('EcmReports','EcmReport', array('default','assignable'));
?>