Files
crm.twinpol.com/modules/EcmReceipts2/EcmReceipt.php

1737 lines
71 KiB
PHP
Raw Normal View History

2025-05-12 15:44:39 +00: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');
include_once("modules/EcmPaymentStates/helper.php");
require_once('include/utils.php');
class EcmReceipt 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_type;
var $parent_name;
var $parent_id;
var $type;
var $ecmreceipt_id;
var $ecmreceipt_name;
var $status;
var $register_date;
var $sell_date;
var $payment_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 $to_nip;
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 $wz_id;
var $order_no;
var $supplier_code;
var $delivery_place;
var $ecmpaymentcondition_id;
var $ecmpaymentcondition_name;
var $ecmpaymentcondition_text;
var $currency_symbol;
var $parent_name_copy;
var $parent_contact_name;
var $parent_contact_title;
var $template;
var $pdf;
var $position_list;
var $parser;
var $account;
var $contact;
var $user;
var $mfp;
var $ecmreceipt;
var $correct_reason;
var $so_id;
// 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 = "EcmReceipts";
var $table_name = "ecmreceipts";
var $object_name = "EcmReceipt";
//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'
);
function EcmReceipt() {
parent::SugarBean();
$this->setupCustomFields('EcmReceipts');
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 .= "ecmreceipts.*
,users.user_name as assigned_user_name";
if ($custom_join) {
$query .= $custom_join['select'];
}
$query .= " FROM ecmreceipts
LEFT JOIN users
ON ecmreceipts.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 ecmreceipts.name";
return $query;
}
function create_export_query($order_by, $where) {
$custom_join = $this->custom_fields->getJOIN();
$query = "SELECT
ecmreceipts.*,
users.user_name assigned_user_name";
if ($custom_join) {
$query .= $custom_join['select'];
}
$query .= " FROM ecmreceipts ";
$query .= " LEFT JOIN users
ON ecmreceipts.assigned_user_id=users.id";
if ($custom_join) {
$query .= $custom_join['join'];
}
$query .= "";
$where_auto = " ecmreceipts.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 ecmreceipts.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 FROM ecmreceipts WHERE id='$this->id'");
if ($result)
$row = $this->db->fetchByAssoc($result);
if (is_resource($result)) {
$row = $this->db->fetchByAssoc($result);
if ($row) {
$this->status = $row['status'];
}
}
$db = $GLOBALS['db'];
if (isset($this->id)) {
$w = $db->query("select document_no, id from ecmreceipts where ecmreceipt_id='" . $this->id . "' and deleted='0'");
while ($r = $db->fetchByAssoc($w)) {
$invs[] = "<a href='http://localhost/crm/index.php?module=EcmReceipts&return_module=EcmInvoiceOuts&action=DetailView&record=" . $r['id'] . "'/a>" . $r['document_no'] . "</a>";
}
$this->ecmreceipt_name = @implode(", ", $invs);
}
}
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, 'EcmReceipts');
$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.
$the_array['NAME'] = (($this->name == "") ? "<em>blank</em>" : $this->name);
//$the_array['STATUS_IMG'] = "<img border='0' src='modules/EcmReceipts/images/$this->status.gif' >";
$the_array['STATUS'] = EcmReceipt::CreateImgStatus($this->id, $this->status);
$the_array['TOTAL'] = format_number($this->total);
/*
$the_array['PDF_URL'] = '<img border="0" id="sendemail_'.$this->id.'" src="modules/EcmReceipts/images/send_email_enabled.gif" title="'.translate('LBL_SENDEMAIL_BUTTON','EcmInvoiceOuts').'" onClick="'.$this->createSendEmailLink().'" style="cursor:pointer;" />&nbsp;';
$the_array['PDF_URL'] .= '<img border="0" src="modules/EcmReceipts/images/pdf.gif" title="'.translate('LBL_LIST_PREVIEW_PDF','EcmInvoiceOuts').'" onClick="EcmPreviewPDF(\'index.php?module=EcmInvoiceOuts&action=previewPDF&method=I&record='.$this->id.'&to_pdf=1\',{zoom:75,toolbar:1});" style="cursor:pointer" />&nbsp;';
$the_array['PDF_URL'] .= '<img border="0" src="modules/EcmReceipts/images/download_enabled.gif" title="'.translate('LBL_LIST_DOWNLOAD_PDF','EcmInvoiceOuts').'" onClick="window.location=\'index.php?module=EcmInvoiceOuts&action=previewPDF&method=D&record='.$this->id.'&to_pdf=1\';" style="cursor:pointer"/>&nbsp;';
if($_REQUEST['module'] != "Home" && $_REQUEST['module'] != "EcmReceipts")
$the_array['PDF_URL'] .= '<img border="0" id="edit_'.$this->id.'" src="modules/EcmReceipts/images/edit_inline_enabled.gif" title="'.$app_strings['LBL_EDIT_BUTTON'].'" onClick="javascript:window.location=\'index.php?module=EcmInvoiceOuts&action=EditView&record='.$this->id.'\';" style="cursor:pointer;" />';
*/
$this->retrieve($this->id);
$the_array['OPTIONS'] = $this->ListIconsView();
$total = 0;
$db = $GLOBALS['db'];
if ((isset($this->currency_value)) && ($this->currency_value != 0))
$the_array['SUBTOTAL'] = $this->subtotal * $this->currency_value;
else
$the_array['SUBTOTAL'] = $this->subtotal;
if ($this->ecmreceipt_id) {
$w = $db->query("select price,ecmvat_value,quantity,ecmreceiptitem_id from ecmreceiptitems where ecmreceipt_id='" . $this->id . "'");
while ($r = $db->fetchByAssoc($w)) {
$total+=$r['price'] * $r['quantity'] + round($r['price'] * $r['quantity'] * $r['ecmvat_value'] / 100, 2);
$rr = $db->fetchByAssoc($db->query("select price,quantity,ecmvat_value from ecmreceiptitems where id='" . $r['ecmreceiptitem_id'] . "'"));
$total-=$rr['price'] * $rr['quantity'] + round($rr['price'] * $rr['quantity'] * $rr['ecmvat_value'] / 100, 2);
}
} else {
$w = $db->query("select price,ecmvat_value,quantity,ecmreceiptitem_id from ecmreceiptitems where ecmreceipt_id='" . $this->id . "'");
while ($r = $db->fetchByAssoc($w)) {
$total+=($r['price'] * $r['quantity']) + round(($r['price'] * $r['quantity'] * $r['ecmvat_value'] / 100), 2);
}
}
$w = $db->query("select document_no, id from ecmreceipts where ecmreceipt_id='" . $this->id . "' and deleted='0'");
while ($r = $db->fetchByAssoc($w)) {
$invs[] = "<a href='http://localhost/crm/index.php?module=EcmReceipts&return_module=EcmInvoiceOuts&action=DetailView&record=" . $r['id'] . "'/a>" . $r['document_no'] . "</a>";
}
$the_array['CORRECT'] = @implode(", ", $invs);
$the_array['TOTAL'] = format_number($total - $this->discount);
$r = $db->fetchByAssoc($db->query("select paid from ecmpayments_ecmreceipts where ecmreceipt_id='" . $this->id . "' and deleted='0'"));
if ($r['paid'] == 1)
$the_array['PAID'] = "Yes";
else
$the_array['PAID'] = "No";
$the_array['NUMBER'] = '';
return $the_array;
}
function getEmailTemplateId($what) {
$GLOBALS['db'] = new MysqlManager();
$GLOBALS['db']->connect();
$query = "SELECT `id` FROM `email_templates` WHERE `name` LIKE 'InvoiceTemplate" . $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();
}
static function CreateImgStatus($id, $status) {
global $app_list_strings;
return '<span id="statusListEcmReceipt_' . $id . '" ><img src="modules/EcmInvoiceOuts/images/' . $status . '.gif" title="' . $app_list_strings['ecmreceipts_status_dom'][$status] . '" /></span>';
}
function createPdfFileName($format = true) {
$arr1 = array('\\', '/', ':', '*', '?', '"', '<', '>', '|', ' ');
$arr2 = array('', '', '', '', '', '\'', '[', ']', '', '_');
$tmp = $this->document_no;
if ($format) {
if ($this->type == "normal")
$tmp = str_replace($arr1, $arr2, 'Invoice_' . $tmp . '.pdf');
else
if ($this->type == "correct")
$tmp = str_replace($arr1, $arr2, 'Correct_' . $tmp . '__to_Invoice_' . $this->ecmreceipt->document_no . '.pdf');
}
else
$tmp = 'Receipt ' . $tmp . '.pdf';
//$mod = return_module_language($current_language, 'EcmReceipts');
//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::receipt(from_html($the_query_string));
array_push($where_clauses, "ecmreceipts.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 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>';
return parent::create_new_list_query($order_by, $where, $filter, $params, $show_deleted, $join_type, $return_array, $parentbean, $singleSelect);
}
function generateOptions($icon, $module = '', $action = '') {
global $app_strings, $mod_strings;
$tmp = '';
if ($icon == "desc") {
//$tmp=Hint($this->id,$this->description);
}
if ($icon == 'pdf') {
//pdf
if ($this->ACLAccess('pdf_toolbar')) {
$tmp = '<img border="0" src="modules/' . $this->module_dir . '/images/pdf.gif" title="' . translate('LBL_LIST_PREVIEW_PDF', $this->module_dir) . '" onClick="EcmPreviewPDF(\'index.php?module=' . $this->module_dir . '&action=previewPDF&method=I&record=' . $this->id . '&to_pdf=1\',{zoom:75,toolbar:1});" style="cursor:pointer" />';
} else {
$tmp = '<img border="0" src="modules/' . $this->module_dir . '/images/pdf.gif" title="' . translate('LBL_LIST_PREVIEW_PDF', $this->module_dir) . '" onClick="EcmPreviewPDF(\'index.php?module=' . $this->module_dir . '&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/' . $this->module_dir . '/images/download_enabled.gif" title="' . translate('LBL_LIST_DOWNLOAD_PDF', $this->module_dir) . '" onClick="window.location=\'index.php?module=' . $this->module_dir . '&action=previewPDF&method=D&record=' . $this->id . '&to_pdf=1\';" style="cursor:pointer"/>';
} else {
$tmp = '<img border="0" src="modules/' . $this->module_dir . '/images/download_disabled.gif" title="' . translate('LBL_LIST_DOWNLOAD_PDF', $this->module_dir) . '"/>';
}
} else
if ($icon == 'duplicate') {
//duplicate
$tmp = '<a href="index.php?module=' . $this->module_dir . '&action=EditView&record=' . $this->id . '&isDuplicate=true"><img border="0" src="modules/' . $this->module_dir . '/images/duplicate.jpg" title="' . translate('LBL_LIST_DUPLICATE', $this->module_dir) . '" /></a>';
} else
if ($icon == 'edit') {
//edit
if ($this->ACLAccess('edit') && $this->status == "registered")
$tmp = '<img border="0" id="edit_' . $this->id . '" src="modules/' . $this->module_dir . '/images/edit_inline_enabled.gif" title="' . $app_strings['LBL_EDIT_BUTTON'] . '" onClick="javascript:window.location=\'index.php?module=' . $this->module_dir . '&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/' . $this->module_dir . '/images/edit_inline_disabled.gif" title="' . $app_strings['LBL_EDIT_BUTTON'] . '" />';
} else
if ($icon == 'send_email') {
//send_email
if ($this->status == "accepted")
$tmp = '<img border="0" id="sendemail_' . $this->id . '" src="modules/' . $this->module_dir . '/images/send_email_enabled.gif" title="' . translate('LBL_SENDEMAIL_BUTTON', $this->module_dir) . '" onClick="' . $this->createSendEmailLink() . '" style="cursor:pointer;" />';
else
$tmp = '<img border="0" id="sendemail_' . $this->id . '" src="modules/' . $this->module_dir . '/images/send_email_disabled.gif" title="' . translate('LBL_SENDEMAIL_BUTTON', $this->module_dir) . '" style="cursor:pointer;" />';
} else
if ($icon == 'correct') {
if ($this->status != "registered")
$tmp = '<a href="index.php?module=' . $this->module_dir . '&offset=1&return_module=' . $this->module_dir . '&action=EditView&return_action=index&record=' . $this->id . '&isCorrect=true"><img border="0" src="modules/' . $this->module_dir . '/images/correct.jpg" title="' . $mod_strings['LBL_CORRECT_TITLE'] . '" /></a>';
else
$tmp = '<img border="0" src="modules/' . $this->module_dir . '/images/correct_disabled.jpg" title="' . $mod_strings['LBL_CORRECT_TITLE'] . '" style="cursor:pointer;" />';
} else if ($icon == 'view') {
$tmp = '<img border="0" src="themes/Sugar/images/view_inline.gif" style="cursor: pointer;" onClick="javascript:window.location=\'index.php?module=' . $this->module_dir . '&action=DetailView&record=' . $this->id . '&return_module=' . $_REQUEST['module'] . '&return_action=' . $_REQUEST['action'] . '&return_id=' . $_REQUEST['record'] . '\';" title="' . $mod_strings['LBL_DETAIL_BUTTON'] . '" />';
}
return $tmp;
}
function ListIconsView() {
if (isset($_REQUEST['module']) && $_REQUEST['module'] != '' && isset($_REQUEST['action'])) {
$module = $_REQUEST['module'];
$action = $_REQUEST['action'];
$glue = "&nbsp;";
$viewIcons = array();
if ($module == $this->module_dir) { //This module, action ListView or index
$viewIcons = array('desc', 'send_email', 'download', 'correct', 'pdf', 'duplicate', 'edit');
if ($this->status == "registered")
$viewIcons = array('desc', 'send_email', 'download', 'correct', 'pdf', 'duplicate', 'edit');
}
else
if ($module == "Home") { //This is for a Home module for Dashlets
$glue = "&nbsp;";
$viewIcons = array('send_email', 'download', 'correct', 'pdf', 'duplicate', 'edit');
if ($this->status == "registered")
$viewIcons = array('send_email', 'download', 'correct', 'pdf', 'duplicate', 'edit');
} else { //this is for subpanels, popups
$glue = "&nbsp;";
$viewIcons = array('send_email', 'download', 'correct', 'pdf', 'duplicate', 'edit');
if ($this->status == "registered")
$viewIcons = array('send_email', 'download', 'correct', 'pdf', 'duplicate', 'edit');
}
$arr = array();
foreach ($viewIcons as $value) {
$tmp = $this->generateOptions($value);
if ($tmp != '')
$arr[] = $tmp;
}
return '<span id="optionsList' . $this->object_name . '_' . $this->id . '">' . implode($glue, $arr) . '<script language="javascript">var List' . $this->module_dir . 'Module="' . $module . '"; var List' . $this->module_dir . 'Action="' . $action . '";</script></span>';
}
return '';
}
function save($check_notify = FALSE) {
global $current_user;
//echo var_export($this->number, true). PHP_EOL;
//echo var_export($this->document_no, true). PHP_EOL;
if (($this->fetched_row && $this->fetched_row['template_id'] != $this->template_id) || (empty($this->id) || $this->id == '')) {
if (true) { //$this->type == "normal") {
$this->number = $this->generateNumber();
$this->document_no = $this->formatNumber();
} else {
$this->number = $this->generateNumberCorrect();
$this->document_no = $this->formatNumberCorrect();
}
}
//add 0
$date = substr($this->number,0,8);
$number = substr($this->number,8,strlen($this->number));
if (strlen($number)<5) {
while(strlen($number)!=5)
$number = '0'.$number;
}
$this->number = $date.$number;
//echo var_export($this->number, true). PHP_EOL;
//echo var_export($this->document_no, true). PHP_EOL;
//exit;
$this->status = 'accepted';
$this->ecmpaymentcondition_text = EcmReceipt::getTranslation('EcmPaymentConditions', $this->ecmpaymentcondition_id, $this->ecmlanguage);
$this->ecmdeliverycondition_text = EcmReceipt::getTranslation('EcmDeliveryConditions', $this->ecmdeliverycondition_id, $this->ecmlanguage);
$return_id = parent::save($check_notify);
// dump('xarr', $this->toArray());
$this->savePositions($return_id);
// return $return_id;
//delete document temp reservations
include_once("modules/EcmStockOperations/EcmStockOperation.php");
$op = new EcmStockOperation();
$op->removeDocumentReservations($_REQUEST['temp_id']);
$rdsc = $GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select discount,type from ecmreceipts where id='" . $return_id . "'"));
if ($rdsc['type'] == "correct") {
$total = 0;
$w = $GLOBALS[db]->query("select price,quantity,ecmvat_value,ecmreceiptitem_id from ecmreceiptitems where ecmreceipt_id='" . $return_id . "' and deleted='0'");
while ($r = $GLOBALS[db]->fetchByAssoc($w)) {
$total+=round($r['price'] * $r['quantity'] * (1 + $r['ecmvat_value'] / 100), 2);
$rr = $GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select price,quantity,ecmvat_value from ecmreceiptitems where id='" . $r['ecmreceiptitem_id'] . "'"));
$total-=round($rr['price'] * $rr['quantity'] * (1 + $r['ecmvat_value'] / 100), 2);
}
$GLOBALS[db]->query("update ecmreceipts set total=" . $total . " where id='" . $return_id . "'");
} else {
$total = 0;
$w = $GLOBALS[db]->query("select price, quantity, ecmvat_value, ecmreceiptitem_id from ecmreceiptitems where ecmreceipt_id = '" . $return_id . "' and deleted='0'");
while ($r = $GLOBALS[db]->fetchByAssoc($w)) {
// $total+=round($r['price'] * $r['quantity'] * (1 + $r['ecmvat_value'] / 100), 2);
$total += round($r['price'] * $r['quantity'], 2);
}
$GLOBALS[db]->query("update ecmreceipts set total=" . $total . "-discount where id='" . $return_id . "'");
}
return $return_id;
}
// ***************************Start Managing Positions************************* //
function constructInsertQuery($data, $table = '') {
if ($table == '' && isset($this->object_name) && $this->object_name != '') {
$table = strtolower($this->object_name) . "items";
}
else
return "";
$keys = array();
$values = array();
foreach ($data as $key => $value) {
$keys[] = $key;
if (is_array($value))
$values[] = $value[1] . str_replace("'", "\'", $value[0]) . $value[1];
else
$values[] = "'" . str_replace("'", "\'", $value) . "'";
}
$q = "insert into `$table` (`";
$q .= implode('`, `', $keys);
$q .= "`) values (";
$q .= implode(", ", $values);
$q .= ");";
return $q;
}
function savePositions($id = null, $position_list = null) {
global $current_user, $timedate;
if ($_REQUEST['out_id'])
$this->wz_id = $_REQUEST['out_id'];
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;
$t_position_list = $position_list;
for ($i = 0; $i < count($t_position_list); $i++) {
if (mysql_num_rows($GLOBALS[db]->query("select id from ecmreceiptitems where ecmproduct_id='" . $t_position_list[$i]['id'] . "' and ecmreceipt_id='" . $this->ecmreceipt_id . "' and price='" . $t_position_list[$i]['price'] . "' and quantity='" . $t_position_list[$i]['quantity'] . "' and deleted='0'")) > 0) {
unset($position_list[$i]);
}
}
$m = 0;
if (count($position_list) > 0) {
foreach ($position_list as $pr) {
$plist[$m] = $pr;
$m++;
}
$position_list = $plist;
}
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;
}
$lv = return_app_list_strings_language($this->ecmlanguage);
$arr = array(
'id' => create_guid(),
'date_entered' => array('NOW()', ''),
'date_modified' => array('NOW()', ''),
'modified_user_id' => $current_user->id,
'assigned_user_id' => $current_user->id,
'created_by' => $current_user->id,
'deleted' => '0',
strtolower($this->object_name) . '_id' => $id,
'ecmproduct_id' => $p['id'],
'position' => $position,
'code' => $p['code'],
'name' => $p['name'],
'quantity' => ((empty($p['quantity']) || $p['quantity'] == '') ? 0 : $p['quantity']),
'startprice' => $p['startprice'],
'subprice' => $p['subprice'],
'price' => $p['price'],
'price' => ((empty($p['price']) || $p['price'] == '') ? 0 : $p['price']),
'purchase_price' => $purchase_price,
'discount' => ((empty($p['discount']) || $p['discount'] == '') ? 0 : $p['discount']),
'subtotal' => $p['subtotal'],
'total' => $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'],
'tax_code' => $p['tax_code'],
'recipient_code' => $p['recipient_code'],
'netto_weight' => floatval(str_replace(",", ".", str_replace(".", "", $p['netto_weight']))),
'brutto_weight' => floatval(str_replace(",", ".", str_replace(".", "", $p['brutto_weight']))),
'ecmstockdocout_id' => $p['ecmstockdocout_id'],
'product_type' => $p['type'],
'parent_doc_id' => $p['parent_doc_id'],
'parent_doc_type' => $p['parent_doc_type'],
'parent_doc_item_id' => $p['parent_doc_item_id'],
);
if ($p['item_id'] && $p['item_id'] != "undefined")
$arr['ecmreceiptitem_id'] = $p['item_id'];
$query = $this->constructInsertQuery($arr);
$this->db->query($query);
/*
echo '<pre>P:' . var_export($p, true) . PHP_EOL . PHP_EOL;
echo '<pre>A:' . var_export($arr, true) . PHP_EOL . PHP_EOL;
continue;
exit;
*/
if ($p['parent_doc_type'] == "EcmStockDocOuts") {
// add fv-wz relation
$GLOBALS['db']->query("INSERT INTO ecmreceipts_ecmstockdocouts VALUES ('" . create_guid() . "','" . date("Y-m-d H:i:s") . "','0','" . $this->id . "', '" . $p['ecmstockdocout_id'] . "')");
} else {
// no, stock operation
// product must be article
/*
echo 'P:' . var_export($p, true) . PHP_EOL;
echo 'ID:' . $id . PHP_EOL;
echo 'ARR:' . var_export($arr, true) . PHP_EOL;
exit;
*/
// if ($p['type'] == 'article') {
//$this->addProducts($p, $id, $arr['id']);
if ($p['parent_doc_type'] == "EcmSales") {
//remove Sale Product reservation
include_once("modules/EcmStockOperations/EcmStockOperation.php");
$op = new EcmStockOperation();
$op->removeSaleProductReservations($p['parent_doc_item_id']);
//add relation
$GLOBALS['db']->query("INSERT INTO ecmreceipts_ecmsales VALUES ('" . create_guid() . "','" . date("Y-m-d H:i:s") . "','0','" . $this->id . "', '" . $p['parent_doc_id'] . "')");
}
//}
}
$position++;
}
}
function deleteProductFromStockIn($stock_in_id, $product_id, $qty) {
$z = "update ecmstockoperations set quantity=quantity-" . $qty . " where id='" . $stock_in_id . "' and product_id='" . $product_id . "' and deleted=0";
$GLOBALS['db']->query($z);
}
function addProductToStockOut($stock_in_id, $product_id, $quantity, $price, $date, $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 = $id;
$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select document_no from ecmreceipts where id='" . $id . "'"));
$o->parent_name = $r['document_no'];
$o->parent_type = "EcmReceipts";
$o->quantity = $quantity;
$o->price = floatval($price);
$o->in_id = $stock_in_id;
$o->documentitem_id = $itemid;
$o->type = 1;
$o->save();
require_once("modules/EcmStockStates/EcmStockState.php");
$ss = new EcmStockState();
$ss->UpdateStockState($o->stock_id, $o->product_id);
}
function addProducts($p, $id, $itemid) {
$arr = array();
$wq = "select quantity as qty,id,price from ecmstockoperations where deleted='0' and type='0' and used=0 and in_id IS NULL and stock_id='" . $this->stock_id . "' and product_id='" . $p['id'] . "'";
$w = $GLOBALS['db']->query($wq);
while ($rrr = $GLOBALS['db']->fetchByAssoc($w)) {
$wwq = "select quantity from ecmstockoperations where in_id='" . $rrr['id'] . "' and type='1' and in_id IS NOT NULL and stock_id='" . $this->stock_id . "' and product_id='" . $p['id'] . "' and deleted='0'";
$ww = $GLOBALS['db']->query($wwq);
$rqty = 0;
while ($rrp = $GLOBALS['db']->fetchByAssoc($ww)) {
$rqty+=$rrp['quantity'];
}
$qty = $rrr['qty'] - $rqty;
if ($qty > 0) {
$arr[] = array("qty" => $qty, "id" => $rrr['id'], "price" => $rrr['price']);
}
}
$rr = array();
$used_qty = 0;
$stop = 0;
foreach ($arr as $value) {
if ($p['quantity'] - $used_qty <= $value['qty']) {
$rr[] = array("id" => $value['id'], "qty" => $p['quantity'] - $used_qty, "price" => $value['price']);
$stop = 1;
} else {
$rr[] = array("id" => $value['id'], "qty" => $value['qty'], "price" => $value['price']);
$used_qty+=$value['qty'];
}
if ($stop) {
$stop = 0;
break;
}
}
$qq = 0;
$pp = 0;
$avg_pq = 0;
$avg_q = 0;
foreach ($rr as $r) {
if (!$_REQUEST['correct_id']) {
$this->addProductToStockOut($r['id'], $p['id'], $r['qty'], $r['price'], $this->register_date, $id, $this->stock_id, $itemid);
$avg_pq+=$r['qty'] * $r['price'];
$avg_q+=$r['qty'];
}
}
if (!$_REQUEST['correct_id']) {
$GLOBALS['db']->query("update ecmreceiptitems set purchase_price = '" . ($avg_pq / $avg_q) . "' where id = '" . $itemid . "'");
}
}
function getPosition($position, $stockOperations = false) {
if (!is_array($position))
return '';
//echo '<pre>' . var_export($position, true);
//exit;
global $timedate;
$return_array = array();
if(false == $stockOperations) {
$return_array['iid'] = $position['id'];
$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['tax_code'] = $position['tax_code'];
$return_array['recipient_code'] = $position['recipient_code'];
$return_array['netto_weight'] = $position['netto_weight'];
$return_array['brutto_weight'] = $position['brutto_weight'];
$return_array['ecmstockdocout_id'] = $position['ecmstockdocout_id'];
$return_array['type'] = $position['product_type'];
$return_array['parent_doc_id'] = $position['parent_doc_id'];
$return_array['parent_doc_type'] = $position['parent_doc_type'];
$return_array['parent_doc_item_id'] = $position['product_parent_doc_item_id'];
//mh
$return_array['origin_country_code'] = $position['origin_country_code'];
$return_array['product_code'] = $position['product_code'];
// 16-04-13
$return_array['startprice'] = $position['startprice'];
$return_array['subprice'] = $position['subprice'];
$return_array['subtotal'] = $position['subtotal'];
// 01-07-13
$return_array['pricehelper'] = $position['startprice'] * (1 + $position['ecmvat_value'] / 100);
if ($_REQUEST['isCorrect'] == "true") {
$return_array['item_id'] = $position['id'];
} else {
$return_array['item_id'] = $position['ecmreceiptitem_id'];
}
} else {
$return_array['iid'] = $position['id'];
$return_array['id'] = $position['product_id'];
//$return_array['position'] = $position['position'];
$return_array['code'] = $position['code'];
$return_array['name'] = $position['product_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['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['tax_code'] = $position['tax_code'];
//$return_array['recipient_code'] = $position['recipient_code'];
//$return_array['netto_weight'] = $position['netto_weight'];
//$return_array['brutto_weight'] = $position['brutto_weight'];
//$return_array['ecmstockdocout_id'] = $position['ecmstockdocout_id'];
//$return_array['type'] = $position['product_type'];
//$return_array['parent_doc_id'] = $position['parent_doc_id'];
//$return_array['parent_doc_type'] = $position['parent_doc_type'];
//$return_array['parent_doc_item_id'] = $position['product_parent_doc_item_id'];
//mh
//$return_array['origin_country_code'] = $position['origin_country_code'];
//$return_array['product_code'] = $position['product_code'];
//
//if ($_REQUEST['isCorrect'] == "true") {
// $return_array['item_id'] = $position['id'];
//} else {
// $return_array['item_id'] = $position['ecmreceiptitem_id'];
//}
$return_array['in_name'] = $position['in_name'];
$return_array['in_type'] = $position['in_type'];
}
return $return_array;
}
function getPositionList($array = false, $stockOperations = false) {
if (isset($this->id) && $this->id != '') {
$query = '';
if (false == $stockOperations) {
// $query = 'SELECT p.`origin_country_code`, p.`product_code`, ii.* FROM `ecmproducts` AS p JOIN `ecmreceiptitems` AS ii ON p.`id` = ii.`ecmproduct_id` WHERE ii.`ecmreceipt_id` = \'' . $this->id . '\' ORDER BY ii.`position` ASC';
$query = 'SELECT ii.* FROM `ecmproducts` AS p JOIN `ecmreceiptitems` AS ii ON p.`id` = ii.`ecmproduct_id` WHERE ii.`ecmreceipt_id` = \'' . $this->id . '\' ORDER BY ii.`position` ASC';
} else {
//$query = 'SELECT p.`origin_country_code`, p.`product_code`, ii.* FROM `ecmproducts` AS p JOIN `ecmreceiptitems` AS ii ON p.`id` = ii.`ecmproduct_id` WHERE ii.`ecmreceipt_id` = \'' . $this->id . '\' ORDER BY ii.`position` ASC';
//$query = 'SELECT soo.`parent_name` AS in_name, p.`unit_name`, so.*, p.`product_code` FROM `ecmstockoperations` AS so JOIN `ecmstockoperations` AS soo ON soo.`id` = so.`in_id` JOIN `ecmproducts` AS p ON p.`id` = so.`product_id` WHERE so.`parent_id` = \'' . $this->id . '\';';
$query = 'SELECT so.*, soo.`parent_name` AS `in_name`, soo.`parent_type` AS `in_type`, p.`index_dbf` AS `code`, p.`unit_name` FROM `ecmstockoperations` AS so JOIN `ecmstockoperations` AS soo ON soo.`id` = so.`in_id` JOIN `ecmproducts` AS p ON p.`id` = so.`product_id` WHERE so.`parent_id` = \'' . $this->id . '\';';
}
// echo $query; exit;
$r = $this->db->query($query);
$return_array = array();
if ($r) {
while ($w = $this->db->fetchByAssoc($r)) {
$return_array [] = $this->getPosition($w, $stockOperations);
}
$json = getJSONobj();
// var_dump($return_array);exit;
return $array ? $return_array : $json->encode($return_array);
}
}
return $array ? false : '[]';
}
function deleteAssignedPositions() {
if (isset($this->id) && $this->id != '') {
$query = "DELETE FROM `" . strtolower($this->object_name) . "items` WHERE `" . strtolower($this->object_name) . "_id`='" . $this->id . "'";
$r = $this->db->query($query);
if ($r)
return true;
}
return false;
}
//***************************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() {
global $db;
$query = "select `id`,`name` from `ecmdocumenttemplates` where `deleted`='0' order by `name`";
$result = $db->query($query);
$arr = array();
if ($result)
while ($row = $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 generateInvoiceNumber() {
global $db;
$year = date('y');
$q = 'SELECT r.`inside_inv_number` AS n FROM `ecmreceipts` AS r WHERE r.`inside_inv_number` LIKE \'%/' . $year . '/p\' AND `deleted` = 0 ORDER BY r.`inside_inv_number` DESC;';
$res = $db->query($q);
if (mysql_num_rows($res) == 0) {
return '1/' . $year . '/p';
}
$row = $db->fetchByAssoc($res);
$last = $row['n'];
$last = explode('/', $last);
$last = trim($last[0]);
$last = intval($last);
$new = $last + 1;
return trim($new . '/' . $year . '/p');
}
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;
$currency = new Currency();
$currency->retrieve($this->currency_id);
$this->currency_symbol = $currency->iso4217;
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 = 22;
//if($calc['draw_discount']) $name_w -= 8;
//if($calc['draw_vat']) $name_w -= 8;
$table = array();
$table [0]['position'] = array('width' => 4, 'value' => $mod_strings['LBL_PDF_LIST_POSITION'], 'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 8);
$table [0]['description'] = array('width' => $name_w, 'value' => $mod_strings['LBL_PDF_LIST_DESCRIPTION'], 'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
$table [0]['tax_code'] = array('width' => 8, 'value' => $mod_strings['LBL_PDF_LIST_TAX_CODE'], 'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
$table [0]['quantity'] = array('width' => 7, 'value' => $mod_strings['LBL_PDF_LIST_QUANTITY'], 'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
$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' => 10, 'value' => $mod_strings['LBL_PDF_LIST_PRICE'], 'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
$table [0]['unit_price_total'] = array('width' => 12, 'value' => $mod_strings['LBL_PDF_LIST_TOTAL_PRICE'], 'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
//if($calc['draw_discount']) $table [0]['discount'] = array('width' => 8, 'value' => $mod_strings['LBL_PDF_LIST_DISCOUNT'], 'border' => 0, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
//if($calc['draw_vat']) {
$table [0]['vat_id'] = array('width' => 5, 'value' => $mod_strings['LBL_PDF_LIST_VAT'], 'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
$table [0]['vat_value'] = array('width' => 13, 'value' => $mod_strings['LBL_PDF_LIST_VAT_VALUE'], 'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
//}
$table [0]['total'] = array('width' => 14, 'value' => $mod_strings['LBL_PDF_LIST_TOTAL'], 'border' => 1, 'overflow' => 1, 'align' => 'C', 'font-style' => 'b', 'font-size' => 7);
$pdf->DrawTable($table, array(0));
$pdf->Ln(0);
$i = 1;
$table = array();
if ($this->position_list != '')
foreach ($this->position_list as $p) {
$table [$i]['position'] = array('width' => 4, 'value' => $i, 'border' => 1, 'align' => 'R', 'font-size' => 7);
$table [$i]['description'] = array('width' => $name_w, 'value' => htmlspecialchars_decode($p['name']), 'border' => 1, 'align' => 'L', 'font-size' => 7);
$table [$i]['tax_code'] = array('width' => 8, 'value' => $p['tax_code'], 'border' => 1, 'align' => 'C', 'font-size' => 7);
$table [$i]['quantity'] = array('width' => 7, 'value' => $p['quantity'], 'border' => 1, 'align' => 'C', 'font-size' => 7);
$table [$i]['unit'] = array('width' => 5, 'value' => $GLOBALS['app_list_strings']['ecmproducts_unit_dom'][$p['unit']], 'border' => 1, 'align' => 'C', 'font-size' => 7);
$table [$i]['unit_price'] = array('width' => 10, 'value' => $p['price'], 'border' => 1, 'align' => 'R', 'font-size' => 7);
$price_total = $p['price'] * $p['quantity'];
$table [$i]['unit_price_total'] = array('width' => 12, 'value' => ($price_total), 'border' => 1, 'align' => 'R', 'font-size' => 7);
//if($calc['draw_discount']) $table [$i]['discount'] = array('width' => 8, 'value' => $p['discount'], 'border' => 0, 'align' => 'R', 'font-size' => 7 );
//if($calc['draw_vat']){
$table [$i]['vat_id'] = array('width' => 5, 'value' => ($p['vat_value']), 'border' => 1, 'align' => 'R', 'font-size' => 7);
$vat_value = $p['vat_value'] / 100 * $p['price'] * $p['quantity'];
$table [$i]['vat_value'] = array('width' => 13, 'value' => ($vat_value), 'border' => 1, 'align' => 'R', 'font-size' => 7);
//}
$table [$i]['total'] = array('width' => 14, 'value' => ($price_total + $vat_value), 'border' => 1, 'align' => 'R', 'font-size' => 7);
$totals[$p['vat_id']]['price']+=$price_total;
$totals[$p['vat_id']]['total']+=$price_total + $vat_value;
$totals[$p['vat_id']]['vat']+=$vat_value;
$i++;
}
$pdf->DrawTable($table, array(0));
//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' => 42, 'value' => $mod_strings['LBL_PDF_TOTAL'], 'background' => array(255,255,255), 'border' => 1, 'overflow' => 1, 'align' => 'L', 'font-size' => 7),
'subtotal2' => array('width' => 14, 'value' => $calc['subtotal'].' PLN', 'border' => 1, 'overflow' => 1, 'align' => 'R', 'font-size' => 7), );
*/
foreach ($calc['vats'] as $key => $value) {
$r = $GLOBALS[db]->fetchByAssoc($GLOBALS[db]->query("select id,name,value from ecmvats where id='" . $key . "'"));
$vvn = $r['name'];
$table [] = array(
'vat1' => array('width' => 10, 'value' => $mod_strings['LBL_PDF_VAT'] . ' (' . $vvn . ')', 'background' => array(255, 255, 255), 'border' => 1, 'overflow' => 1, 'align' => 'L', 'font-size' => 7),
'netto_total' => array('width' => 12, 'value' => format_number($totals[$r['id']]['price']), 'background' => array(255, 255, 255), 'border' => 1, 'overflow' => 1, 'align' => 'R', 'font-size' => 7),
'vat_rate' => array('width' => 5, 'value' => format_number($r['value']), 'background' => array(255, 255, 255), 'border' => 1, 'overflow' => 1, 'align' => 'R', 'font-size' => 7),
'vat_total' => array('width' => 13, 'value' => format_number($totals[$r['id']]['vat']), 'background' => array(255, 255, 255), 'border' => 1, 'overflow' => 1, 'align' => 'R', 'font-size' => 7),
'vat2' => array('width' => 14, 'value' => format_number($totals[$r['id']]['total']), 'border' => 1, 'overflow' => 1, 'align' => 'R', 'font-size' => 7),);
}
}
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' => 7, 'font-style' => 'b'),
'total22' => array('width' => 34, 'value' => $calc['total2'], 'border' => 0, 'overflow' => 1, 'align' => 'R', 'font-size' => 7),);
$table [] = array(
'discount1' => array('width' => 86, 'value' => $mod_strings['LBL_PDF_DISCOUNT'] . ' ' . $calc['discount']['procent'], 'background' => array(255, 255, 255), 'border' => 0, 'overflow' => 1, 'align' => 'L', 'font-size' => 7, 'font-style' => 'b'),
'discount2' => array('width' => 14, 'value' => $calc['discount']['value'], 'border' => 0, 'overflow' => 1, 'align' => 'R', 'font-size' => 7),);
}
$table [] = array(
'total1' => array('width' => 40, 'value' => $mod_strings['LBL_PDF_END_TOTAL'], 'border' => 1, 'overflow' => 1, 'align' => 'L', 'font-size' => 7, 'font-style' => 'b'),
'total2' => array('width' => 14, 'value' => $calc['total'], 'border' => 1, 'overflow' => 1, 'align' => 'R', 'font-size' => 7, 'font-style' => 'b'),);
$pdf->SetX(103);
$pdf->DrawTable($table);
$pdf->Ln(1);
//$table=array();
//$pdf->DrawTable($table);
}
/**
* @var $pdf
* @var $type => pdf_type
*/
function DrawMainPDF($pdf, $type = null) {
switch ($type = strtolower($type ? : $this->pdf_type)) {
default:
include($this->template->getTemplateFile('subheader.php'));
include($this->template->getTemplateFile('subfooter.php'));
break;
case 'inv':
case 'exp':
include($this->template->getTemplateFile('subheader_' . $type . '.php'));
include($this->template->getTemplateFile('subfooter_' . $type . '.php'));
break;
}
return;
}
function getPDF($id = null, $method = 'I', $name = null, $type = 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 != '') {
$data = EcmText::LoadText(null, null, "EcmReceipts", $this->ecmlanguage);
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();
//$type = $_REQUEST['type'];
if (isset($this->template->id) && $this->template->id != '') {
if ($type == 'inv') {
//create new number if invoice not exists
if (!$this->inside_inv_number) {
$this->inside_inv_number = $this->generateInvoiceNumber();
$q = 'UPDATE `ecmreceipts` SET `inside_inv_number` = \'' . $this->inside_inv_number. '\' WHERE `id` = \'' . $this->id . '\'';
$GLOBALS['db']->query($q);
}
}
$this->template->setPDF($this->template_id);
$this->template->pdf->SetAutoPageBreak(true, 40);
$this->DrawMainPDF($this->template->pdf, $type);
$this->template->outputPDF((($name) ? $name : $this->createPdfFileName()), $method);
}
}
function calculate($position_list, $format = false) {
global $db;
if (!is_array($position_list))
return false;
$result = array(
'total' => 0.0,
'subtotal' => 0.0,
//
'vats' => array(),
'draw_vat' => false,
//
//'discounts' => array(),
'draw_discount' => false,
//
'weight_netto' => 0.0,
);
$vats = array();
//$discounts = array();
foreach ($position_list as $position) {
//echo '<pre>' . var_export($position, true) . '</pre>';
//exit;
$wq = 'SELECT `weight_netto` FROM `ecmproducts` AS p WHERE p.`id` = \'' . $position['id'] . '\';';
$wr = $db->query($wq);
$w = $db->fetchByAssoc($wr);
$result['weight_netto'] += $w['weight_netto'] * $position['quantity'];
if (!isset($vats[$position['vat_id']])) {
$vats[$position['vat_id']]['b'] = $vats[$position['vat_id']]['n'] = 0;
}
//$position['total'] = floatval($position['price']) * floatval($position['quantity']);
$vats[$position['vat_id']]['b'] += floatval($position['total']);
$result['subtotal'] += floatval($position['total']);
if (!$result['draw_discount'] && floatval($position['discount']) > 0) {
$result['draw_discount'] = true;
}
}
$result['total'] = $result['subtotal'];
// Calculate vats.
if (false == $this->to_is_vat_free) {
$vats2 = $vats;//array();
foreach ($vats2 as $key => &$value) {
$qv = 'SELECT v.`value` FROM `ecmvats` AS v WHERE v.`id` = \'' . $key . '\';';
$rv = $db->query($qv);
$r = $db->fetchByAssoc($rv);
$vva = $r['value'];
$vats2[$key]['n'] = floatval($value['b']) / (1 + (floatval($vva) / 100));
$result['total'] += $vats2[$key]['n'];//floatval($value) * (floatval($vva) / 100);
/*
if (true == $format) {
$vats2[$key]['n'] = format_number($vats2[$key]['n']);
}
*/
}
$this->total = $result['total'];
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 (true == $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']);
$result['weight_netto'] = format_number($result['weight_netto']);
foreach($result['vats'] as $key => &$value) {
$value['n'] = format_number($value['n']);
$value['b'] = format_number($value['b']);
}
}
//echo '<pre>calculate: ' . var_export($result, true);
//exit;
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("EcmQuotes", "quote_", $this);
$this->template->mfp->add("Users", "user_", $this->setUser());
if ($this->setAccount() != null)
$this->template->mfp->add("Accounts", 'account_', $this->account);
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("EcmReceipts", "receipt_", '', $app_list_strings['moduleList']['EcmInvoiceOuts']);
$mfp->add("Users", "user_", '', $app_list_strings['moduleList']['Users']);
$mfp->add("Accounts", 'account_', '', $app_list_strings['moduleList']['Accounts']);
$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 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_receipts');
if (isset($cq) && $cq) {
$query = "UPDATE `ecmreceipts` 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 loadEcmReceipt() {
$this->ecmreceipt = new EcmReceipt();
if (isset($this->ecmreceipt_id) && $this->ecmreceipt_id != '') {
$this->ecmreceipt->retrieve($this->ecmreceipt_id);
}
}
function slownieEN($kw) {
}
function slowniePL($kw) {
$t_a = array('', 'sto', 'dwieście', 'trzysta', 'czterysta', 'pięćset', 'sześćset', 'siedemset', 'osiemset', 'dziewięćset');
$t_b = array('', 'dziesięć', 'dwadzieścia', 'trzydzieści', 'czterdzieści', 'pięćdziesiąt', 'sześćdziesiąt', 'siedemdziesiąt', 'osiemdziesiąt', 'dziewięćdziesiąt');
$t_c = array('', 'jeden', 'dwa', 'trzy', 'cztery', 'pięć', 'sześć', 'siedem', 'osiem', 'dziewięć');
$t_d = array('dziesięć', 'jedenaście', 'dwanaście', 'trzynaście', 'czternaście', 'piętnaście', 'szesnaście', 'siedmnaście', 'osiemnaście', 'dziewiętnaście');
$t_kw_15 = array('septyliard', 'septyliardów', 'septyliardy');
$t_kw_14 = array('septylion', 'septylionów', 'septyliony');
$t_kw_13 = array('sekstyliard', 'sekstyliardów', 'sekstyliardy');
$t_kw_12 = array('sekstylion', 'sekstylionów', 'sepstyliony');
$t_kw_11 = array('kwintyliard', 'kwintyliardów', 'kwintyliardy');
$t_kw_10 = array('kwintylion', 'kwintylionów', 'kwintyliony');
$t_kw_9 = array('kwadryliard', 'kwadryliardów', 'kwaryliardy');
$t_kw_8 = array('kwadrylion', 'kwadrylionów', 'kwadryliony');
$t_kw_7 = array('tryliard', 'tryliardów', 'tryliardy');
$t_kw_6 = array('trylion', 'trylionów', 'tryliony');
$t_kw_5 = array('biliard', 'biliardów', 'biliardy');
$t_kw_4 = array('bilion', 'bilionów', 'bilony');
$t_kw_3 = array('miliard', 'miliardów', 'miliardy');
$t_kw_2 = array('milion', 'milionów', 'miliony');
$t_kw_1 = array('tysiąc', 'tysięcy', 'tysiące');
//$t_kw_0 = array('złoty','złotych','złote');
$t_kw_0 = array('', '', '');
if ($kw != '') {
$kw = (substr_count($kw, ',') == 0) ? $kw . ',00' : $kw;
$tmp = explode(",", $kw);
$ln = strlen($tmp[0]);
$tmp_a = ($ln % 3 == 0) ? (floor($ln / 3) * 3) : ((floor($ln / 3) + 1) * 3);
for ($i = $ln; $i < $tmp_a; $i++) {
$l_pad .= '0';
$kw_w = $l_pad . $tmp[0];
}
$kw_w = ($kw_w == '') ? $tmp[0] : $kw_w;
$paczki = (strlen($kw_w) / 3) - 1;
$p_tmp = $paczki;
for ($i = 0; $i <= $paczki; $i++) {
$t_tmp = 't_kw_' . $p_tmp;
$p_tmp--;
$p_kw = substr($kw_w, ($i * 3), 3);
$kw_w_s = ($p_kw{1} != 1) ? $t_a[$p_kw{0}] . ' ' . $t_b[$p_kw{1}] . ' ' . $t_c[$p_kw{2}] : $t_a[$p_kw{0}] . ' ' . $t_d[$p_kw{2}];
if (($p_kw{0} == 0) && ($p_kw{2} == 1) && ($p_kw{1} < 1))
$ka = ${$t_tmp}[0]; //mozliwe ze $p_kw{1}!=1
else if (($p_kw{2} > 1 && $p_kw{2} < 5) && $p_kw{1} != 1)
$ka = ${$t_tmp}[2];
else
$ka = ${$t_tmp}[1];
$kw_slow.=$kw_w_s . ' ' . $ka . ' ';
}
}
if ($kw < 1000000 && eregi("milion", $kw_slow)) {
$kw_slow = substr($kw_slow, 11, strlen($kw_slow));
}
$text = $kw_slow . ' ' . str_replace("PLN", "", str_replace("USD", "", $tmp[1])) . '/100.';
return $text;
}
//add mz 2012-05-21
//for subpanels
//public function get_parent_for_subpanel() {
// return "SELECT
//}
//end mz
}