'notes', 'email_id' => 'emails' ); function EcmInvoiceOutOld() { parent::SugarBean (); $this->setupCustomFields ( 'EcmInvoiceOutOlds' ); 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 .= "ecminvoiceoutolds.* ,users.user_name as assigned_user_name"; if ($custom_join) { $query .= $custom_join ['select']; } $query .= " FROM ecminvoiceoutolds LEFT JOIN users ON ecminvoiceoutolds.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 ecminvoiceoutolds.name"; return $query; } function create_export_query($order_by, $where) { $custom_join = $this->custom_fields->getJOIN (); $query = "SELECT ecminvoiceoutolds.*, users.user_name assigned_user_name"; if ($custom_join) { $query .= $custom_join ['select']; } $query .= " FROM ecminvoiceoutolds "; $query .= " LEFT JOIN users ON ecminvoiceoutolds.assigned_user_id=users.id"; if ($custom_join) { $query .= $custom_join ['join']; } $query .= ""; $where_auto = " ecminvoiceoutolds.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 ecminvoiceoutolds.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 ecminvoiceoutolds 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']; } } if ($this->canceled == '1' && $_REQUEST ['action'] == 'DetailView') $this->document_no .= ' '; } function getEcmSalesSubPanel() { $bean = $GLOBALS ['app']->controller->bean; $query = "SELECT sale.id as id, sale.status as status, sale.document_no as document_no, sale.name as name, sale.total_brutto as total, sale.register_date as register_date FROM ecminvoiceoutolds as iv inner join ecmstockdocouts as wz on wz.id = iv.wz_id inner join ecmsales as sale on sale.id = wz.ecmsale_id WHERE iv.id='" . $this->id . "'"; $result = $GLOBALS ['db']->query ( $query ); $row = $GLOBALS ['db']->fetchByAssoc ( $result ); $the_array ['id'] = $row ['id']; $the_array ['status'] = $row ['status']; $the_array ['document_no'] = '' . $row ['document_no'] . ''; $the_array ['name'] = $row ['name']; $the_array ['total2'] = $row ['total']; $the_array ['register_date'] = $row ['register_date']; return $query; } function getEcmStockDocOutsSubPanel() { $bean = $GLOBALS ['app']->controller->bean; $query = "SELECT wz.id as id, wz.status as status, wz.document_no as document_no, wz.name as name, wz.total as total, wz.register_date as register_date FROM crm.ecmstockdocouts as wz inner join crm.ecminvoiceoutolds as inv ON wz.id=inv.wz_id where inv.id='" . $this->id . "'"; $result = $GLOBALS ['db']->query ( $query ); $row = $GLOBALS ['db']->fetchByAssoc ( $result ); $the_array ['id'] = $row ['id']; $the_array ['status'] = $row ['status']; $the_array ['document_no'] = '' . $row ['document_no'] . ''; $the_array ['name'] = $row ['name']; $the_array ['total2'] = $row ['total']; $the_array ['register_date'] = $row ['register_date']; return $query; } 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, 'EcmInvoiceOutOlds' ); $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 == "") ? "blank" : $this->name); // $the_array['STATUS_IMG'] = ""; $cc = $GLOBALS ['db']->fetchByAssoc ( $GLOBALS ['db']->query ( "SELECT canceled FROM ecminvoiceoutolds WHERE id='" . $this->id . "'" ) ); $the_array ['STATUS'] = EcmInvoiceOutOld::CreateImgStatus ( $this->id, $this->status, $cc ['canceled'] ); global $current_user; $the_array ['TOTAL'] = $this->total; /* * $the_array['PDF_URL'] = ' '; $the_array['PDF_URL'] .= ' '; $the_array['PDF_URL'] .= ' '; if($_REQUEST['module'] != "Home" && $_REQUEST['module'] != "EcmInvoiceOutOlds") $the_array['PDF_URL'] .= ''; */ $this->retrieve ( $this->id ); $the_array ['OPTIONS'] = $this->ListIconsView (); $total = 0; if ($_REQUEST ['record'] && $_REQUEST ['module'] == "EcmProducts") { $rp = $GLOBALS ['db']->fetchByAssoc ( $GLOBALS ['db']->query ( "select p.subprice as subprice,p.quantity as quantity from ecminvoiceoutolditems as p where p.ecmproduct_id='" . $_REQUEST ['record'] . "' and p.ecminvoiceoutold_id='" . $this->id . "' and p.deleted='0'" ) ); $the_array ['SUBPRICE'] = number_format ( $rp ['subprice'], 2, ",", "." ); $the_array ['QUANTITY'] = number_format ( $rp ['quantity'], 2, ",", "." ); $the_array ['WARTOSC'] = number_format ( ($rp ['quantity'] * $rp ['subprice']), 2, ",", "." ); } $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->ecminvoiceoutold_id) { * $w = $db->query ( "select price,ecmvat_value,quantity,ecminvoiceoutolditem_id from ecminvoiceoutolditems where ecminvoiceoutold_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 ecminvoiceoutolditems where id='" . $r ['ecminvoiceoutolditem_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,ecminvoiceoutolditem_id from ecminvoiceoutolditems where ecminvoiceoutold_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 ecminvoiceoutolds where ecminvoiceoutold_id='" . $this->id . "' and deleted='0'" ); while ( $r = $db->fetchByAssoc ( $w ) ) { $invs [] = "" . $r ['document_no'] . ""; } $the_array ['CORRECT'] = @implode ( ", ", $invs ); $the_array ['TOTAL'] = $this->total; $the_array ['PAID'] = "-"; 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, $canceled = 0) { global $app_list_strings; if ($canceled == 1) return ''; // else return ''; } 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->ecminvoiceoutold->document_no . '.pdf' ); } else $tmp = 'InvoiceOut ' . $tmp . '.pdf'; // $mod = return_module_language($current_language, 'EcmInvoiceOutOlds'); // 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::invoiceout ( from_html ( $the_query_string ) ); array_push ( $where_clauses, "ecminvoiceoutolds.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 ''; 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 = ''; } else { $tmp = ''; } } else if ($icon == 'download') { // download if ($this->ACLAccess ( 'pdf_toolbar' )) { $tmp = ''; } else { $tmp = ''; } } else if ($icon == 'duplicate') { // duplicate $tmp = ''; } else if ($icon == 'edit') { // edit if ($this->ACLAccess ( 'edit' ) && $this->status == "registered") $tmp = ''; else $tmp = ''; } else if ($icon == 'send_email') { // send_email if ($this->status == "accepted") $tmp = ''; else $tmp = ''; } else if ($icon == 'correct') { if ($this->status != "registered") $tmp = ''; else $tmp = ''; } else if ($icon == 'view') { $tmp = ''; } return $tmp; } function ListIconsView() { if (isset ( $_REQUEST ['module'] ) && $_REQUEST ['module'] != '' && isset ( $_REQUEST ['action'] )) { $module = $_REQUEST ['module']; $action = $_REQUEST ['action']; $glue = " "; $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 = " "; $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 = " "; $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 '' . implode ( $glue, $arr ) . ''; } return ''; } function save($check_notify = FALSE) { global $current_user; $db = $GLOBALS ['db']; if (($this->fetched_row && $this->fetched_row ['template_id'] != $this->template_id) || (empty ( $this->id ) || $this->id == '')) { if ($this->type == "normal") { $this->number = $this->generateNumber (); $this->document_no = 'FV ' . $this->formatNumber (); } else { $this->number = $this->generateNumberCorrect (); $this->document_no = 'FVKOR ' . $this->formatNumberCorrect (); } } $this->status = 'accepted'; $this->ecmpaymentcondition_text = EcmInvoiceOutOld::getTranslation ( 'EcmPaymentConditions', $this->ecmpaymentcondition_id, $this->ecmlanguage ); $this->ecmdeliverycondition_text = EcmInvoiceOutOld::getTranslation ( 'EcmDeliveryConditions', $this->ecmdeliverycondition_id, $this->ecmlanguage ); $return_id = parent::save ( $check_notify ); $this->savePositions ( $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 ecminvoiceoutolds where id='" . $return_id . "'" ) ); $subtotal = $this->getInvoiceSubtotal (); $total = $this->getInvoiceTotal (); $db->query ( "update ecminvoiceoutolds set total=$total where id='" . $return_id . "'" ); $db->query ( "update ecminvoiceoutolds set subtotal=$subtotal where id='" . $return_id . "'" ); // $total=$this->pdf_total; $res_count = $db->query ( "select id from ecmtransactions where record_id='" . $this->id . "' and deleted='0'" ); $count = $res_count->num_rows; $a = new Account (); $a->retrieve ( $this->parent_id ); if ($a->parent_id == '1249') { $t_parent_id = '1249'; $t_parent_name = 'Media Saturn Holding Polska Sp. z o.o.'; } else { $t_parent_id = $this->parent_id; $t_parent_name = $this->parent_name; } unset ( $a ); if ($count == 0) { $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,currency_id,currency_value)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->canceled . "','" . $this->assigned_user_id . "','" . $total . "','" . $t_parent_name . "','" . $t_parent_id . "','" . $this->payment_date . "','0','" . $this->paid . "','" . $this->register_date . "','" . $this->id . "','EcmInvoiceOutOlds','" . $this->currency_id . "','" . $this->currency_value . "')" ); } else { $db->query ( "update ecmtransactions set value=$total where record_id='" . $this->id . "'" ); } $this->CalculatePurchasePrices (); return $return_id; } // ***************************Start Managing Positions************************* // function constructInsertQuery($data, $table = '') { if ($table == '' && isset ( $this->object_name ) && $this->object_name != '') { $table = strtolower ( $this->object_name ) . "items"; } else return ""; $keys = array (); $values = array (); foreach ( $data as $key => $value ) { $keys [] = $key; if (is_array ( $value )) $values [] = $value [1] . str_replace ( "'", "\'", $value [0] ) . $value [1]; else $values [] = "'" . str_replace ( "'", "\'", $value ) . "'"; } $q = "insert into `$table` (`"; $q .= implode ( '`, `', $keys ); $q .= "`) values ("; $q .= implode ( ", ", $values ); $q .= ");"; return $q; } function savePositions($id = null, $position_list = null) { global $current_user, $timedate; if ($position_list == null) $position_list = $this->position_list; if ($id == null) $id = $this->id; if (count ( $position_list ) > 0) $this->deleteAssignedPositions ( $id ); $arr = array (); $position = 0; $t_position_list = $position_list; for($i = 0; $i < count ( $t_position_list ); $i ++) { if (mysql_num_rows ( $GLOBALS [db]->query ( "select id from ecminvoiceoutolditems where ecmproduct_id='" . $t_position_list [$i] ['id'] . "' and ecminvoiceoutold_id='" . $this->ecminvoiceoutold_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'], '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'], 'old_ecminvoiceoutolditem_id' => $p ['old_ecminvoiceoutolditem_id'] ); if ($p ['parent_doc_type'] == 'EcmStockDocOut') $this->wz_id = $p ['parent_doc_id']; if ($p ['item_id'] && $p ['item_id'] != "undefined") $arr ['ecminvoiceoutolditem_id'] = $p ['item_id']; $query = $this->constructInsertQuery ( $arr ); $this->db->query ( $query ); /* * echo '
P:' . var_export($p, true) . PHP_EOL . PHP_EOL; echo '
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 ecminvoiceoutolds_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 ecminvoiceoutolds_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 ecminvoiceoutolds where id='" . $id . "'" ) );
		$o->parent_name = $r ['document_no'];
		$o->parent_type = "EcmInvoiceOutOlds";
		
		$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 ecminvoiceoutolditems set purchase_price = '" . ($avg_pq / $avg_q) . "' where id = '" . $itemid . "'" );
		}
	}
	function getPosition($position, $stockOperations = false) {
		if (! is_array ( $position ))
			return '';
		
		global $timedate;
		
		$return_array = array ();
		
		if (false == $stockOperations) {
			
			// get ENG name
			$db = $GLOBALS ['db'];
			$en = $db->fetchByAssoc ( $db->query ( "SELECT short_description FROM ecmproduct_language_en_view WHERE ecmproduct_id='" . $position ['ecmproduct_id'] . "'" ) );
			$return_array ['name_en'] = $en ['short_description'];
			
			if ($return_array ['name_en'] == ' ')
				$return_array ['name_en'] = '';
			
			$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 ['subprice'] = $position ['subprice'];
			$return_array ['startprice'] = $position ['startprice'];
			$return_array ['discount'] = $position ['discount'];
			$return_array ['total'] = $position ['total'];
			$return_array ['subtotal'] = $position ['subtotal'];
			$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'];
			$return_array ['date_entered'] = $position ['date_entered'];
			$return_array ['old_ecminvoiceoutolditem_id'] = $position ['old_ecminvoiceoutolditem_id'];
			$return_array ['old_total'] = $position ['old_total'];
			$return_array ['old_subtotal'] = $position ['old_subtotal'];
			
			// 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'];
				
				// get values from previous corrects
				
				$cc = $GLOBALS ['db']->fetchByAssoc ( $GLOBALS ['db']->query ( "SELECT ii.startprice, ii.subprice, ii.price, ii.quantity, ii.discount, 
						ii.ecmvat_value, ii.ecmvat_id, ii.ecmvat_name FROM ecminvoiceoutolditems as ii
						 INNER JOIN ecminvoiceoutolds AS i ON i.id=ii.ecminvoiceoutold_id WHERE i.canceled='0' and ii.ecminvoiceoutolditem_id='" . $position ['id'] . "' ORDER BY ii.date_entered DESC LIMIT 0,1" ) );
				if ($cc ['subprice']) {
					$return_array ['startprice'] = $cc ['startprice'];
					$return_array ['subprice'] = $cc ['subprice'];
					$return_array ['price'] = $cc ['price'];
					$return_array ['quantity'] = $cc ['quantity'];
					$return_array ['discount'] = $cc ['discount'];
					$return_array ['vat_value'] = $cc ['ecmvat_value'];
					$return_array ['vat_id'] = $cc ['ecmvat_id'];
					$return_array ['vat_name'] = $cc ['ecmvat_name'];
				}
			} else {
				$return_array ['item_id'] = $position ['ecminvoiceoutolditem_id'];
			}
		} else {
			
			// echo '
' . var_export($position, true);
			// exit;
			
			$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['ecminvoiceoutolditem_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  ii.* FROM `ecmproducts` AS p JOIN `ecminvoiceoutolditems` AS ii ON p.`id` = ii.`ecmproduct_id` WHERE ii.`ecminvoiceoutold_id` = \'' . $this->id . '\' AND ii.deleted=\'0\' ORDER BY ii.`position` ASC;';
				// echo 'SELECT ii.*, p.`weight_netto` AS `netto_weight` FROM `ecmproducts` AS p JOIN `ecminvoiceoutolditems` AS ii ON p.`id` = ii.`ecmproduct_id` WHERE ii.`ecminvoiceoutold_id` = \'' . $this->id . '\' ORDER BY ii.`position` ASC;';
			} else {
				// $query = 'SELECT p.`origin_country_code`, p.`product_code`, ii.* FROM `ecmproducts` AS p JOIN `ecminvoiceoutolditems` AS ii ON p.`id` = ii.`ecmproduct_id` WHERE ii.`ecminvoiceoutold_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`, p.`weight_netto` AS `netto_weight` 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 ();
				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 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) {
		global $mod_strings;
		
		$arr = $this->template->getTemplateFile ( 'EcmInvoiceOuts' );
		
		// var_dump($type ? : $this->pdf_type); exit;
		
		switch (strtolower ( $type ?  : $this->pdf_type )) {
			case 'exp' :
				include_once ("modules/EcmDocumentTemplates/templates/" . $arr [0] . "/" . $arr [1] . "/subheader_exp.php");
				include_once ("modules/EcmDocumentTemplates/templates/" . $arr [0] . "/" . $arr [1] . "/subfooter_exp.php");
				
				break;
			case 'e' :
				include_once ("modules/EcmDocumentTemplates/templates/" . $arr [0] . "/" . $arr [1] . "/subheader_e.php");
				include_once ("modules/EcmDocumentTemplates/templates/" . $arr [0] . "/" . $arr [1] . "/subfooter_e.php");
				
				break;
			default :
			case 'k' :
				include_once ("modules/EcmDocumentTemplates/templates/" . $arr [0] . "/" . $arr [1] . "/subheader_k.php");
				include_once ("modules/EcmDocumentTemplates/templates/" . $arr [0] . "/" . $arr [1] . "/subfooter_k.php");
				
				break;
			case 'u' :
				include_once ("modules/EcmDocumentTemplates/templates/" . $arr [0] . "/" . $arr [1] . "/subheader_u.php");
				include_once ("modules/EcmDocumentTemplates/templates/" . $arr [0] . "/" . $arr [1] . "/subfooter_u.php");
				
				break;
			case 'pl' :
				include_once ("modules/EcmDocumentTemplates/templates/" . $arr [0] . "/" . $arr [1] . "/subheader_pl.php");
				include_once ("modules/EcmDocumentTemplates/templates/" . $arr [0] . "/" . $arr [1] . "/subfooter_pl.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, "EcmInvoiceOutOlds", $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 != '') {
			$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 ()), 'I' );
		}
	}
	function calculate($position_list, $format = false) {
		global $db;
		
		if (! is_array ( $position_list ))
			return false;
		
		$result = array (
				'total' => 0.0,
				'vats' => false,
				'subtotal' => 0.0,
				'draw_vat' => false,
				'draw_discount' => false,
				'draw_recipient_code' => false 
		);
		
		$vats = array ();
		
		$weight_netto = 0;
		
		foreach ( $position_list as $p ) {
			$w = $db->fetchByAssoc ( $db->query ( "SELECT weight_netto FROM ecmproducts WHERE id='" . $p ['id'] . "'" ) );
			$weight_netto += $w ['weight_netto'] * $p ['quantity'];
			
			if (! isset ( $vats [$p ['vat_id']] ))
				$vats [$p ['vat_id']] = 0;
			
			$p ['total'] = floatval ( $p ['price'] ) * floatval ( $p ['quantity'] );
			
			$vats [$p ['vat_id']] += floatval ( $p ['total'] );
			
			$result ['subtotal'] += floatval ( $p ['total'] );
			
			if (! $result ['draw_discount'] && floatval ( $p ['discount'] ) > 0)
				$result ['draw_discount'] = true;
			
			if (! $result ['draw_recipient_code'] && $p ['recipient_code'] != '')
				$result ['draw_recipient_code'] = true;
		}
		
		$result ['total'] = $result ['subtotal'];
		
		if (! $this->to_is_vat_free) {
			$vats2 = array ();
			
			foreach ( $vats as $key => $value ) {
				$r = $db->fetchByAssoc ( $db->query ( "select value from ecmvats where id='" . $key . "'" ) );
				$vva = $r ['value'];
				
				if (! $format) {
					$vats2 [$key] = floatval ( $value ) * (floatval ( $vva ) / 100);
				} else {
					$vats2 [$key] = format_number ( floatval ( $value ) * (floatval ( $vva ) / 100) );
				}
				
				$result ['total'] += floatval ( $value ) * (floatval ( $vva ) / 100);
			}
			
			$this->total;
			// die();
			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'] );
		}
		
		$result ['weight_netto'] = $weight_netto;
		
		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 ( "EcmInvoiceOutOlds", "invoiceout_", '', $app_list_strings ['moduleList'] ['EcmInvoiceOutOlds'] );
		$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_invoiceouts' );
		if (isset ( $cq ) && $cq) {
			$query = "UPDATE `ecminvoiceoutolds` 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 loadEcmInvoiceOutOld() {
		$this->ecminvoiceoutold = new EcmInvoiceOutOld ();
		if (isset ( $this->ecminvoiceoutold_id ) && $this->ecminvoiceoutold_id != '') {
			$this->ecminvoiceoutold->retrieve ( $this->ecminvoiceoutold_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
	function getCorrectInvoiceOldValues() {
		$db = $GLOBALS ['db'];
		global $datetime;
		
		$w = $db->query ( "select id, date_entered, subtotal,total ,ecminvoiceoutolditem_id, parent_doc_type from ecminvoiceoutolditems where ecminvoiceoutold_id='" . $this->id . "' AND deleted='0'" );
		while ( $r = $db->fetchByAssoc ( $w ) ) {
			// if ($r['parent_doc_type'] == 'EcmReturn')
			// TODO: return invoice old values search
			$oi = $db->fetchByAssoc ( $db->query ( "SELECT ii.id, ii.ecminvoiceoutold_id, ii.total,ii.subtotal, ii.quantity FROM ecminvoiceoutolditems as ii INNER JOIN ecminvoiceoutolds AS i ON i.id=ii.ecminvoiceoutold_id WHERE ii.date_entered < '" . $r ['date_entered'] . "' AND i.canceled='0' AND i.deleted='0' AND ii.ecminvoiceoutolditem_id='" . $r ['ecminvoiceoutolditem_id'] . "' AND ii.ecminvoiceoutold_id!='" . $this->id . "' order by ii.date_entered desc limit 0,1" ) );
			if ($oi && $oi ['id'] && $oi ['id'] != '') {
				// była wcześniejsza korekta
				if (( float ) $r ['subtotal'] == ( float ) $oi ['subtotal'])
					continue; // produkt nie był korygowany
						          // wpisz old_
				$db->query ( "UPDATE ecminvoiceoutolditems SET subtotal_corrected = '" . round ( floatval ( $r ['subtotal'] ) - floatval ( $oi ['old_subtotal'] ), 2 ) . "', old_subtotal='" . $oi ['subtotal'] . "', old_total='" . $oi ['total'] . "',old_quantity='" . $oi ['quantity'] . "', old_ecminvoiceoutolditem_id='" . $oi ['id'] . "' WHERE id='" . $r ['id'] . "'" );
			} else {
				// nie było korekty - weź dane z FV
				$oi = $db->fetchByAssoc ( $db->query ( "SELECT id, quantity, subtotal, total, ecminvoiceoutold_id FROM ecminvoiceoutolditems WHERE id='" . $r ['ecminvoiceoutolditem_id'] . "'" ) );
				if (( float ) $r ['subtotal'] == ( float ) $oi ['subtotal'])
					continue;
					// update old_
				$db->query ( "UPDATE ecminvoiceoutolditems SET subtotal_corrected = '" . round ( floatval ( $r ['subtotal'] ) - floatval ( $oi ['old_subtotal'] ), 2 ) . "', old_subtotal='" . $oi ['subtotal'] . "',old_total='" . $oi ['total'] . "', old_quantity='" . $oi ['quantity'] . "', old_ecminvoiceoutolditem_id='" . $oi ['id'] . "' WHERE id='" . $r ['id'] . "'" );
			}
		}
	}
	function getInvoiceSubtotal($search_old = true) {
		$db = $GLOBALS ['db'];
		
		$multi_correct = false;
		// is multi corect??
		$ret = $db->query ( "
SELECT distinct o.ecminvoiceoutold_id
FROM
    ecminvoiceoutolditems as ii
INNER JOIN ecminvoiceoutolds as i
ON ii.ecminvoiceoutold_id = i.id
INNER JOIN ecminvoiceoutolditems AS o
ON o.id = ii.ecminvoiceoutolditem_id
WHERE
    ii.ecminvoiceoutold_id = '" . $this->id . "'" );
		if ($ret->num_rows > 1) {
			$this->getMultiCorrectTotals ();
			// $multi_correct = true;
		}
		
		$subtotal = 0;
		if ($this->type == 'correct') {
			if ($search_old && ! $multi_correct)
				$this->getCorrectInvoiceOldValues ();
			$w = $db->query ( "select id, subtotal, old_subtotal, old_ecminvoiceoutolditem_id from ecminvoiceoutolditems where ecminvoiceoutold_id='" . $this->id . "' AND deleted='0'" );
			while ( $r = $db->fetchByAssoc ( $w ) ) {
				if (is_null ( $r ['old_ecminvoiceoutolditem_id'] ) || $r ['old_ecminvoiceoutolditem_id'] == '')
					continue; // ten produkt nie był korygowany
				$subtotal += $r ['subtotal'] - $r ['old_subtotal'];
			}
		} else {
			$w = $db->query ( "select subtotal from ecminvoiceoutolditems where ecminvoiceoutold_id='" . $this->id . "' AND deleted='0'" );
			while ( $r = $db->fetchByAssoc ( $w ) ) {
				$subtotal += $r ['subtotal'];
			}
		}
		return round ( $subtotal, 2 );
	}
	function getInvoiceTotal() {
		$db = $GLOBALS ['db'];
		$total = 0;
		if ($this->type == 'correct') {
			$w = $db->query ( "select id, total, old_total, old_ecminvoiceoutolditem_id from ecminvoiceoutolditems where ecminvoiceoutold_id='" . $this->id . "' AND deleted='0'" );
			while ( $r = $db->fetchByAssoc ( $w ) ) {
				if (is_null ( $r ['old_ecminvoiceoutolditem_id'] ) || $r ['old_ecminvoiceoutolditem_id'] == '')
					continue; // ten produkt nie był korygowany
				$total += ($r ['total'] - $r ['old_total']);
			}
		} else {
			$w = $db->query ( "select total from ecminvoiceoutolditems where ecminvoiceoutold_id='" . $this->id . "' AND deleted='0'" );
			while ( $r = $db->fetchByAssoc ( $w ) ) {
				$total += $r ['total'];
			}
		}
		return round ( $total, 2 );
	}
	function CalculatePurchasePrices() {
		$db = $GLOBALS ['db'];
		
		// update items
		if ($this->type == 'normal')
			$query = "
update 
    ecminvoiceoutolditems as ii
        inner join
    ecmstockdocoutitems as wi ON ii.parent_doc_item_id = wi.id
set
	ii.purchase_price = wi.price
where
    ii.ecminvoiceoutold_id = '$this->id';	
";
		else 
			$query = "
UPDATE ecminvoiceoutolditems AS ii
INNER JOIN ecminvoiceoutolds as i
ON ii.ecminvoiceoutold_id = i.id
INNER JOIN ecminvoiceoutolditems AS o
ON o.id = ii.ecminvoiceoutolditem_id
INNER JOIN ecmstockdocoutitems AS wi
ON wi.id = o.parent_doc_item_id
SET ii.purchase_price = wi.price
WHERE
    ii.ecminvoiceoutold_id = '".$this->id."';
";
		
		$db->query ( $query );
		
		// update purchase_price on invoice
		if ($this->type == 'normal')
			$r = $db->fetchByAssoc ( $db->query ( "SELECT sum(purchase_price*quantity) as sum FROM ecminvoiceoutolditems WHERE ecminvoiceoutold_id='$this->id' and deleted='0'" ) );
		else
			$r = $db->fetchByAssoc ( $db->query ( "SELECT sum(purchase_price*quantity_corrected) as sum FROM ecminvoiceoutolditems WHERE ecminvoiceoutold_id='$this->id' and deleted='0'" ) );
		$db->query ( "UPDATE ecminvoiceoutolds SET purchase_price='" . $r ['sum'] . "' WHERE id='$this->id'" );
	}
	function getMultiCorrectTotals() {
		$db = $GLOBALS ['db'];
		
		$res = $db->query ( "select id, old_ecminvoiceoutolditem_id as old, code, subtotal from ecminvoiceoutolditems where ecminvoiceoutold_id='" . $this->id . "' AND deleted='0'" );
		while ( $row = $db->fetchByAssoc ( $res ) ) {
			echo $row ['old_ecminvoiceoutolditem_id'];
			$ww = $db->fetchByAssoc ( $db->query ( "SELECT code, subprice,price,quantity,subtotal, total FROM ecminvoiceoutolditems WHERE id='" . $row ['old'] . "'" ) );
			if (! $ww ['subtotal'] || $ww ['subtotal'] == "" || $ww ['subtotal'] == 0)
				$ww ['subtotal'] = $ww ['subprice'] * $ww ['quantity'];
			if (! $ww ['total'] || $ww ['total'] == '')
				$ww ['total'] = $ww ['price'] * $ww ['quantity'];
			$db->query ( "UPDATE ecminvoiceoutolditems SET subtotal_corrected = '" . round ( floatval ( $row ['subtotal'] ) - floatval ( $oi ['old_subtotal'] ), 2 ) . "', old_subtotal='" . $ww ['subtotal'] . "', old_total='" . $ww ['total'] . "' WHERE id='" . $row ['id'] . "'" );
		}
	}
	
	// add mz 2012-05-21
	// for subpanels
	// public function get_parent_for_subpanel() {
	// return "SELECT
	// }
	// end mz
}