From 806d25ae4116f5141a0c2f8f6404ed4b738d4979 Mon Sep 17 00:00:00 2001
From: Alexandre SPANGARO <alexandre.spangaro@gmail.com>
Date: Mon, 5 Jun 2017 06:44:53 +0200
Subject: [PATCH] Activate multi-journal on expensereport journal

---
 .../journal/expensereportsjournal.php         | 311 +++++++++---------
 htdocs/core/menus/standard/eldy.lib.php       |   1 +
 htdocs/install/mysql/data/llx_accounting.sql  |   1 +
 .../install/mysql/migration/5.0.0-6.0.0.sql   |   1 +
 .../mysql/tables/llx_accounting_journal.sql   |   2 +-
 5 files changed, 163 insertions(+), 153 deletions(-)

diff --git a/htdocs/accountancy/journal/expensereportsjournal.php b/htdocs/accountancy/journal/expensereportsjournal.php
index f67224e3996..9bd9f8b7f42 100644
--- a/htdocs/accountancy/journal/expensereportsjournal.php
+++ b/htdocs/accountancy/journal/expensereportsjournal.php
@@ -3,7 +3,7 @@
  * Copyright (C) 2007-2010	Jean Heimburger		<jean@tiaris.info>
  * Copyright (C) 2011		Juanjo Menent		<jmenent@2byte.es>
  * Copyright (C) 2012		Regis Houssin		<regis@dolibarr.fr>
- * Copyright (C) 2013-2016	Alexandre Spangaro	<aspangaro@zendsi.com>
+ * Copyright (C) 2013-2017	Alexandre Spangaro	<aspangaro@zendsi.com>
  * Copyright (C) 2013-2016	Olivier Geffroy		<jeff@jeffinfo.com>
  * Copyright (C) 2013-2016	Florian Henry		<florian.henry@open-concept.pro>
  *
@@ -32,10 +32,11 @@ require '../../main.inc.php';
 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 . '/expensereport/class/expensereport.class.php';
 require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php';
-require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php';
 
 // Langs
 $langs->load("compta");
@@ -45,6 +46,9 @@ $langs->load("main");
 $langs->load("accountancy");
 $langs->load("trips");
 
+// Multi journal
+$id_journal = GETPOST('id_journal', 'int');
+
 $date_startmonth = GETPOST('date_startmonth');
 $date_startday = GETPOST('date_startday');
 $date_startyear = GETPOST('date_startyear');
@@ -64,6 +68,10 @@ $action = GETPOST('action','aZ09');
 /*
  * Actions
  */
+// Get code of finance journal
+$accountingjournalstatic = new AccountingJournal($db);
+$accountingjournalstatic->fetch($id_journal);
+$journal = $accountingjournalstatic->code;
 
 $year_current = strftime("%Y", dol_now());
 $pastmonth = strftime("%m", dol_now()) - 1;
