Files
crm.e5.pl/modules/EcmStockDocIns/EcmStockDocIn.php

2049 lines
68 KiB
PHP
Raw Normal View History

2024-04-27 09:23:34 +02:00
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*****************************************************************************
* The contents of this file are subject to the RECIPROCAL PUBLIC LICENSE
* Version 1.1 ("License"); You may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/rpl.php. Software distributed under the
* License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
* either express or implied.
*
* You may:
* a) Use and distribute this code exactly as you received without payment or
* a royalty or other fee.
* b) Create extensions for this code, provided that you make the extensions
* publicly available and document your modifications clearly.
* c) Charge for a fee for warranty or support or for accepting liability
* obligations for your customers.
*
* You may NOT:
* a) Charge for the use of the original code or extensions, including in
* electronic distribution models, such as ASP (Application Service
* Provider).
* b) Charge for the original source code or your extensions other than a
* nominal fee to cover distribution costs where such distribution
* involves PHYSICAL media.
* c) Modify or delete any pre-existing copyright notices, change notices,
* or License text in the Licensed Software
* d) Assert any patent claims against the Licensor or Contributors, or
* which would in any way restrict the ability of any third party to use the
* Licensed Software.
*
* You must:
* a) Document any modifications you make to this code including the nature of
* the change, the authors of the change, and the date of the change.
* b) Make the source code for any extensions you deploy available via an
* Electronic Distribution Mechanism such as FTP or HTTP download.
* c) Notify the licensor of the availability of source code to your extensions
* and include instructions on how to acquire the source code and updates.
* d) Grant Licensor a world-wide, non-exclusive, royalty-free license to use,
* reproduce, perform, modify, sublicense, and distribute your extensions.
*
* The Original Code is: CommuniCore
* Olavo Farias
* 2006-04-7 olavo.farias@gmail.com
*
* The Initial Developer of the Original Code is CommuniCore.
* Portions created by CommuniCore are Copyright (C) 2005 CommuniCore Ltda
* All Rights Reserved.
********************************************************************************/
require_once('data/SugarBean.php');
require_once('include/utils.php');
class EcmStockDocIn extends SugarBean {
var $field_name_map = array();
// STANDARD FIELDS
var $id;
var $date_entered;
var $date_modified;
var $modified_user_id;
var $assigned_user_id;
var $name;
var $description;
//TABLE COLUMNS
var $currency_id;
var $number;
var $document_no;
var $parent_name;
var $parent_id;
var $type;
var $status;
var $register_date;
var $parent_address_street;
var $parent_address_city;
var $parent_address_postalcode;
var $parent_address_country;
var $subtotal;
var $total;
var $discount;
var $to_vatid;
var $ecmlanguage;
var $to_is_vat_free;
var $header_text;
var $footer_text;
var $ads_text;
var $template_id;
var $template_name;
var $email_id;
var $parent_name_copy;
var $parent_contact_name;
var $parent_contact_title;
var $ecmpaymentcondition_id;
var $ecmpaymentcondition_name;
var $ecmpaymentcondition_text;
var $ecmdeliverycondition_id;
var $ecmdeliverycondition_name;
var $ecmdeliverycondition_text;
var $validtill_date;
var $order_origin;
var $contact_id;
var $contact_name;
var $show_images_on_offers;
var $stock_id;
var $stock_name;
var $po_id;
var $pdflanguages;
var $currency_symbol;
var $template;
var $pdf;
var $position_list;
var $parser;
var $account;
var $contact;
var $ecmvendor;
var $user;
var $mfp;
var $correct_id;
var $correct_name;
2025-07-06 08:39:16 +00:00
var $kind;
2024-04-27 09:23:34 +02:00
// RELATED FIELDS
var $created_by;
var $created_by_name;
var $modified_by_name;
var $assigned_user_name;
// SUBPANELS RELATED
// MODULE OBJECT DETAILS
var $module_dir = "EcmStockDocIns";
var $table_name = "ecmstockdocins";
var $object_name = "EcmStockDocIn";
//RELATED TABLE NAMES
// USED TO RETRIEVE RELATED FIELDS FROM FORM POSTS.
var $additional_column_fields = Array (
'assigned_user_name',
'assigned_user_id',
'modified_user_id',
'created_by',
);
//RELATIONSHIP FIELDS
var $relationship_fields = Array (
'note_id' => 'notes',
'email_id' => 'emails'
// 'account_id' => 'account',
// 'contact_id' => 'contact',
);
function EcmStockDocIn() {
parent::SugarBean();
$this->setupCustomFields('EcmStockDocIns');
foreach($this->field_defs as $field) {
$this->field_name_map[$field['name']] = $field;
}
}
var $new_schema = true;
function get_summary_text(){
return "$this->name";
}
function create_list_query($order_by, $where, $show_deleted = 0) {
// Fill in the assigned_user_name
$custom_join = $this->custom_fields->getJOIN();
$query = "SELECT ";
$query .= "ecmstockdocins.*
,users.user_name as assigned_user_name";
if($custom_join) {
$query .= $custom_join['select'];
}
$query .= " FROM ecmstockdocins
LEFT JOIN users
ON ecmstockdocins.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 ";
} else if($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";
}
else if($order_by != "")
$query .= " ORDER BY $order_by";
else
$query .= " ORDER BY ecmstockdocins.name";
return $query;
}
function create_export_query($order_by, $where) {
$custom_join = $this->custom_fields->getJOIN();
$query = "SELECT
ecmstockdocins.*,
users.user_name assigned_user_name";
if($custom_join) {
$query .= $custom_join['select'];
}
$query .= " FROM ecmstockdocins ";
$query .= " LEFT JOIN users
ON ecmstockdocins.assigned_user_id=users.id";
if($custom_join) {
$query .= $custom_join['join'];
}
$query .= "";
$where_auto = " ecmstockdocins.deleted=0
";
if($where != "")
$query .= " where $where AND ".$where_auto;
else
$query .= " where ".$where_auto;
if($order_by != "")
$query .= " ORDER BY $order_by";
else
$query .= " ORDER BY ecmstockdocins.name";
return $query;
}
function fill_in_additional_list_fields(){
}
function fill_in_additional_detail_fields(){
//FILL IN THE ASSIGNED_USER_NAME
$this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
$this->created_by_name = get_assigned_user_name($this->created_by);
$this->modified_by_name = get_assigned_user_name($this->modified_user_id);
$result = $this->db->query("SELECT status, parent_id, contact_id, template_id, assigned_user_id FROM ecmstockdocins WHERE id='$this->id'");
if($result) $row = $this->db->fetchByAssoc($result);
$this->status = $row['status'];
$this->parent_id = $row['parent_id'];
$this->contact_id = $row['contact_id'];
$this->template_id = $row['template_id'];
$this->assigned_user_id = $row['assigned_user_id'];
/*
$query = "select `number`, `template_id` from `ecmstockdocins` where `id`='$this->id' limit 1";
$r = $this->db->query($query);
if($r) {
$r = $this->db->fetchByAssoc($r);
$this->template_id = $r['template_id'];
$this->number = $r['number'];
$this->setTemplate();
$this->document_no = $this->formatNumber();
}
*/
}
function get_list_view_data(){
global $current_language;
$this->fill_in_additional_detail_fields();
$app_list_strings = return_app_list_strings_language($current_language);
$mod_strings = return_module_language($current_language, 'EcmStockDocIns');
$the_array = parent::get_list_view_data();
// THE NEW LISTVIEW CODE ONLY FETCHES COLUMNS THAT WE'RE DISPLAYING AND NOT ALL
// THE COLUMNS SO WE NEED THESE CHECKS.
$subpanel_pr_id=$this->ecmproduct_id;
$this->retrieve($this->id);
$the_array['NAME'] = (($this->name == "") ? "<em>blank</em>" : $this->name);
$the_array['PARENT_NAME'] = '<a class="listViewTdLinkS1" href="index.php?module=Accounts&action=DetailView&record='.$this->parent_id.'">'.$this->parent_name.'</a>';
// $the_array['NUMBER'] = $this->document_no;
$the_array['TOTAL'] = $this->getTotal();
$the_array['PDF_URL'] = '';
if($_REQUEST['record'] && $_REQUEST['module']=="EcmProducts"){
$rp=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select p.price as price,p.quantity as quantity from
ecmstockdocinitems as p
where p.ecmproduct_id='".$_REQUEST['record']."'
and p.ecmstockdocin_id='".$this->id."'
and p.deleted='0'"));
$the_array['PRICE']=number_format($rp['price'],2,",",".");
$the_array['QUANTITY']=number_format($rp['quantity'],2,",",".");
$the_array['WARTOSC']=number_format(($rp['quantity']*$rp['price']),2,",",".");
}
if($subpanel_pr_id!=''){
//add subpanel data
$tmp=$this->getPriceFromDocument($subpanel_pr_id);
$the_array ['QUANTITY'] = format_number ( $tmp['quantity'] );
$the_array ['PRICE_NETTO'] = format_number ( $tmp['price'] );
$the_array ['TOTAL_NETTO'] = format_number ( $tmp['total'] );
}
$the_array['OPTIONS'] = $this->ListIconsView();
$the_array['STATUS'] = EcmStockDocIn::CreateImgStatus($this->id,$this->status);
if($this->correct_id)$the_array['CORRECT']=translate('LBL_TYPE_CORRECT','EcmStockDocIns');
else $the_array['CORRECT']=translate('LBL_TYPE_NORMAL','EcmStockDocIns');
return $the_array;
}
function getPriceFromDocument($product){
$zap=$this->db->query("select quantity,price,total from ecmstockdocinitems where id='".$product."'");
$dane=$this->db->fetchByAssoc($zap);
return $dane;
}
function getStatusMenuInfo($inJSON = true) {
global $app_list_strings;
$arr = array();
/*foreach($app_list_strings['ecmstockdocins_status_dom'] as $key => $value) {
$arr[$key] = array (
'enabled' => '<div><img src="modules/EcmStockDocIns/images/'.$key.'.gif" />'.$value.'</div>',
'disabled' => '<div><img src="modules/EcmStockDocIns/images/'.$key.'.gif" />'.$value.'</div>',
);
}*/
$json = getJSONobj();
if($inJSON)
return str_replace('&quot;', '\"', $json->encode($arr));
else
return $arr;
}
function create_new_list_query($order_by, $where,$filter=array(),$params=array(), $show_deleted = 0,$join_type='', $return_array = false,$parentbean, $singleSelect = false) {
echo '<script type="text/javascript" src="include/ECM/EcmPreviewPDF/EcmPreviewPDF.js"></script>';
echo '<script type="text/javascript" src="modules/EcmStockDocIns/ListView.js"></script>';
echo '<link rel="stylesheet" type="text/css" href="modules/EcmStockDocIns/ListView.css" />';
echo '<script language="javascript"> var EcmStockDocInsStatusMenu = '.$this->getStatusMenuInfo().'; </script>';
return parent::create_new_list_query($order_by, $where, $filter, $params, $show_deleted, $join_type, $return_array, $parentbean, $singleSelect);
}
static function CreateImgStatus($id, $status) {
global $app_list_strings;
// return '<span id="statusListEcmStockDocIn_'.$id.'" onClick="list_showStatusMenu(\''.$id.'\');"><img src="modules/EcmStockDocIns/images/'.$status.'.gif" title="'.$app_list_strings['ecmstockdocins_status_dom'][$status].'" /></span>';
// return '<span id="statusListEcmStockDocIn_'.$id.'" onClick="list_showStatusMenu(\''.$id.'\');"><img src="modules/EcmStockDocIns/images/'.$status.'.gif" title="'.$app_list_strings['ecmstockdocins_status_dom'][$status].'" /></span>';
return '<span id="statusListEcmStockDocIn_'.$id.'" style="display:inline;"><img src="modules/EcmInvoiceOuts/images/'.$status.'.gif" title="'.$app_list_strings['ecmstockdocins_status_dom'][$status].'" /></span>';
}
function generateOptions($icon,$module='',$action='') {
global $app_strings,$mod_strings;
$tmp = '';
if($icon == "confirming") {
if($this->ACLAccess('import')) {
$tmp .= '<span id="confirmingListEcmStockDocIn_'.$this->id.'" style="display:'.($this->ACLAccess('confirming')?'':'none').';"><img border="0" src="modules/EcmStockDocIns/images/accept_enabled.gif" title="'.translate('LBL_LIST_ACCEPT','EcmStockDocIns').'" onClick="list_setQuoteStatus(\''.$this->id.'\',\'s30\');" style="cursor:pointer;" />&nbsp;';
$tmp .= '<img border="0" src="modules/EcmStockDocIns/images/reject_enabled.gif" title="'.translate('LBL_LIST_REJECT','EcmStockDocIns').'" onClick="list_setQuoteStatus(\''.$this->id.'\',\'s40\');" style="cursor:pointer;" />&nbsp;&nbsp;&nbsp;|</span>';
}
} else
if($icon == 'send_to_confirm') {
//send to confirm
if($this->ACLAccess('send_to_confirm') && $this->status=="accepted")
$tmp = '<img border="0" id="send_to_confirm_'.$this->id.'" src="modules/EcmStockDocIns/images/sendtoconfirm_enabled.gif" title="'.translate('LBL_LIST_SEND_TO_CONFIRM','EcmStockDocIns').'" style="cursor:pointer;" onClick="list_setQuoteStatus(\''.$this->id.'\',\'s20\');" />';
else
$tmp = '<img border="0" id="send_to_confirm_'.$this->id.'" src="modules/EcmStockDocIns/images/sendtoconfirm_disabled.gif" title="'.translate('LBL_LIST_SEND_TO_CONFIRM','EcmStockDocIns').'" style="cursor:pointer;" />';
} else
if($icon == "convert_to_invoice") {
//convert to invoice
if($this->ACLAccess('pzdocument_to_invoice') && $this->status=="accepted")
$tmp = '<img border="0" id="convert_to_invoice_'.$this->id.'" src="modules/EcmStockDocIns/images/convert_enabled.gif" title="'.translate('LBL_LIST_TO_INVOICE','EcmStockDocIns').'" onClick="javascript:window.location=\'index.php?module=EcmInvoiceOuts&action=EditView&out_id='.$this->id.'&out_module=EcmStockDocIns&return_module=EcmStockDocIns&return_action=index\';" style="cursor:pointer;" />';
else
$tmp = '<img border="0" id="convert_to_invoice_'.$this->id.'" src="modules/EcmStockDocIns/images/convert_disabled.gif" title="'.translate('LBL_LIST_TO_INVOICE','EcmStockDocIns').'" style="cursor:pointer;" />';
} else
if($icon == 'convert_to_sale') {
if($this->ACLAccess('pzdocument_to_sale') && $this->status=="accepted")
$tmp = '<img border="0" id="convert_to_sale_'.$this->id.'" src="modules/EcmStockDocIns/images/create_sales_enabled.gif" title="'.translate('LBL_LIST_TO_SALE','EcmStockDocIns').'" onClick="javascript:window.location=\'index.php?module=EcmSales&action=EditView&out_id='.$this->id.'&out_module=EcmStockDocIns&return_module=EcmStockDocIns&return_action=index\';" style="cursor:pointer;" />';
else
$tmp = '<img border="0" id="convert_to_sale_'.$this->id.'" src="modules/EcmStockDocIns/images/create_sales_disabled.gif" title="'.translate('LBL_LIST_TO_SALE','EcmStockDocIns').'" style="cursor:pointer;" />';
} else
if($icon == 'pdf') {
//pdf
if($this->ACLAccess('pdf_toolbar')) {
$tmp = '<img border="0" src="modules/EcmStockDocIns/images/pdf.gif" title="'.translate('LBL_LIST_PREVIEW_PDF','EcmStockDocIns').'" onClick="EcmPreviewPDF(\'index.php?module=EcmStockDocIns&action=previewPDF&method=I&record='.$this->id.'&to_pdf=1\',{zoom:75,toolbar:1});" style="cursor:pointer" />';
} else {
$tmp = '<img border="0" src="modules/EcmStockDocIns/images/pdf.gif" title="'.translate('LBL_LIST_PREVIEW_PDF','EcmStockDocIns').'" onClick="EcmPreviewPDF(\'index.php?module=EcmStockDocIns&action=previewPDF&method=I&record='.$this->id.'&to_pdf=1\',{zoom:75,toolbar:0});" style="cursor:pointer" />';
}
} else
if($icon == 'download') {
//download
if($this->ACLAccess('pdf_toolbar')) {
$tmp = '<img border="0" src="modules/EcmStockDocIns/images/download_enabled.gif" title="'.translate('LBL_LIST_DOWNLOAD_PDF','EcmStockDocIns').'" onClick="window.location=\'index.php?module=EcmStockDocIns&action=previewPDF&method=D&record='.$this->id.'&to_pdf=1\';" style="cursor:pointer"/>';
} else {
$tmp = '<img border="0" src="modules/EcmStockDocIns/images/download_disabled.gif" title="'.translate('LBL_LIST_DOWNLOAD_PDF','EcmStockDocIns').'" style="cursor:pointer;" />';
}
} else
if($icon == 'duplicate') {
//duplicate
$tmp = '<a href="index.php?module=EcmStockDocIns&action=EditView&record='.$this->id.'&isDuplicate=true"><img border="0" src="modules/EcmStockDocIns/images/duplicate.jpg" title="'.translate('LBL_LIST_DUPLICATE','EcmStockDocIns').'" /></a>';
} else
if($icon == 'edit') {
//edit
if($this->ACLAccess('edit') && $this->status=="registered")
$tmp = '<img border="0" id="edit_'.$this->id.'" src="modules/EcmStockDocIns/images/edit_inline_enabled.gif" title="'.$app_strings['LBL_EDIT_BUTTON'].'" onClick="javascript:window.location=\'index.php?module=EcmStockDocIns&action=EditView&record='.$this->id.'&return_module='.$_REQUEST['module'].'&return_action='.$_REQUEST['action'].'&return_id='.$_REQUEST['record'].'\';" style="cursor:pointer;" />';
else
$tmp = '<img border="0" id="edit_'.$this->id.'" src="modules/EcmStockDocIns/images/edit_inline_disabled.gif" title="'.$app_strings['LBL_EDIT_BUTTON'].'" style="cursor:pointer;" />';
} else
if($icon == 'send_email') {
//send_email
if($this->ACLAccess('send_email') && $this->status=="accepted")
$tmp = '<img border="0" id="sendemail_'.$this->id.'" src="modules/EcmStockDocIns/images/send_email_enabled.gif" title="'.translate('LBL_SENDEMAIL_BUTTON','EcmStockDocIns').'" onClick="'.$this->createSendEmailLink().'" style="cursor:pointer;" />';
else
$tmp = '<img border="0" id="sendemail_'.$this->id.'" src="modules/EcmStockDocIns/images/send_email_disabled.gif" title="'.translate('LBL_SENDEMAIL_BUTTON','EcmStockDocIns').'" style="cursor:pointer;" />';
} else
if($icon == 'correct') {
$cnt=mysql_num_rows($GLOBALS['db']->query("select id from ecmstockdocins where correct_id='".$this->id."'"));
$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select type from ecmstockdocins where id='".$this->id."'"));
if($r['type']!=1 && $cnt==0 && $this->status=="accepted"){
$tmp = '<img border="0" id="correct_'.$this->id.'" src="modules/EcmInvoiceOuts/images/correct.jpg" onClick="if(confirm(\''.translate('LBL_CORRECT_CONFIRMATION','EcmStockDocIns').'\')){location.href=\'index.php?module=EcmStockDocIns&action=SaveCorrect&correct_id='.$this->id.'\';}" style="cursor:pointer;" title="'.$mod_strings['LBL_CORRECT_TITLE'].'" />';
}
else{
$tmp='<img border="0" src="modules/EcmInvoiceOuts/images/correct_disabled.jpg" style="cursor: pointer;" title="'.$mod_strings['LBL_CORRECT_TITLE'].'" style="cursor:pointer;" />';
}
}
return $tmp;
}
function getEmailTemplateId($what) {
$GLOBALS['db'] = new MysqlManager();
$GLOBALS['db']->connect();
$query = "SELECT `id` FROM `email_templates` WHERE `name` LIKE 'QuoteTemplate".$what."%' LIMIT 1";
$result = $GLOBALS['db']->query($query);
if(is_resource($result)) {
$row = $GLOBALS['db']->fetchByAssoc($result);
if(is_array($row)) {
return $row['id'];
}
}
return '';
}
function createSendEmailLink() {
require_once('modules/EcmEmails/EcmEmailsDataCreator.php');
$eedc = new EcmEmailsDataCreator();
if(isset($this->contact_id) && $this->contact_id != '') {
$eedc->addToModule('Contacts', $this->contact_id);
$eedc->setEmailTemplateId($this->getEmailTemplateId("Contact"));
}
else {
$eedc->addToModule('Accounts', $this->parent_id);
$eedc->setEmailTemplateId($this->getEmailTemplateId("Account"));
}
global $current_user;
$eedc->setFromModule('Users', $current_user->id);
$eedc->addAssigned('Accounts', $this->parent_id);
$eedc->addAssigned('Contacts', $this->contact_id);
$eedc->addAssigned('EcmDocumentTemplates', $this->template_id);
$eedc->addAssigned('Users', '');
$eedc->addAssigned($this->module_dir, $this->id);
$eedc->addAttachmentBySugar($this->createPdfFileName(), $this->module_dir, "previewPDF", array("record" => $this->id, "method" => "S", "to_pdf" => "1"), array("method" => "I"));
return $eedc->createJavaScriptAction();
}
function ListIconsView() {
if(isset($_REQUEST['module']) && $_REQUEST['module'] != '') {
$module = $_REQUEST['module'];
$action = $_REQUEST['action'];
$glue = "&nbsp;";
$viewIcons = array();
if($module == $this->module_dir){ //This module, action ListView or index
$viewIcons = array( 'send_email', 'download', 'pdf', 'duplicate', 'correct', 'edit' , 'view');
}
else
if($module == "Home") { //This is for a Home module for Dashlets
$glue = "&nbsp;";
$viewIcons = array( 'send_email', 'download', 'pdf', 'duplicate', 'correct', 'edit' , 'view');
} else { //this is for subpanels, popups
$glue = "&nbsp;";
$viewIcons = array( 'send_email', 'download', 'pdf', 'duplicate', 'correct', 'edit' , 'view');
}
$arr = array();
foreach($viewIcons as $value) {
$tmp = $this->generateOptions($value);
if($tmp != '') $arr[] = $tmp;
}
return '<span id="optionsListEcmStockDocIn_'.$this->id.'">'.implode($glue,$arr).'<script language="javascript">var ListQuotesModule="'.$module.'"; var ListQuotesAction="'.$action.'";</script></span>';
}
return '';
}
function createPdfFileName($format=true) {
global $mod_strings;
$arr1 = Array('\\', '/', ':', '*', '?' , '"', '<', '>', '|', ' ');
$arr2 = Array('', '', '', '', '', '\'', '[', ']', '', '_');
$tmp = $this->document_no;
if($format)
$tmp = str_replace($arr1, $arr2, $mod_strings['LBL_PDF_FILENAME'].$tmp.'.pdf');
else
$tmp = $mod_strings['LBL_PDF_FILENAME'].$tmp.'.pdf';
//$mod = return_module_language($current_language, 'EcmInvoiceOuts');
//return urlencode(
// return $mod['LBL_PDF_INVOICE_FILE_NAME'].$tmp.'.pdf';//);
return $tmp; //);
}
/**
BUILDS A GENERIC SEARCH BASED ON THE QUERY STRING USING OR.
DO NOT INCLUDE ANY $THIS-> BECAUSE THIS IS CALLED ON WITHOUT HAVING THE CLASS INSTANTIATED.
*/
function build_generic_where_clause ($the_query_string) {
$where_clauses = Array();
$the_query_string = PearDatabase::quote(from_html($the_query_string));
array_push($where_clauses, "ecmstockdocins.name like '$the_query_string%'");
$the_where = "";
foreach($where_clauses as $clause) {
if($the_where != "") $the_where .= " or ";
$the_where .= $clause;
}
return $the_where;
}
function set_notification_body($xtpl, $simplemodule) {
global $mod_strings, $app_list_strings;
$xtpl->assign("NAME", $simplemodule->name);
$xtpl->assign("DESCRIPTION", $simplemodule->description);
return $xtpl;
}
function bean_implements($interface) {
switch($interface) {
case 'ACL':return true;
}
return false;
}
function getTotal(){
global $sugar_config;
$w=$GLOBALS['db']->query("select quantity,total,ecmvat_value from ecmstockdocinitems where ecmstockdocin_id='".$this->id."' and deleted='0'");
$t=0;
while($r=$GLOBALS['db']->fetchByAssoc($w)){
$t+=$r['total']*(1+$r['ecmvat_value']/100);
}
return number_format($t,2,$sugar_config['default_decimal_seperator'],$sugar_config['default_number_grouping_seperator']);
}
function save($check_notify = FALSE) {
global $current_user;
//if($this->status == 'accepted' && $current_user->getPreference('confirm_quotes')){ $this->accepted = 1; } else { $this->accepted = 0; }
//if($this->status == 'not_accepted' && $current_user->getPreference('confirm_quotes')){ $this->accepted = 0; }
if(($this->fetched_row && $this->fetched_row['template_id'] != $this->template_id) || (empty($this->id) || $this->id == '')) {
$this->number = $this->generateNumber();
$this->document_no = 'PZ '.$this->formatNumber();
}
if(isset($this->ecmpaymentcondition_id) && $this->ecmpaymentcondition_id != '')
$this->ecmpaymentcondition_text = EcmStockDocIn::getTranslation('EcmPaymentConditions',$this->ecmpaymentcondition_id,$this->ecmlanguage);
else
$this->ecmpaymentcondition_text = '';
if(isset($this->ecmdeliverycondition_id) && $this->ecmdeliverycondition_id != '')
$this->ecmdeliverycondition_text = EcmStockDocIn::getTranslation('EcmDeliveryConditions',$this->ecmdeliverycondition_id,$this->ecmlanguage);
else
$this->ecmdeliverycondition_text = '';
require_once("modules/EcmTexts/EcmText.php");
$data = EcmText::LoadText(null,null,"EcmStockDocIns",$this->ecmlanguage);
$this->pdflanguages=base64_encode(serialize($data));
$return_id = parent::save($check_notify);
$this->savePositions($return_id);
EcmStockDocIn::setStatus($return_id,$this->status);
// $GLOBALS ['db']->query ("INSERT INTO ecmtransactions(id,name,date_entered,date_modified,modified_user_id,created_by,description,deleted,assigned_user_id,value,parent_name,parent_id,payment_date,type,paid,register_date,record_id,record_type)VALUES('".create_guid()."','".$this->document_no."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."','".$_SESSION['authenticated_user_id']."','".$_SESSION['authenticated_user_id']."','".$this->description."','".$this->deleted."','".$this->assigned_user_id."','".$this->total."','".$this->parent_name."','".$this->parent_id."','".$this->payment_date."','1','0','".$this->register_date."','".$this->id."','EcmStockDocIns')");
return $return_id;
}
function saveCorrect($check_notify = FALSE) {
global $current_user;
$this->number = $this->generateNumberCorrect();
$this->document_no = $this->formatNumberCorrect();
require_once("modules/EcmTexts/EcmText.php");
$data = EcmText::LoadText(null,null,"EcmStockDocIns",$this->ecmlanguage);
$this->pdflanguages=base64_encode(serialize($data));
$return_id = parent::save($check_notify);
$this->savePositions($return_id);
return $return_id;
}
//***************************Start Managing Positions*************************//
function constructInsertQuery($data, $table = '') {
if($table == '' && isset($this->object_name) && $this->object_name != '') {
$table = strtolower($this->object_name)."items";
} else return "";
$keys = array();
$values = array();
foreach($data as $key => $value) {
$keys[] = $key;
if(is_array($value))
$values[] = $value[1].str_replace("'", "\'", $value[0]).$value[1];
else
$values[] = "'".str_replace("'", "\'", $value)."'";
}
$q = "insert into ecmstockdocinitems (`";
$q .= implode('`, `', $keys);
$q .= "`) values (";
$q .= implode(", ", $values);
$q .= ");";
return $q;
}
function savePositions($id = null, $position_list = null) {
global $current_user, $timedate;
if($position_list == null) $position_list = $this->position_list;
if($id == null) $id = $this->id;
if(count($position_list) > 0) $this->deleteAssignedPositions($id);
$arr = array();
$position = 0;
for($i = 0; $i < count($position_list); $i ++) {
if($position_list[$i]['name'] == '') continue;
$p = $position_list[$i];
require_once("modules/EcmVats/EcmVat.php");
$vats = new EcmVat();
$vats->retrieve($p['vat_id']);
$p['vat_name'] = $vats->name;
require_once("modules/Currencies/Currency.php");
$curr = new Currency();
$curr->retrieve($p['currency_id']);
$p['currency_name'] = $curr->name;
if(!empty($p['category_id']) || $p['category_id'] == '') {
require_once("modules/EcmProducts/EcmProduct.php");
$pr = new EcmProduct();
$pr->retrieve($p['id']);
$p['category_id'] = $pr->product_category_id;
}
$itemid=create_guid();
$lv=return_app_list_strings_language($this->ecmlanguage);
$arr = array(
'id' => $itemid,
'date_entered' => array('NOW()', ''),
'date_modified' => array('NOW()', ''),
'modified_user_id' => $current_user->id,
'assigned_user_id' => $current_user->id,
'created_by' => $current_user->id,
'deleted' => '0',
'ecmstockdocin_id' => $id,
'ecmproduct_id' => $p['id'],
'position' => $position,
'code' => $p['code'],
'name' => $p['name'],
'quantity' => ((empty($p['quantity']) || $p['quantity'] == '') ? 0 : $p['quantity']),
'price' => ((empty($p['price']) || $p['price'] == '') ? 0 : $p['price']),
'discount' => ((empty($p['discount']) || $p['discount'] == '') ? 0 : $p['discount']),
'total' => ((empty($p['total']) || $p['total'] == '') ? 0 : $p['total']),
'dd_unit_id' => $p['unit_id'],
'dd_unit_name' => $lv['ecmproducts_unit_dom'][$p['unit_id']],
'ecmvat_id' => $p['vat_id'],
'ecmvat_name' => $p['vat_name'],
'ecmvat_value' => $p['vat_value'],
'ecmproductcategory_id' => $p['category_id'],
'currency_id' => $p['currency_id'],
'currency_name' => $p['currency_name'],
'duty' => $p['duty'],
'invoice_price' => $p['invoice_price'],
'weight_netto' => $p['weight_netto'],
'part_no'=> $p['part_no'],
'part_date'=>$p['part_date'],
);
//print_r($p);
$this->db->query($this->constructInsertQuery($arr));
$GLOBALS['db']->query("update ecmstockdocinsideinitems set price='".$p['price']."',total='".($p['price']*$p['quantity'])."' where id='".$itemid."'");
//print $p['id']." ".$p['name']."<br>";
if($this->status=="accepted"){
$this->insertProductsToStock($p,$id,$this->stock_id,$itemid);
}
$position ++;
}
}
function insertProductsToStock($pl,$return_id,$stock_id,$itemid)
{
require_once("modules/EcmStockOperations/EcmStockOperation.php");
$o=new EcmStockOperation();
require_once("modules/EcmProducts/EcmProduct.php");
$o->product_id=$pl['id'];
$p=new EcmProduct();
$p->retrieve($pl['id']);
$o->product_code=$p->code;
$o->product_name=$p->name;
require_once("modules/EcmStocks/EcmStock.php");
$o->stock_id=$stock_id;
$s=new EcmStock();
$s->retrieve($stock_id);
$o->stock_name=$s->name;
$o->parent_id=$return_id;
$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select document_no from ecmstockdocins where id='".$return_id."'"));
$o->parent_name=$r['document_no'];
$o->parent_type="EcmStockDocIns";
$o->part_no = $pl['part_no'];
if($pl['part_date']!=""){
$partDate = new DateTime($pl['part_date']);
$o->part_date = $partDate->format("d.m.Y");
}
$o->quantity=format_number($pl['quantity']);
$o->price=str_replace(",",".",str_replace(".","",$pl['price']));
$o->documentitem_id=$itemid;
$o->type=0;
$oid=$o->save();
$GLOBALS['db']->query("update ecmstockoperations set price='".$pl['price']."' where id='".$oid."'");
require_once("modules/EcmStockStates/EcmStockState.php");
$ss=new EcmStockState();
$ss->UpdateStockState($o->stock_id,$o->product_id);
}
function addProductToStockOut($stock_in_id,$product_id,$quantity,$price,$date,$wz_id,$stock_id,$itemid)
{
require_once("modules/EcmStockOperations/EcmStockOperation.php");
$o=new EcmStockOperation();
$o->unformat_all_fields();
require_once("modules/EcmProducts/EcmProduct.php");
$o->product_id=$product_id;
$p=new EcmProduct();
$p->retrieve($product_id);
$o->product_code=$p->code;
$o->product_name=$p->name;
require_once("modules/EcmStocks/EcmStock.php");
$o->stock_id=$stock_id;
$s=new EcmStock();
$s->retrieve($stock_id);
$o->stock_name=$s->name;
$o->parent_id=$wz_id;
$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select document_no from ecmstockdocins where id='".$wz_id."'"));
$o->parent_name=$r['document_no'];
$o->parent_type="EcmStockDocIns";
$o->quantity=$quantity;
$o->price=$price;
$o->in_id=$stock_in_id;
$o->documentitem_id=$itemid;
$o->type=1;
$oid=$o->save();
$GLOBALS['db']->query("update ecmstockoperations set price='".$price."' where id='".$oid."'");
require_once("modules/EcmStockStates/EcmStockState.php");
$ss=new EcmStockState();
$ss->UpdateStockState($o->stock_id,$o->product_id);
}
function addRelationPurchaseOrderStockIn($pz_id,$stock_in_id)
{
$w=$GLOBALS['db']->query("select po_id from ecmstockdocins where id='".$pz_id."'");
while($r=$GLOBALS['db']->fetchByAssoc($w))
{
$GLOBALS['db']->query("insert into ecmpurchaseorders_ecmstockins(id,date_modified,po_id,ecmstockin_id,deleted) values('".create_guid()."','".date("Y-m-d H:i:s")."','".$r['po_id']."','".$stock_in_id."','0')");
}
}
function getPosition($position) {
if(!is_array($position)) return '';
global $timedate;
$return_array = array();
$return_array['id'] = $position['ecmproduct_id'];
$return_array['position'] = $position['position'];
$return_array['code'] = $position['code'];
$return_array['name'] = $position['name'];
$return_array['quantity'] = $position['quantity'];
$return_array['price'] = $position['price'];
$return_array['discount'] = $position['discount'];
$return_array['total'] = $position['total'];
$return_array['unit_id'] = $position['dd_unit_id'];
$return_array['unit_name'] = $position['dd_unit_name'];
$return_array['vat_id'] = $position['ecmvat_id'];
$return_array['vat_name'] = $position['ecmvat_name'];
$return_array['vat_value'] = $position['ecmvat_value'];
$return_array['category_id'] = $position['ecmproductcategory_id'];
$return_array['currency_id'] = $position['currency_id'];
$return_array['currency_name'] = $position['currency_name'];
$return_array['duty'] = $position['duty'];
$return_array['invoice_price'] = $position['invoice_price'];
$return_array['weight_netto'] = $position['weight_netto'];
$return_array['part_no'] = $position['part_no'];
$return_array['part_date'] = $position['part_date'];
return $return_array;
}
function getPositionList($array = false) {
if(isset($this->id) && $this->id != '') {
$query = "SELECT * FROM `ecmstockdocinitems` WHERE ecmstockdocin_id='".$this->id."' order by position asc";
$r = $this->db->query($query);
$return_array = array();
if($r) {
while($w = $this->db->fetchByAssoc($r)) {
$return_array [] = $this->getPosition($w);
}
$json = getJSONobj();
return $array ? $return_array : $json->encode($return_array);
}
}
return $array ? false : '[]';
}
function deleteAssignedPositions() {
if(isset($this->id) && $this->id != '') {
$query = "DELETE FROM `ecmstockdocinitems` WHERE ecmstockdocin_id='".$this->id."'";
$r = $this->db->query($query);
if($r) return true;
}
return false;
}
//***************************End Managing Positions*************************//
static function getTranslation($module,$id,$language) {
if(isset($id) && $id != '' && isset($module) && $module != '') {
global $beanList, $beanFiles;
$file = $beanFiles[$beanList[$module]];
if(file_exists($file)) {
require_once($file);
$bean = new $beanList[$module]();
$bean->retrieve($id);
if(isset($bean->id) && $bean->id != '') {
if(isset($bean->translations[$language]) && $bean->translations[$language] != '') return $bean->translations[$language];
}
}
}
return null;
}
function getTemplateList() {
$query = "select `id`,`name` from `ecmdocumenttemplates` where `deleted`='0' order by `name`";
$result = $GLOBALS['db']->query($query);
$arr = array();
if($result)
while($row = $GLOBALS['db']->fetchByAssoc($result))
$arr[$row['id']] = $row['name'];
return $arr;
}
function setTemplate() {
if(!isset($this->template_id) || $this->template_id == '') return null;
if(isset($this->template)) return $this->template;
require_once('modules/EcmDocumentTemplates/EcmDocumentTemplate.php');
$this->template = new EcmDocumentTemplate();
//$this->template->retrieve($this->template_id);
$this->template->retrieve($this->template_id, true, false);
if(isset($this->template->id) && $this->template->id != '') {
$this->template->format_all_fields();
}
else
$this->template = null;
return $this->template;
}
function generateNumber() {
$this->setTemplate();
$this->number = isset($this->template) ? $this->template->generateNumber($this->table_name) : '';
return $this->number;
}
function formatNumber() {
$this->setTemplate();
$this->document_no = isset($this->template) ? $this->template->formatNumber($this->number, $this->module_dir) : '';
return $this->document_no;
}
function generateNumberCorrect() {
$this->setTemplate();
$this->number = $this->template->generateNumberCorrect($this->table_name);
return $this->number;
}
function formatNumberCorrect() {
$this->setTemplate();
$this->document_no = $this->template->formatNumberCorrect($this->number, $this->module_dir);
return $this->document_no;
}
function formatDocumentNumber($documentNumber = '', $code = '') {
return isset($this->template) ? $this->template->formatDocumentNumber($documentNumber, $code) : '';
}
function DrawPositions($pdf = null) {
global $mod_strings;
if(!isset($this->position_list) || !is_array($this->position_list))
$this->position_list = $this->getPositionList(true);
$calc = $this->calculate($this->position_list,true);
$this->position_list = $this->formatPositions($this->position_list);
$calc['total'] .= ' '.$this->currency_symbol;
$calc['subtotal'] .= ' '.$this->currency_symbol;
if($calc['discount']) {
$calc['total2'] .= ' '.$this->currency_symbol;
$calc['discount']['value'] .= ' '.$this->currency_symbol;
}
if(isset($calc['vats']) && is_array($calc['vats']) && count($calc['vats']) > 0)
foreach($calc['vats'] as $key => $value) $calc['vats'][$key] .= ' '.$this->currency_symbol;
$name_w = 47;
$image_w = 10;
$recipient_code_w = 10;
if($this->show_images_on_offers){
$name_w -= $image_w;
}
if($this->show_recipient_code){
$name_w -= $recipient_code_w;
}
if($calc['draw_discount']){
$name_w -= 8;
}
if($calc['draw_vat']){
$name_w -= 8;
}
$table = array();
if($this->show_images_on_offers)
$table [0]['image'] = array('width' => $image_w, 'value' => $mod_strings['LBL_PDF_LIST_IMAGE'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'R');
$table [0]['position'] = array('width' => 5, 'value' => $mod_strings['LBL_PDF_LIST_POSITION'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
$table [0]['code'] = array('width' => 12, 'value' => $mod_strings['LBL_PDF_LIST_CODE'],'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
if($this->show_recipient_code)
$table [0]['recipient_code'] = array('width' => $recipient_code_w, 'value' => $mod_strings['LBL_PDF_LIST_RECIPIENT_CODE'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
//$table [0]['unit'] = array('width' => 10, 'value' => $mod_strings['LBL_PDF_LIST_UNIT'],'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
$table [0]['description'] = array('width' => $name_w, 'value' => $mod_strings['LBL_PDF_LIST_DESCRIPTION'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
$table [0]['quantity'] = array('width' => 8, 'value' => $mod_strings['LBL_PDF_LIST_QUANTITY'],'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
$table [0]['unit'] = array('width' => 5, 'value' => $mod_strings['LBL_PDF_LIST_UNIT'], 'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 8);
$table [0]['unit_price'] = array('width' => 14, 'value' => $mod_strings['LBL_PDF_LIST_PRICE'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'C');
if($calc['draw_discount']) $table [0]['discount'] = array('width' => 8, 'value' => $mod_strings['LBL_PDF_LIST_DISCOUNT'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'R');
if($calc['draw_vat']) $table [0]['vat_id'] = array('width' => 8, 'value' => $mod_strings['LBL_PDF_LIST_VAT'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'R');
$table [0]['total'] = array('width' => 14, 'value' => $mod_strings['LBL_PDF_LIST_TOTAL'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'R');
$i = 1;
$lv=return_app_list_strings_language($this->ecmlanguage);
if($this->position_list != '')
foreach($this->position_list as $p) {
if($this->show_images_on_offers){
if(file_exists($this->getProductImage($p['id']))){$table [$i]['image'] = array('width' => $image_w, 'value' => '', 'border' => 0, 'align' => 'R', 'image_path' => $this->getProductImage($p['id']));
//$iarr[]=$this->getProductImage($p['id']);
}
else $table [$i]['image'] = array('width' => $image_w, 'value' => '', 'border' => 0, 'align' => 'R');
}
$table [$i]['position'] = array('width' => 5, 'value' => $i, 'border' => 0, 'align' => 'C', );
$table [$i]['code'] = array('width' => 12, 'value' => $p['code'], 'border' => 0, 'align' => 'C', );
if($this->show_recipient_code)
$table [$i]['recipient_code'] = array('width' => $recipient_code_w, 'value' => $p['recipient_code'], 'border' => 0, 'align' => 'C', );
//$table [$i]['unit'] = array('width' => 10, 'value' => $p['unit_id'], 'border' => 0, 'align' => 'C', );
/*
if($this->ecmlanguage=="en_us"){
$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select short_description from ecmproduct_language_en_view where ecmproduct_id='".$p['id']."'"));
$dname=$r['short_description'];
}
elseif($this->ecmlanguage=="ge_ge"){
$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select short_description from ecmproduct_language_de_view where ecmproduct_id='".$p['id']."'"));
$dname=$r['short_description'];
}
else $dname=$p['name'];
*/
$table [$i]['description'] = array('width' => $name_w, 'value' => htmlspecialchars_decode($p['name']), 'border' => 0, 'align' => 'L', );
$table [$i]['quantity'] = array('width' => 8, 'value' => $p['quantity'], 'border' => 0, 'align' => 'C', );
$table [$i]['unit'] = array('width' => 5, 'value' => $lv['ecmproducts_unit_dom'][$p['unit_id']], 'border' => 1, 'align' => 'C', 'font-size' => 7 );
$table [$i]['unit_price'] = array('width' => 14, 'value' => $p['price'], 'border' => 0, 'align' => 'C', );
if($calc['draw_discount']) $table [$i]['discount'] = array('width' => 8, 'value' => $p['discount'], 'border' => 0, 'align' => 'R', );
if($calc['draw_vat']) $table [$i]['vat_id'] = array('width' => 8, 'value' => $p['vat_name'], 'border' => 0, 'align' => 'R', );
$table [$i]['total'] = array('width' => 14, 'value' => $p['total'], 'border' => 0, 'align' => 'R', );
$i++;
}
$starttab=$pdf->GetY()+10;
$pdf->DrawTable($table,array(0));
$endtab=$pdf->GetY();
//for($n=0;$n<$i;$n++){
//if(file_exists($iarr[$n]))$pdf->Image($iarr[$n],$pdf->GetX()+1,$starttab+$n*18+1,15,0);
//}
$pdf->SetY($endtab);
//total, vat, subtotal
$pdf->Ln(4);
$pr = ($pdf->fw-$pdf->lMargin-$pdf->rMargin)/100;
//$pdf->SetX($pdf->fw-$pdf->rMargin-$pr*34);
$table = array();
if($calc['vats']) {
$table [] = array(
'subtotal1' => array('width' => 66, 'value' => $mod_strings['LBL_PDF_TOTAL'], 'background' => array(255,255,255), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 9),
'subtotal2' => array('width' => 34, 'value' => $calc['subtotal'], 'border' => 0, 'overflow' => 1, 'align' => 'R', 'font-size' => 9), );
foreach($calc['vats'] as $key => $value){
$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name from ecmvats where id='".$key."'"));
$vvn=$r['name'];
$table [] = array(
'vat1' => array('width' => 66, 'value' => $mod_strings['LBL_PDF_VAT'].' ('.$vvn.')', 'background' => array(255,255,255), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 9),
'vat2' => array('width' => 34, 'value' => $value, 'border' => 0, 'overflow' => 1, 'align' => 'R', 'font-size' => 9), );
}
}
if(isset($calc['discount'])) {
$table [] = array(
'total21' => array('width' => 66, 'value' => $mod_strings['LBL_PDF_TOTAL'], 'background' => array(255,255,255), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 9, 'font-style' => 'b'),
'total22' => array('width' => 34, 'value' => $calc['total2'], 'border' => 0, 'overflow' => 1, 'align' => 'R' , 'font-size' => 9), );
$table [] = array(
'discount1' => array('width' => 66, 'value' => $mod_strings['LBL_PDF_DISCOUNT'].' '.$calc['discount']['procent'], 'background' => array(255,255,255), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 9, 'font-style' => 'b'),
'discount2' => array('width' => 34, 'value' => $calc['discount']['value'], 'border' => 0, 'overflow' => 1, 'align' => 'R' , 'font-size' => 9), );
}
$table [] = array(
'total1' => array('width' => 66, 'value' => $mod_strings['LBL_PDF_END_TOTAL'], 'background' => array(233,233,233), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 9, 'font-style' => 'b'),
'total2' => array('width' => 34, 'value' => $calc['total'], 'border' => 0, 'background' => array(233,233,233), 'overflow' => 1, 'align' => 'R' , 'font-size' => 9, 'font-style' => 'b'), );
$pdf->DrawTable($table);
}
function getProductImage($pr_id) {
$query = "SELECT `product_picture` FROM `ecmproducts` WHERE `id`='$pr_id'";
$result = $GLOBALS['db']->query($query);
if(is_resource($result)) {
$result = $GLOBALS['db']->fetchByAssoc($result);
if(isset($result['product_picture']) && $result['product_picture'] != '') return 'modules/EcmProducts/upload/images/'.$result['product_picture'];
}
return '';
}
function DrawMainPDF($pdf) {
global $mod_strings;
$arr=$this->template->getTemplateFile($_REQUEST['module']);
echo "pozycje!";
include("modules/EcmDocumentTemplates/templates/".$arr[0]."/".$arr[1]."/subheader.php");
//$this->DrawPositions($pdf);
include("modules/EcmDocumentTemplates/templates/".$arr[0]."/".$arr[1]."/subfooter.php");
}
function getPDF($id = null,$method = 'I',$name = null) {
global $sugar_config;
if($id != null) {
$this->retrieve($id);
if($this->id == '') return;
}
global $mod_strings;
require_once('modules/EcmTexts/EcmText.php');
if(isset($this->ecmlanguage) && $this->ecmlanguage != '') {
if(!$_REQUEST['record'])$data = EcmText::LoadText(null,null,"EcmStockDocIns",$this->ecmlanguage);
else $data=unserialize(base64_decode($this->pdflanguages));
if(isset($data[0]) && isset($data[0]['data']) && isset($data[0]['data']['labels'])) {
$data = $data[0]['data']['labels'];
foreach($data as $key => $value) {
$mod_strings[$value['label']] = $value['translation'];
}
}
}
$this->format_all_fields();
$this->setTemplate();
if(isset($this->template->id) && $this->template->id != '') {
$this->template->setPDF($this->template_id);
$this->DrawMainPDF($this->template->pdf);
if($method=='F'){
$filename=$filename= $this->template->outputPDF((($name) ? $name : './pdfkopie/'.$this->createPdfFileName()), $method);
} else {
$filename= $this->template->outputPDF((($name) ? $name : $this->createPdfFileName()), $method);
}
}
return $filename;
}
function calculate($position_list, $format = false) {
if(!is_array($position_list)) return false;
$result = Array('total' => 0.0, 'vats' => false, 'subtotal' => 0.0, 'draw_vat' => false, 'draw_discount' => false);
$vats = Array();
foreach($position_list as $p) {
if(!isset($vats[$p['vat_id']])) $vats[$p['vat_id']] = 0;
$vats[$p['vat_id']] += floatval($p['total']);
$result['subtotal'] += floatval($p['total']);
if(!$result['draw_discount'] && floatval($p['discount']) > 0) $result['draw_discount'] = true;
}
$result['total'] = $result['subtotal'];
if(!$this->to_is_vat_free) {
$vats2 = Array();
foreach($vats as $key => $value) {
$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select value from ecmvats where id='".$key."'"));
$vva=$r['value'];
if(!$format) $vats2[$key] = $value*(floatval($vva)/100);
else $vats2[$key] = format_number($value*(floatval($vva)/100));
$result['total'] += $value*(floatval($vva)/100);
}
asort($vats2,SORT_NUMERIC);
$result['vats'] = $vats2;
if(count($result['vats'])>1) $result['draw_vat'] = true;
}
$discount = $this->discount;
if(!is_float($discount)) $discount = unformat_number($discount);
if(isset($discount) && $discount != 0 && $discount != '') {
$result['discount'] = array (
'procent' => format_number(floatval($discount)).'%',
'value' => $result['subtotal']*$discount/100,
);
$result['total2'] = $result['total'];
$result['total'] = $result['total']-$result['discount']['value'];
}
if($format) {
if(isset($result['discount']) && isset($result['discount']['value']) && $result['discount']['value'] != '' && $result['discount']['value'] != 0) {
$result['discount']['value'] = format_number($result['discount']['value']);
$result['total2'] = format_number($result['total2']);
}
$result['total'] = format_number($result['total']);
$result['subtotal'] = format_number($result['subtotal']);
}
return $result;
}
function formatPositions($position_list) {
if(!is_array($position_list) || count($position_list) == 0) return false;
global $app_list_strings;
require_once('modules/Currencies/Currency.php');
foreach($position_list as $key => $value) {
$position_list[$key]['category_id'] = $app_list_strings['ecmproducts_category_dom'][$value['category_id']];
//$position_list[$key]['vat_id'] = format_number($value['vat_id']).'%';
$position_list[$key]['discount'] = format_number($value['discount']).'%';
if(isset($currency) && ($currency->id == $this->currency_id)) {}
else {
$currency = new Currency();
$currency->retrieve($this->currency_id);
}
$position_list[$key]['price'] = format_number($value['price']).' '.$currency->iso4217;
$position_list[$key]['total'] = format_number($value['total']).' '.$currency->iso4217;
$this->currency_symbol = $currency->iso4217;
}
return $position_list;
}
function loadParser() {
$this->template->mfp->clear();
$this->template->mfp->add("EcmStockDocIns","pzdocument_",$this);
$this->template->mfp->add("Users","user_",$this->setUser());
if($this->setAccount() != null)
$this->template->mfp->add("Accounts",'account_',$this->account);
if($this->setEcmVendor() != null)
$this->template->mfp->add("EcmVendors",'vendor_',$this->ecmvendor);
if($this->setContact() != null)
$this->template->mfp->add("Contacts",'contact_',$this->contact);
$this->template->mfp->add("EcmDocumentTemplates","documenttemplate_",$this->template);
}
function loadParserArray($name = '') {
require_once('modules/EcmDocumentTemplates/ModuleFieldsParser/ModuleFieldsParser.php');
$mfp = new ModuleFieldsParser();
$mfp->clear();
global $app_list_strings;
$mfp->add("EcmStockDocIns","pzdocument_",'',$app_list_strings['moduleList']['EcmStockDocIns']);
$mfp->add("Users","user_",'',$app_list_strings['moduleList']['Users']);
$mfp->add("Accounts",'account_','',$app_list_strings['moduleList']['Accounts']);
$mfp->add("EcmVendors",'vendor_','',$app_list_strings['moduleList']['EcmVendors']);
$mfp->add("Contacts",'contact_','',$app_list_strings['moduleList']['Contacts']);
$mfp->add("EcmDocumentTemplates","documenttemplate_",'',$app_list_strings['moduleList']['EcmDocumentTemplates']);
if($name == '') {
$mfp_arr = array(
'header' => $mfp->getFormHTML(false, 'header'),
'footer' => $mfp->getFormHTML(false, 'footer'),
'ads' => $mfp->getFormHTML(false, 'ads'),
);
} else $mfp_arr = $mfp->getFormHTML(false,$name);
return $mfp_arr;
}
function setAccount() {
require_once('modules/Accounts/Account.php');
$this->account = new Account();
$this->account->retrieve($this->parent_id);
return $this->account;
}
function setEcmVendor() {
require_once('modules/EcmVendors/EcmVendor.php');
$this->ecmvendor = new EcmVendor();
$this->ecmvendor->retrieve($this->parent_id);
return $this->ecmvendor;
}
function setContact() {
require_once('modules/Contacts/Contact.php');
$us = new Contact();
$us->retrieve($this->contact_id);
$this->contact = $us;
return $this->contact;
}
function setUser() {
if(is_object($this->user)) return $this->user;
require_once('modules/Users/User.php');
$us = new User();
global $current_user;
$us->retrieve(($this->assigned_user_id)?$this->assigned_user_id:$current_user->id);
if(isset($us->id) && $us->id != '') {
$this->user = $us;
}
else
$this->user = null;
return $this->user;
}
function doNotAccepted() {
global $current_user;
$cq = $current_user->getPreference('confirm_quotes');
if(isset($cq) && $cq) {
$query = "UPDATE `ecmstockdocins` SET `status` = 'not_accepted',`accepted` = '0' WHERE CONVERT( `id` USING utf8 ) = '".$this->id."' LIMIT 1 ;";
$result = $this->db->query($query);
if($result) {
$this->status = 'not_accepted';
$this->accepted = 0;
}
}
}
function ACLAccess($view,$is_owner='not_set')
{
global $current_user;
$file = 'modules/EcmGroupSales/EcmGroupSale.php';
if(file_exists($file)) {
require_once($file);
$cc = EcmGroupSale::loadSettings(true);
} else return true;
if(is_admin($current_user)) {
switch ($view)
{
case 'confirming':
return ($this->status == "s20");
case 'send_to_confirm':
return ($this->status == "s10");
case 'pdf_toolbar':
return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
}
return true;
}
if($is_owner == 'not_set')
{
$is_owner = $this->isOwner($current_user->id);
}
//if we don't implent acls return true
if(!$this->bean_implements('ACL'))
return true;
$view = strtolower($view);
if($cc['user_manager_role']) { //Manager
switch ($view)
{
case 'list':
case 'index':
case 'listview':
return ACLController::checkAccess($this->module_dir,'list', true);
case 'edit':
case 'save':
case 'popupeditview':
case 'editview':
return (ACLController::checkAccess($this->module_dir,'edit', $is_owner));
case 'view':
case 'detail':
case 'detailview':
return ACLController::checkAccess($this->module_dir,'view', $is_owner);
case 'delete':
return ACLController::checkAccess($this->module_dir,'delete', $is_owner);
case 'export':
return ACLController::checkAccess($this->module_dir,'export', $is_owner);
case 'import':
return ACLController::checkAccess($this->module_dir,'import', true);
case 'send_to_confirm':
return ($this->status == "s10");
case 'can_commit':
return true;
case 'confirming':
return ($this->status == "s20");
case 'auto_commiting':
return true;
case 'pdf_toolbar':
return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
}
} else
if($cc['user_representative_extra_role']) { //Representative Extra
switch ($view)
{
case 'list':
case 'index':
case 'listview':
return ACLController::checkAccess($this->module_dir,'list', true);
case 'edit':
return (ACLController::checkAccess($this->module_dir,'edit', $is_owner) && ($this->status == "s10" || $this->status == "s40"));
case 'save':
case 'popupeditview':
case 'editview':
return (ACLController::checkAccess($this->module_dir,'edit', $is_owner));
case 'view':
case 'detail':
case 'detailview':
return ACLController::checkAccess($this->module_dir,'view', $is_owner);
case 'delete':
return (ACLController::checkAccess($this->module_dir,'delete', $is_owner) && $this->status == "s10");
case 'export':
return ACLController::checkAccess($this->module_dir,'export', $is_owner);
case 'import':
return ACLController::checkAccess($this->module_dir,'import', true);
case 'pzdocument_to_sale':
case 'pzdocument_to_invoice':
return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40" && $this->status != "s60");
case 'send_to_confirm':
return ($this->status == "s10");
case 'send_email':
return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
case 'can_commit':
return true;
case 'confirming':
return false;
case 'auto_commiting':
return true;
case 'pdf_toolbar':
return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
}
} else
if($cc['user_representative_role']) { //Representative
switch ($view)
{
case 'list':
case 'index':
case 'listview':
return ACLController::checkAccess($this->module_dir,'list', true);
case 'edit':
return (ACLController::checkAccess($this->module_dir,'edit', $is_owner) && ($this->status == "s10" || $this->status == "s40"));
case 'save':
case 'popupeditview':
case 'editview':
return (ACLController::checkAccess($this->module_dir,'edit', $is_owner));
case 'view':
case 'detail':
case 'detailview':
return ACLController::checkAccess($this->module_dir,'view', $is_owner);
case 'delete':
return (ACLController::checkAccess($this->module_dir,'delete', $is_owner) && $this->status == "s10");
case 'export':
return ACLController::checkAccess($this->module_dir,'export', $is_owner);
case 'import':
return ACLController::checkAccess($this->module_dir,'import', true);
case 'pzdocument_to_sale':
case 'pzdocument_to_invoice':
return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40" && $this->status != "s60");
case 'send_to_confirm':
return ($this->status == "s10");
case 'send_email':
return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
case 'can_commit':
return false;
case 'confirming':
return false;
case 'auto_commiting':
return false;
case 'pdf_toolbar':
return ($this->status != "s10" && $this->status != "s20" && $this->status != "s40");
}
}
//if it is not one of the above views then it should be implemented on the page level
return true;
}
function getUserSatusAccess() {
global $current_user;
require_once('modules/EcmStockDocIns/StatusAccess.php');
$file = 'modules/EcmGroupSales/EcmGroupSale.php';
if(file_exists($file)) {
require_once($file);
$cc = EcmGroupSale::loadSettings(true);
}
}
static function setStatus($record,$status) {
global $app_list_strings, $mod_strings;
$arr = array ();
require_once('modules/EcmStockDocIns/EcmStockDocIn.php');
$focus = new EcmStockDocIn();
if($focus->ACLAccess('auto_commiting') && $status == "s20") $status = "s30";
$query = "UPDATE ecmstockdocins SET status='$status' WHERE id='$record' AND deleted='0'";
$result = $GLOBALS['db']->query($query);
if(!$result) {
$arr['message'] = $mod_strings["LBL_STATUS_".$status."_FAIL_MESSAGE"];
} else {
$arr['record'] = $record;
$arr['status'] = array( 'text' => $app_list_strings['ecmstockdocins_status_dom'][$status], 'code' => $status, 'image' => EcmStockDocIn::CreateImgStatus($record,$status) );
$arr['message'] = $mod_strings["LBL_STATUS_".$status."_SET_MESSAGE"];
if(isset($_REQUEST['ListQuotesModule']) && $_REQUEST['ListQuotesModule'] != '' && isset($_REQUEST['ListQuotesAction']) && $_REQUEST['ListQuotesAction'] != '') {
$m_old = $_REQUEST['module']; $a_old = $_REQUEST['action'];
$_REQUEST['module'] = $_REQUEST['ListQuotesModule']; $_REQUEST['action'] = $_REQUEST['ListQuotesAction'];
$focus->id = $record;
$focus->status = $status;
$arr['list_images'] = $focus->ListIconsView();
$_REQUEST['module'] = $m_old; $_REQUEST['action'] = $a_old;
}
}
if(isset($status)) {
$file = 'modules/EcmGroupSales/EcmGroupSale.php';
$cc = array();
if(file_exists($file)) {
require_once($file);
$cc = EcmGroupSale::loadSettings(true);
}
if($status == 's20')
if(isset($cc['default_manager_role_id']) && $cc['default_manager_role_id'] != '')
foreach($cc['default_manager_role_id'] as $key => $manager_role_id) {
EcmStockDocIn::SetReminder($record, 'EcmStockDocIns', $arr['status']['image'].' '.$arr['status']['text'], $manager_role_id);
}
if(($status == 's30' || $status == 's40')) { // && !$focus->ACLAccess('auto_commiting')
EcmStockDocIn::SetReminder($record, 'EcmStockDocIns', $arr['status']['image'].'<span style="display:inline;">&nbsp;'.$arr['status']['text'].'</span>');
}
if($status == 's10') {
//deleting before reminders
$query = "DELETE FROM `ecmreminders` WHERE `parent_id`='$record'";
$GLOBALS['db']->query($query);
}
}
return $arr;
}
static function SetReminder($parent_id, $parent_name, $status, $role_id = '') {
$file = 'modules/EcmReminders/EcmReminder.php';
if(file_exists($file)) {
$name = 'EcmStockDocIns - Status Change';
$query = "SELECT name, assigned_user_id FROM ecmstockdocins WHERE id='$parent_id' LIMIT 1";
$result = $GLOBALS['db']->query($query);
if($result) {
$row = $GLOBALS['db']->fetchByAssoc($result);
if($row && isset($row['name'])) $name = $row['name'];
if($row && isset($row['assigned_user_id']) && $row['assigned_user_id'] != '') $assigned_user_id = $row['assigned_user_id'];
}
if(!isset($assigned_user_id) || $assigned_user_id == '') {
global $current_user;
$assigned_user_id = $current_user->id;
}
//deleting before reminders
$query = "DELETE FROM `ecmreminders` WHERE `parent_id`='$parent_id'";
if(isset($role_id) && $role_id != '') $query .= " AND `role_id`='$role_id'"; else $query .= " AND `role_id` IS NULL";
$GLOBALS['db']->query($query);
require_once($file);
$reminder = new EcmReminder();
$reminder->assigned_user_id = $assigned_user_id;
$reminder->name = $name;
$reminder->reminder_time = 0;
$reminder->parent_id = $parent_id;
$reminder->parent_name = $parent_name;
$reminder->role_id = $role_id;
$reminder->status = $status;
global $timedate;
$reminder->date_start = $timedate->to_display_date_time(gmdate('Y-m-d H:i:s'));
$reminder->save(FALSE);
}
}
public static function getReceiptsList($where,$product_category){
global $db;
//print_r($where);
if(empty($where['ecmrecipes'])){
$query = "SELECT * FROM ecmstockdocins WHERE (deleted=0 OR deleted IS NULL) ORDER BY date_entered, register_date";
}else{
$query = "SELECT * FROM ecmstockdocins WHERE (deleted=0 OR deleted IS NULL) AND " . implode(" AND ", $where['ecmrecipes']) . ' ORDER BY date_entered, register_date';
}
$result = $db->query($query);
$returnArray = [];
$returnArr=[];
if($result->num_rows > 0){
$returnArray = array();
while ($row = $db->fetchByAssoc($result)){
$currency_value = 1;
if($row['currency_value']!= ''){
$currency_value = 1;
}
$positionQuery = "SELECT
ecmstockdocinitems.id as position_id,
ecmstockdocinitems.name as position_name,
ecmstockdocinitems.total as position_total_netto,
ecmstockdocinitems.total as position_total_brutto,
ecmstockdocinitems.price as position_price_purchase,
ecmstockdocinitems.quantity as position_quantity,
ecmstockdocinitems.dd_unit_id as position_unit_id,
ecmstockdocinitems.dd_unit_name as position_unit_name,
ecmstockdocinitems.total as position_total_netto_corrected,
ecmstockdocinitems.quantity as position_quantity_corrected,
ecmstockdocinitems.total as position_total_brutto_corrected,
ecmstockdocinitems.ecmstockdocin_id as old_position_id,
ecmstockdocinitems.code as position_code,
ecmproducts.id as product_id,
ecmproducts.product_netto_weight as position_weight
FROM ecmstockdocinitems , ecmproducts ".($product_category!="" ? ',ecmproductcategories_bean' : '')."
WHERE
ecmstockdocinitems.ecmstockdocin_id='" . $row['id'] . "'
AND ecmstockdocinitems.ecmproduct_id = ecmproducts.id
".($product_category!="" ? 'and ecmproductcategories_bean.bean_id=ecmproducts.id and ecmproductcategories_bean.ecmproductcategory_id= "'.$product_category.'"' : '');
if(count($where['ecmproducts'])>0){
$positionQuery .= ' AND '. implode(" AND ", $where['ecmproducts']);
}
$positionQuery .= " ORDER BY ecmstockdocinitems.position ";
$positionresult = $db->query($positionQuery);
$positionArray = NULL;
$i=0;
if($positionresult->num_rows > 0){
$positionArray = array();
while ($rowposition = $db->fetchByAssoc($positionresult)){
$tmprow = array();
$tmprow['position_name'] = $rowposition['position_name'];
$tmprow['position_id'] = $rowposition['position_id'];
$tmprow['position_code'] = $rowposition['position_code'];
$tmprow['position_total_netto'] = round($rowposition['position_total_netto'] * $currency_value,2);
$tmprow['position_total_brutto'] = round($rowposition['position_total_brutto'] * $currency_value,2);
$tmprow['position_total_price_purchase'] = round($rowposition['position_price_purchase'] * $rowposition['position_quantity'],2);
$tmprow['position_weight'] = $rowposition['position_weight'];
$tmprow['position_total_weight'] = round($rowposition['position_weight'] * $rowposition['position_quantity'],6);
$tmprow['position_quantity'] = $rowposition['position_quantity'];
$tmprow['position_unit_id'] = $rowposition['position_unit_id'];
$tmprow['position_unit_name'] = $rowposition['position_unit_name'];
$tmprow['product_id'] = $rowposition['product_id'];
//print_r($tmprow);die();
$positionArray[] = $tmprow;
}
//print_r($row);die();
$i++;
}
$row['position_list'] = $positionArray;
$row['document_type'] = "EcmStockDocIn";
$returnArray[] = $row;
}
}
//print_r($row);die();
return $returnArray;
}
}
?>