Heray-Was-Here
Server : Apache
System : Linux mail.lomejor.cr 6.8.0-1059-azure #65~22.04.1-Ubuntu SMP Thu May 28 16:59:19 UTC 2026 x86_64
User : www-data ( 33)
PHP Version : 8.2.31
Disable Function : NONE
Directory :  /var/www/erp/htdocs/custom/sydinitprocess/class/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/erp/htdocs/custom/sydinitprocess/class/sydinitprocess.class.php
<?php
	require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
	require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
	require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
	require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
	require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
	require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_expression.class.php';
	require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
	require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';

	class sydinitprocess extends CommonObject{
		var $expe='';
		var $dest='';
		var $message='';
		var $deferred='';
		var $priority='';
		var $class='';
		var $error;
        var $timeDrift = 0;
		
		function sydinitprocess($DB) {
		}
		public function UnvalidateCommande()
		{
			global $conf, $user ,$db, $langs;

			if(empty($conf->global->OFICOMER_MAX_TIME_COMMANDE)){
				$timedue = 2;
			}else{
				$timedue = $conf->global->OFICOMER_MAX_TIME_COMMANDE;
			}
			
			$sql = "SELECT c.rowid ";
			$sql .= " FROM " . MAIN_DB_PREFIX . "commande c  INNER JOIN " . MAIN_DB_PREFIX . "commande_extrafields ec ON (c.rowid = ec.fk_object )";
			$sql .= " WHERE c.fk_statut = 1 AND isnull(ec.ind_reserva) AND c.date_valid <= NOW() - INTERVAL ". $timedue ." HOUR";
			$result = $db->query($sql);
			$commande = new Commande($db);
			if ($result) {
				while ($obj = $db->fetch_object($result)) {
					$ret = $commande->fetch($obj->rowid);
					if( $ret > 0 ){
						$commande->setDraft($user);
					}else{
						$this->output = 'No encontrado pedido N.'.$obj->rowid;
						return -1;
					}
				}
			}else{
				$this->output = 'No encontrado registros';
				return -1;
			}
			
		}
		public function CustomerValidate( $notify = '' )
		{
			global $conf, $user ,$db, $langs, $mysoc;

			require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
			require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
			require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
			require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
			$formmail = new FormMail($db);

			$now = dol_now();
			// Load translation files required by the page
			$langs->loadLangs(array("compta", "bills", "other", "accountancy"));
			$chartaccountcode = dol_getIdFromCode($db, $conf->global->CHARTOFACCOUNTS, 'accounting_system', 'rowid', 'pcg_version');

			$error = 0;
			$nbbinddone = 0;
			$notpossible = 0;
			$this->output = '';
			$this->error = '';

			$db->begin();

			$accountingAccount = new AccountingAccount($db);

			// Customer Invoice lines (must be same request than into page list.php for manual binding)
			$sql = "SELECT f.rowid as facid, f.ref as ref, f.datef, f.type as ftype,";
			$sql .= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, l.vat_src_code,";
			$sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.tva_tx as tva_tx_prod,";
			if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
				$sql .= " ppe.accountancy_code_sell as code_sell, ppe.accountancy_code_sell_intra as code_sell_intra, ppe.accountancy_code_sell_export as code_sell_export,";
			} else {
				$sql .= " p.accountancy_code_sell as code_sell, p.accountancy_code_sell_intra as code_sell_intra, p.accountancy_code_sell_export as code_sell_export,";
			}
			$sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export, aa4.rowid as aarowid_thirdparty,";
			$sql .= " co.code as country_code, co.label as country_label,";
			$sql .= " s.tva_intra,";
			if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
				$sql .= " spe.accountancy_code_sell as company_code_sell";	// accounting code for product but stored on thirdparty
			} else {
				$sql .= " s.accountancy_code_sell as company_code_sell";	// accounting code for product but stored on thirdparty
			}
			$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
			$sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc";
			if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
				$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
			}
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON co.rowid = s.fk_pays ";
			$sql .= " INNER JOIN ".MAIN_DB_PREFIX."facturedet as l ON f.rowid = l.fk_facture";	// the main table
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = l.fk_product";
			if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
				$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
			}
			$alias_societe_perentity = empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED) ? "s" : "spe";
			$alias_product_perentity = empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED) ? "p" : "ppe";
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa  ON " . $alias_product_perentity . ".accountancy_code_sell = aa.account_number         AND aa.active = 1  AND aa.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa.entity = ".$conf->entity;
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa2 ON " . $alias_product_perentity . ".accountancy_code_sell_intra = aa2.account_number  AND aa2.active = 1 AND aa2.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa2.entity = ".$conf->entity;
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa3 ON " . $alias_product_perentity . ".accountancy_code_sell_export = aa3.account_number AND aa3.active = 1 AND aa3.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa3.entity = ".$conf->entity;
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa4 ON " . $alias_societe_perentity . ".accountancy_code_sell = aa4.account_number        AND aa4.active = 1 AND aa4.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa4.entity = ".$conf->entity;
			$sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0 AND l.product_type <= 2 AND f.entity = ".((int) $conf->entity);
			if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) {
				$sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'";
			}
			if ($validatemonth && $validateyear) {
				$sql .= dolSqlDateFilter('f.datef', 0, $validatemonth, $validateyear);
			}

			dol_syslog('htdocs/accountancy/customer/index.php');

			$result = $db->query($sql);
			if (!$result) {
				$error++;
				$this->output = $db->lasterror();
			} else {
				$num_lines = $db->num_rows($result);

				$facture_static = new Facture($db);

				$isSellerInEEC = isInEEC($mysoc);

				$thirdpartystatic = new Societe($db);
				$facture_static = new Facture($db);
				$facture_static_det = new FactureLigne($db);
				$product_static = new Product($db);

				$i = 0;
				while ($i < min($num_lines, 10000)) {	// No more than 10000 at once
					$objp = $db->fetch_object($result);

					$thirdpartystatic->id = $objp->socid;
					$thirdpartystatic->name = $objp->name;
					$thirdpartystatic->client = $objp->client;
					$thirdpartystatic->fournisseur = $objp->fournisseur;
					$thirdpartystatic->code_client = $objp->code_client;
					$thirdpartystatic->code_compta_client = $objp->code_compta_client;
					$thirdpartystatic->code_fournisseur = $objp->code_fournisseur;
					$thirdpartystatic->code_compta_fournisseur = $objp->code_compta_fournisseur;
					$thirdpartystatic->email = $objp->email;
					$thirdpartystatic->country_code = $objp->country_code;
					$thirdpartystatic->tva_intra = $objp->tva_intra;
					$thirdpartystatic->code_compta_product = $objp->company_code_sell;		// The accounting account for product stored on thirdparty object (for level3 suggestion)

					$product_static->ref = $objp->product_ref;
					$product_static->id = $objp->product_id;
					$product_static->type = $objp->type;
					$product_static->label = $objp->product_label;
					$product_static->status = $objp->status;
					$product_static->status_buy = $objp->status_buy;
					$product_static->accountancy_code_sell = $objp->code_sell;
					$product_static->accountancy_code_sell_intra = $objp->code_sell_intra;
					$product_static->accountancy_code_sell_export = $objp->code_sell_export;
					$product_static->accountancy_code_buy = $objp->code_buy;
					$product_static->accountancy_code_buy_intra = $objp->code_buy_intra;
					$product_static->accountancy_code_buy_export = $objp->code_buy_export;
					$product_static->tva_tx = $objp->tva_tx_prod;

					$facture_static->ref = $objp->ref;
					$facture_static->id = $objp->facid;
					$facture_static->type = $objp->ftype;
					$facture_static->date = $objp->datef;

					$facture_static_det->id = $objp->rowid;
					$facture_static_det->total_ht = $objp->total_ht;
					$facture_static_det->tva_tx = $objp->tva_tx_line;
					$facture_static_det->vat_src_code = $objp->vat_src_code;
					$facture_static_det->product_type = $objp->type_l;
					$facture_static_det->desc = $objp->description;

					$accountingAccountArray = array(
						'dom'=>$objp->aarowid,
						'intra'=>$objp->aarowid_intra,
						'export'=>$objp->aarowid_export,
						'thirdparty' =>$objp->aarowid_thirdparty);

					$code_sell_p_notset = '';
					$code_sell_t_notset = '';

					$suggestedid = 0;

					$return = $accountingAccount->getAccountingCodeToBind($thirdpartystatic, $mysoc, $product_static, $facture_static, $facture_static_det, $accountingAccountArray, 'customer');
					if (!is_array($return) && $return < 0) {
						$this->output = $accountingAccount->error ;
					} else {
						$suggestedid = $return['suggestedid'];
						$suggestedaccountingaccountfor = $return['suggestedaccountingaccountfor'];

						if (!empty($suggestedid) && $suggestedaccountingaccountfor != '' && $suggestedaccountingaccountfor != 'eecwithoutvatnumber') {
							$suggestedid = $return['suggestedid'];
						} else {
							$suggestedid = 0;
						}
					}

					if ($suggestedid > 0) {
						$sqlupdate = "UPDATE ".MAIN_DB_PREFIX."facturedet";
						$sqlupdate .= " SET fk_code_ventilation = ".((int) $suggestedid);
						$sqlupdate .= " WHERE fk_code_ventilation <= 0 AND product_type <= 2 AND rowid = ".((int) $facture_static_det->id);

						$resqlupdate = $db->query($sqlupdate);
						if (!$resqlupdate) {
							$error++;
							$this->output = $db->lasterror();
							break;
						} else {
							$nbbinddone++;
						}
					} else {
						$notpossible++;
					}

					$i++;
				}
				if ($num_lines > 10000) {
					$notpossible += ($num_lines - 10000);
				}
			}

			// Errors Recipient
			$errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
			$from = $conf->global->MAIN_MAIL_EMAIL_FROM;
			$sendTopic = 'Tarea automatica de vinculacion de facturas de cliente';

			if ($error) {
				$db->rollback();
				if (!empty($notify)) {
					$sendContent = $this->output;
					// Mail Creation
					$cMailFile = new CMailFile($sendTopic, $notify, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
					// Sending Mail
					$cMailFile->sendfile();
				}
				return $error;
			} else {
				$db->commit();
				$this->output = $langs->trans('AutomaticBindingDone', 	$nbbinddone, $notpossible);
				if ($notpossible >0 ){
					if (!empty($notify)) {
						$sendContent = $this->output;
						// Mail Creation
						$cMailFile = new CMailFile($sendTopic, $notify, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
						// Sending Mail
						$cMailFile->sendfile();
					}
				}
				return 0;
			}
		}
		public function SupplierValidate( $notify = '' )
		{
			global $conf, $user ,$db, $langs, $mysoc;

			require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
			require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
			require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
			require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
			$formmail = new FormMail($db);
			$chartaccountcode = dol_getIdFromCode($db, $conf->global->CHARTOFACCOUNTS, 'accounting_system', 'rowid', 'pcg_version');
			$now = dol_now();
			// Load translation files required by the page
			$langs->loadLangs(array("compta", "bills", "other", "accountancy"));

			$error = 0;
			$nbbinddone = 0;
			$notpossible = 0;
			$this->output = '';
			$this->error = '';

			$db->begin();

			$accountingAccount = new AccountingAccount($db);

			// Supplier Invoice Lines (must be same request than into page list.php for manual binding)
			$sql = "SELECT f.rowid as facid, f.ref, f.ref_supplier, f.libelle as invoice_label, f.datef, f.type as ftype,";
			$sql .= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, l.vat_src_code,";
			$sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.tva_tx as tva_tx_prod,";
			if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
				$sql .= " ppe.accountancy_code_buy as code_buy, ppe.accountancy_code_buy_intra as code_buy_intra, ppe.accountancy_code_buy_export as code_buy_export,";
			} else {
				$sql .= " p.accountancy_code_buy as code_buy, p.accountancy_code_buy_intra as code_buy_intra, p.accountancy_code_buy_export as code_buy_export,";
			}
			$sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export, aa4.rowid as aarowid_thirdparty,";
			$sql .= " co.code as country_code, co.label as country_label,";
			$sql .= " s.tva_intra,";
			if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
				$sql .= " spe.accountancy_code_buy as company_code_buy";
			} else {
				$sql .= " s.accountancy_code_buy as company_code_buy";
			}
			$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
			$sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc";
			if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
				$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
			}
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON co.rowid = s.fk_pays ";
			$sql .= " INNER JOIN ".MAIN_DB_PREFIX."facture_fourn_det as l ON f.rowid = l.fk_facture_fourn";
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = l.fk_product";
			if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
				$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
			}
			$alias_societe_perentity = empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED) ? "s" : "spe";
			$alias_product_perentity = empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED) ? "p" : "ppe";
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa  ON " . $alias_product_perentity . ".accountancy_code_buy = aa.account_number         AND aa.active = 1  AND aa.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa.entity = ".$conf->entity;
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa2 ON " . $alias_product_perentity . ".accountancy_code_buy_intra = aa2.account_number  AND aa2.active = 1 AND aa2.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa2.entity = ".$conf->entity;
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa3 ON " . $alias_product_perentity . ".accountancy_code_buy_export = aa3.account_number AND aa3.active = 1 AND aa3.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa3.entity = ".$conf->entity;
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa4 ON " . $alias_societe_perentity . ".accountancy_code_buy = aa4.account_number        AND aa4.active = 1 AND aa4.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa4.entity = ".$conf->entity;
			$sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0 AND l.product_type <= 2 AND f.entity = ".((int) $conf->entity);
			if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) {
				$sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'";
			}
			if ($validatemonth && $validateyear) {
				$sql .= dolSqlDateFilter('f.datef', 0, $validatemonth, $validateyear);
			}

			dol_syslog('htdocs/accountancy/supplier/index.php');

			$result = $db->query($sql);
			if (!$result) {
				$error++;
				$this->output = $db->lasterror();
			} else {
				$num_lines = $db->num_rows($result);

				$isBuyerInEEC = isInEEC($mysoc);

				$thirdpartystatic = new Societe($db);
				$facture_static = new FactureFournisseur($db);
				$facture_static_det = new SupplierInvoiceLine($db);
				$product_static = new Product($db);

				$i = 0;
				while ($i < min($num_lines, 10000)) {	// No more than 10000 at once
					$objp = $db->fetch_object($result);

					$thirdpartystatic->id = $objp->socid;
					$thirdpartystatic->name = $objp->name;
					$thirdpartystatic->client = $objp->client;
					$thirdpartystatic->fournisseur = $objp->fournisseur;
					$thirdpartystatic->code_client = $objp->code_client;
					$thirdpartystatic->code_compta_client = $objp->code_compta_client;
					$thirdpartystatic->code_fournisseur = $objp->code_fournisseur;
					$thirdpartystatic->code_compta_fournisseur = $objp->code_compta_fournisseur;
					$thirdpartystatic->email = $objp->email;
					$thirdpartystatic->country_code = $objp->country_code;
					$thirdpartystatic->tva_intra = $objp->tva_intra;
					$thirdpartystatic->code_compta_product = $objp->company_code_buy;		// The accounting account for product stored on thirdparty object (for level3 suggestion)

					$product_static->ref = $objp->product_ref;
					$product_static->id = $objp->product_id;
					$product_static->type = $objp->type;
					$product_static->label = $objp->product_label;
					$product_static->status = $objp->status;
					$product_static->status_buy = $objp->status_buy;
					$product_static->accountancy_code_sell = $objp->code_sell;
					$product_static->accountancy_code_sell_intra = $objp->code_sell_intra;
					$product_static->accountancy_code_sell_export = $objp->code_sell_export;
					$product_static->accountancy_code_buy = $objp->code_buy;
					$product_static->accountancy_code_buy_intra = $objp->code_buy_intra;
					$product_static->accountancy_code_buy_export = $objp->code_buy_export;
					$product_static->tva_tx = $objp->tva_tx_prod;

					$facture_static->ref = $objp->ref;
					$facture_static->id = $objp->facid;
					$facture_static->type = $objp->ftype;
					$facture_static->date = $objp->datef;

					$facture_static_det->id = $objp->rowid;
					$facture_static_det->total_ht = $objp->total_ht;
					$facture_static_det->tva_tx = $objp->tva_tx_line;
					$facture_static_det->vat_src_code = $objp->vat_src_code;
					$facture_static_det->product_type = $objp->type_l;
					$facture_static_det->desc = $objp->description;

					$accountingAccountArray = array(
						'dom'=>$objp->aarowid,
						'intra'=>$objp->aarowid_intra,
						'export'=>$objp->aarowid_export,
						'thirdparty' =>$objp->aarowid_thirdparty);

					$code_buy_p_notset = '';
					$code_buy_t_notset = '';

					$suggestedid = 0;

					$return = $accountingAccount->getAccountingCodeToBind($mysoc, $thirdpartystatic, $product_static, $facture_static, $facture_static_det, $accountingAccountArray, 'supplier');
					if (!is_array($return) && $return<0) {
						$this->output = $accountingAccount->error ;
					} else {
						$suggestedid = $return['suggestedid'];
						$suggestedaccountingaccountfor = $return['suggestedaccountingaccountfor'];

						if (!empty($suggestedid) && $suggestedaccountingaccountfor != '' && $suggestedaccountingaccountfor != 'eecwithoutvatnumber') {
							$suggestedid = $return['suggestedid'];
						} else {
							$suggestedid = 0;
						}
					}

					if ($suggestedid > 0) {
						$sqlupdate = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det";
						$sqlupdate .= " SET fk_code_ventilation = ".((int) $suggestedid);
						$sqlupdate .= " WHERE fk_code_ventilation <= 0 AND product_type <= 2 AND rowid = ".((int) $facture_static_det->id);

						$resqlupdate = $db->query($sqlupdate);
						if (!$resqlupdate) {
							$error++;
							$this->output = $db->lasterror();
							break;
						} else {
							$nbbinddone++;
						}
					} else {
						$notpossible++;
					}

					$i++;
				}
				if ($num_lines > 10000) {
					$notpossible += ($num_lines - 10000);
				}
			}
			// Errors Recipient
			$errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
			$from = $conf->global->MAIN_MAIL_EMAIL_FROM;
			$sendTopic = 'Tarea automatica de vinculacion de facturas de proveedor';

			if ($error) {
				$db->rollback();
				if (!empty($notify)) {
					$sendContent = $this->output;
					// Mail Creation
					$cMailFile = new CMailFile($sendTopic, $notify, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
					// Sending Mail
					$cMailFile->sendfile();
				}
				return $error;
			} else {
				$db->commit();
				$this->output = $langs->trans('AutomaticBindingDone', 	$nbbinddone, $notpossible);
				if ($notpossible >0 ){
					if (!empty($notify)) {
						$sendContent = $this->output;
						// Mail Creation
						$cMailFile = new CMailFile($sendTopic, $notify, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
						// Sending Mail
						$cMailFile->sendfile();
					}
				}
				return 0;
			}
		}
		public function SellsJournal( $notify = '' )
		{
			global $conf, $user ,$db, $langs, $mysoc;

			require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
			require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
			require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
			require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
			require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
			require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
			require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';

			$langs->loadLangs(array("commercial", "compta", "bills", "other", "accountancy", "errors"));

			$id_journal = 1;
			$action = 'writebookkeeping';

			$accountingaccount = new AccountingAccount($db);

			// Get informations of journal
			$accountingjournalstatic = new AccountingJournal($db);
			$accountingjournalstatic->fetch($id_journal);
			$journal = $accountingjournalstatic->code;
			$journal_label = $accountingjournalstatic->label;

			$sql = "SELECT f.rowid, f.ref, f.type, f.datef as df, f.ref_client, f.date_lim_reglement as dlr, f.close_code,";
			$sql .= " fd.rowid as fdid, fd.description, fd.product_type, fd.total_ht, fd.total_tva, fd.total_localtax1, fd.total_localtax2, fd.tva_tx, fd.total_ttc, fd.situation_percent, fd.vat_src_code,";
			$sql .= " s.rowid as socid, s.nom as name, s.code_client, s.code_fournisseur,";
			if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
				$sql .= " spe.accountancy_code_customer as code_compta,";
				$sql .= " spe.accountancy_code_supplier as code_compta_fournisseur,";
			} else {
				$sql .= " s.code_compta as code_compta,";
				$sql .= " s.code_compta_fournisseur,";
			}
			$sql .= " p.rowid as pid, p.ref as pref, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte,";
			if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
				$sql .= " ppe.accountancy_code_sell";
			} else {
				$sql .= " p.accountancy_code_sell";
			}
			$sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product";
			if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
				$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
			}
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
			$sql .= " JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
			$sql .= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc";
			if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
				$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
			}
			$sql .= " WHERE fd.fk_code_ventilation > 0";
			$sql .= " AND f.entity IN (".getEntity('invoice', 0).')'; // We don't share object for accountancy, we use source object sharing
			$sql .= " AND f.fk_statut > 0";
			if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {	// Non common setup
				$sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")";
			} else {
				$sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")";
			}
			$sql .= " AND fd.product_type IN (0,1)";
			if ($date_start && $date_end) {
				$sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
			}
			// Define begin binding date
			if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) {
				$sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'";
			}
			$sql .= " AND f.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
			$sql .= " ORDER BY f.datef";
			//print $sql; exit;

			dol_syslog('accountancy/journal/sellsjournal.php', LOG_DEBUG);
			$result = $db->query($sql);
			if ($result) {
				$tabfac = array();
				$tabht = array();
				$tabtva = array();
				$def_tva = array();
				$tabttc = array();
				$tablocaltax1 = array();
				$tablocaltax2 = array();
				$tabcompany = array();
			
				$num = $db->num_rows($result);
			
				// Variables
				$cptcli = (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER != "")) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : 'NotDefined';
				$cpttva = (!empty($conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT : 'NotDefined';
			
				$i = 0;
				while ($i < $num) {
					$obj = $db->fetch_object($result);
			
					// Controls
					$compta_soc = (!empty($obj->code_compta)) ? $obj->code_compta : $cptcli;
			
					$compta_prod = $obj->compte;
					if (empty($compta_prod)) {
						if ($obj->product_type == 0) {
							$compta_prod = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : 'NotDefined';
						} else {
							$compta_prod = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : 'NotDefined';
						}
					}
			
					$vatdata = getTaxesFromId($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), $mysoc, $mysoc, 0);
					$compta_tva = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
					$compta_localtax1 = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
					$compta_localtax2 = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
			
					// Define array to display all VAT rates that use this accounting account $compta_tva
					if (price2num($obj->tva_tx) || !empty($obj->vat_src_code)) {
						$def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : '')] = (vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''));
					}
			
					$line = new FactureLigne($db);
					$line->fetch($obj->fdid);
			
					// Situation invoices handling
					$prev_progress = $line->get_prev_progress($obj->rowid);
			
					if ($obj->type == Facture::TYPE_SITUATION) {
						// Avoid divide by 0
						if ($obj->situation_percent == 0) {
							$situation_ratio = 0;
						} else {
							$situation_ratio = ($obj->situation_percent - $prev_progress) / $obj->situation_percent;
						}
					} else {
						$situation_ratio = 1;
					}
			
					// Invoice lines
					$tabfac[$obj->rowid]["date"] = $db->jdate($obj->df);
					$tabfac[$obj->rowid]["datereg"] = $db->jdate($obj->dlr);
					$tabfac[$obj->rowid]["ref"] = $obj->ref;
					$tabfac[$obj->rowid]["type"] = $obj->type;
					$tabfac[$obj->rowid]["description"] = $obj->label_compte;
					$tabfac[$obj->rowid]["close_code"] = $obj->close_code; // close_code = 'replaced' for replacement invoices (not used in most european countries)
					//$tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid;
			
					// Avoid warnings
					if (!isset($tabttc[$obj->rowid][$compta_soc])) {
						$tabttc[$obj->rowid][$compta_soc] = 0;
					}
					if (!isset($tabht[$obj->rowid][$compta_prod])) {
						$tabht[$obj->rowid][$compta_prod] = 0;
					}
					if (!isset($tabtva[$obj->rowid][$compta_tva])) {
						$tabtva[$obj->rowid][$compta_tva] = 0;
					}
					if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
						$tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
					}
					if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
						$tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
					}
			
					$tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio;
					$tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
					if (empty($line->tva_npr)) {
						$tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio; // We ignore line if VAT is a NPR
					}
					$tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1 * $situation_ratio;
					$tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2 * $situation_ratio;
					$tabcompany[$obj->rowid] = array(
						'id' => $obj->socid,
						'name' => $obj->name,
						'code_client' => $obj->code_client,
						'code_compta' => $compta_soc
					);
			
					$i++;
				}
			} else {
				dol_print_error($db);
			}
			
			$errorforinvoice = array();
			
			// Loop in invoices to detect lines with not binding lines
			foreach ($tabfac as $key => $val) {		// Loop on each invoice
				$sql = "SELECT COUNT(fd.rowid) as nb";
				$sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
				$sql .= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
				$sql .= " AND fd.total_ttc <> 0 AND fk_facture = ".((int) $key);
				$resql = $db->query($sql);
				if ($resql) {
					$obj = $db->fetch_object($resql);
					if ($obj->nb > 0) {
						$errorforinvoice[$key] = 'somelinesarenotbound';
					}
				} else {
					dol_print_error($db);
				}
			}
			//var_dump($errorforinvoice);exit;
			
			// Bookkeeping Write
			if ($action == 'writebookkeeping') {
				$now = dol_now();
				$error = 0;
			
				$companystatic = new Societe($db);
				$invoicestatic = new Facture($db);
				$accountingaccountcustomer = new AccountingAccount($db);
			
				$accountingaccountcustomer->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER, true);
			
				foreach ($tabfac as $key => $val) {		// Loop on each invoice
					$errorforline = 0;
			
					$totalcredit = 0;
					$totaldebit = 0;
			
					$db->begin();
			
					$companystatic->id = $tabcompany[$key]['id'];
					$companystatic->name = $tabcompany[$key]['name'];
					$companystatic->code_compta = $tabcompany[$key]['code_compta'];
					$companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
					$companystatic->code_client = $tabcompany[$key]['code_client'];
					$companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
					$companystatic->client = 3;
			
					$invoicestatic->id = $key;
					$invoicestatic->ref = (string) $val["ref"];
					$invoicestatic->type = $val["type"];
					$invoicestatic->close_code = $val["close_code"];
			
					$date = dol_print_date($val["date"], 'day');
			
					// Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
					$replacedinvoice = 0;
					if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
						$replacedinvoice = 1;
						$alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
						if ($alreadydispatched) {
							$replacedinvoice = 2;
						}
					}
			
					// If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
					if ($replacedinvoice == 1) {
						$db->rollback();
						continue;
					}
			
					// Error if some lines are not binded/ready to be journalized
					if ($errorforinvoice[$key] == 'somelinesarenotbound') {
						$error++;
						$errorforline++;
						$this->output = $langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $val['ref']);
					}
			
					// Thirdparty
					if (!$errorforline) {
						foreach ($tabttc[$key] as $k => $mt) {
							$bookkeeping = new BookKeeping($db);
							$bookkeeping->doc_date = $val["date"];
							$bookkeeping->date_lim_reglement = $val["datereg"];
							$bookkeeping->doc_ref = $val["ref"];
							$bookkeeping->date_creation = $now;
							$bookkeeping->doc_type = 'customer_invoice';
							$bookkeeping->fk_doc = $key;
							$bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
							$bookkeeping->thirdparty_code = $companystatic->code_client;
			
							$bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
							$bookkeeping->subledger_label = $tabcompany[$key]['name'];
			
							$bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
							$bookkeeping->label_compte = $accountingaccountcustomer->label;
			
							$bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$langs->trans("SubledgerAccount");
							$bookkeeping->montant = $mt;
							$bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
							$bookkeeping->debit = ($mt >= 0) ? $mt : 0;
							$bookkeeping->credit = ($mt < 0) ? -$mt : 0;
							$bookkeeping->code_journal = $journal;
							$bookkeeping->journal_label = $langs->transnoentities($journal_label);
							$bookkeeping->fk_user_author = $user->id;
							$bookkeeping->entity = $conf->entity;
			
							$totaldebit += $bookkeeping->debit;
							$totalcredit += $bookkeeping->credit;
			
							$result = $bookkeeping->create($user);
							if ($result < 0) {
								if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
									$error++;
									$errorforline++;
									$errorforinvoice[$key] = 'alreadyjournalized';
									$this->output = 'Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded';
								} else {
									echo '<pre>';var_dump($bookkeeping);
									$error++;
									$errorforline++;
									$errorforinvoice[$key] = 'other';
									$this->output = $bookkeeping->error;
								}
								
							}
						}
					}
			
					// Product / Service
					if (!$errorforline) {
						foreach ($tabht[$key] as $k => $mt) {
							$resultfetch = $accountingaccount->fetch(null, $k, true);	// TODO Use a cache
							$label_account = $accountingaccount->label;
			
							// get compte id and label
							if ($resultfetch > 0) {
								$bookkeeping = new BookKeeping($db);
								$bookkeeping->doc_date = $val["date"];
								$bookkeeping->date_lim_reglement = $val["datereg"];
								$bookkeeping->doc_ref = $val["ref"];
								$bookkeeping->date_creation = $now;
								$bookkeeping->doc_type = 'customer_invoice';
								$bookkeeping->fk_doc = $key;
								$bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
								$bookkeeping->thirdparty_code = $companystatic->code_client;
			
								$bookkeeping->subledger_account = '';
								$bookkeeping->subledger_label = '';
			
								$bookkeeping->numero_compte = $k;
								$bookkeeping->label_compte = $label_account;
			
								$bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$label_account;
								$bookkeeping->montant = $mt;
								$bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
								$bookkeeping->debit = ($mt < 0) ? -$mt : 0;
								$bookkeeping->credit = ($mt >= 0) ? $mt : 0;
								$bookkeeping->code_journal = $journal;
								$bookkeeping->journal_label = $langs->transnoentities($journal_label);
								$bookkeeping->fk_user_author = $user->id;
								$bookkeeping->entity = $conf->entity;
			
								$totaldebit += $bookkeeping->debit;
								$totalcredit += $bookkeeping->credit;
			
								$result = $bookkeeping->create($user);
								if ($result < 0) {
									if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
										$error++;
										$errorforline++;
										$errorforinvoice[$key] = 'alreadyjournalized';
										$this->output = 'Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded';
									} else {
										$error++;
										$errorforline++;
										$errorforinvoice[$key] = 'other';
										$this->output = $bookkeeping->error;
									}
								}
							}
						}
					}
			
					// VAT
					if (!$errorforline) {
						$listoftax = array(0, 1, 2);
						foreach ($listoftax as $numtax) {
							$arrayofvat = $tabtva;
							if ($numtax == 1) {
								$arrayofvat = $tablocaltax1;
							}
							if ($numtax == 2) {
								$arrayofvat = $tablocaltax2;
							}
			
							foreach ($arrayofvat[$key] as $k => $mt) {
								if ($mt) {
									$accountingaccount->fetch($k, null, true);	// TODO Use a cache for label
									$label_account = $accountingaccount->label;
			
									$bookkeeping = new BookKeeping($db);
									$bookkeeping->doc_date = $val["date"];
									$bookkeeping->date_lim_reglement = $val["datereg"];
									$bookkeeping->doc_ref = $val["ref"];
									$bookkeeping->date_creation = $now;
									$bookkeeping->doc_type = 'customer_invoice';
									$bookkeeping->fk_doc = $key;
									$bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
									$bookkeeping->thirdparty_code = $companystatic->code_client;
			
									$bookkeeping->subledger_account = '';
									$bookkeeping->subledger_label = '';
			
									$bookkeeping->numero_compte = $k;
									$bookkeeping->label_compte = $label_account;
			
									$bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
									$bookkeeping->montant = $mt;
									$bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
									$bookkeeping->debit = ($mt < 0) ? -$mt : 0;
									$bookkeeping->credit = ($mt >= 0) ? $mt : 0;
									$bookkeeping->code_journal = $journal;
									$bookkeeping->journal_label = $langs->transnoentities($journal_label);
									$bookkeeping->fk_user_author = $user->id;
									$bookkeeping->entity = $conf->entity;
			
									$totaldebit += $bookkeeping->debit;
									$totalcredit += $bookkeeping->credit;
			
									$result = $bookkeeping->create($user);
									if ($result < 0) {
										if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
											$error++;
											$errorforline++;
											$errorforinvoice[$key] = 'alreadyjournalized';
											$this->output = 'Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded';
										} else {
											$error++;
											$errorforline++;
											$errorforinvoice[$key] = 'other';
											$this->output = $bookkeeping->error;
										}
									}
								}
							}
						}
					}

					// Protection against a bug on lines before
					if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
						$error++;
						$errorforline++;
						$errorforinvoice[$key] = 'amountsnotbalanced';
						$this->output = 'Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.';
					}

					// Errors Recipient
					$errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
					$from = $conf->global->MAIN_MAIL_EMAIL_FROM;
					$sendTopic = 'Tarea automatica de mayorizacion de facturas de cliente';
					if (!$errorforline) {
						$db->commit();
					} else {
						$db->rollback();
						if ($error >= 10) {
							$this->output = $langs->trans("ErrorTooManyErrorsProcessStopped");
						}
						if (!empty($notify)) {
							$sendContent = $this->output;
							// Mail Creation
							$cMailFile = new CMailFile($sendTopic, $notify, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
							// Sending Mail
							$cMailFile->sendfile();
						}
						$this->error = $this->output;
						return $error;
					}
				}
				if (!$error){
					return 0;
				}
			}
		}
		public function PurchasesJournal( $notify = '' )
		{
			global $conf, $user ,$db, $langs, $mysoc;

			require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
			require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
			require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
			require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
			require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
			require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
			require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';

			// Load translation files required by the page
			$langs->loadLangs(array("commercial", "compta", "bills", "other", "accountancy", "errors"));

			$id_journal =2;
			$action = 'writebookkeeping';
			$this->output ='';
			$accountingaccount = new AccountingAccount($db);

			// Get informations of journal
			$accountingjournalstatic = new AccountingJournal($db);
			$accountingjournalstatic->fetch($id_journal);
			$journal = $accountingjournalstatic->code;
			$journal_label = $accountingjournalstatic->label;
			
			$sql = "SELECT f.rowid, f.ref as ref, f.type, f.datef as df, f.libelle,f.ref_supplier, f.date_lim_reglement as dlr, f.close_code,";
			$sql .= " fd.rowid as fdid, fd.description, fd.product_type, fd.total_ht, fd.tva as total_tva, fd.total_localtax1, fd.total_localtax2, fd.tva_tx, fd.total_ttc, fd.vat_src_code,";
			$sql .= " s.rowid as socid, s.nom as name, s.fournisseur, s.code_client, s.code_fournisseur,";
			if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
				$sql .= " spe.accountancy_code_customer as code_compta,";
				$sql .= " spe.accountancy_code_supplier as code_compta_fournisseur,";
			} else {
				$sql .= " s.code_compta as code_compta,";
				$sql .= " s.code_compta_fournisseur,";
			}
			if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
				$sql .= " ppe.accountancy_code_buy,";
			} else {
				$sql .= " p.accountancy_code_buy,";
			}
			$sql .= " aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte";
			$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as fd";
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product";
			if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
				$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
			}
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
			$sql .= " JOIN ".MAIN_DB_PREFIX."facture_fourn as f ON f.rowid = fd.fk_facture_fourn";
			$sql .= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc";
			if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
				$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
			}
			$sql .= " WHERE f.fk_statut > 0";
			$sql .= " AND fd.fk_code_ventilation > 0";
			$sql .= " AND f.entity IN (".getEntity('facture_fourn', 0).")"; // We don't share object for accountancy
			if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
				$sql .= " AND f.type IN (".FactureFournisseur::TYPE_STANDARD.",".FactureFournisseur::TYPE_REPLACEMENT.",".FactureFournisseur::TYPE_CREDIT_NOTE.",".FactureFournisseur::TYPE_SITUATION.")";
			} else {
				$sql .= " AND f.type IN (".FactureFournisseur::TYPE_STANDARD.",".FactureFournisseur::TYPE_REPLACEMENT.",".FactureFournisseur::TYPE_CREDIT_NOTE.",".FactureFournisseur::TYPE_DEPOSIT.",".FactureFournisseur::TYPE_SITUATION.")";
			}
			if ($date_start && $date_end) {
				$sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
			}
			// Define begin binding date
			if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) {
				$sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'";
			}

			$sql .= " AND f.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='supplier_invoice')";
			$sql .= " ORDER BY f.datef";

			dol_syslog('accountancy/journal/purchasesjournal.php', LOG_DEBUG);
			$result = $db->query($sql);
			if ($result) {
				$tabfac = array();
				$tabht = array();
				$tabtva = array();
				$def_tva = array();
				$tabttc = array();
				$tablocaltax1 = array();
				$tablocaltax2 = array();
				$tabcompany = array();
				$tabother = array();
			
				$num = $db->num_rows($result);
			
				// Variables
				$cptfour = ($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER != "") ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : 'NotDefined';
				$cpttva = (!empty($conf->global->ACCOUNTING_VAT_BUY_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_BUY_ACCOUNT : 'NotDefined';
			
				$i = 0;
				while ($i < $num) {
					$obj = $db->fetch_object($result);
			
					// Controls
					$compta_soc = ($obj->code_compta_fournisseur != "") ? $obj->code_compta_fournisseur : $cptfour;
			
					$compta_prod = $obj->compte;
					if (empty($compta_prod)) {
						if ($obj->product_type == 0) {
							$compta_prod = (!empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT : 'NotDefined';
						} else {
							$compta_prod = (!empty($conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT : 'NotDefined';
						}
					}
			
					$vatdata = getTaxesFromId($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), $mysoc, $mysoc, 0);
					$compta_tva = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $cpttva);
					$compta_localtax1 = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $cpttva);
					$compta_localtax2 = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $cpttva);
					$compta_counterpart_tva_npr = (!empty($conf->global->ACCOUNTING_COUNTERPART_VAT_NPR)) ? $conf->global->ACCOUNTING_COUNTERPART_VAT_NPR : 'NotDefined';
			
					// Define array to display all VAT rates that use this accounting account $compta_tva
					if (price2num($obj->tva_tx) || !empty($obj->vat_src_code)) {
						$def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : '')] = (vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''));
					}
			
					$line = new SupplierInvoiceLine($db);
					$line->fetch($obj->fdid);
			
					$tabfac[$obj->rowid]["date"] = $db->jdate($obj->df);
					$tabfac[$obj->rowid]["datereg"] = $db->jdate($obj->dlr);
					$tabfac[$obj->rowid]["ref"] = $obj->ref_supplier.' ('.$obj->ref.')';
					$tabfac[$obj->rowid]["refsologest"] = $obj->ref;
					$tabfac[$obj->rowid]["refsuppliersologest"] = $obj->ref_supplier;
					$tabfac[$obj->rowid]["type"] = $obj->type;
					$tabfac[$obj->rowid]["description"] = $obj->description;
					$tabfac[$obj->rowid]["close_code"] = $obj->close_code; // close_code = 'replaced' for replacement invoices (not used in most european countries)
					//$tabfac[$obj->rowid]["fk_facturefourndet"] = $obj->fdid;
			
					// Avoid warnings
					if (!isset($tabttc[$obj->rowid][$compta_soc])) {
						$tabttc[$obj->rowid][$compta_soc] = 0;
					}
					if (!isset($tabht[$obj->rowid][$compta_prod])) {
						$tabht[$obj->rowid][$compta_prod] = 0;
					}
					if (!isset($tabtva[$obj->rowid][$compta_tva])) {
						$tabtva[$obj->rowid][$compta_tva] = 0;
					}
					if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
						$tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
					}
					if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
						$tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
					}
			
					$tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc;
					$tabht[$obj->rowid][$compta_prod] += $obj->total_ht;
					$tabtva[$obj->rowid][$compta_tva] += $obj->total_tva;
					if (!empty($line->tva_npr)) {	// Add an entry for counterpart
						$tabother[$obj->rowid][$compta_counterpart_tva_npr] += $obj->total_tva;
					}
					$tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1;
					$tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2;
					$tabcompany[$obj->rowid] = array(
							'id' => $obj->socid,
							'name' => $obj->name,
							'code_fournisseur' => $obj->code_fournisseur,
							'code_compta_fournisseur' => $compta_soc
						);
			
					$i++;
				}
			} else {
				dol_print_error($db);
			}
			
			$errorforinvoice = array();
			
			// Loop in invoices to detect lines with not binding lines
			foreach ($tabfac as $key => $val) {		// Loop on each invoice
				$sql = "SELECT COUNT(fd.rowid) as nb";
				$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as fd";
				$sql .= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
				$sql .= " AND fd.total_ttc <> 0 AND fk_facture_fourn = ".((int) $key);
				$resql = $db->query($sql);
				if ($resql) {
					$obj = $db->fetch_object($resql);
					if ($obj->nb > 0) {
						$errorforinvoice[$key] = 'somelinesarenotbound';
					}
				} else {
					dol_print_error($db);
				}
			}
			//var_dump($errorforinvoice);exit;

			// Bookkeeping Write
			if ($action == 'writebookkeeping') {
				$now = dol_now();
				$error = 0;
			
				$companystatic = new Societe($db);
				$invoicestatic = new FactureFournisseur($db);
				$accountingaccountsupplier = new AccountingAccount($db);
			
				$accountingaccountsupplier->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER, true);
			
				foreach ($tabfac as $key => $val) {		// Loop on each invoice
					$errorforline = 0;
			
					$totalcredit = 0;
					$totaldebit = 0;
			
					$db->begin();
			
					$companystatic->id = $tabcompany[$key]['id'];
					$companystatic->name = $tabcompany[$key]['name'];
					$companystatic->code_compta = $tabcompany[$key]['code_compta'];
					$companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
					$companystatic->code_client = $tabcompany[$key]['code_client'];
					$companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
					$companystatic->fournisseur = 1;
			
					$invoicestatic->id = $key;
					$invoicestatic->ref = (string) $val["refsologest"];
					$invoicestatic->ref_supplier = $val["refsuppliersologest"];
					$invoicestatic->type = $val["type"];
					$invoicestatic->description = html_entity_decode(dol_trunc($val["description"], 32));
					$invoicestatic->close_code = $val["close_code"];
			
					$date = dol_print_date($val["date"], 'day');
			
					// Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
					$replacedinvoice = 0;
					if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED) {
						$replacedinvoice = 1;
						$alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
						if ($alreadydispatched) {
							$replacedinvoice = 2;
						}
					}
			
					// If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
					if ($replacedinvoice == 1) {
						$db->rollback();
						continue;
					}
			
					// Error if some lines are not binded/ready to be journalized
					if ($errorforinvoice[$key] == 'somelinesarenotbound') {
						$error++;
						$errorforline++;
						$this->output = $langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $val['ref']);
					}

					// Thirdparty
					if (!$errorforline) {
						foreach ($tabttc[$key] as $k => $mt) {
							$bookkeeping = new BookKeeping($db);
							$bookkeeping->doc_date = $val["date"];
							$bookkeeping->date_lim_reglement = $val["datereg"];
							$bookkeeping->doc_ref = $val["refsologest"];
							$bookkeeping->date_creation = $now;
							$bookkeeping->doc_type = 'supplier_invoice';
							$bookkeeping->fk_doc = $key;
							$bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
							$bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
			
							$bookkeeping->subledger_account = $tabcompany[$key]['code_compta_fournisseur'];
							$bookkeeping->subledger_label = $tabcompany[$key]['name'];
			
							$bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER;
							$bookkeeping->label_compte = $accountingaccountsupplier->label;
			
							$bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("SubledgerAccount");
							$bookkeeping->montant = $mt;
							$bookkeeping->sens = ($mt >= 0) ? 'C' : 'D';
							$bookkeeping->debit = ($mt <= 0) ? -$mt : 0;
							$bookkeeping->credit = ($mt > 0) ? $mt : 0;
							$bookkeeping->code_journal = $journal;
							$bookkeeping->journal_label = $langs->transnoentities($journal_label);
							$bookkeeping->fk_user_author = $user->id;
							$bookkeeping->entity = $conf->entity;
			
							$totaldebit += $bookkeeping->debit;
							$totalcredit += $bookkeeping->credit;
			
							$result = $bookkeeping->create($user);
							if ($result < 0) {
								if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
									$error++;
									$errorforline++;
									$errorforinvoice[$key] = 'alreadyjournalized';
									$this->output = 'Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded';
								} else {
									$error++;
									$errorforline++;
									$errorforinvoice[$key] = 'other';
									$this->output = $bookkeeping->error;
								}
							}
						}
					}

					// Product / Service
					if (!$errorforline) {
						foreach ($tabht[$key] as $k => $mt) {
							$resultfetch = $accountingaccount->fetch(null, $k, true);	// TODO Use a cache
							$label_account = $accountingaccount->label;
			
							// get compte id and label
							if ($resultfetch > 0) {
								$bookkeeping = new BookKeeping($db);
								$bookkeeping->doc_date = $val["date"];
								$bookkeeping->date_lim_reglement = $val["datereg"];
								$bookkeeping->doc_ref = $val["refsologest"];
								$bookkeeping->date_creation = $now;
								$bookkeeping->doc_type = 'supplier_invoice';
								$bookkeeping->fk_doc = $key;
								$bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
								$bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
			
								$bookkeeping->subledger_account = '';
								$bookkeeping->subledger_label = '';
			
								$bookkeeping->numero_compte = $k;
								$bookkeeping->label_compte = $label_account;
			
								$bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$label_account;
								$bookkeeping->montant = $mt;
								$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
								$bookkeeping->debit = ($mt > 0) ? $mt : 0;
								$bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
								$bookkeeping->code_journal = $journal;
								$bookkeeping->journal_label = $langs->transnoentities($journal_label);
								$bookkeeping->fk_user_author = $user->id;
								$bookkeeping->entity = $conf->entity;
			
								$totaldebit += $bookkeeping->debit;
								$totalcredit += $bookkeeping->credit;
			
								$result = $bookkeeping->create($user);
								if ($result < 0) {
									if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
										$error++;
										$errorforline++;
										$errorforinvoice[$key] = 'alreadyjournalized';
										$this->output = 'Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded';
									} else {
										$error++;
										$errorforline++;
										$errorforinvoice[$key] = 'other';
										$this->output = $bookkeeping->error;
									}
								}
							}
						}
					}
			
					// VAT
					// var_dump($tabtva);
					if (!$errorforline) {
						$listoftax = array(0, 1, 2);
						foreach ($listoftax as $numtax) {
							$arrayofvat = $tabtva;
							if ($numtax == 1) {
								$arrayofvat = $tablocaltax1;
							}
							if ($numtax == 2) {
								$arrayofvat = $tablocaltax2;
							}
			
							foreach ($arrayofvat[$key] as $k => $mt) {
								if ($mt) {
									$accountingaccount->fetch($k, null, true);		// TODO Use a cache for label
									$label_account = $accountingaccount->label;
			
									$bookkeeping = new BookKeeping($db);
									$bookkeeping->doc_date = $val["date"];
									$bookkeeping->date_lim_reglement = $val["datereg"];
									$bookkeeping->doc_ref = $val["refsologest"];
									$bookkeeping->date_creation = $now;
									$bookkeeping->doc_type = 'supplier_invoice';
									$bookkeeping->fk_doc = $key;
									$bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
									$bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
			
									$bookkeeping->subledger_account = '';
									$bookkeeping->subledger_label = '';
			
									$bookkeeping->numero_compte = $k;
									$bookkeeping->label_compte = $label_account;
			
									$bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
									$bookkeeping->montant = $mt;
									$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
									$bookkeeping->debit = ($mt > 0) ? $mt : 0;
									$bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
									$bookkeeping->code_journal = $journal;
									$bookkeeping->journal_label = $langs->transnoentities($journal_label);
									$bookkeeping->fk_user_author = $user->id;
									$bookkeeping->entity = $conf->entity;
			
									$totaldebit += $bookkeeping->debit;
									$totalcredit += $bookkeeping->credit;
			
									$result = $bookkeeping->create($user);
									if ($result < 0) {
										if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
											$error++;
											$errorforline++;
											$errorforinvoice[$key] = 'alreadyjournalized';
											$this->output = 'Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded';
										} else {
											$error++;
											$errorforline++;
											$errorforinvoice[$key] = 'other';
											$this->output = $bookkeeping->error;
										}
									}
								}
							}
						}
					}
					// Counterpart of VAT for VAT NPR
					// var_dump($tabother);
					if (!$errorforline && is_array($tabother[$key])) {
						foreach ($tabother[$key] as $k => $mt) {
							if ($mt) {
								$bookkeeping = new BookKeeping($db);
								$bookkeeping->doc_date = $val["date"];
								$bookkeeping->date_lim_reglement = $val["datereg"];
								$bookkeeping->doc_ref = $val["refsologest"];
								$bookkeeping->date_creation = $now;
								$bookkeeping->doc_type = 'supplier_invoice';
								$bookkeeping->fk_doc = $key;
								$bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
								$bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
			
								$bookkeeping->subledger_account = '';
								$bookkeeping->subledger_label = '';
			
								$bookkeeping->numero_compte = $k;
			
								$bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT").' NPR';
								$bookkeeping->montant = $mt;
								$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
								$bookkeeping->debit = ($mt > 0) ? $mt : 0;
								$bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
								$bookkeeping->code_journal = $journal;
								$bookkeeping->journal_label = $langs->transnoentities($journal_label);
								$bookkeeping->fk_user_author = $user->id;
								$bookkeeping->entity = $conf->entity;
			
								$totaldebit += $bookkeeping->debit;
								$totalcredit += $bookkeeping->credit;
			
								$result = $bookkeeping->create($user);
								if ($result < 0) {
									if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
										$error++;
										$errorforline++;
										$errorforinvoice[$key] = 'alreadyjournalized';
										$this->output = 'Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded';
									} else {
										$error++;
										$errorforline++;
										$errorforinvoice[$key] = 'other';
										$this->output = $bookkeeping->error;
									}
								}
							}
						}
					}
					// Protection against a bug on lines before
					if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
						$error++;
						$errorforline++;
						$errorforinvoice[$key] = 'amountsnotbalanced';
						$this->output = 'Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.';
					}
					if (!$errorforline) {
						$db->commit();
					} else {
						$db->rollback();
						// Errors Recipient
						$errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
						$from = $conf->global->MAIN_MAIL_EMAIL_FROM;
						$sendTopic = 'Tarea automatica de mayorizacion de facturas de Compras';
						
						if ($error >= 10) {
							$this->output = $langs->trans("ErrorTooManyErrorsProcessStopped");
						}
						if (!empty($notify)) {
							$sendContent = $this->output;
							// Mail Creation
							$cMailFile = new CMailFile($sendTopic, $notify, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
							// Sending Mail
							$cMailFile->sendfile();
						}
						$this->error =$this->output;
						return $error;
					}
				}
				if (!$error){
					return 0;
				}
			}
		}
		public function BankJournal( $notify = '', $idjournal = 3 )
		{
			global $conf, $user ,$db, $langs, $mysoc;
        
			require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
			require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
			require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
			require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
			require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
			require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
			require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
			require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
			require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
			require_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php';
			require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
			require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php';
			require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
			require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
			require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
			require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
			require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
			require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
			require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
			require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php';
			require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php';
			require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
			require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php';
			require_once DOL_DOCUMENT_ROOT.'/loan/class/paymentloan.class.php';
			require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
			require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
			require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
			
			// Load translation files required by the page
			$langs->loadLangs(array("companies", "other", "compta", "banks", "bills", "donations", "loan", "accountancy", "trips", "salaries", "hrm", "members"));
			
			// Multi journal
			$id_journal = $idjournal;

			$action = 'writebookkeeping';
			$this->output ='';

			$sql  = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.multicurrency_amount, b.multicurrency_code, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type, b.fk_account,";
			$sql .= " ba.courant, ba.ref as baref, ba.account_number, ba.fk_accountancy_journal,";
			$sql .= " soc.rowid as socid, soc.nom as name, soc.email as email, bu1.type as typeop_company,";
			if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
				$sql .= " spe.accountancy_code_customer as code_compta,";
				$sql .= " spe.accountancy_code_supplier as code_compta_fournisseur,";
			} else {
				$sql .= " soc.code_compta,";
				$sql .= " soc.code_compta_fournisseur,";
			}
			$sql .= " u.accountancy_code, u.rowid as userid, u.lastname as lastname, u.firstname as firstname, u.email as useremail, u.statut as userstatus,";
			$sql .= " bu2.type as typeop_user,";
			$sql .= " bu3.type as typeop_payment, bu4.type as typeop_payment_supplier, bu5.type as typeop_banktransfert";
			$sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
			$sql .= " JOIN ".MAIN_DB_PREFIX."bank_account as ba on b.fk_account=ba.rowid";
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu1 ON bu1.fk_bank = b.rowid AND bu1.type='company'";
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON bu2.fk_bank = b.rowid AND bu2.type='user'";
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu3 ON bu3.fk_bank = b.rowid AND bu3.type='payment'";
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu4 ON bu4.fk_bank = b.rowid AND bu4.type='payment_supplier'";
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu5 ON bu5.fk_bank = b.rowid AND bu5.type='banktransfert'";
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as soc on bu1.url_id=soc.rowid";
			if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
				$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_perentity as spe ON spe.fk_soc = soc.rowid AND spe.entity = " . ((int) $conf->entity);
			}
			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on bu2.url_id=u.rowid";
			$sql .= " WHERE ba.fk_accountancy_journal=".((int) $id_journal);
			$sql .= ' AND b.amount != 0 AND ba.entity IN ('.getEntity('bank_account', 0).')'; // We don't share object for accountancy
			if ($date_start && $date_end) {
				$sql .= " AND b.dateo >= '".$db->idate($date_start)."' AND b.dateo <= '".$db->idate($date_end)."'";
			}
			// Define begin binding date
			if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) {
				$sql .= " AND b.dateo >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'";
			}
			$sql .= " AND (b.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab  WHERE ab.doc_type='bank') )";			$sql .= " ORDER BY b.rowid, b.datev";
			//print $sql;
			
			$object = new Account($db);
			$paymentstatic = new Paiement($db);
			$paymentsupplierstatic = new PaiementFourn($db);
			$societestatic = new Societe($db);
			$userstatic = new User($db);
			$bankaccountstatic = new Account($db);
			$chargestatic = new ChargeSociales($db);
			$paymentdonstatic = new PaymentDonation($db);
			$paymentvatstatic = new Tva($db);
			$paymentsalstatic = new PaymentSalary($db);
			$paymentexpensereportstatic = new PaymentExpenseReport($db);
			$paymentvariousstatic = new PaymentVarious($db);
			$paymentloanstatic = new PaymentLoan($db);
			$accountLinestatic = new AccountLine($db);
			$paymentsubscriptionstatic = new Subscription($db);
			
			$tmppayment = new Paiement($db);
			$tmpinvoice = new Facture($db);
			
			$accountingaccount = new AccountingAccount($db);
			
			// Get code of finance journal
			$accountingjournalstatic = new AccountingJournal($db);
			$accountingjournalstatic->fetch($id_journal);
			$journal = $accountingjournalstatic->code;
			$journal_label = $accountingjournalstatic->label;
			
			dol_syslog("accountancy/journal/bankjournal.php", LOG_DEBUG);
			$result = $db->query($sql);
			if ($result) {
				$num = $db->num_rows($result);
				//print $sql;
			
				// Variables
				$account_supplier = (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER != "") ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : 'NotDefined'); // NotDefined is a reserved word
				$account_customer = (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER != "") ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : 'NotDefined'); // NotDefined is a reserved word
				$account_employee = (!empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) ? $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT : 'NotDefined'); // NotDefined is a reserved word
				$account_pay_vat = (!empty($conf->global->ACCOUNTING_VAT_PAY_ACCOUNT) ? $conf->global->ACCOUNTING_VAT_PAY_ACCOUNT : 'NotDefined'); // NotDefined is a reserved word
				$account_pay_donation = (!empty($conf->global->DONATION_ACCOUNTINGACCOUNT) ? $conf->global->DONATION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word
				$account_pay_subscription = (!empty($conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT) ? $conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word
				$account_customer_exchdiff = (!empty($conf->global->ACCOUNTING_ACCOUNT_EXCHANGE_DIFF_PAY) ? $conf->global->ACCOUNTING_ACCOUNT_EXCHANGE_DIFF_PAY : 'NotDefined'); // NotDefined is a reserved word
				$account_supplier_exchdiff = (!empty($conf->global->ACCOUNTING_ACCOUNT_EXCHANGE_DIFF_SPAY) ? $conf->global->ACCOUNTING_ACCOUNT_EXCHANGE_DIFF_SPAY : 'NotDefined'); // NotDefined is a reserved word
				$account_transfer = (!empty($conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH) ? $conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH : 'NotDefined'); // NotDefined is a reserved word
			
				$tabcompany = array();
				$tabuser = array();
				$tabpay = array();
				$tabbq = array();
				$tabtp = array();
				$tabtype = array();
				$tabmoreinfo = array();
			
				// Loop on each line into llx_bank table. For each line, we should get:
				// one line tabpay = line into bank
				// one line for bank record = tabbq
				// one line for thirdparty record = tabtp
				$i = 0;
				while ($i < $num) {
					$obj = $db->fetch_object($result);
			
					$lineisapurchase = -1;
					$lineisasale = -1;
					// Old method to detect if it's a sale or purchase
					if ($obj->label == '(SupplierInvoicePayment)' || $obj->label == '(SupplierInvoicePaymentBack)') {
						$lineisapurchase = 1;
					}
					if ($obj->label == '(CustomerInvoicePayment)' || $obj->label == '(CustomerInvoicePaymentBack)') {
						$lineisasale = 1;
					}
					// Try a more reliable method to detect if record is a supplier payment or a customer payment
					if ($lineisapurchase < 0) {
						if ($obj->typeop_payment_supplier == 'payment_supplier') {
							$lineisapurchase = 1;
						}
					}
					if ($lineisasale < 0) {
						if ($obj->typeop_payment == 'payment') {
							$lineisasale = 1;
						}
					}
					//var_dump($obj->type_payment); var_dump($obj->type_payment_supplier);
					//var_dump($lineisapurchase); //var_dump($lineisasale);
			
					// Set accountancy code for bank
					$compta_bank = $obj->account_number;
			
					// Set accountancy code for thirdparty (example: '411CU...' or '411' if no subledger account defined on customer)
					$compta_soc = 'NotDefined';
					if ($lineisapurchase > 0) {
						$compta_soc = (($obj->code_compta_fournisseur != "") ? $obj->code_compta_fournisseur : $account_supplier);
					}
					if ($lineisasale > 0) {
						$compta_soc = (!empty($obj->code_compta) ? $obj->code_compta : $account_customer);
					}
			
					$tabcompany[$obj->rowid] = array(
						'id' => $obj->socid,
						'name' => $obj->name,
						'code_compta' => $compta_soc,
						'email' => $obj->email
					);
			
					// Set accountancy code for user
					// $obj->accountancy_code is the accountancy_code of table u=user but it is defined only if a link with type 'user' exists)
					$compta_user = (!empty($obj->accountancy_code) ? $obj->accountancy_code : '');
			
					$tabuser[$obj->rowid] = array(
						'id' => $obj->userid,
						'name' => dolGetFirstLastname($obj->firstname, $obj->lastname),
						'lastname' => $obj->lastname,
						'firstname' => $obj->firstname,
						'email' => $obj->useremail,
						'accountancy_code' => $compta_user,
						'status' => $obj->userstatus
					);
			
					// Variable bookkeeping ($obj->rowid is Bank Id)
					$tabpay[$obj->rowid]["date"] = $obj->do;
					$tabpay[$obj->rowid]["type_payment"] = $obj->fk_type; // CHQ, VIR, LIQ, CB, ...
					$tabpay[$obj->rowid]["ref"] = $obj->label; // By default. Not unique. May be changed later
					$tabpay[$obj->rowid]["fk_bank"] = $obj->rowid;
					$tabpay[$obj->rowid]["bank_account_ref"] = $obj->baref;
					$tabpay[$obj->rowid]["fk_bank_account"] = $obj->fk_account;
					if (preg_match('/^\((.*)\)$/i', $obj->label, $reg)) {
						$tabpay[$obj->rowid]["lib"] = $langs->trans($reg[1]);
					} else {
						$tabpay[$obj->rowid]["lib"] = dol_trunc($obj->label, 60);
					}
			
					//echo '<pre>';var_dump($tabpay);echo '</pre>';
					
					// Load of url links to the line into llx_bank (so load llx_bank_url)
					$links = $object->get_url($obj->rowid); // Get an array('url'=>, 'url_id'=>, 'label'=>, 'type'=> 'fk_bank'=> )
			
					// By default
					$tabpay[$obj->rowid]['type'] = 'unknown'; // Can be SOLD, miscellaneous entry, payment of patient, or any old record with no links in bank_url.
					$tabtype[$obj->rowid] = 'unknown';
					$tabmoreinfo[$obj->rowid] = array();
			
					// get_url may return -1 which is not traversable
					if (is_array($links) && count($links) > 0) {
						// Now loop on each link of record in bank (code similar to bankentries_list.php)
						foreach ($links as $key => $val) {
							if (in_array($links[$key]['type'], array('sc', 'payment_sc', 'payment', 'payment_supplier', 'payment_vat', 'payment_expensereport', 'banktransfert', 'payment_donation', 'member', 'payment_loan', 'payment_salary', 'payment_various'))) {
								// So we excluded 'company' and 'user' here. We want only payment lines
			
								// We save tabtype for a future use, to remember what kind of payment it is
								$tabpay[$obj->rowid]['type'] = $links[$key]['type'];
								$tabtype[$obj->rowid] = $links[$key]['type'];
							} elseif (in_array($links[$key]['type'], array('company', 'user'))) {
								if ($tabpay[$obj->rowid]['type'] == 'unknown') {
									// We can guess here it is a bank record for a thirdparty company or a user.
									// But we won't be able to record somewhere else than into a waiting account, because there is no other journal to record the contreparty.
								}
							}
			
							// Special case to ask later to add more request to get information for old links without company link.
							if ($links[$key]['type'] == 'withdraw') {
								$tabmoreinfo[$obj->rowid]['withdraw'] = 1;
							}
			
							if ($links[$key]['type'] == 'payment') {
								$paymentstatic->id = $links[$key]['url_id'];
								$paymentstatic->ref = $links[$key]['url_id'];
								$tabpay[$obj->rowid]["lib"] .= ' '.$paymentstatic->getNomUrl(2, '', ''); // TODO Do not include list of invoice in tooltip, the dol_string_nohtmltag is ko with this
								$tabpay[$obj->rowid]["paymentid"] = $paymentstatic->id;
								//RMME
								$resul=$paymentstatic->fetch($paymentstatic->id);
								if ($resul) {									
                                    if ($conf->global->MAIN_MONNAIE != ( empty($obj->multicurrency_code) ? $conf->global->MAIN_MONNAIE : $obj->multicurrency_code) ) {
										$tabtp[$obj->rowid][$account_customer_exchdiff] = $obj->amount - $paymentstatic->amount;
										$tabtp[$obj->rowid][$compta_soc] = $paymentstatic->amount;
									}
									
								}
							} elseif ($links[$key]['type'] == 'payment_supplier') {
								$paymentsupplierstatic->id = $links[$key]['url_id'];
								$paymentsupplierstatic->ref = $links[$key]['url_id'];
								$tabpay[$obj->rowid]["lib"] .= ' '.$paymentsupplierstatic->getNomUrl(2);
								$tabpay[$obj->rowid]["paymentsupplierid"] = $paymentsupplierstatic->id;
								//RMME
								$resul=$paymentsupplierstatic->fetch($paymentsupplierstatic->id);
								//var_dump($paymentsupplierstatic);
			
								if ($resul) {
									if ($conf->global->MAIN_MONNAIE != ( empty($obj->multicurrency_code) ? $conf->global->MAIN_MONNAIE : $obj->multicurrency_code) ) {
										$variacion =  abs($obj->amount) - abs( $paymentsupplierstatic->amount) ;
							      		// Debe    <     Haber
										// Si el monto de banco es menor el monto a pagar  ocupa que la variacion sea 
										// var_dump(abs($obj->amount));
										// var_dump(abs($paymentsupplierstatic->amount));
										// var_dump( $variacion  );
										if (abs($obj->amount) < abs($paymentsupplierstatic->amount) && $variacion > 0 ) 
											$variacion = $variacion * 1 ;
										else
											$variacion = $variacion * -1 ;
										//die;
										$tabtp[$obj->rowid][$account_supplier_exchdiff] = $variacion;
										$tabtp[$obj->rowid][$compta_soc] = -$paymentsupplierstatic->amount;
									}
									
								}
							} elseif ($links[$key]['type'] == 'company') {
								$societestatic->id = $links[$key]['url_id'];
								$societestatic->name = $links[$key]['label'];
								$societestatic->email = $tabcompany[$obj->rowid]['email'];
								$tabpay[$obj->rowid]["soclib"] = $societestatic->getNomUrl(1, '', 30);
								if ($compta_soc) {
									$tabtp[$obj->rowid][$compta_soc] += $obj->amount;
								}
							} elseif ($links[$key]['type'] == 'user') {
								$userstatic->id = $links[$key]['url_id'];
								$userstatic->name = $links[$key]['label'];
								$userstatic->email = $tabuser[$obj->rowid]['email'];
								$userstatic->firstname = $tabuser[$obj->rowid]['firstname'];
								$userstatic->lastname = $tabuser[$obj->rowid]['lastname'];
								$userstatic->statut = $tabuser[$obj->rowid]['status'];
								$userstatic->accountancy_code = $tabuser[$obj->rowid]['accountancy_code'];
								if ($userstatic->id > 0) {
									$tabpay[$obj->rowid]["soclib"] = $userstatic->getNomUrl(1, 'accountancy', 0);
								} else {
									$tabpay[$obj->rowid]["soclib"] = '???'; // Should not happen, but happens with old data when id of user was not saved on expense report payment.
								}
								if ($compta_user) {
									$tabtp[$obj->rowid][$compta_user] += $obj->amount;
								}
							} elseif ($links[$key]['type'] == 'sc') {
								$chargestatic->id = $links[$key]['url_id'];
								$chargestatic->ref = $links[$key]['url_id'];
			
								$tabpay[$obj->rowid]["lib"] .= ' '.$chargestatic->getNomUrl(2);
								$reg = array();
								if (preg_match('/^\((.*)\)$/i', $links[$key]['label'], $reg)) {
									if ($reg[1] == 'socialcontribution') {
										$reg[1] = 'SocialContribution';
									}
									$chargestatic->label = $langs->trans($reg[1]);
								} else {
									$chargestatic->label = $links[$key]['label'];
								}
								$chargestatic->ref = $chargestatic->label;
								$tabpay[$obj->rowid]["soclib"] = $chargestatic->getNomUrl(1, 30);
								$tabpay[$obj->rowid]["paymentscid"] = $chargestatic->id;
			
								// Retrieve the accounting code of the social contribution of the payment from link of payment.
								// Note: We have the social contribution id, it can be faster to get accounting code from social contribution id.
								$sqlmid = "SELECT cchgsoc.accountancy_code";
								$sqlmid .= " FROM ".MAIN_DB_PREFIX."c_chargesociales cchgsoc";
								$sqlmid .= " INNER JOIN ".MAIN_DB_PREFIX."chargesociales as chgsoc ON chgsoc.fk_type = cchgsoc.id";
								$sqlmid .= " INNER JOIN ".MAIN_DB_PREFIX."paiementcharge as paycharg ON paycharg.fk_charge = chgsoc.rowid";
								$sqlmid .= " INNER JOIN ".MAIN_DB_PREFIX."bank_url as bkurl ON bkurl.url_id=paycharg.rowid AND bkurl.type = 'payment_sc'";
								$sqlmid .= " WHERE bkurl.fk_bank = ".((int) $obj->rowid);
			
								dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=".$sqlmid, LOG_DEBUG);
								$resultmid = $db->query($sqlmid);
								if ($resultmid) {
									$objmid = $db->fetch_object($resultmid);
									$tabtp[$obj->rowid][$objmid->accountancy_code] += $obj->amount;
								}
							} elseif ($links[$key]['type'] == 'payment_donation') {
								$paymentdonstatic->id = $links[$key]['url_id'];
								$paymentdonstatic->ref = $links[$key]['url_id'];
								$paymentdonstatic->fk_donation = $links[$key]['url_id'];
								$tabpay[$obj->rowid]["lib"] .= ' '.$paymentdonstatic->getNomUrl(2);
								$tabpay[$obj->rowid]["paymentdonationid"] = $paymentdonstatic->id;
								$tabtp[$obj->rowid][$account_pay_donation] += $obj->amount;
							} elseif ($links[$key]['type'] == 'member') {
								$paymentsubscriptionstatic->id = $links[$key]['url_id'];
								$paymentsubscriptionstatic->ref = $links[$key]['url_id'];
								$paymentsubscriptionstatic->label = $links[$key]['label'];
								$tabpay[$obj->rowid]["lib"] .= ' '.$paymentsubscriptionstatic->getNomUrl(2);
								$tabpay[$obj->rowid]["paymentsubscriptionid"] = $paymentsubscriptionstatic->id;
								$paymentsubscriptionstatic->fetch($paymentsubscriptionstatic->id);
								$tabtp[$obj->rowid][$account_pay_subscription] += $obj->amount;
							} elseif ($links[$key]['type'] == 'payment_vat') {				// Payment VAT
								$paymentvatstatic->id = $links[$key]['url_id'];
								$paymentvatstatic->ref = $links[$key]['url_id'];
								$paymentvatstatic->label = $links[$key]['label'];
								$tabpay[$obj->rowid]["lib"] .= ' '.$paymentvatstatic->getNomUrl(2);
								$tabpay[$obj->rowid]["paymentvatid"] = $paymentvatstatic->id;
								$tabtp[$obj->rowid][$account_pay_vat] += $obj->amount;
							} elseif ($links[$key]['type'] == 'payment_salary') {
								$paymentsalstatic->id = $links[$key]['url_id'];
								$paymentsalstatic->ref = $links[$key]['url_id'];
								$paymentsalstatic->label = $links[$key]['label'];
								$tabpay[$obj->rowid]["lib"] .= ' '.$paymentsalstatic->getNomUrl(2);
								$tabpay[$obj->rowid]["paymentsalid"] = $paymentsalstatic->id;
			
								// This part of code is no more required. it is here to solve case where a link were missing (ith v14.0.0) and keep writing in accountancy complete.
								// Note: A better way to fix this is to delete payement of salary and recreate it, or to fix the bookkeeping table manually after.
								if (!empty($conf->global->ACCOUNTANCY_AUTOFIX_MISSING_LINK_TO_USEr_ON_SALARY_BANK_PAYMENT)) {
									$tmpsalary = new Salary($db);
									$tmpsalary->fetch($paymentsalstatic->id);
									$tmpsalary->fetch_user($tmpsalary->fk_user);
			
									$userstatic->id = $tmpsalary->user->id;
									$userstatic->name = $tmpsalary->user->name;
									$userstatic->email = $tmpsalary->user->email;
									$userstatic->firstname = $tmpsalary->user->firstname;
									$userstatic->lastname = $tmpsalary->user->lastname;
									$userstatic->statut = $tmpsalary->user->statut;
									$userstatic->accountancy_code = $tmpsalary->user->accountancy_code;
			
									if ($userstatic->id > 0) {
										$tabpay[$obj->rowid]["soclib"] = $userstatic->getNomUrl(1, 'accountancy', 0);
									} else {
										$tabpay[$obj->rowid]["soclib"] = '???'; // Should not happen
									}
			
									if (empty($obj->typeop_user)) {	// Add test to avoid to add amount twice if a link already exists also on user.
										$compta_user = $userstatic->accountancy_code;
										if ($compta_user) {
											$tabtp[$obj->rowid][$compta_user] += $obj->amount;
											$tabuser[$obj->rowid] = array(
											'id' => $userstatic->id,
											'name' => dolGetFirstLastname($userstatic->firstname, $userstatic->lastname),
											'lastname' => $userstatic->lastname,
											'firstname' => $userstatic->firstname,
											'email' => $userstatic->email,
											'accountancy_code' => $compta_user,
											'status' => $userstatic->statut
											);
										}
									}
								}
							} elseif ($links[$key]['type'] == 'payment_expensereport') {
								$paymentexpensereportstatic->id = $links[$key]['url_id'];
								$tabpay[$obj->rowid]["lib"] .= $paymentexpensereportstatic->getNomUrl(2);
								$tabpay[$obj->rowid]["paymentexpensereport"] = $paymentexpensereportstatic->id;
							} elseif ($links[$key]['type'] == 'payment_various') {
								$paymentvariousstatic->id = $links[$key]['url_id'];
								$paymentvariousstatic->ref = $links[$key]['url_id'];
								$paymentvariousstatic->label = $links[$key]['label'];
								$tabpay[$obj->rowid]["lib"] .= ' '.$paymentvariousstatic->getNomUrl(2);
								$tabpay[$obj->rowid]["paymentvariousid"] = $paymentvariousstatic->id;
								$paymentvariousstatic->fetch($paymentvariousstatic->id);
								$account_various = (!empty($paymentvariousstatic->accountancy_code) ? $paymentvariousstatic->accountancy_code : 'NotDefined'); // NotDefined is a reserved word
								$account_subledger = (!empty($paymentvariousstatic->subledger_account) ? $paymentvariousstatic->subledger_account : ''); // NotDefined is a reserved word
								$tabpay[$obj->rowid]["account_various"] = $account_various;
								$tabtp[$obj->rowid][$account_subledger] += $obj->amount;
							} elseif ($links[$key]['type'] == 'payment_loan') {
								$paymentloanstatic->id = $links[$key]['url_id'];
								$paymentloanstatic->ref = $links[$key]['url_id'];
								$paymentloanstatic->fk_loan = $links[$key]['url_id'];
								$tabpay[$obj->rowid]["lib"] .= ' '.$paymentloanstatic->getNomUrl(2);
								$tabpay[$obj->rowid]["paymentloanid"] = $paymentloanstatic->id;
								//$tabtp[$obj->rowid][$account_pay_loan] += $obj->amount;
								$sqlmid = 'SELECT pl.amount_capital, pl.amount_insurance, pl.amount_interest, l.accountancy_account_capital, l.accountancy_account_insurance, l.accountancy_account_interest';
								$sqlmid .= ' FROM '.MAIN_DB_PREFIX.'payment_loan as pl, '.MAIN_DB_PREFIX.'loan as l';
								$sqlmid .= ' WHERE l.rowid = pl.fk_loan AND pl.fk_bank = '.((int) $obj->rowid);
			
								dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=".$sqlmid, LOG_DEBUG);
								$resultmid = $db->query($sqlmid);
								if ($resultmid) {
									$objmid = $db->fetch_object($resultmid);
									$tabtp[$obj->rowid][$objmid->accountancy_account_capital] -= $objmid->amount_capital;
									$tabtp[$obj->rowid][$objmid->accountancy_account_insurance] -= $objmid->amount_insurance;
									$tabtp[$obj->rowid][$objmid->accountancy_account_interest] -= $objmid->amount_interest;
								}
							} elseif ($links[$key]['type'] == 'banktransfert') {
								$accountLinestatic->fetch($links[$key]['url_id']);
								$tabpay[$obj->rowid]["lib"] .= ' '.$langs->trans("BankTransfer").'- '.$accountLinestatic->getNomUrl(1);
								$tabtp[$obj->rowid][$account_transfer] += $obj->amount;
								$bankaccountstatic->fetch($tabpay[$obj->rowid]['fk_bank_account']);
								$tabpay[$obj->rowid]["soclib"] = $bankaccountstatic->getNomUrl(2);
							}
						}
					}
			
					$tabbq[$obj->rowid][$compta_bank] += $obj->amount;
			
					// If no links were found to know the amount on thirdparty, we try to guess it.
					// This may happens on bank entries without the links lines to 'company'.
					if (empty($tabtp[$obj->rowid]) && !empty($tabmoreinfo[$obj->rowid]['withdraw'])) {	// If we dont find 'company' link because it is an old 'withdraw' record
						foreach ($links as $key => $val) {
							if ($links[$key]['type'] == 'payment') {
								// Get thirdparty
								$tmppayment->fetch($links[$key]['url_id']);
								$arrayofamounts = $tmppayment->getAmountsArray();
								if (is_array($arrayofamounts)) {
									foreach ($arrayofamounts as $invoiceid => $amount) {
										$tmpinvoice->fetch($invoiceid);
										$tmpinvoice->fetch_thirdparty();
										if ($tmpinvoice->thirdparty->code_compta) {
											$tabtp[$obj->rowid][$tmpinvoice->thirdparty->code_compta] += $amount;
										}
									}
								}
							}
						}
					}
			
					// If no links were found to know the amount on thirdparty/user, we init it to account 'NotDefined'.
					if (empty($tabtp[$obj->rowid])) {
						$tabtp[$obj->rowid]['NotDefined'] = $tabbq[$obj->rowid][$compta_bank];
					}
			
					$i++;
				}
			} else {
				dol_print_error($db);
			}
			
			
			// var_dump($tabpay);
			// var_dump($tabcompany);
			// var_dump($tabbq);
			// var_dump($tabtp);
			// var_dump($tabtype);
			
			// Write bookkeeping
			if (!$error && $action == 'writebookkeeping') {
				$now = dol_now();
			
				$accountingaccountcustomer = new AccountingAccount($db);
				$accountingaccountcustomer->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER, true);
			
				$accountingaccountsupplier = new AccountingAccount($db);
				$accountingaccountsupplier->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER, true);
			
				$accountingaccountpayment = new AccountingAccount($db);
				$accountingaccountpayment->fetch(null, $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT, true);
			
				$accountingaccountsuspense = new AccountingAccount($db);
				$accountingaccountsuspense->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE, true);
			
				$accountingaccountcustomerexchangediff = new AccountingAccount($db);
				$accountingaccountcustomerexchangediff->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_EXCHANGE_DIFF_PAY, true);
			
				$accountingaccountsupplierexchangediff = new AccountingAccount($db);
				$accountingaccountsupplierexchangediff->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_EXCHANGE_DIFF_SPAY, true);
			
				$error = 0;
				
				foreach ($tabpay as $key => $val) {		// $key is rowid into llx_bank
					$date = dol_print_date($db->jdate($val["date"]), 'day');
			
					$ref = $this->getSourceDocRef($val, $tabtype[$key]);
			
					$errorforline = 0;
			
					$totalcredit = 0;
					$totaldebit = 0;
			
					$db->begin();
			
					// Introduce a protection. Total of tabtp must be total of tabbq
					// echo '<pre>';var_dump($tabpay);echo '</pre>';
					// echo '<pre>';var_dump($tabtp);echo '</pre>';
					// echo '<pre>';var_dump($tabbq);echo '</pre>';
					// exit;
			
					// Bank
					if (!$errorforline && is_array($tabbq[$key])) {
						// Line into bank account
						foreach ($tabbq[$key] as $k => $mt) {
							if ($mt) {
								$accountingaccount->fetch(null, $k, true);	// $k is accounting bank account. TODO We should use a cache here to avoid this fetch
								$account_label = $accountingaccount->label;
			
								$reflabel = '';
								if (!empty($val['lib'])) {
									$reflabel .= dol_string_nohtmltag($val['lib'])." - ";
								}
								$reflabel .= $langs->trans("Bank").' '.dol_string_nohtmltag($val['bank_account_ref']);
								if (!empty($val['soclib'])) {
									$reflabel .= " - ".dol_string_nohtmltag($val['soclib']);
								}
			
								$bookkeeping = new BookKeeping($db);
								$bookkeeping->doc_date = $val["date"];
								$bookkeeping->doc_ref = $ref;
								$bookkeeping->doc_type = 'bank';
								$bookkeeping->fk_doc = $key;
								$bookkeeping->fk_docdet = $val["fk_bank"];
			
								$bookkeeping->numero_compte = $k;
								$bookkeeping->label_compte = $account_label;
			
								$bookkeeping->label_operation = $reflabel;
								$bookkeeping->montant = $mt;
								$bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
								$bookkeeping->debit = ($mt >= 0 ? $mt : 0);
								$bookkeeping->credit = ($mt < 0 ? -$mt : 0);
								$bookkeeping->code_journal = $journal;
								$bookkeeping->journal_label = $langs->transnoentities($journal_label);
								$bookkeeping->fk_user_author = $user->id;
								$bookkeeping->date_creation = $now;
			
								// No subledger_account value for the bank line but add a specific label_operation
								$bookkeeping->subledger_account = '';
								$bookkeeping->label_operation = $reflabel;
								$bookkeeping->entity = $conf->entity;
			
								$totaldebit += $bookkeeping->debit;
								$totalcredit += $bookkeeping->credit;
			
								$result = $bookkeeping->create($user);
								if ($result < 0) {
									if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
										$error++;
										$errorforline++;
										$this->output = 'Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded';
									} else {
										$error++;
										$errorforline++;
										$this->output = $bookkeeping->error;
									}
								}
							}
						}
					}
			//echo '<pre>';var_dump($bookkeeping);echo '</pre>';die;
					// Third party
					if (!$errorforline) {
						if (is_array($tabtp[$key])) {
							// Line into thirdparty account
							foreach ($tabtp[$key] as $k => $mt) {
                            
								if ($mt) {
									$reflabel = '';
									if (!empty($val['lib'])) {
										$reflabel .= dol_string_nohtmltag($val['lib']).($val['soclib'] ? " - " : "");
									}
									if ($tabtype[$key] == 'banktransfert') {
										$reflabel .= dol_string_nohtmltag($langs->transnoentitiesnoconv('TransitionalAccount').' '.$account_transfer);
									} else {
										$reflabel .= dol_string_nohtmltag($val['soclib']);
									}
			
									$bookkeeping = new BookKeeping($db);
									$bookkeeping->doc_date = $val["date"];
									$bookkeeping->doc_ref = $ref;
									$bookkeeping->doc_type = 'bank';
									$bookkeeping->fk_doc = $key;
									$bookkeeping->fk_docdet = $val["fk_bank"];
			
									$bookkeeping->label_operation = $reflabel;
									$bookkeeping->montant = $mt;
									$bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
									$bookkeeping->debit = ($mt < 0 ? -$mt : 0);
									$bookkeeping->credit = ($mt >= 0) ? $mt : 0;
									$bookkeeping->code_journal = $journal;
									$bookkeeping->journal_label = $langs->transnoentities($journal_label);
									$bookkeeping->fk_user_author = $user->id;
									$bookkeeping->date_creation = $now;
			
									if ($tabtype[$key] == 'payment') {	// If payment is payment of customer invoice, we get ref of invoice
										
										//RMME
										if ($k == $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER ){
											$bookkeeping->subledger_account = $k; // For payment, the subledger account is stored as $key of $tabtp
											$bookkeeping->subledger_label = $tabcompany[$key]['name']; // $tabcompany is defined only if we are sure there is 1 thirdparty for the bank transaction
											$bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
											$bookkeeping->label_compte = $accountingaccountcustomer->label;
										}else{
											$bookkeeping->subledger_account = $k; // For payment, the subledger account is stored as $key of $tabtp
											$bookkeeping->subledger_label = $tabcompany[$key]['name']; // $tabcompany is defined only if we are sure there is 1 thirdparty for the bank transaction
											$bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_EXCHANGE_DIFF_PAY;
											$bookkeeping->label_compte = $accountingaccountcustomerexchangediff->label;
										}
									} elseif ($tabtype[$key] == 'payment_supplier') {	// If payment is payment of supplier invoice, we get ref of invoice
										//RMME
										if ($k == $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER ){
											$bookkeeping->subledger_account = $k; // For payment, the subledger account is stored as $key of $tabtp
											$bookkeeping->subledger_label = $tabcompany[$key]['name']; // $tabcompany is defined only if we are sure there is 1 thirdparty for the bank transaction
											$bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER;
											$bookkeeping->label_compte = $accountingaccountsupplier->label;
										}else{
											$bookkeeping->subledger_account = $k; // For payment, the subledger account is stored as $key of $tabtp
											$bookkeeping->subledger_label = $tabcompany[$key]['name']; // $tabcompany is defined only if we are sure there is 1 thirdparty for the bank transaction
											$bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_EXCHANGE_DIFF_SPAY;
											$bookkeeping->label_compte = $accountingaccountsupplierexchangediff->label;
										}
			
									} elseif ($tabtype[$key] == 'payment_expensereport') {
										$bookkeeping->subledger_account = $tabuser[$key]['accountancy_code'];
										$bookkeeping->subledger_label = $tabuser[$key]['name'];
										$bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
										$bookkeeping->label_compte = $accountingaccountpayment->label;
									} elseif ($tabtype[$key] == 'payment_salary') {
										$bookkeeping->subledger_account = $tabuser[$key]['accountancy_code'];
										$bookkeeping->subledger_label = $tabuser[$key]['name'];
										$bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
										$bookkeeping->label_compte = $accountingaccountpayment->label;
									} elseif (in_array($tabtype[$key], array('sc', 'payment_sc'))) {   // If payment is payment of social contribution
										$bookkeeping->subledger_account = '';
										$bookkeeping->subledger_label = '';
										$accountingaccount->fetch(null, $k, true);	// TODO Use a cache
										$bookkeeping->numero_compte = $k;
										$bookkeeping->label_compte = $accountingaccount->label;
									} elseif ($tabtype[$key] == 'payment_vat') {
										$bookkeeping->subledger_account = '';
										$bookkeeping->subledger_label = '';
										$accountingaccount->fetch(null, $k, true);		// TODO Use a cache
										$bookkeeping->numero_compte = $k;
										$bookkeeping->label_compte = $accountingaccount->label;
									} elseif ($tabtype[$key] == 'payment_donation') {
										$bookkeeping->subledger_account = '';
										$bookkeeping->subledger_label = '';
										$accountingaccount->fetch(null, $k, true);		// TODO Use a cache
										$bookkeeping->numero_compte = $k;
										$bookkeeping->label_compte = $accountingaccount->label;
									} elseif ($tabtype[$key] == 'member') {
										$bookkeeping->subledger_account = '';
										$bookkeeping->subledger_label = '';
										$accountingaccount->fetch(null, $k, true);		// TODO Use a cache
										$bookkeeping->numero_compte = $k;
										$bookkeeping->label_compte = $accountingaccount->label;
									} elseif ($tabtype[$key] == 'payment_loan') {
										$bookkeeping->subledger_account = '';
										$bookkeeping->subledger_label = '';
										$accountingaccount->fetch(null, $k, true);		// TODO Use a cache
										$bookkeeping->numero_compte = $k;
										$bookkeeping->label_compte = $accountingaccount->label;
									} elseif ($tabtype[$key] == 'payment_various') {
										$bookkeeping->subledger_account = $k;
										$bookkeeping->subledger_label = $tabcompany[$key]['name'];
										$accountingaccount->fetch(null, $tabpay[$key]["account_various"], true);	// TODO Use a cache
										$bookkeeping->numero_compte = $tabpay[$key]["account_various"];
										$bookkeeping->label_compte = $accountingaccount->label;
									} elseif ($tabtype[$key] == 'banktransfert') {
										$bookkeeping->subledger_account = '';
										$bookkeeping->subledger_label = '';
										$accountingaccount->fetch(null, $k, true);		// TODO Use a cache
										$bookkeeping->numero_compte = $k;
										$bookkeeping->label_compte = $accountingaccount->label;
									} else {
										if ($tabtype[$key] == 'unknown') {	// Unknown transaction, we will use a waiting account for thirdparty.
											// Temporary account
											$bookkeeping->subledger_account = '';
											$bookkeeping->subledger_label = '';
											$bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE;
											$bookkeeping->label_compte = $accountingaccountsuspense->label;
										}
									}
									$bookkeeping->label_operation = $reflabel;
									$bookkeeping->entity = $conf->entity;
			
									$totaldebit += $bookkeeping->debit;
									$totalcredit += $bookkeeping->credit;
			
									$result = $bookkeeping->create($user);
			
									if ($result < 0) {
										if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
											$error++;
											$errorforline++;
											$this->output = 'Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded';
										} else {
											$error++;
											$errorforline++;
											$this->output = $bookkeeping->error;
										}
									}
								}
							}
						} else {	// If thirdparty unknown, output the waiting account
							foreach ($tabbq[$key] as $k => $mt) {
								if ($mt) {
									$reflabel = '';
									if (!empty($val['lib'])) {
										$reflabel .= dol_string_nohtmltag($val['lib'])." - ";
									}
									$reflabel .= dol_string_nohtmltag('WaitingAccount');
			
									$bookkeeping = new BookKeeping($db);
									$bookkeeping->doc_date = $val["date"];
									$bookkeeping->doc_ref = $ref;
									$bookkeeping->doc_type = 'bank';
									$bookkeeping->fk_doc = $key;
									$bookkeeping->fk_docdet = $val["fk_bank"];
									$bookkeeping->montant = $mt;
									$bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
									$bookkeeping->debit = ($mt < 0 ? -$mt : 0);
									$bookkeeping->credit = ($mt >= 0) ? $mt : 0;
									$bookkeeping->code_journal = $journal;
									$bookkeeping->journal_label = $langs->transnoentities($journal_label);
									$bookkeeping->fk_user_author = $user->id;
									$bookkeeping->date_creation = $now;
									$bookkeeping->label_compte = '';
									$bookkeeping->label_operation = $reflabel;
									$bookkeeping->entity = $conf->entity;
			
									$totaldebit += $bookkeeping->debit;
									$totalcredit += $bookkeeping->credit;
			
									$result = $bookkeeping->create($user);
			
									if ($result < 0) {
										if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') {	// Already exists
											$error++;
											$errorforline++;
											$this->output = 'Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded';
										} else {
											$error++;
											$errorforline++;
											$this->output = $bookkeeping->error;
										}
									}
								}
							}
						}
					}

					if (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT')) {
						$error++;
						$errorforline++;
						$this->output = 'Try to insert a non balanced transaction in book for '.$ref.'. Canceled. Surely a bug.';
					}
			
					if (!$errorforline) {
						$db->commit();
					} else {
						//print 'KO for line '.$key.' '.$error.'<br>';
						$db->rollback();
						$MAXNBERRORS = 5;
						if ($error >= $MAXNBERRORS) {
							$this->output = $langs->trans("ErrorTooManyErrorsProcessStopped").' (>'.$MAXNBERRORS.')';
						}
						if (!empty($notify)) {
                        	$sendTopic = 'Error automatizacion Diario de Bancos';
							$sendContent = 'Msg:'.$this->output;
                        	$errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
                        // Sender
                        $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
                        
							// Mail Creation
							$cMailFile = new CMailFile($sendTopic, $notify, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
						 // echo '<pre>';var_dump($cMailFile);die;	
                        // Sending Mail
							$cMailFile->sendfile();
						}
						$this->error =$this->output;
						return $error;
					}
				}

			}
			if (!$error){
				return 0;
			}
		}

	/**
	 * Return source for doc_ref of a bank transaction
	 *
	 * @param 	string 	$val			Array of val
	 * @param 	string	$typerecord		Type of record ('payment', 'payment_supplier', 'payment_expensereport', 'payment_vat', ...)
	 * @return 	string					A string label to describe a record into llx_bank_url
	 */
	function getSourceDocRef($val, $typerecord)
	{
		global $db, $langs;

		// Defined the docref into $ref (We start with $val['ref'] by default and we complete according to other data)
		// WE MUST HAVE SAME REF FOR ALL LINES WE WILL RECORD INTO THE BOOKKEEPING
		$ref = $val['ref'];
		if ($ref == '(SupplierInvoicePayment)' || $ref == '(SupplierInvoicePaymentBack)') {
			$ref = $langs->transnoentitiesnoconv('Supplier');
		}
		if ($ref == '(CustomerInvoicePayment)' || $ref == '(CustomerInvoicePaymentBack)') {
			$ref = $langs->transnoentitiesnoconv('Customer');
		}
		if ($ref == '(SocialContributionPayment)') {
			$ref = $langs->transnoentitiesnoconv('SocialContribution');
		}
		if ($ref == '(DonationPayment)') {
			$ref = $langs->transnoentitiesnoconv('Donation');
		}
		if ($ref == '(SubscriptionPayment)') {
			$ref = $langs->transnoentitiesnoconv('Subscription');
		}
		if ($ref == '(ExpenseReportPayment)') {
			$ref = $langs->transnoentitiesnoconv('Employee');
		}
		if ($ref == '(LoanPayment)') {
			$ref = $langs->transnoentitiesnoconv('Loan');
		}
		if ($ref == '(payment_salary)') {
			$ref = $langs->transnoentitiesnoconv('Employee');
		}

		$sqlmid = '';
		if ($typerecord == 'payment') {
			$sqlmid = 'SELECT payfac.fk_facture as id, f.ref as ref';
			$sqlmid .= " FROM ".MAIN_DB_PREFIX."paiement_facture as payfac, ".MAIN_DB_PREFIX."facture as f";
			$sqlmid .= " WHERE payfac.fk_facture = f.rowid AND payfac.fk_paiement=".((int) $val["paymentid"]);
			$ref = $langs->transnoentitiesnoconv("Invoice");
		} elseif ($typerecord == 'payment_supplier') {
			$sqlmid = 'SELECT payfac.fk_facturefourn as id, f.ref';
			$sqlmid .= " FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn as payfac, ".MAIN_DB_PREFIX."facture_fourn as f";
			$sqlmid .= " WHERE payfac.fk_facturefourn = f.rowid AND payfac.fk_paiementfourn=".((int) $val["paymentsupplierid"]);
			$ref = $langs->transnoentitiesnoconv("SupplierInvoice");
		} elseif ($typerecord == 'payment_expensereport') {
			$sqlmid = 'SELECT e.rowid as id, e.ref';
			$sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_expensereport as pe, ".MAIN_DB_PREFIX."expensereport as e";
			$sqlmid .= " WHERE pe.rowid=".((int) $val["paymentexpensereport"])." AND pe.fk_expensereport = e.rowid";
			$ref = $langs->transnoentitiesnoconv("ExpenseReport");
		} elseif ($typerecord == 'payment_salary') {
			$sqlmid = 'SELECT s.rowid as ref';
			$sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_salary as s";
			$sqlmid .= " WHERE s.rowid=".((int) $val["paymentsalid"]);
			$ref = $langs->transnoentitiesnoconv("SalaryPayment");
		} elseif ($typerecord == 'sc') {
			$sqlmid = 'SELECT sc.rowid as ref';
			$sqlmid .= " FROM ".MAIN_DB_PREFIX."paiementcharge as sc";
			$sqlmid .= " WHERE sc.rowid=".((int) $val["paymentscid"]);
			$ref = $langs->transnoentitiesnoconv("SocialContribution");
		} elseif ($typerecord == 'payment_vat') {
			$sqlmid = 'SELECT v.rowid as ref';
			$sqlmid .= " FROM ".MAIN_DB_PREFIX."tva as v";
			$sqlmid .= " WHERE v.rowid=".((int) $val["paymentvatid"]);
			$ref = $langs->transnoentitiesnoconv("PaymentVat");
		} elseif ($typerecord == 'payment_donation') {
			$sqlmid = 'SELECT payd.fk_donation as ref';
			$sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_donation as payd";
			$sqlmid .= " WHERE payd.fk_donation=".((int) $val["paymentdonationid"]);
			$ref = $langs->transnoentitiesnoconv("Donation");
		} elseif ($typerecord == 'payment_loan') {
			$sqlmid = 'SELECT l.rowid as ref';
			$sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_loan as l";
			$sqlmid .= " WHERE l.rowid=".((int) $val["paymentloanid"]);
			$ref = $langs->transnoentitiesnoconv("LoanPayment");
		} elseif ($typerecord == 'payment_various') {
			$sqlmid = 'SELECT v.rowid as ref';
			$sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_various as v";
			$sqlmid .= " WHERE v.rowid=".((int) $val["paymentvariousid"]);
			$ref = $langs->transnoentitiesnoconv("VariousPayment");
		}
		// Add warning
		if (empty($sqlmid)) {
			dol_syslog("Found a typerecord=".$typerecord." not supported", LOG_WARNING);
		}

		if ($sqlmid) {
			dol_syslog("accountancy/journal/bankjournal.php::sqlmid=".$sqlmid, LOG_DEBUG);
			$resultmid = $db->query($sqlmid);
			if ($resultmid) {
				while ($objmid = $db->fetch_object($resultmid)) {
					$ref .= ' '.$objmid->ref;
				}
			} else {
				dol_print_error($db);
			}
		}

		$ref = dol_trunc($langs->transnoentitiesnoconv("BankId").' '.$val['fk_bank'].' - '.$ref, 295); // 295 + 3 dots (...) is < than max size of 300
		return $ref;
	}


	public function LicenceReport( $notify = '' ){
		
		global $conf, $user ,$db, $langs;
						
		$sql = "SELECT 'Admin Externo' as Descr,  login, firstname, lastname, email, datelastlogin, datec, '' as fk_soc, '' as nom
		FROM llx_user 
		WHERE admin = 1 and employee = 0 ";
		$resql = $db->query($sql);
		if ($resql) {
			$totalexternaladmin=$resql->num_rows;
		}

		$sql = "SELECT 'Admin Interno Activo' as Descr,  login, firstname, lastname, email, datelastlogin, datec, '' as fk_soc, '' as nom
		FROM llx_user 
		WHERE admin = 1 and employee = 1 and statut =1";
		$resql = $db->query($sql);
		if ($resql) {
			$totalinternaladminA=$resql->num_rows;
		}

		$sql = "SELECT 'Admin Interno Inactivo' as Descr,  login, firstname, lastname, email, datelastlogin, datec, '' as fk_soc, '' as nom
		FROM llx_user 
		WHERE admin = 1 and employee = 1 and statut =0";
		$resql = $db->query($sql);
		if ($resql) {
			$totalinternaladminI=$resql->num_rows;
		}

		$sql = "SELECT 'Usuario Interno Activo' as Descr,  login, firstname, lastname, email, datelastlogin, datec, '' as fk_soc, '' as nom
		FROM llx_user 
		WHERE admin = 0 and employee = 1 and statut =1";
		$resql = $db->query($sql);
		if ($resql) {
			$totalinternaluserA=$resql->num_rows;
		}

		$sql = "SELECT 'Usuario Interno Inactivo' as Descr,  login, firstname, lastname, email, datelastlogin, datec, '' as fk_soc, '' as nom
		FROM llx_user 
		WHERE admin = 0 and employee = 1 and statut =0";
		$resql = $db->query($sql);
		if ($resql) {
			$totalinternaluserI=$resql->num_rows;
		}

		$sql = "SELECT 'Usuario Externo ACTIVO' as Descr,  login, firstname, lastname, u.email, datelastlogin, u.datec, fk_soc, nom
		FROM llx_user u inner join llx_societe s on u.fk_soc = s.rowid
		WHERE admin = 0 and employee = 0 and not fk_soc is null and u.statut =1";
		$resql = $db->query($sql);
		if ($resql) {
			$totalexternaluserA=$resql->num_rows;
		}

		$sql = "SELECT 'Usuario Externo INACTIVO' as Descr,  login, firstname, lastname, u.email, datelastlogin, u.datec, fk_soc, nom
		FROM llx_user u inner join llx_societe s on u.fk_soc = s.rowid
		WHERE admin = 0 and employee = 0 and not fk_soc is null and u.statut =0";
		$resql = $db->query($sql);
		if ($resql) {
			$totalexternaluserI=$resql->num_rows;
		}

		$body = "<br>";
		$sql = "SELECT rowid as id, label, description, active
		FROM llx_entity e ";
		$resql = $db->query($sql);
		if ($resql) {
			if ($resql->num_rows > 0) {
				$body = "<table border='1'>";
				$body .= "<tr> <td colspan=4> <strong>Listado de Usuarios Registrados</strong></td> </tr>";
				$body .= "<tr>
						<th>ID</th>
						<th>Nombre</th>
						<th>Descripcion</th>
						<th>Estado</th>
					</tr>";

				// Recorrer resultados
				while($row = $db->fetch_object($resql)) {
					$body .= "<tr>";
					$body .= "<td>" . $row->id . "</td>";
					$body .= "<td>" . $row->label . "</td>";
					$body .= "<td>" . $row->description . "</td>";
					$body .= "<td>" . $row->active . "  ***(1 Activa / 0 Inactiva)</td>";
					$body .= "</tr>";
				}

				$body .= "</table>";
			} else {
				$body .= "<strong>Solo la Entidad maestra </strong>";
			}
		}
		else {
				$body = "<strong>Solo la Entidad maestra </strong> ";
		}

		$body .= '<br><table > <tbody>
		<tr> <td colspan=2> <strong>Listado de Usuarios Registrados</strong></td> </tr>
		<tr> <td><strong>Descripcion</strong></td> <td align="right"><strong>Cantidad</strong></td> </tr>
		<tr> <td>ADMIN EXTERNO DPS* No genera cargo</td> <td align="right">'.$totalexternaladmin.'</td> </tr>
		<tr> <td>ADMIN INTERNO ACTIVO</td> <td align="right">'.$totalinternaladminA.'</td> </tr>
		<tr> <td>ADMIN INTERNO INACTIVO</td> <td align="right">'.$totalinternaladminI.'</td> </tr>
		<tr> <td>Usuario Interno Activo</td> <td align="right">'.$totalinternaluserA.'</td> </tr>
		<tr> <td>Usuario Interno Inactivo</td> <td align="right">'.$totalinternaluserI.'</td> </tr>
		<tr> <td>Usuario Externo ACTIVO (Autogestion)</td> <td align="right">'.$totalexternaluserA.'</td> </tr>
		<tr> <td>Usuario Externo INACTIVVO (Autogestion)</td> <td align="right">'.$totalexternaluserI.'</td> </tr>
		<tr> <td><strong>Total Usuarios Registrados</strong></td> <td align="right"><strong>'. ( $totalexternaladmin+ $totalinternaladminA +$totalinternaladminI+$totalinternaluserA+$totalinternaluserI+$totalexternaluserA+$totalexternaluser).'</strong></td> </tr>
		</tbody></table><br><br>
		<table  > <tbody>
		<tr> <td colspan=2><strong>Listado de Licencias</strong></td> </tr>
		<tr> <td><strong>Descripcion</strong></td> <td align="right"><strong>Cantidad</strong></td> </tr>
		<tr> <td>ADMIN EXTERNO DPS* No genera cargo</td> <td align="right">'.$totalexternaladmin.'</td> </tr>
		<tr> <td>ADMIN INTERNO ACTIVO</td> <td align="right">'.$totalinternaladminA.'</td> </tr>
		<tr> <td>Usuario Interno Activo </td> <td align="right">'.$totalinternaluserA.'</td> </tr>
		<tr> <td>Usuario Externo ACTIVO (Autogestion)</td> <td align="right">'.$totalexternaluserA.'</td> </tr>
		<tr> <td><strong>Total Licencias Cosumidas</strong></td> <td align="right"><strong>'.($totalexternaladmin+$totalinternaladminA+$totalinternaluserA+$totalexternaluserA).'</strong></td> </tr>
		<tr> <td><strong>Total Licencias Activas</strong></td> <td align="right"><strong>'.($conf->file->main_limit_users).'</strong></td> </tr>  
		<tr> <td><strong>Disponibilidad ó Faltante </strong></td> <td align="right"><strong>'.( ($conf->file->main_limit_users)-($totalexternaladmin+$totalinternaladminA+$totalinternaluserA+$totalexternaluserA)).'</strong></td> </tr>  
		</tbody></table>';

		if (!empty($notify)) {
			require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';

			$sendTopic = 'Reporte de Usuarios y Licencias';
			$sendContent = '<p>Informe de Licencias Instancia : <b>'.$conf->global->MAIN_INFO_SOCIETE_NOM.'</b></p>'.$body;
			$errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
			// Sender
			$from = $conf->global->MAIN_MAIL_EMAIL_FROM;
		
			// Mail Creation
			$cMailFile = new CMailFile($sendTopic, $notify, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', '', '', '', '');
		 // echo '<pre>';var_dump($cMailFile);die;	
		// Sending Mail
			$cMailFile->sendfile();
		}
		$this->output = 'Cantidad de Licencias Disponible ó Faltante:'. ( ($conf->file->main_limit_users)-($totalexternaladmin+$totalinternaladminA+$totalinternaluserA+$totalexternaluserA));
		return 0;
	}

	}
?>

Hry