@@ -157,161 +165,159 @@ if ($action == 'writebookkeeping') {
 	{
 		$errorforline = 0;
 
-	    $db->begin();
-	     
-        if (! $errorforline)
-        {
-    	    foreach ( $tabttc[$key] as $k => $mt ) {
-    			if ($mt) {
-        	        // get compte id and label
-        
-        			$bookkeeping = new BookKeeping($db);
-        			$bookkeeping->doc_date = $val["date"];
-        			$bookkeeping->doc_ref = $val["ref"];
-        			$bookkeeping->date_create = $now;
-        			$bookkeeping->doc_type = 'expense_report';
-        			$bookkeeping->fk_doc = $key;
-        			$bookkeeping->fk_docdet = $val["fk_expensereportdet"];
-        			$bookkeeping->code_tiers = $tabuser[$key]['user_accountancy_code'];
-        			$bookkeeping->label_compte = $tabuser[$key]['name'];
-        			$bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
-        			$bookkeeping->montant = $mt;
-        			$bookkeeping->sens = ($mt >= 0) ? 'C' : 'D';
-        			$bookkeeping->debit = ($mt <= 0) ? $mt : 0;
-        			$bookkeeping->credit = ($mt > 0) ? $mt : 0;
-        			$bookkeeping->code_journal = $conf->global->ACCOUNTING_EXPENSEREPORT_JOURNAL;
-        			$bookkeeping->fk_user_author = $user->id;
-        
-        			$result = $bookkeeping->create($user);
-        			if ($result < 0) {
-        			    if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-        			    {
-        			        $error++;
-        			        $errorforline++;
-        			        //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
-        			    }
-        			    else
-        			    {
-        			        $error++;
-        			        $errorforline++;
-        			        setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
-        			    }
-        			}
-    			}
-    		}
-        }
-        
-        if (! $errorforline)
-        {
-            // Fees
-    		foreach ( $tabht[$key] as $k => $mt ) {
-    			$accountingaccount = new AccountingAccount($db);
-    			$accountingaccount->fetch(null, $k, true);
-    			if ($mt) {
-    				// get compte id and label
-    				$accountingaccount = new AccountingAccount($db);
-    				if ($accountingaccount->fetch(null, $k, true)) {
-    					$bookkeeping = new BookKeeping($db);
-    					$bookkeeping->doc_date = $val["date"];
-    					$bookkeeping->doc_ref = $val["ref"];
-    					$bookkeeping->date_create = $now;
-    					$bookkeeping->doc_type = 'expense_report';
-    					$bookkeeping->fk_doc = $key;
-    					$bookkeeping->fk_docdet = $val["fk_expensereportdet"];
-    					$bookkeeping->code_tiers = '';
-    					$bookkeeping->label_compte = $accountingaccount->label;
-    					$bookkeeping->numero_compte = $k;
-    					$bookkeeping->montant = $mt;
-    					$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
-    					$bookkeeping->debit = ($mt > 0) ? $mt : 0;
-    					$bookkeeping->credit = ($mt <= 0) ? $mt : 0;
-    					$bookkeeping->code_journal = $conf->global->ACCOUNTING_EXPENSEREPORT_JOURNAL;
-    					$bookkeeping->fk_user_author = $user->id;
-    
-    					$result = $bookkeeping->create($user);
-	        			if ($result < 0) {
-            			    if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-            			    {
-            			        $error++;
-            			        $errorforline++;
-            			        //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
-            			    }
-            			    else
-            			    {
-            			        $error++;
-            			        $errorforline++;
-            			        setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
-            			    }
-	        			}
-    				}
-    			}
-    		}
-        }
-        
-        if (! $errorforline)
-        {
-            // VAT
-    		// var_dump($tabtva);
-    		foreach ( $tabtva[$key] as $k => $mt ) {
-    			if ($mt) {
-    				// get compte id and label
-    				$bookkeeping = new BookKeeping($db);
-    				$bookkeeping->doc_date = $val["date"];
-    				$bookkeeping->doc_ref = $val["ref"];
-    				$bookkeeping->date_create = $now;
-    				$bookkeeping->doc_type = 'expense_report';
-    				$bookkeeping->fk_doc = $key;
-    				$bookkeeping->fk_docdet = $val["fk_expensereportdet"];
-    				$bookkeeping->code_tiers = '';
-    				$bookkeeping->label_compte = $langs->trans("VAT"). ' '.$def_tva[$key];
-    				$bookkeeping->numero_compte = $k;
-    				$bookkeeping->montant = $mt;
-    				$bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
-    				$bookkeeping->debit = ($mt > 0) ? $mt : 0;
-    				$bookkeeping->credit = ($mt <= 0) ? $mt : 0;
-    				$bookkeeping->code_journal = $conf->global->ACCOUNTING_EXPENSEREPORT_JOURNAL;
-    				$bookkeeping->fk_user_author = $user->id;
-    
-    				$result = $bookkeeping->create($user);
-    				if ($result < 0) {
-           			    if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
-        			    {
-        			        $error++;
-        			        $errorforline++;
-        			        //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
-        			    }
-        			    else
-        			    {
-        			        $error++;
-        			        $errorforline++;
-        			        setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
-        			    }
-    				}
-    			}
-    		}
-        }
-        
+		$db->begin();
+
+		if (! $errorforline)
+		{
+			foreach ( $tabttc[$key] as $k => $mt ) {
+				if ($mt) {
+					// get compte id and label
+					$bookkeeping = new BookKeeping($db);
+					$bookkeeping->doc_date = $val["date"];
+					$bookkeeping->doc_ref = $val["ref"];
+					$bookkeeping->date_create = $now;
+					$bookkeeping->doc_type = 'expense_report';
+					$bookkeeping->fk_doc = $key;
+					$bookkeeping->fk_docdet = $val["fk_expensereportdet"];
+					$bookkeeping->code_tiers = $tabuser[$key]['user_accountancy_code'];
+					$bookkeeping->label_compte = $tabuser[$key]['name'];
+					$bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
+					$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->fk_user_author = $user->id;
+
+					$result = $bookkeeping->create($user);
+					if ($result < 0) {
+						if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+						{
+							$error++;
+							$errorforline++;
+							//setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+						}
+						else
+						{
+							$error++;
+							$errorforline++;
+							setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+						}
+					}
+				}
+			}
+		}
+
+		if (! $errorforline)
+		{
+			// Fees
+			foreach ( $tabht[$key] as $k => $mt ) {
+				$accountingaccount = new AccountingAccount($db);
+				$accountingaccount->fetch(null, $k, true);
+				if ($mt) {
+					// get compte id and label
+					$accountingaccount = new AccountingAccount($db);
+					if ($accountingaccount->fetch(null, $k, true)) {
+						$bookkeeping = new BookKeeping($db);
+						$bookkeeping->doc_date = $val["date"];
+						$bookkeeping->doc_ref = $val["ref"];
+						$bookkeeping->date_create = $now;
+						$bookkeeping->doc_type = 'expense_report';
+						$bookkeeping->fk_doc = $key;
+						$bookkeeping->fk_docdet = $val["fk_expensereportdet"];
+						$bookkeeping->code_tiers = '';
+						$bookkeeping->label_compte = $accountingaccount->label;
+						$bookkeeping->numero_compte = $k;
+						$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->fk_user_author = $user->id;
+
+						$result = $bookkeeping->create($user);
+						if ($result < 0) {
+							if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+							{
+								$error++;
+								$errorforline++;
+								//setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+							}
+							else
+							{
+								$error++;
+								$errorforline++;
+								setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+							}
+						}
+					}
+				}
+			}
+		}
+
 		if (! $errorforline)
 		{
-		    $db->commit();
+			// VAT
+			// var_dump($tabtva);
+			foreach ( $tabtva[$key] as $k => $mt ) {
+				if ($mt) {
+					// get compte id and label
+					$bookkeeping = new BookKeeping($db);
+					$bookkeeping->doc_date = $val["date"];
+					$bookkeeping->doc_ref = $val["ref"];
+					$bookkeeping->date_create = $now;
+					$bookkeeping->doc_type = 'expense_report';
+					$bookkeeping->fk_doc = $key;
+					$bookkeeping->fk_docdet = $val["fk_expensereportdet"];
+					$bookkeeping->code_tiers = '';
+					$bookkeeping->label_compte = $langs->trans("VAT"). ' '.$def_tva[$key];
+					$bookkeeping->numero_compte = $k;
+					$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->fk_user_author = $user->id;
+
+					$result = $bookkeeping->create($user);
+					if ($result < 0) {
+						if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists')	// Already exists
+						{
+							$error++;
+							$errorforline++;
+							//setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->doc_ref.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
+						}
+						else
+						{
+							$error++;
+							$errorforline++;
+							setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
+						}
+					}
+				}
+			}
+		}
+
+		if (! $errorforline)
+		{
+			$db->commit();
 		}
 		else
 		{
-		    $db->rollback();
+			$db->rollback();
 		}
-		
 	}
 
 	if (empty($error) && count($tabpay)) {
-	    setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
+		setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
 	}
 	elseif (count($tabpay) == $error)
 	{
-	    setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
+		setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
 	}
 	else
 	{
-	    setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
+		setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
 	}
 
 	$action='';
@@ -328,7 +334,6 @@ $userstatic = new User($db);
 // Export
 /*if ($action == 'export_csv') {
 	$sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
-	$journal = $conf->global->ACCOUNTING_EXPENSEREPORT_JOURNAL;
 
 	include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php';
 
@@ -448,7 +453,9 @@ if (empty($action) || $action == 'view') {
 
 	$period = $form->select_date($date_start, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end, 'date_end', 0, 0, 0, '', 1, 0, 1);
 
-	journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''));
+	$varlink = 'id_journal=' . $id_journal;
+
+	journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
 
 	/*if ($conf->global->ACCOUNTING_EXPORT_MODELCSV != 1 && $conf->global->ACCOUNTING_EXPORT_MODELCSV != 2) {
 		print '<input type="button" class="butActionRefused" style="float: right;" value="' . $langs->trans("Export") . '" disabled="disabled" title="' . $langs->trans('ExportNotSupported') . '"/>';
@@ -456,10 +463,10 @@ if (empty($action) || $action == 'view') {
 		print '<input type="button" class="butAction" style="float: right;" value="' . $langs->trans("Export") . '" onclick="launch_export();" />';
 	}*/
 
-    print '<div class="tabsAction">';
+	print '<div class="tabsAction">';
 	print '<input type="button" class="butAction" value="' . $langs->trans("WriteBookKeeping") . '" onclick="writebookkeeping();" />';
-    print '</div>';
-    
+	print '</div>';
+
 	print '
 	<script type="text/javascript">
 		function launch_export() {
@@ -556,9 +563,9 @@ if (empty($action) || $action == 'view') {
 
 		// Third party
 		foreach ( $tabttc[$key] as $k => $mt ) {
-		    print '<tr class="oddeven">';
-		    print "<td><!-- Thirdparty --></td>";
-		    print "<td>" . $date . "</td>";
+			print '<tr class="oddeven">';
+			print "<td><!-- Thirdparty --></td>";
+			print "<td>" . $date . "</td>";
 			print "<td>" . $expensereportstatic->getNomUrl(1) . "</td>";
 			$userstatic->id = $tabuser[$key]['id'];
 			$userstatic->name = $tabuser[$key]['name'];
@@ -566,14 +573,14 @@ if (empty($action) || $action == 'view') {
 			$accountoshow = length_accounta($k);
 			if (empty($accountoshow) || $accountoshow == 'NotDefined')
 			{
-			    print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
+				print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
 			}
 			else print $accountoshow;
 			print "</td>";
 			print "<td>" . $userstatic->getNomUrl(0, 'user', 16) . ' - ' . $langs->trans("Code_tiers") . "</td>";
 			print '<td align="right">' . ($mt < 0 ? - price(- $mt) : '') . "</td>";
 			print '<td align="right">' . ($mt >= 0 ? price($mt) : '') . "</td>";
-		    print "</tr>";
+			print "</tr>";
 		}
 	}
 
diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php
index 8b167e3a6f6..8b6b26d772c 100644
--- a/htdocs/core/menus/standard/eldy.lib.php
+++ b/htdocs/core/menus/standard/eldy.lib.php
@@ -1027,6 +1027,7 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after,&$tabMenu
 								if ($objp->nature == 2) $nature="sells";
 								if ($objp->nature == 3) $nature="purchases";
 								if ($objp->nature == 4) $nature="bank";
+								if ($objp->nature == 5) $nature="expensereports";
 								if ($objp->nature == 1) $nature="various";
 								if ($objp->nature == 9) $nature="hasnew";
 
diff --git a/htdocs/install/mysql/data/llx_accounting.sql b/htdocs/install/mysql/data/llx_accounting.sql
index e81d13dd2b8..ea1fe7a7dd7 100644
--- a/htdocs/install/mysql/data/llx_accounting.sql
+++ b/htdocs/install/mysql/data/llx_accounting.sql
@@ -32,6 +32,7 @@ INSERT INTO llx_accounting_journal (code, label, nature, active) VALUES ('AC', '
 INSERT INTO llx_accounting_journal (code, label, nature, active) VALUES ('BQ', 'Journal de banque', 4, 1);
 INSERT INTO llx_accounting_journal (code, label, nature, active) VALUES ('OD', 'Journal des opérations diverses', 1, 1);
 INSERT INTO llx_accounting_journal (code, label, nature, active) VALUES ('AN', 'Journal des à-nouveaux', 9, 1);
+INSERT INTO llx_accounting_journal (code, label, nature, active) VALUES ('ER', 'Journal des notes de frais', 5, 1);
 --
 -- Descriptif des plans comptables FR PCG99-ABREGE
 --
diff --git a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql
index d7e68346511..594568307a6 100644
--- a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql
+++ b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql
@@ -168,6 +168,7 @@ INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (
 INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (3,'BQ', 'Bank journal', 4, 1);
 INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (4,'OD', 'Other journal', 1, 1);
 INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (5,'AN', 'Has new journal', 9, 1);
+INSERT INTO llx_accounting_journal (rowid, code, label, nature, active) VALUES (6,'ER', 'Expense report journal', 5, 1);
 -- Fix old entries
 UPDATE llx_accounting_journal SET nature = 1 where code = 'OD' and nature = 0;
 UPDATE llx_accounting_journal SET nature = 2 where code = 'VT' and nature = 1;
diff --git a/htdocs/install/mysql/tables/llx_accounting_journal.sql b/htdocs/install/mysql/tables/llx_accounting_journal.sql
index dbd9e4d311b..51f1f972859 100644
--- a/htdocs/install/mysql/tables/llx_accounting_journal.sql
+++ b/htdocs/install/mysql/tables/llx_accounting_journal.sql
@@ -23,6 +23,6 @@ create table llx_accounting_journal
   entity            integer DEFAULT 1 NOT NULL,
   code              varchar(32) NOT NULL,
   label             varchar(128) NOT NULL,
-  nature            smallint DEFAULT 1 NOT NULL,        -- type of journals (1:various operations / 2:sale / 3:purchase / 4:bank / 9: has-new)
+  nature            smallint DEFAULT 1 NOT NULL,        -- type of journals (1:various operations / 2:sale / 3:purchase / 4:bank / 5:expense report / 9:has-new)
   active            smallint DEFAULT 0
 )ENGINE=innodb;
-- 
GitLab