expensereportsjournal.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. <?php
  2. /* Copyright (C) 2007-2010 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2007-2010 Jean Heimburger <jean@tiaris.info>
  4. * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
  6. * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  7. * Copyright (C) 2013-2016 Olivier Geffroy <jeff@jeffinfo.com>
  8. * Copyright (C) 2013-2016 Florian Henry <florian.henry@open-concept.pro>
  9. * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
  10. * Copyright (C) 2018 Eric Seigne <eric.seigne@cap-rel.fr>
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 3 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  24. */
  25. /**
  26. * \file htdocs/accountancy/journal/expensereportsjournal.php
  27. * \ingroup Accountancy (Double entries)
  28. * \brief Page with expense reports journal
  29. */
  30. require '../../main.inc.php';
  31. require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
  32. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  33. require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  34. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
  35. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
  36. require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
  39. // Load translation files required by the page
  40. $langs->loadLangs(array("commercial", "compta", "bills", "other", "accountancy", "trips", "errors"));
  41. $id_journal = GETPOST('id_journal', 'int');
  42. $action = GETPOST('action', 'aZ09');
  43. $date_startmonth = GETPOST('date_startmonth');
  44. $date_startday = GETPOST('date_startday');
  45. $date_startyear = GETPOST('date_startyear');
  46. $date_endmonth = GETPOST('date_endmonth');
  47. $date_endday = GETPOST('date_endday');
  48. $date_endyear = GETPOST('date_endyear');
  49. $in_bookkeeping = GETPOST('in_bookkeeping');
  50. if ($in_bookkeeping == '') {
  51. $in_bookkeeping = 'notyet';
  52. }
  53. $now = dol_now();
  54. // Security check
  55. if (!isModEnabled('accounting')) {
  56. accessforbidden();
  57. }
  58. if ($user->socid > 0) {
  59. accessforbidden();
  60. }
  61. if (!$user->hasRight('accounting', 'mouvements', 'lire')) {
  62. accessforbidden();
  63. }
  64. /*
  65. * Actions
  66. */
  67. $accountingaccount = new AccountingAccount($db);
  68. // Get informations of journal
  69. $accountingjournalstatic = new AccountingJournal($db);
  70. $accountingjournalstatic->fetch($id_journal);
  71. $journal = $accountingjournalstatic->code;
  72. $journal_label = $accountingjournalstatic->label;
  73. $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
  74. $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
  75. if (empty($date_startmonth) || empty($date_endmonth)) {
  76. // Period by default on transfer
  77. $dates = getDefaultDatesForTransfer();
  78. $date_start = $dates['date_start'];
  79. $date_end = $dates['date_end'];
  80. $pastmonthyear = $dates['pastmonthyear'];
  81. $pastmonth = $dates['pastmonth'];
  82. }
  83. if (!GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) { // We define date_start and date_end, only if we did not submit the form
  84. $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
  85. $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
  86. }
  87. $sql = "SELECT er.rowid, er.ref, er.date_debut as de,";
  88. $sql .= " erd.rowid as erdid, erd.comments, erd.total_ht, erd.total_tva, erd.total_localtax1, erd.total_localtax2, erd.tva_tx, erd.total_ttc, erd.fk_code_ventilation, erd.vat_src_code, ";
  89. $sql .= " u.rowid as uid, u.firstname, u.lastname, u.accountancy_code as user_accountancy_account,";
  90. $sql .= " f.accountancy_code, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte";
  91. $sql .= " FROM ".MAIN_DB_PREFIX."expensereport_det as erd";
  92. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_type_fees as f ON f.id = erd.fk_c_type_fees";
  93. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = erd.fk_code_ventilation";
  94. $sql .= " JOIN ".MAIN_DB_PREFIX."expensereport as er ON er.rowid = erd.fk_expensereport";
  95. $sql .= " JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = er.fk_user_author";
  96. $sql .= " WHERE er.fk_statut > 0";
  97. $sql .= " AND erd.fk_code_ventilation > 0";
  98. $sql .= " AND er.entity IN (".getEntity('expensereport', 0).")"; // We don't share object for accountancy
  99. if ($date_start && $date_end) {
  100. $sql .= " AND er.date_debut >= '".$db->idate($date_start)."' AND er.date_debut <= '".$db->idate($date_end)."'";
  101. }
  102. // Define begin binding date
  103. if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) {
  104. $sql .= " AND er.date_debut >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'";
  105. }
  106. // Already in bookkeeping or not
  107. if ($in_bookkeeping == 'already') {
  108. $sql .= " AND er.rowid IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='expense_report')";
  109. }
  110. if ($in_bookkeeping == 'notyet') {
  111. $sql .= " AND er.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='expense_report')";
  112. }
  113. $sql .= " ORDER BY er.date_debut";
  114. dol_syslog('accountancy/journal/expensereportsjournal.php', LOG_DEBUG);
  115. $result = $db->query($sql);
  116. if ($result) {
  117. $taber = array();
  118. $tabht = array();
  119. $tabtva = array();
  120. $def_tva = array();
  121. $tabttc = array();
  122. $tablocaltax1 = array();
  123. $tablocaltax2 = array();
  124. $tabuser = array();
  125. $num = $db->num_rows($result);
  126. // Variables
  127. $account_salary = (!empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT)) ? $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT : 'NotDefined';
  128. $account_vat = (!empty($conf->global->ACCOUNTING_VAT_BUY_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_BUY_ACCOUNT : 'NotDefined';
  129. $i = 0;
  130. while ($i < $num) {
  131. $obj = $db->fetch_object($result);
  132. // Controls
  133. $compta_user = (!empty($obj->user_accountancy_account)) ? $obj->user_accountancy_account : $account_salary;
  134. $compta_fees = $obj->compte;
  135. $vatdata = getTaxesFromId($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), $mysoc, $mysoc, 0);
  136. $compta_tva = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $account_vat);
  137. $compta_localtax1 = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $cpttva);
  138. $compta_localtax2 = (!empty($vatdata['accountancy_code_buy']) ? $vatdata['accountancy_code_buy'] : $cpttva);
  139. // Define array to display all VAT rates that use this accounting account $compta_tva
  140. if (price2num($obj->tva_tx) || !empty($obj->vat_src_code)) {
  141. $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.')' : ''));
  142. }
  143. $taber[$obj->rowid]["date"] = $db->jdate($obj->de);
  144. $taber[$obj->rowid]["ref"] = $obj->ref;
  145. $taber[$obj->rowid]["comments"] = $obj->comments;
  146. $taber[$obj->rowid]["fk_expensereportdet"] = $obj->erdid;
  147. // Avoid warnings
  148. if (!isset($tabttc[$obj->rowid][$compta_user])) {
  149. $tabttc[$obj->rowid][$compta_user] = 0;
  150. }
  151. if (!isset($tabht[$obj->rowid][$compta_fees])) {
  152. $tabht[$obj->rowid][$compta_fees] = 0;
  153. }
  154. if (!isset($tabtva[$obj->rowid][$compta_tva])) {
  155. $tabtva[$obj->rowid][$compta_tva] = 0;
  156. }
  157. if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
  158. $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
  159. }
  160. if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
  161. $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
  162. }
  163. $tabttc[$obj->rowid][$compta_user] += $obj->total_ttc;
  164. $tabht[$obj->rowid][$compta_fees] += $obj->total_ht;
  165. $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva;
  166. $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1;
  167. $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2;
  168. $tabuser[$obj->rowid] = array(
  169. 'id' => $obj->uid,
  170. 'name' => dolGetFirstLastname($obj->firstname, $obj->lastname),
  171. 'user_accountancy_code' => $obj->user_accountancy_account
  172. );
  173. $i++;
  174. }
  175. } else {
  176. dol_print_error($db);
  177. }
  178. // Bookkeeping Write
  179. if ($action == 'writebookkeeping') {
  180. $now = dol_now();
  181. $error = 0;
  182. $accountingaccountexpense = new AccountingAccount($db);
  183. $accountingaccountexpense->fetch(null, $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT, true);
  184. foreach ($taber as $key => $val) { // Loop on each expense report
  185. $errorforline = 0;
  186. $totalcredit = 0;
  187. $totaldebit = 0;
  188. $db->begin();
  189. // Thirdparty
  190. if (!$errorforline) {
  191. foreach ($tabttc[$key] as $k => $mt) {
  192. if ($mt) {
  193. $bookkeeping = new BookKeeping($db);
  194. $bookkeeping->doc_date = $val["date"];
  195. $bookkeeping->doc_ref = $val["ref"];
  196. $bookkeeping->date_creation = $now;
  197. $bookkeeping->doc_type = 'expense_report';
  198. $bookkeeping->fk_doc = $key;
  199. $bookkeeping->fk_docdet = $val["fk_expensereportdet"];
  200. $bookkeeping->subledger_account = $tabuser[$key]['user_accountancy_code'];
  201. $bookkeeping->subledger_label = $tabuser[$key]['name'];
  202. $bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
  203. $bookkeeping->label_compte = $accountingaccountexpense->label;
  204. $bookkeeping->label_operation = $tabuser[$key]['name'];
  205. $bookkeeping->montant = $mt;
  206. $bookkeeping->sens = ($mt >= 0) ? 'C' : 'D';
  207. $bookkeeping->debit = ($mt <= 0) ? -$mt : 0;
  208. $bookkeeping->credit = ($mt > 0) ? $mt : 0;
  209. $bookkeeping->code_journal = $journal;
  210. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  211. $bookkeeping->fk_user_author = $user->id;
  212. $bookkeeping->entity = $conf->entity;
  213. $totaldebit += $bookkeeping->debit;
  214. $totalcredit += $bookkeeping->credit;
  215. $result = $bookkeeping->create($user);
  216. if ($result < 0) {
  217. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  218. $error++;
  219. $errorforline++;
  220. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  221. } else {
  222. $error++;
  223. $errorforline++;
  224. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  225. }
  226. }
  227. }
  228. }
  229. }
  230. // Fees
  231. if (!$errorforline) {
  232. foreach ($tabht[$key] as $k => $mt) {
  233. if ($mt) {
  234. // get compte id and label
  235. if ($accountingaccount->fetch(null, $k, true)) {
  236. $bookkeeping = new BookKeeping($db);
  237. $bookkeeping->doc_date = $val["date"];
  238. $bookkeeping->doc_ref = $val["ref"];
  239. $bookkeeping->date_creation = $now;
  240. $bookkeeping->doc_type = 'expense_report';
  241. $bookkeeping->fk_doc = $key;
  242. $bookkeeping->fk_docdet = $val["fk_expensereportdet"];
  243. $bookkeeping->subledger_account = '';
  244. $bookkeeping->subledger_label = '';
  245. $bookkeeping->numero_compte = $k;
  246. $bookkeeping->label_compte = $accountingaccount->label;
  247. $bookkeeping->label_operation = $accountingaccount->label;
  248. $bookkeeping->montant = $mt;
  249. $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
  250. $bookkeeping->debit = ($mt > 0) ? $mt : 0;
  251. $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
  252. $bookkeeping->code_journal = $journal;
  253. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  254. $bookkeeping->fk_user_author = $user->id;
  255. $bookkeeping->entity = $conf->entity;
  256. $totaldebit += $bookkeeping->debit;
  257. $totalcredit += $bookkeeping->credit;
  258. $result = $bookkeeping->create($user);
  259. if ($result < 0) {
  260. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  261. $error++;
  262. $errorforline++;
  263. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  264. } else {
  265. $error++;
  266. $errorforline++;
  267. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  268. }
  269. }
  270. }
  271. }
  272. }
  273. }
  274. // VAT
  275. if (!$errorforline) {
  276. $listoftax = array(0, 1, 2);
  277. foreach ($listoftax as $numtax) {
  278. $arrayofvat = $tabtva;
  279. if ($numtax == 1) {
  280. $arrayofvat = $tablocaltax1;
  281. }
  282. if ($numtax == 2) {
  283. $arrayofvat = $tablocaltax2;
  284. }
  285. foreach ($arrayofvat[$key] as $k => $mt) {
  286. if ($mt) {
  287. $accountingaccount->fetch(null, $k, true); // TODO Use a cache for label
  288. $account_label = $accountingaccount->label;
  289. // get compte id and label
  290. $bookkeeping = new BookKeeping($db);
  291. $bookkeeping->doc_date = $val["date"];
  292. $bookkeeping->doc_ref = $val["ref"];
  293. $bookkeeping->date_creation = $now;
  294. $bookkeeping->doc_type = 'expense_report';
  295. $bookkeeping->fk_doc = $key;
  296. $bookkeeping->fk_docdet = $val["fk_expensereportdet"];
  297. $bookkeeping->subledger_account = '';
  298. $bookkeeping->subledger_label = '';
  299. $bookkeeping->numero_compte = $k;
  300. $bookkeeping->label_compte = $account_label;
  301. $bookkeeping->label_operation = $langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %';
  302. $bookkeeping->montant = $mt;
  303. $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
  304. $bookkeeping->debit = ($mt > 0) ? $mt : 0;
  305. $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
  306. $bookkeeping->code_journal = $journal;
  307. $bookkeeping->journal_label = $langs->transnoentities($journal_label);
  308. $bookkeeping->fk_user_author = $user->id;
  309. $bookkeeping->entity = $conf->entity;
  310. $totaldebit += $bookkeeping->debit;
  311. $totalcredit += $bookkeeping->credit;
  312. $result = $bookkeeping->create($user);
  313. if ($result < 0) {
  314. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
  315. $error++;
  316. $errorforline++;
  317. //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  318. } else {
  319. $error++;
  320. $errorforline++;
  321. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  322. }
  323. }
  324. }
  325. }
  326. }
  327. }
  328. // Protection against a bug on line before
  329. if (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT')) {
  330. $error++;
  331. $errorforline++;
  332. setEventMessages('Try to insert a non balanced transaction in book for '.$val["ref"].'. Canceled. Surely a bug.', null, 'errors');
  333. }
  334. if (!$errorforline) {
  335. $db->commit();
  336. } else {
  337. $db->rollback();
  338. if ($error >= 10) {
  339. setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
  340. break; // Break in the foreach
  341. }
  342. }
  343. }
  344. $tabpay = $taber;
  345. if (empty($error) && count($tabpay) > 0) {
  346. setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
  347. } elseif (count($tabpay) == $error) {
  348. setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
  349. } else {
  350. setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
  351. }
  352. $action = '';
  353. // Must reload data, so we make a redirect
  354. if (count($tabpay) != $error) {
  355. $param = 'id_journal='.$id_journal;
  356. $param .= '&date_startday='.$date_startday;
  357. $param .= '&date_startmonth='.$date_startmonth;
  358. $param .= '&date_startyear='.$date_startyear;
  359. $param .= '&date_endday='.$date_endday;
  360. $param .= '&date_endmonth='.$date_endmonth;
  361. $param .= '&date_endyear='.$date_endyear;
  362. $param .= '&in_bookkeeping='.$in_bookkeeping;
  363. header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
  364. exit;
  365. }
  366. }
  367. /*
  368. * View
  369. */
  370. $form = new Form($db);
  371. $userstatic = new User($db);
  372. // Export
  373. if ($action == 'exportcsv') { // ISO and not UTF8 !
  374. $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
  375. $filename = 'journal';
  376. $type_export = 'journal';
  377. include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
  378. // CSV header line
  379. print '"'.$langs->transnoentitiesnoconv("Date").'"'.$sep;
  380. print '"'.$langs->transnoentitiesnoconv("Piece").'"'.$sep;
  381. print '"'.$langs->transnoentitiesnoconv("AccountAccounting").'"'.$sep;
  382. print '"'.$langs->transnoentitiesnoconv("LabelOperation").'"'.$sep;
  383. print '"'.$langs->transnoentitiesnoconv("AccountingDebit").'"'.$sep;
  384. print '"'.$langs->transnoentitiesnoconv("AccountingCredit").'"'.$sep;
  385. print "\n";
  386. foreach ($taber as $key => $val) {
  387. $date = dol_print_date($val["date"], 'day');
  388. $userstatic->id = $tabuser[$key]['id'];
  389. $userstatic->name = $tabuser[$key]['name'];
  390. // Fees
  391. foreach ($tabht[$key] as $k => $mt) {
  392. $accountingaccount = new AccountingAccount($db);
  393. $accountingaccount->fetch(null, $k, true);
  394. if ($mt) {
  395. print '"'.$date.'"'.$sep;
  396. print '"'.$val["ref"].'"'.$sep;
  397. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  398. print '"'.dol_trunc($accountingaccount->label, 32).'"'.$sep;
  399. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  400. print '"'.($mt < 0 ? price(-$mt) : '').'"';
  401. print "\n";
  402. }
  403. }
  404. // VAT
  405. foreach ($tabtva[$key] as $k => $mt) {
  406. if ($mt) {
  407. print '"'.$date.'"'.$sep;
  408. print '"'.$val["ref"].'"'.$sep;
  409. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  410. print '"'.dol_trunc($langs->trans("VAT")).'"'.$sep;
  411. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  412. print '"'.($mt < 0 ? price(-$mt) : '').'"';
  413. print "\n";
  414. }
  415. }
  416. // Third party
  417. foreach ($tabttc[$key] as $k => $mt) {
  418. print '"'.$date.'"'.$sep;
  419. print '"'.$val["ref"].'"'.$sep;
  420. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  421. print '"'.dol_trunc($userstatic->name).'"'.$sep;
  422. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  423. print '"'.($mt >= 0 ? price($mt) : '').'"';
  424. }
  425. print "\n";
  426. }
  427. }
  428. if (empty($action) || $action == 'view') {
  429. $title = $langs->trans("GenerationOfAccountingEntries").' - '.$accountingjournalstatic->getNomUrl(0, 2, 1, '', 1);
  430. llxHeader('', dol_string_nohtmltag($title));
  431. $nom = $title;
  432. $nomlink = '';
  433. $periodlink = '';
  434. $exportlink = '';
  435. $builddate = dol_now();
  436. $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
  437. $listofchoices = array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
  438. $period = $form->selectDate($date_start ? $date_start : -1, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end ? $date_end : -1, 'date_end', 0, 0, 0, '', 1, 0);
  439. $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
  440. $varlink = 'id_journal='.$id_journal;
  441. journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
  442. // Button to write into Ledger
  443. if (empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) || $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT == '-1') {
  444. print '<br><div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
  445. $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
  446. $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
  447. print $desc;
  448. print '</div>';
  449. }
  450. print '<div class="tabsAction tabsActionNoBottom centerimp">';
  451. if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL) && $in_bookkeeping == 'notyet') {
  452. print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
  453. }
  454. if (empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) || $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT == '-1') {
  455. print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
  456. } else {
  457. if ($in_bookkeeping == 'notyet') {
  458. print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
  459. } else {
  460. print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
  461. }
  462. }
  463. print '</div>';
  464. // TODO Avoid using js. We can use a direct link with $param
  465. print '
  466. <script type="text/javascript">
  467. function launch_export() {
  468. $("div.fiche form input[name=\"action\"]").val("exportcsv");
  469. $("div.fiche form input[type=\"submit\"]").click();
  470. $("div.fiche form input[name=\"action\"]").val("");
  471. }
  472. function writebookkeeping() {
  473. console.log("click on writebookkeeping");
  474. $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
  475. $("div.fiche form input[type=\"submit\"]").click();
  476. $("div.fiche form input[name=\"action\"]").val("");
  477. }
  478. </script>';
  479. /*
  480. * Show result array
  481. */
  482. print '<br>';
  483. $i = 0;
  484. print '<div class="div-table-responsive">';
  485. print "<table class=\"noborder\" width=\"100%\">";
  486. print "<tr class=\"liste_titre\">";
  487. print "<td>".$langs->trans("Date")."</td>";
  488. print "<td>".$langs->trans("Piece").' ('.$langs->trans("ExpenseReportRef").")</td>";
  489. print "<td>".$langs->trans("AccountAccounting")."</td>";
  490. print "<td>".$langs->trans("SubledgerAccount")."</td>";
  491. print "<td>".$langs->trans("LabelOperation")."</td>";
  492. print '<td class="right">'.$langs->trans("AccountingDebit")."</td>";
  493. print '<td class="right">'.$langs->trans("AccountingCredit")."</td>";
  494. print "</tr>\n";
  495. $r = '';
  496. $expensereportstatic = new ExpenseReport($db);
  497. $expensereportlinestatic = new ExpenseReportLine($db);
  498. foreach ($taber as $key => $val) {
  499. $expensereportstatic->id = $key;
  500. $expensereportstatic->ref = $val["ref"];
  501. $expensereportlinestatic->comments = html_entity_decode(dol_trunc($val["comments"], 32));
  502. $date = dol_print_date($val["date"], 'day');
  503. // Fees
  504. foreach ($tabht[$key] as $k => $mt) {
  505. $accountingaccount = new AccountingAccount($db);
  506. $accountingaccount->fetch(null, $k, true);
  507. if ($mt) {
  508. print '<tr class="oddeven">';
  509. print "<!-- Fees -->";
  510. print "<td>".$date."</td>";
  511. print "<td>".$expensereportstatic->getNomUrl(1)."</td>";
  512. $userstatic->id = $tabuser[$key]['id'];
  513. $userstatic->name = $tabuser[$key]['name'];
  514. // Account
  515. print "<td>";
  516. $accountoshow = length_accountg($k);
  517. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  518. print '<span class="error">'.$langs->trans("FeeAccountNotDefined").'</span>';
  519. } else {
  520. print $accountoshow;
  521. }
  522. print '</td>';
  523. // Subledger account
  524. print "<td>";
  525. print '</td>';
  526. $userstatic->id = $tabuser[$key]['id'];
  527. $userstatic->name = $tabuser[$key]['name'];
  528. print "<td>".$userstatic->getNomUrl(0, 'user', 16).' - '.$accountingaccount->label."</td>";
  529. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  530. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  531. print "</tr>";
  532. $i++;
  533. }
  534. }
  535. // Third party
  536. foreach ($tabttc[$key] as $k => $mt) {
  537. $userstatic->id = $tabuser[$key]['id'];
  538. $userstatic->name = $tabuser[$key]['name'];
  539. print '<tr class="oddeven">';
  540. print "<!-- Thirdparty -->";
  541. print "<td>".$date."</td>";
  542. print "<td>".$expensereportstatic->getNomUrl(1)."</td>";
  543. // Account
  544. print "<td>";
  545. $accountoshow = length_accountg($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT);
  546. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  547. print '<span class="error">'.$langs->trans("MainAccountForUsersNotDefined").'</span>';
  548. } else {
  549. print $accountoshow;
  550. }
  551. print "</td>";
  552. // Subledger account
  553. print "<td>";
  554. $accountoshow = length_accounta($k);
  555. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  556. print '<span class="error">'.$langs->trans("UserAccountNotDefined").'</span>';
  557. } else {
  558. print $accountoshow;
  559. }
  560. print '</td>';
  561. print "<td>".$userstatic->getNomUrl(0, 'user', 16).' - '.$langs->trans("SubledgerAccount")."</td>";
  562. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  563. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  564. print "</tr>";
  565. $i++;
  566. }
  567. // VAT
  568. $listoftax = array(0, 1, 2);
  569. foreach ($listoftax as $numtax) {
  570. $arrayofvat = $tabtva;
  571. if ($numtax == 1) {
  572. $arrayofvat = $tablocaltax1;
  573. }
  574. if ($numtax == 2) {
  575. $arrayofvat = $tablocaltax2;
  576. }
  577. foreach ($arrayofvat[$key] as $k => $mt) {
  578. if ($mt) {
  579. print '<tr class="oddeven">';
  580. print "<!-- VAT -->";
  581. print "<td>".$date."</td>";
  582. print "<td>".$expensereportstatic->getNomUrl(1)."</td>";
  583. // Account
  584. print "<td>";
  585. $accountoshow = length_accountg($k);
  586. if (($accountoshow == "") || $accountoshow == 'NotDefined') {
  587. print '<span class="error">'.$langs->trans("VATAccountNotDefined").'</span>';
  588. } else {
  589. print $accountoshow;
  590. }
  591. print "</td>";
  592. // Subledger account
  593. print "<td>";
  594. print '</td>';
  595. print "<td>".$userstatic->getNomUrl(0, 'user', 16).' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
  596. print "</td>";
  597. print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
  598. print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
  599. print "</tr>";
  600. $i++;
  601. }
  602. }
  603. }
  604. }
  605. if (!$i) {
  606. $colspan = 7;
  607. print '<tr class="oddeven"><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
  608. }
  609. print "</table>";
  610. print '</div>';
  611. // End of page
  612. llxFooter();
  613. }
  614. $db->close();