bankjournal.php 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  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 Christophe Battarel <christophe.battarel@altairis.fr>
  7. * Copyright (C) 2013-2019 Alexandre Spangaro <aspangaro@open-dsi.fr>
  8. * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
  9. * Copyright (C) 2013-2014 Olivier Geffroy <jeff@jeffinfo.com>
  10. * Copyright (C) 2017-2018 Frédéric France <frederic.france@netlogic.fr>
  11. * Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es>
  12. * Copyright (C) 2018 Eric Seigne <eric.seigne@cap-rel.fr>
  13. *
  14. * This program is free software; you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation; either version 3 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public License
  25. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  26. */
  27. /**
  28. * \file htdocs/accountancy/journal/bankjournal.php
  29. * \ingroup Accountancy (Double entries)
  30. * \brief Page with bank journal
  31. */
  32. require '../../main.inc.php';
  33. require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
  34. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  35. require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
  36. require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  37. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
  43. require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  44. require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
  45. require_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php';
  46. require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
  47. require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php';
  48. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  49. require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
  50. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  51. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
  52. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
  53. require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
  54. require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
  55. require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php';
  56. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php';
  57. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  58. require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php';
  59. require_once DOL_DOCUMENT_ROOT.'/loan/class/paymentloan.class.php';
  60. require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
  61. // Load translation files required by the page
  62. $langs->loadLangs(array("companies", "other", "compta", "banks", "bills", "donations", "loan", "accountancy", "trips", "salaries", "hrm", "members"));
  63. // Multi journal
  64. $id_journal = GETPOST('id_journal', 'int');
  65. $date_startmonth = GETPOST('date_startmonth', 'int');
  66. $date_startday = GETPOST('date_startday', 'int');
  67. $date_startyear = GETPOST('date_startyear', 'int');
  68. $date_endmonth = GETPOST('date_endmonth', 'int');
  69. $date_endday = GETPOST('date_endday', 'int');
  70. $date_endyear = GETPOST('date_endyear', 'int');
  71. $in_bookkeeping = GETPOST('in_bookkeeping', 'aZ09');
  72. if ($in_bookkeeping == '') $in_bookkeeping = 'notyet';
  73. $now = dol_now();
  74. $action = GETPOST('action', 'aZ09');
  75. // Security check
  76. if ($user->socid > 0 && empty($id_journal))
  77. accessforbidden();
  78. /*
  79. * Actions
  80. */
  81. $error = 0;
  82. $year_current = strftime("%Y", dol_now());
  83. $pastmonth = strftime("%m", dol_now()) - 1;
  84. $pastmonthyear = $year_current;
  85. if ($pastmonth == 0) {
  86. $pastmonth = 12;
  87. $pastmonthyear--;
  88. }
  89. $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
  90. $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
  91. 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
  92. {
  93. $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
  94. $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
  95. }
  96. $sql = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type, b.fk_account,";
  97. $sql .= " ba.courant, ba.ref as baref, ba.account_number, ba.fk_accountancy_journal,";
  98. $sql .= " soc.code_compta, soc.code_compta_fournisseur, soc.rowid as socid, soc.nom as name, soc.email as email, bu1.type as typeop_company,";
  99. $sql .= " u.accountancy_code, u.rowid as userid, u.lastname as lastname, u.firstname as firstname, u.email as useremail, bu2.type as typeop_user,";
  100. $sql .= " bu3.type as typeop_payment, bu4.type as typeop_payment_supplier";
  101. $sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
  102. $sql .= " JOIN ".MAIN_DB_PREFIX."bank_account as ba on b.fk_account=ba.rowid";
  103. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu1 ON bu1.fk_bank = b.rowid AND bu1.type='company'";
  104. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu2 ON bu2.fk_bank = b.rowid AND bu2.type='user'";
  105. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu3 ON bu3.fk_bank = b.rowid AND bu3.type='payment'";
  106. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu4 ON bu4.fk_bank = b.rowid AND bu4.type='payment_supplier'";
  107. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as soc on bu1.url_id=soc.rowid";
  108. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on bu2.url_id=u.rowid";
  109. $sql .= " WHERE ba.fk_accountancy_journal=".$id_journal;
  110. $sql .= ' AND b.amount != 0 AND ba.entity IN ('.getEntity('bank_account', 0).')'; // We don't share object for accountancy
  111. if ($date_start && $date_end)
  112. $sql .= " AND b.dateo >= '".$db->idate($date_start)."' AND b.dateo <= '".$db->idate($date_end)."'";
  113. // Already in bookkeeping or not
  114. if ($in_bookkeeping == 'already')
  115. {
  116. $sql .= " AND (b.rowid IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='bank') )";
  117. }
  118. if ($in_bookkeeping == 'notyet')
  119. {
  120. $sql .= " AND (b.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='bank') )";
  121. }
  122. $sql .= " ORDER BY b.datev";
  123. //print $sql;
  124. $object = new Account($db);
  125. $paymentstatic = new Paiement($db);
  126. $paymentsupplierstatic = new PaiementFourn($db);
  127. $societestatic = new Societe($db);
  128. $userstatic = new User($db);
  129. $bankaccountstatic = new Account($db);
  130. $chargestatic = new ChargeSociales($db);
  131. $paymentdonstatic = new PaymentDonation($db);
  132. $paymentvatstatic = new TVA($db);
  133. $paymentsalstatic = new PaymentSalary($db);
  134. $paymentexpensereportstatic = new PaymentExpenseReport($db);
  135. $paymentvariousstatic = new PaymentVarious($db);
  136. $paymentloanstatic = new PaymentLoan($db);
  137. $accountLinestatic = new AccountLine($db);
  138. $paymentsubscriptionstatic = new Subscription($db);
  139. $tmppayment = new Paiement($db);
  140. $tmpinvoice = new Facture($db);
  141. $accountingaccount = new AccountingAccount($db);
  142. // Get code of finance journal
  143. $accountingjournalstatic = new AccountingJournal($db);
  144. $accountingjournalstatic->fetch($id_journal);
  145. $journal = $accountingjournalstatic->code;
  146. $journal_label = $accountingjournalstatic->label;
  147. dol_syslog("accountancy/journal/bankjournal.php", LOG_DEBUG);
  148. $result = $db->query($sql);
  149. if ($result) {
  150. $num = $db->num_rows($result);
  151. //print $sql;
  152. // Variables
  153. $account_supplier = (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER != "") ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : 'NotDefined'); // NotDefined is a reserved word
  154. $account_customer = (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER != "") ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : 'NotDefined'); // NotDefined is a reserved word
  155. $account_employee = (!empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) ? $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT : 'NotDefined'); // NotDefined is a reserved word
  156. $account_pay_vat = (!empty($conf->global->ACCOUNTING_VAT_PAY_ACCOUNT) ? $conf->global->ACCOUNTING_VAT_PAY_ACCOUNT : 'NotDefined'); // NotDefined is a reserved word
  157. $account_pay_donation = (!empty($conf->global->DONATION_ACCOUNTINGACCOUNT) ? $conf->global->DONATION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word
  158. $account_pay_subscription = (!empty($conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT) ? $conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word
  159. $account_transfer = (!empty($conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH) ? $conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH : 'NotDefined'); // NotDefined is a reserved word
  160. $tabcompany = array();
  161. $tabuser = array();
  162. $tabpay = array();
  163. $tabbq = array();
  164. $tabtp = array();
  165. $tabtype = array();
  166. $tabmoreinfo = array();
  167. // Loop on each line into llx_bank table. For each line, we should get:
  168. // one line tabpay = line into bank
  169. // one line for bank record = tabbq
  170. // one line for thirdparty record = tabtp
  171. $i = 0;
  172. while ($i < $num)
  173. {
  174. $obj = $db->fetch_object($result);
  175. $lineisapurchase = -1;
  176. $lineisasale = -1;
  177. // Old method to detect if it's a sale or purchase
  178. if ($obj->label == '(SupplierInvoicePayment)' || $obj->label == '(SupplierInvoicePaymentBack)') $lineisapurchase = 1;
  179. if ($obj->label == '(CustomerInvoicePayment)' || $obj->label == '(CustomerInvoicePaymentBack)') $lineisasale = 1;
  180. // Try a more reliable method to detect if record is a supplier payment or a customer payment
  181. if ($lineisapurchase < 0)
  182. {
  183. if ($obj->typeop_payment_supplier == 'payment_supplier') $lineisapurchase = 1;
  184. }
  185. if ($lineisasale < 0)
  186. {
  187. if ($obj->typeop_payment == 'payment') $lineisasale = 1;
  188. }
  189. //var_dump($obj->type_payment); var_dump($obj->type_payment_supplier);
  190. //var_dump($lineisapurchase); //var_dump($lineisasale);
  191. // Set accountancy code for bank
  192. $compta_bank = $obj->account_number;
  193. // Set accountancy code for thirdparty (example: '411CU...' or '411' if no subledger account defined on customer)
  194. $compta_soc = 'NotDefined';
  195. if ($lineisapurchase > 0)
  196. $compta_soc = (($obj->code_compta_fournisseur != "") ? $obj->code_compta_fournisseur : $account_supplier);
  197. if ($lineisasale > 0)
  198. $compta_soc = (!empty($obj->code_compta) ? $obj->code_compta : $account_customer);
  199. $tabcompany[$obj->rowid] = array(
  200. 'id' => $obj->socid,
  201. 'name' => $obj->name,
  202. 'code_compta' => $compta_soc,
  203. 'email' => $obj->email
  204. );
  205. // Set accountancy code for user
  206. $compta_user = (!empty($obj->accountancy_code) ? $obj->accountancy_code : $account_employee);
  207. $tabuser[$obj->rowid] = array(
  208. 'id' => $obj->userid,
  209. 'name' => dolGetFirstLastname($obj->firstname, $obj->lastname),
  210. 'lastname' => $obj->lastname,
  211. 'firstname' => $obj->firstname,
  212. 'email' => $obj->useremail,
  213. 'accountancy_code' => $compta_user
  214. );
  215. // Variable bookkeeping ($obj->rowid is Bank Id)
  216. $tabpay[$obj->rowid]["date"] = $obj->do;
  217. $tabpay[$obj->rowid]["type_payment"] = $obj->fk_type; // CHQ, VIR, LIQ, CB, ...
  218. $tabpay[$obj->rowid]["ref"] = $obj->label; // By default. Not unique. May be changed later
  219. $tabpay[$obj->rowid]["fk_bank"] = $obj->rowid;
  220. $tabpay[$obj->rowid]["bank_account_ref"] = $obj->baref;
  221. $tabpay[$obj->rowid]["fk_bank_account"] = $obj->fk_account;
  222. if (preg_match('/^\((.*)\)$/i', $obj->label, $reg)) {
  223. $tabpay[$obj->rowid]["lib"] = $langs->trans($reg[1]);
  224. } else {
  225. $tabpay[$obj->rowid]["lib"] = dol_trunc($obj->label, 60);
  226. }
  227. $links = $object->get_url($obj->rowid); // Get an array('url'=>, 'url_id'=>, 'label'=>, 'type'=> 'fk_bank'=> )
  228. //var_dump($i);
  229. //var_dump($tabpay);
  230. //var_dump($tabcompany);
  231. // By default
  232. $tabpay[$obj->rowid]['type'] = 'unknown'; // Can be SOLD, miscellaneous entry, payment of patient, or any old record with no links in bank_url.
  233. $tabtype[$obj->rowid] = 'unknown';
  234. $tabmoreinfo[$obj->rowid] = array();
  235. // get_url may return -1 which is not traversable
  236. if (is_array($links) && count($links) > 0) {
  237. // Now loop on each link of record in bank.
  238. foreach ($links as $key => $val) {
  239. 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')))
  240. {
  241. // So we excluded 'company' and 'user' here. We want only payment lines
  242. // We save tabtype for a future use, to remember what kind of payment it is
  243. $tabpay[$obj->rowid]['type'] = $links[$key]['type'];
  244. $tabtype[$obj->rowid] = $links[$key]['type'];
  245. }
  246. elseif (in_array($links[$key]['type'], array('company', 'user')))
  247. {
  248. if ($tabpay[$obj->rowid]['type'] == 'unknown')
  249. {
  250. // We can guess here it is a bank record for a thirdparty company or a user.
  251. // 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.
  252. }
  253. }
  254. if ($links[$key]['type'] == 'withdraw') {
  255. $tabmoreinfo[$obj->rowid]['withdraw'] = 1;
  256. }
  257. if ($links[$key]['type'] == 'payment') {
  258. $paymentstatic->id = $links[$key]['url_id'];
  259. $paymentstatic->ref = $links[$key]['url_id'];
  260. $tabpay[$obj->rowid]["lib"] .= ' '.$paymentstatic->getNomUrl(2, '', ''); // TODO Do not include list of invoice in tooltip, the dol_string_nohtmltag is ko with this
  261. $tabpay[$obj->rowid]["paymentid"] = $paymentstatic->id;
  262. } elseif ($links[$key]['type'] == 'payment_supplier') {
  263. $paymentsupplierstatic->id = $links[$key]['url_id'];
  264. $paymentsupplierstatic->ref = $links[$key]['url_id'];
  265. $tabpay[$obj->rowid]["lib"] .= ' '.$paymentsupplierstatic->getNomUrl(2);
  266. $tabpay[$obj->rowid]["paymentsupplierid"] = $paymentsupplierstatic->id;
  267. } elseif ($links[$key]['type'] == 'company') {
  268. $societestatic->id = $links[$key]['url_id'];
  269. $societestatic->name = $links[$key]['label'];
  270. $societestatic->email = $tabcompany[$obj->rowid]['email'];
  271. $tabpay[$obj->rowid]["soclib"] = $societestatic->getNomUrl(1, '', 30);
  272. if ($compta_soc) $tabtp[$obj->rowid][$compta_soc] += $obj->amount;
  273. } elseif ($links[$key]['type'] == 'user') {
  274. $userstatic->id = $links[$key]['url_id'];
  275. $userstatic->name = $links[$key]['label'];
  276. $userstatic->email = $tabuser[$obj->rowid]['email'];
  277. $userstatic->firstname = $tabuser[$obj->rowid]['firstname'];
  278. $userstatic->lastname = $tabuser[$obj->rowid]['lastname'];
  279. if ($userstatic->id > 0) $tabpay[$obj->rowid]["soclib"] = $userstatic->getNomUrl(1, '', 30);
  280. else $tabpay[$obj->rowid]["soclib"] = '???'; // Should not happen, but happens with old data when id of user was not saved on expense report payment.
  281. if ($compta_user) $tabtp[$obj->rowid][$compta_user] += $obj->amount;
  282. } elseif ($links[$key]['type'] == 'sc') {
  283. $chargestatic->id = $links[$key]['url_id'];
  284. $chargestatic->ref = $links[$key]['url_id'];
  285. $tabpay[$obj->rowid]["lib"] .= ' '.$chargestatic->getNomUrl(2);
  286. if (preg_match('/^\((.*)\)$/i', $links[$key]['label'], $reg)) {
  287. if ($reg[1] == 'socialcontribution')
  288. $reg[1] = 'SocialContribution';
  289. $chargestatic->label = $langs->trans($reg[1]);
  290. } else {
  291. $chargestatic->label = $links[$key]['label'];
  292. }
  293. $chargestatic->ref = $chargestatic->label;
  294. $tabpay[$obj->rowid]["soclib"] = $chargestatic->getNomUrl(1, 30);
  295. $tabpay[$obj->rowid]["paymentscid"] = $chargestatic->id;
  296. $sqlmid = 'SELECT cchgsoc.accountancy_code';
  297. $sqlmid .= " FROM ".MAIN_DB_PREFIX."c_chargesociales cchgsoc ";
  298. $sqlmid .= " INNER JOIN ".MAIN_DB_PREFIX."chargesociales as chgsoc ON chgsoc.fk_type=cchgsoc.id";
  299. $sqlmid .= " INNER JOIN ".MAIN_DB_PREFIX."paiementcharge as paycharg ON paycharg.fk_charge=chgsoc.rowid";
  300. $sqlmid .= " INNER JOIN ".MAIN_DB_PREFIX."bank_url as bkurl ON bkurl.url_id=paycharg.rowid";
  301. $sqlmid .= " WHERE bkurl.fk_bank=".$obj->rowid;
  302. dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=".$sqlmid, LOG_DEBUG);
  303. $resultmid = $db->query($sqlmid);
  304. if ($resultmid) {
  305. $objmid = $db->fetch_object($resultmid);
  306. $tabtp[$obj->rowid][$objmid->accountancy_code] += $obj->amount;
  307. }
  308. } elseif ($links[$key]['type'] == 'payment_donation') {
  309. $paymentdonstatic->id = $links[$key]['url_id'];
  310. $paymentdonstatic->ref = $links[$key]['url_id'];
  311. $paymentdonstatic->fk_donation = $links[$key]['url_id'];
  312. $tabpay[$obj->rowid]["lib"] .= ' '.$paymentdonstatic->getNomUrl(2);
  313. $tabpay[$obj->rowid]["paymentdonationid"] = $paymentdonstatic->id;
  314. $tabtp[$obj->rowid][$account_pay_donation] += $obj->amount;
  315. } elseif ($links[$key]['type'] == 'member') {
  316. $paymentsubscriptionstatic->id = $links[$key]['url_id'];
  317. $paymentsubscriptionstatic->ref = $links[$key]['url_id'];
  318. $paymentsubscriptionstatic->label = $links[$key]['label'];
  319. $tabpay[$obj->rowid]["lib"] .= ' '.$paymentsubscriptionstatic->getNomUrl(2);
  320. $tabpay[$obj->rowid]["paymentsubscriptionid"] = $paymentsubscriptionstatic->id;
  321. $paymentsubscriptionstatic->fetch($paymentsubscriptionstatic->id);
  322. $tabtp[$obj->rowid][$account_pay_subscription] += $obj->amount;
  323. } elseif ($links[$key]['type'] == 'payment_vat') { // Payment VAT
  324. $paymentvatstatic->id = $links[$key]['url_id'];
  325. $paymentvatstatic->ref = $links[$key]['url_id'];
  326. $paymentvatstatic->label = $links[$key]['label'];
  327. $tabpay[$obj->rowid]["lib"] .= ' '.$paymentvatstatic->getNomUrl(2);
  328. $tabpay[$obj->rowid]["paymentvatid"] = $paymentvatstatic->id;
  329. $tabtp[$obj->rowid][$account_pay_vat] += $obj->amount;
  330. } elseif ($links[$key]['type'] == 'payment_salary') {
  331. $paymentsalstatic->id = $links[$key]['url_id'];
  332. $paymentsalstatic->ref = $links[$key]['url_id'];
  333. $paymentsalstatic->label = $links[$key]['label'];
  334. $tabpay[$obj->rowid]["lib"] .= ' '.$paymentsalstatic->getNomUrl(2);
  335. $tabpay[$obj->rowid]["paymentsalid"] = $paymentsalstatic->id;
  336. } elseif ($links[$key]['type'] == 'payment_expensereport') {
  337. $paymentexpensereportstatic->id = $links[$key]['url_id'];
  338. $tabpay[$obj->rowid]["lib"] .= $paymentexpensereportstatic->getNomUrl(2);
  339. $tabpay[$obj->rowid]["paymentexpensereport"] = $paymentexpensereportstatic->id;
  340. } elseif ($links[$key]['type'] == 'payment_various') {
  341. $paymentvariousstatic->id = $links[$key]['url_id'];
  342. $paymentvariousstatic->ref = $links[$key]['url_id'];
  343. $paymentvariousstatic->label = $links[$key]['label'];
  344. $tabpay[$obj->rowid]["lib"] .= ' '.$paymentvariousstatic->getNomUrl(2);
  345. $tabpay[$obj->rowid]["paymentvariousid"] = $paymentvariousstatic->id;
  346. $paymentvariousstatic->fetch($paymentvariousstatic->id);
  347. $account_various = (!empty($paymentvariousstatic->accountancy_code) ? $paymentvariousstatic->accountancy_code : 'NotDefined'); // NotDefined is a reserved word
  348. $account_subledger = (!empty($paymentvariousstatic->subledger_account) ? $paymentvariousstatic->subledger_account : ''); // NotDefined is a reserved word
  349. $tabpay[$obj->rowid]["account_various"] = $account_various;
  350. $tabtp[$obj->rowid][$account_subledger] += $obj->amount;
  351. } elseif ($links[$key]['type'] == 'payment_loan') {
  352. $paymentloanstatic->id = $links[$key]['url_id'];
  353. $paymentloanstatic->ref = $links[$key]['url_id'];
  354. $paymentloanstatic->fk_loan = $links[$key]['url_id'];
  355. $tabpay[$obj->rowid]["lib"] .= ' '.$paymentloanstatic->getNomUrl(2);
  356. $tabpay[$obj->rowid]["paymentloanid"] = $paymentloanstatic->id;
  357. //$tabtp[$obj->rowid][$account_pay_loan] += $obj->amount;
  358. $sqlmid = 'SELECT pl.amount_capital, pl.amount_insurance, pl.amount_interest, l.accountancy_account_capital, l.accountancy_account_insurance, l.accountancy_account_interest';
  359. $sqlmid .= ' FROM '.MAIN_DB_PREFIX.'payment_loan as pl, '.MAIN_DB_PREFIX.'loan as l';
  360. $sqlmid .= ' WHERE l.rowid = pl.fk_loan AND pl.fk_bank = '.$obj->rowid;
  361. dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=".$sqlmid, LOG_DEBUG);
  362. $resultmid = $db->query($sqlmid);
  363. if ($resultmid) {
  364. $objmid = $db->fetch_object($resultmid);
  365. $tabtp[$obj->rowid][$objmid->accountancy_account_capital] -= $objmid->amount_capital;
  366. $tabtp[$obj->rowid][$objmid->accountancy_account_insurance] -= $objmid->amount_insurance;
  367. $tabtp[$obj->rowid][$objmid->accountancy_account_interest] -= $objmid->amount_interest;
  368. }
  369. } elseif ($links[$key]['type'] == 'banktransfert') {
  370. $accountLinestatic->fetch($links[$key]['url_id']);
  371. $tabpay[$obj->rowid]["lib"] .= ' '.$langs->trans("BankTransfer").'- '.$accountLinestatic ->getNomUrl(1);
  372. $tabtp[$obj->rowid][$account_transfer] += $obj->amount;
  373. $bankaccountstatic->fetch($tabpay[$obj->rowid]['fk_bank_account']);
  374. $tabpay[$obj->rowid]["soclib"] = $bankaccountstatic->getNomUrl(2);
  375. }
  376. }
  377. }
  378. $tabbq[$obj->rowid][$compta_bank] += $obj->amount;
  379. // If no links were found to know the amount on thirdparty, we try to guess it.
  380. // This may happens on bank entries without the links lines to 'company'.
  381. if (empty($tabtp[$obj->rowid]) && !empty($tabmoreinfo[$obj->rowid]['withdraw'])) // If we dont find 'company' link because it is an old 'withdraw' record
  382. {
  383. foreach ($links as $key => $val) {
  384. if ($links[$key]['type'] == 'payment') {
  385. // Get thirdparty
  386. $tmppayment->fetch($links[$key]['url_id']);
  387. $arrayofamounts = $tmppayment->getAmountsArray();
  388. foreach ($arrayofamounts as $invoiceid => $amount)
  389. {
  390. $tmpinvoice->fetch($invoiceid);
  391. $tmpinvoice->fetch_thirdparty();
  392. if ($tmpinvoice->thirdparty->code_compta)
  393. {
  394. $tabtp[$obj->rowid][$tmpinvoice->thirdparty->code_compta] += $amount;
  395. }
  396. }
  397. }
  398. }
  399. }
  400. // If no links were found to know the amount on thirdparty, we init it to account 'NotDefined'.
  401. if (empty($tabtp[$obj->rowid])) $tabtp[$obj->rowid]['NotDefined'] = $tabbq[$obj->rowid][$compta_bank];
  402. // Check account number is ok
  403. /*if ($action == 'writebookkeeping') // Make test now in such a case
  404. {
  405. reset($tabbq[$obj->rowid]);
  406. $first_key_tabbq = key($tabbq[$obj->rowid]);
  407. if (empty($first_key_tabbq))
  408. {
  409. $error++;
  410. setEventMessages($langs->trans('ErrorAccountancyCodeOnBankAccountNotDefined', $obj->baref), null, 'errors');
  411. }
  412. reset($tabtp[$obj->rowid]);
  413. $first_key_tabtp = key($tabtp[$obj->rowid]);
  414. if (empty($first_key_tabtp))
  415. {
  416. $error++;
  417. setEventMessages($langs->trans('ErrorAccountancyCodeOnThirdPartyNotDefined'), null, 'errors');
  418. }
  419. }*/
  420. // if($obj->socid)$tabtp[$obj->rowid][$compta_soc] += $obj->amount;
  421. $i++;
  422. }
  423. } else {
  424. dol_print_error($db);
  425. }
  426. /*var_dump($tabpay);
  427. var_dump($tabcompany);
  428. var_dump($tabbq);
  429. var_dump($tabtp);
  430. var_dump($tabtype);*/
  431. // Write bookkeeping
  432. if (!$error && $action == 'writebookkeeping') {
  433. $now = dol_now();
  434. $error = 0;
  435. foreach ($tabpay as $key => $val) // $key is rowid into llx_bank
  436. {
  437. $date = dol_print_date($db->jdate($val["date"]), 'day');
  438. $ref = getSourceDocRef($val, $tabtype[$key]);
  439. $errorforline = 0;
  440. $totalcredit = 0;
  441. $totaldebit = 0;
  442. $db->begin();
  443. // Introduce a protection. Total of tabtp must be total of tabbq
  444. /*var_dump($tabpay);
  445. var_dump($tabtp);
  446. var_dump($tabbq);exit;*/
  447. // Bank
  448. if (!$errorforline && is_array($tabbq[$key]))
  449. {
  450. // Line into bank account
  451. foreach ($tabbq[$key] as $k => $mt)
  452. {
  453. if ($mt)
  454. {
  455. $reflabel = '';
  456. if (!empty($val['lib'])) $reflabel .= dol_string_nohtmltag($val['lib'])." - ";
  457. $reflabel .= $langs->trans("Bank").' '.dol_string_nohtmltag($val['bank_account_ref']);
  458. if (!empty($val['soclib'])) $reflabel .= " - ".dol_string_nohtmltag($val['soclib']);
  459. $bookkeeping = new BookKeeping($db);
  460. $bookkeeping->doc_date = $val["date"];
  461. $bookkeeping->doc_ref = $ref;
  462. $bookkeeping->doc_type = 'bank';
  463. $bookkeeping->fk_doc = $key;
  464. $bookkeeping->fk_docdet = $val["fk_bank"];
  465. $bookkeeping->numero_compte = $k;
  466. $accountingaccount->fetch(null, $k, true);
  467. $bookkeeping->label_compte = $accountingaccount->label;
  468. $bookkeeping->label_operation = $reflabel;
  469. $bookkeeping->montant = $mt;
  470. $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
  471. $bookkeeping->debit = ($mt >= 0 ? $mt : 0);
  472. $bookkeeping->credit = ($mt < 0 ? -$mt : 0);
  473. $bookkeeping->code_journal = $journal;
  474. $bookkeeping->journal_label = $journal_label;
  475. $bookkeeping->fk_user_author = $user->id;
  476. $bookkeeping->date_creation = $now;
  477. // No subledger_account value for the bank line but add a specific label_operation
  478. $bookkeeping->subledger_account = '';
  479. $bookkeeping->label_operation = $reflabel;
  480. $bookkeeping->entity = $conf->entity;
  481. $totaldebit += $bookkeeping->debit;
  482. $totalcredit += $bookkeeping->credit;
  483. $result = $bookkeeping->create($user);
  484. if ($result < 0) {
  485. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  486. {
  487. $error++;
  488. $errorforline++;
  489. setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  490. }
  491. else
  492. {
  493. $error++;
  494. $errorforline++;
  495. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  496. }
  497. }
  498. }
  499. }
  500. }
  501. // Third party
  502. if (!$errorforline)
  503. {
  504. if (is_array($tabtp[$key]))
  505. {
  506. // Line into thirdparty account
  507. foreach ($tabtp[$key] as $k => $mt) {
  508. if ($mt)
  509. {
  510. $reflabel = '';
  511. if (!empty($val['lib'])) $reflabel .= dol_string_nohtmltag($val['lib']).($val['soclib'] ? " - " : "");
  512. if ($tabtype[$key] == 'banktransfert')
  513. {
  514. $reflabel .= dol_string_nohtmltag($langs->transnoentitiesnoconv('TransitionalAccount').' '.$account_transfer);
  515. }
  516. else
  517. {
  518. $reflabel .= dol_string_nohtmltag($val['soclib']);
  519. }
  520. $bookkeeping = new BookKeeping($db);
  521. $bookkeeping->doc_date = $val["date"];
  522. $bookkeeping->doc_ref = $ref;
  523. $bookkeeping->doc_type = 'bank';
  524. $bookkeeping->fk_doc = $key;
  525. $bookkeeping->fk_docdet = $val["fk_bank"];
  526. $bookkeeping->label_operation = $reflabel;
  527. $bookkeeping->montant = $mt;
  528. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  529. $bookkeeping->debit = ($mt < 0 ? -$mt : 0);
  530. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  531. $bookkeeping->code_journal = $journal;
  532. $bookkeeping->journal_label = $journal_label;
  533. $bookkeeping->fk_user_author = $user->id;
  534. $bookkeeping->date_creation = $now;
  535. if ($tabtype[$key] == 'payment') { // If payment is payment of customer invoice, we get ref of invoice
  536. $bookkeeping->subledger_account = $k; // For payment, the subledger account is stored as $key of $tabtp
  537. $bookkeeping->subledger_label = $tabcompany[$key]['name']; // $tabcompany is defined only if we are sure there is 1 thirdparty for the bank transaction
  538. $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
  539. $accountingaccount->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER, true);
  540. $bookkeeping->label_compte = $accountingaccount->label;
  541. } elseif ($tabtype[$key] == 'payment_supplier') { // If payment is payment of supplier invoice, we get ref of invoice
  542. $bookkeeping->subledger_account = $k; // For payment, the subledger account is stored as $key of $tabtp
  543. $bookkeeping->subledger_label = $tabcompany[$key]['name']; // $tabcompany is defined only if we are sure there is 1 thirdparty for the bank transaction
  544. $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER;
  545. $accountingaccount->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER, true);
  546. $bookkeeping->label_compte = $accountingaccount->label;
  547. } elseif ($tabtype[$key] == 'payment_expensereport') {
  548. $bookkeeping->subledger_account = $tabuser[$key]['accountancy_code'];
  549. $bookkeeping->subledger_label = $tabuser[$key]['name'];
  550. $bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
  551. $accountingaccount->fetch(null, $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT, true);
  552. $bookkeeping->label_compte = $accountingaccount->label;
  553. } elseif ($tabtype[$key] == 'payment_salary') {
  554. $bookkeeping->subledger_account = $tabuser[$key]['accountancy_code'];
  555. $bookkeeping->subledger_label = $tabuser[$key]['name'];
  556. $bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
  557. $accountingaccount->fetch(null, $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT, true);
  558. $bookkeeping->label_compte = $accountingaccount->label;
  559. } elseif (in_array($tabtype[$key], array('sc', 'payment_sc'))) { // If payment is payment of social contribution
  560. $bookkeeping->subledger_account = '';
  561. $bookkeeping->subledger_label = '';
  562. $bookkeeping->numero_compte = $k;
  563. $accountingaccount->fetch(null, $k, true);
  564. $bookkeeping->label_compte = $accountingaccount->label;
  565. } elseif ($tabtype[$key] == 'payment_vat') {
  566. $bookkeeping->subledger_account = '';
  567. $bookkeeping->subledger_label = '';
  568. $bookkeeping->numero_compte = $k;
  569. $accountingaccount->fetch(null, $k, true);
  570. $bookkeeping->label_compte = $accountingaccount->label;
  571. } elseif ($tabtype[$key] == 'payment_donation') {
  572. $bookkeeping->subledger_account = '';
  573. $bookkeeping->subledger_label = '';
  574. $bookkeeping->numero_compte = $k;
  575. $accountingaccount->fetch(null, $k, true);
  576. $bookkeeping->label_compte = $accountingaccount->label;
  577. } elseif ($tabtype[$key] == 'member') {
  578. $bookkeeping->subledger_account = '';
  579. $bookkeeping->subledger_label = '';
  580. $bookkeeping->numero_compte = $k;
  581. $accountingaccount->fetch(null, $k, true);
  582. $bookkeeping->label_compte = $accountingaccount->label;
  583. } elseif ($tabtype[$key] == 'payment_loan') {
  584. $bookkeeping->subledger_account = '';
  585. $bookkeeping->subledger_label = '';
  586. $bookkeeping->numero_compte = $k;
  587. $accountingaccount->fetch(null, $k, true);
  588. $bookkeeping->label_compte = $accountingaccount->label;
  589. } elseif ($tabtype[$key] == 'payment_various') {
  590. $bookkeeping->subledger_account = $k;
  591. $bookkeeping->subledger_label = $tabcompany[$key]['name'];
  592. $bookkeeping->numero_compte = $tabpay[$key]["account_various"];
  593. $accountingaccount->fetch(null, $bookkeeping->numero_compte, true);
  594. $bookkeeping->label_compte = $accountingaccount->label;
  595. } elseif ($tabtype[$key] == 'banktransfert') {
  596. $bookkeeping->subledger_account = '';
  597. $bookkeeping->subledger_label = '';
  598. $bookkeeping->numero_compte = $k;
  599. $accountingaccount->fetch(null, $k, true);
  600. $bookkeeping->label_compte = $accountingaccount->label;
  601. } else {
  602. if ($tabtype[$key] == 'unknown') // Unknown transaction, we will use a waiting account for thirdparty.
  603. {
  604. // Temporary account
  605. $bookkeeping->subledger_account = '';
  606. $bookkeeping->subledger_label = '';
  607. $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE;
  608. $accountingaccount->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE, true);
  609. $bookkeeping->label_compte = $accountingaccount->label;
  610. }
  611. }
  612. $bookkeeping->label_operation = $reflabel;
  613. $bookkeeping->entity = $conf->entity;
  614. $totaldebit += $bookkeeping->debit;
  615. $totalcredit += $bookkeeping->credit;
  616. $result = $bookkeeping->create($user);
  617. if ($result < 0) {
  618. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  619. {
  620. $error++;
  621. $errorforline++;
  622. setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  623. }
  624. else
  625. {
  626. $error++;
  627. $errorforline++;
  628. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  629. }
  630. }
  631. }
  632. }
  633. }
  634. else { // If thirdparty unknown, output the waiting account
  635. foreach ($tabbq[$key] as $k => $mt) {
  636. if ($mt)
  637. {
  638. $reflabel = '';
  639. if (!empty($val['lib'])) $reflabel .= dol_string_nohtmltag($val['lib'])." - ";
  640. $reflabel .= dol_string_nohtmltag('WaitingAccount');
  641. $bookkeeping = new BookKeeping($db);
  642. $bookkeeping->doc_date = $val["date"];
  643. $bookkeeping->doc_ref = $ref;
  644. $bookkeeping->doc_type = 'bank';
  645. $bookkeeping->fk_doc = $key;
  646. $bookkeeping->fk_docdet = $val["fk_bank"];
  647. $bookkeeping->montant = $mt;
  648. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  649. $bookkeeping->debit = ($mt < 0 ? -$mt : 0);
  650. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  651. $bookkeeping->code_journal = $journal;
  652. $bookkeeping->journal_label = $journal_label;
  653. $bookkeeping->fk_user_author = $user->id;
  654. $bookkeeping->date_creation = $now;
  655. $bookkeeping->label_compte = '';
  656. $bookkeeping->label_operation = $reflabel;
  657. $bookkeeping->entity = $conf->entity;
  658. $totaldebit += $bookkeeping->debit;
  659. $totalcredit += $bookkeeping->credit;
  660. $result = $bookkeeping->create($user);
  661. if ($result < 0) {
  662. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  663. {
  664. $error++;
  665. $errorforline++;
  666. setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  667. }
  668. else
  669. {
  670. $error++;
  671. $errorforline++;
  672. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  673. }
  674. }
  675. }
  676. }
  677. }
  678. }
  679. if (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))
  680. {
  681. $error++;
  682. $errorforline++;
  683. setEventMessages('Try to insert a non balanced transaction in book for '.$ref.'. Canceled. Surely a bug.', null, 'errors');
  684. }
  685. if (!$errorforline)
  686. {
  687. $db->commit();
  688. }
  689. else
  690. {
  691. //print 'KO for line '.$key.' '.$error.'<br>';
  692. $db->rollback();
  693. $MAXNBERRORS = 5;
  694. if ($error >= $MAXNBERRORS)
  695. {
  696. setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped").' (>'.$MAXNBERRORS.')', null, 'errors');
  697. break; // Break in the foreach
  698. }
  699. }
  700. }
  701. if (empty($error) && count($tabpay) > 0) {
  702. setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
  703. }
  704. elseif (count($tabpay) == $error)
  705. {
  706. setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
  707. }
  708. else
  709. {
  710. setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
  711. }
  712. $action = '';
  713. // Must reload data, so we make a redirect
  714. if (count($tabpay) != $error)
  715. {
  716. $param = 'id_journal='.$id_journal;
  717. $param .= '&date_startday='.$date_startday;
  718. $param .= '&date_startmonth='.$date_startmonth;
  719. $param .= '&date_startyear='.$date_startyear;
  720. $param .= '&date_endday='.$date_endday;
  721. $param .= '&date_endmonth='.$date_endmonth;
  722. $param .= '&date_endyear='.$date_endyear;
  723. $param .= '&in_bookkeeping='.$in_bookkeeping;
  724. header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
  725. exit;
  726. }
  727. }
  728. // Export
  729. if ($action == 'exportcsv') { // ISO and not UTF8 !
  730. $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
  731. $filename = 'journal';
  732. $type_export = 'journal';
  733. include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
  734. // CSV header line
  735. print '"'.$langs->transnoentitiesnoconv("BankId").'"'.$sep;
  736. print '"'.$langs->transnoentitiesnoconv("Date").'"'.$sep;
  737. print '"'.$langs->transnoentitiesnoconv("PaymentMode").'"'.$sep;
  738. print '"'.$langs->transnoentitiesnoconv("AccountAccounting").'"'.$sep;
  739. print '"'.$langs->transnoentitiesnoconv("LedgerAccount").'"'.$sep;
  740. print '"'.$langs->transnoentitiesnoconv("SubledgerAccount").'"'.$sep;
  741. print '"'.$langs->transnoentitiesnoconv("Label").'"'.$sep;
  742. print '"'.$langs->transnoentitiesnoconv("Debit").'"'.$sep;
  743. print '"'.$langs->transnoentitiesnoconv("Credit").'"'.$sep;
  744. print '"'.$langs->transnoentitiesnoconv("Journal").'"'.$sep;
  745. print '"'.$langs->transnoentitiesnoconv("Note").'"'.$sep;
  746. print "\n";
  747. foreach ($tabpay as $key => $val)
  748. {
  749. $date = dol_print_date($db->jdate($val["date"]), 'day');
  750. $ref = getSourceDocRef($val, $tabtype[$key]);
  751. // Bank
  752. foreach ($tabbq[$key] as $k => $mt) {
  753. if ($mt)
  754. {
  755. $reflabel = '';
  756. if (!empty($val['lib'])) $reflabel .= dol_string_nohtmltag($val['lib'])." - ";
  757. $reflabel .= $langs->trans("Bank").' '.dol_string_nohtmltag($val['bank_account_ref']);
  758. if (!empty($val['soclib'])) $reflabel .= " - ".dol_string_nohtmltag($val['soclib']);
  759. print '"'.$key.'"'.$sep;
  760. print '"'.$date.'"'.$sep;
  761. print '"'.$val["type_payment"].'"'.$sep;
  762. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  763. print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
  764. print " ".$sep;
  765. print '"'.$reflabel.'"'.$sep;
  766. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  767. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  768. print '"'.$journal.'"'.$sep;
  769. print '"'.dol_string_nohtmltag($ref).'"'.$sep;
  770. print "\n";
  771. }
  772. }
  773. // Third party
  774. if (is_array($tabtp[$key])) {
  775. foreach ($tabtp[$key] as $k => $mt) {
  776. if ($mt)
  777. {
  778. $reflabel = '';
  779. if (!empty($val['lib'])) $reflabel .= dol_string_nohtmltag($val['lib']).($val['soclib'] ? " - " : "");
  780. if ($tabtype[$key] == 'banktransfert')
  781. {
  782. $reflabel .= dol_string_nohtmltag($langs->transnoentitiesnoconv('TransitionalAccount').' '.$account_transfer);
  783. }
  784. else
  785. {
  786. $reflabel .= dol_string_nohtmltag($val['soclib']);
  787. }
  788. print '"'.$key.'"'.$sep;
  789. print '"'.$date.'"'.$sep;
  790. print '"'.$val["type_payment"].'"'.$sep;
  791. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  792. if ($tabtype[$key] == 'payment_supplier') {
  793. print '"'.$conf->global->ACCOUNTING_ACCOUNT_SUPPLIER.'"'.$sep;
  794. } elseif ($tabtype[$key] == 'payment') {
  795. print '"'.$conf->global->ACCOUNTING_ACCOUNT_CUSTOMER.'"'.$sep;
  796. } elseif ($tabtype[$key] == 'payment_expensereport') {
  797. print '"'.$conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT.'"'.$sep;
  798. } elseif ($tabtype[$key] == 'payment_salary') {
  799. print '"'.$conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT.'"'.$sep;
  800. } else {
  801. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  802. }
  803. print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
  804. print '"'.$reflabel.'"'.$sep;
  805. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  806. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  807. print '"'.$journal.'"'.$sep;
  808. print '"'.dol_string_nohtmltag($ref).'"'.$sep;
  809. print "\n";
  810. }
  811. }
  812. } else { // If thirdparty unkown, output the waiting account
  813. foreach ($tabbq[$key] as $k => $mt) {
  814. if ($mt)
  815. {
  816. $reflabel = '';
  817. if (!empty($val['lib'])) $reflabel .= dol_string_nohtmltag($val['lib'])." - ";
  818. $reflabel .= dol_string_nohtmltag('WaitingAccount');
  819. print '"'.$key.'"'.$sep;
  820. print '"'.$date.'"'.$sep;
  821. print '"'.$val["type_payment"].'"'.$sep;
  822. print '"'.length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE).'"'.$sep;
  823. print '"'.length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE).'"'.$sep;
  824. print "".$sep;
  825. print '"'.$reflabel.'"'.$sep;
  826. print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
  827. print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
  828. print '"'.$journal.'"'.$sep;
  829. print '"'.dol_string_nohtmltag($ref).'"'.$sep;
  830. print "\n";
  831. }
  832. }
  833. }
  834. }
  835. }
  836. /*
  837. * View
  838. */
  839. $form = new Form($db);
  840. if (empty($action) || $action == 'view') {
  841. $invoicestatic = new Facture($db);
  842. $invoicesupplierstatic = new FactureFournisseur($db);
  843. $expensereportstatic = new ExpenseReport($db);
  844. $vatstatic = new Tva($db);
  845. $donationstatic = new Don($db);
  846. $loanstatic = new Loan($db);
  847. $salarystatic = new PaymentSalary($db);
  848. $variousstatic = new PaymentVarious($db);
  849. llxHeader('', $langs->trans("FinanceJournal"));
  850. $nom = $langs->trans("FinanceJournal").' | '.$accountingjournalstatic->getNomUrl(0, 1, 1, '', 1);
  851. $builddate = dol_now();
  852. //$description = $langs->trans("DescFinanceJournal") . '<br>';
  853. $description .= $langs->trans("DescJournalOnlyBindedVisible").'<br>';
  854. $listofchoices = array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
  855. $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);
  856. $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
  857. $varlink = 'id_journal='.$id_journal;
  858. journalHead($nom, '', $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
  859. // Test that setup is complete (we are in accounting, so test on entity is always on $conf->entity only, no sharing allowed)
  860. $sql = 'SELECT COUNT(rowid) as nb FROM '.MAIN_DB_PREFIX.'bank_account WHERE entity = '.$conf->entity.' AND fk_accountancy_journal IS NULL AND clos=0';
  861. $resql = $db->query($sql);
  862. if ($resql)
  863. {
  864. $obj = $db->fetch_object($resql);
  865. if ($obj->nb > 0)
  866. {
  867. print '<br>'.img_warning().' '.$langs->trans("TheJournalCodeIsNotDefinedOnSomeBankAccount");
  868. print ' : '.$langs->trans("AccountancyAreaDescBank", 9, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("BankAccounts").'</strong>');
  869. }
  870. }
  871. else dol_print_error($db);
  872. // Button to write into Ledger
  873. if (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1'
  874. || ($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1'
  875. || empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) || $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT == '-1') {
  876. print '<br>'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
  877. print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>');
  878. }
  879. print '<div class="tabsAction tabsActionNoBottom">';
  880. if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL)) print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
  881. if (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1'
  882. || ($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1') {
  883. print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
  884. }
  885. else {
  886. if ($in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
  887. else print '<a class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
  888. }
  889. print '</div>';
  890. // TODO Avoid using js. We can use a direct link with $param
  891. print '
  892. <script type="text/javascript">
  893. function launch_export() {
  894. console.log("Set value into form and submit");
  895. $("div.fiche form input[name=\"action\"]").val("exportcsv");
  896. $("div.fiche form input[type=\"submit\"]").click();
  897. $("div.fiche form input[name=\"action\"]").val("");
  898. }
  899. function writebookkeeping() {
  900. console.log("Set value into form and submit");
  901. $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
  902. $("div.fiche form input[type=\"submit\"]").click();
  903. $("div.fiche form input[name=\"action\"]").val("");
  904. }
  905. </script>';
  906. /*
  907. * Show result array
  908. */
  909. print '<br>';
  910. $i = 0;
  911. print '<div class="div-table-responsive">';
  912. print "<table class=\"noborder\" width=\"100%\">";
  913. print "<tr class=\"liste_titre\">";
  914. print "<td>".$langs->trans("Date")."</td>";
  915. print "<td>".$langs->trans("Piece").' ('.$langs->trans("ObjectsRef").")</td>";
  916. print "<td>".$langs->trans("AccountAccounting")."</td>";
  917. print "<td>".$langs->trans("SubledgerAccount")."</td>";
  918. print "<td>".$langs->trans("LabelOperation")."</td>";
  919. print '<td class="center">'.$langs->trans("PaymentMode")."</td>";
  920. print '<td class="right">'.$langs->trans("Debit")."</td>";
  921. print '<td class="right">'.$langs->trans("Credit")."</td>";
  922. print "</tr>\n";
  923. $r = '';
  924. foreach ($tabpay as $key => $val) // $key is rowid in llx_bank
  925. {
  926. $date = dol_print_date($db->jdate($val["date"]), 'day');
  927. $ref = getSourceDocRef($val, $tabtype[$key]);
  928. // Bank
  929. foreach ($tabbq[$key] as $k => $mt)
  930. {
  931. if ($mt)
  932. {
  933. $reflabel = '';
  934. if (!empty($val['lib'])) $reflabel .= $val['lib']." - ";
  935. $reflabel .= $langs->trans("Bank").' '.$val['bank_account_ref'];
  936. if (!empty($val['soclib'])) $reflabel .= " - ".$val['soclib'];
  937. //var_dump($tabpay[$key]);
  938. print '<!-- Bank bank.rowid='.$key.' type='.$tabpay[$key]['type'].' ref='.$tabpay[$key]['ref'].'-->';
  939. print '<tr class="oddeven">';
  940. print "<td>".$date."</td>";
  941. print "<td>".$ref."</td>";
  942. // Ledger account
  943. print "<td>";
  944. $accounttoshow = length_accountg($k);
  945. if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
  946. {
  947. print '<span class="error">'.$langs->trans("BankAccountNotDefined").'</span>';
  948. }
  949. else print $accounttoshow;
  950. print "</td>";
  951. // Subledger account
  952. print "<td>";
  953. /*$accounttoshow = length_accountg($k);
  954. if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
  955. {
  956. print '<span class="error">'.$langs->trans("BankAccountNotDefined").'</span>';
  957. }
  958. else print $accounttoshow;*/
  959. print "</td>";
  960. print "<td>";
  961. print $reflabel;
  962. print "</td>";
  963. print '<td class="center">'.$val["type_payment"]."</td>";
  964. print '<td class="right nowraponall">'.($mt >= 0 ? price($mt) : '')."</td>";
  965. print '<td class="right nowraponall">'.($mt < 0 ? price(-$mt) : '')."</td>";
  966. print "</tr>";
  967. }
  968. }
  969. // Third party
  970. if (is_array($tabtp[$key])) {
  971. foreach ($tabtp[$key] as $k => $mt) {
  972. if ($mt)
  973. {
  974. $reflabel = '';
  975. if (!empty($val['lib'])) $reflabel .= $val['lib'].($val['soclib'] ? " - " : "");
  976. if ($tabtype[$key] == 'banktransfert')
  977. {
  978. $reflabel .= $langs->trans('TransitionalAccount').' '.$account_transfer;
  979. }
  980. else
  981. {
  982. $reflabel .= $val['soclib'];
  983. }
  984. print '<!-- Thirdparty bank.rowid='.$key.' -->';
  985. print '<tr class="oddeven">';
  986. print "<td>".$date."</td>";
  987. print "<td>".$ref."</td>";
  988. // Ledger account
  989. print "<td>";
  990. $account_ledger = $k;
  991. // Try to force general ledger account depending on type
  992. if ($tabtype[$key] == 'payment') $account_ledger = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
  993. if ($tabtype[$key] == 'payment_supplier') $account_ledger = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER;
  994. if ($tabtype[$key] == 'payment_expensereport') $account_ledger = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
  995. if ($tabtype[$key] == 'payment_salary') $account_ledger = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
  996. if ($tabtype[$key] == 'payment_vat') $account_ledger = $conf->global->ACCOUNTING_VAT_PAY_ACCOUNT;
  997. if ($tabtype[$key] == 'member') $account_ledger = $conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT;
  998. if ($tabtype[$key] == 'payment_various') $account_ledger = $tabpay[$key]["account_various"];
  999. $accounttoshow = length_accounta($account_ledger);
  1000. if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
  1001. {
  1002. if ($tabtype[$key] == 'unknown')
  1003. {
  1004. // We will accept writing, but into a waiting account
  1005. if (empty($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE) || $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE == '-1')
  1006. {
  1007. print '<span class="error">'.$langs->trans('UnknownAccountForThirdpartyAndWaitingAccountNotDefinedBlocking').'</span>';
  1008. }
  1009. else
  1010. {
  1011. print '<span class="warning">'.$langs->trans('UnknownAccountForThirdparty', length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE)).'</span>'; // We will use a waiting account
  1012. }
  1013. }
  1014. else
  1015. {
  1016. // We will refuse writing
  1017. $errorstring = 'UnknownAccountForThirdpartyBlocking';
  1018. if ($tabtype[$key] == 'payment') $errorstring = 'MainAccountForCustomersNotDefined';
  1019. if ($tabtype[$key] == 'payment_supplier') $errorstring = 'MainAccountForSuppliersNotDefined';
  1020. if ($tabtype[$key] == 'payment_expensereport') $errorstring = 'MainAccountForUsersNotDefined';
  1021. if ($tabtype[$key] == 'payment_salary') $errorstring = 'MainAccountForUsersNotDefined';
  1022. if ($tabtype[$key] == 'payment_vat') $errorstring = 'MainAccountForVatPaymentNotDefined';
  1023. if ($tabtype[$key] == 'member') $errorstring = 'MainAccountForSubscriptionPaymentNotDefined';
  1024. print '<span class="error">'.$langs->trans($errorstring).'</span>';
  1025. }
  1026. }
  1027. else print $accounttoshow;
  1028. print "</td>";
  1029. // Subledger account
  1030. print "<td>";
  1031. if (in_array($tabtype[$key], array('payment', 'payment_supplier', 'payment_expensereport', 'payment_salary', 'payment_various'))) // Type of payment with subledger
  1032. {
  1033. $accounttoshowsubledger = length_accounta($k);
  1034. if ($accounttoshow != $accounttoshowsubledger)
  1035. {
  1036. if (empty($accounttoshowsubledger) || $accounttoshowsubledger == 'NotDefined')
  1037. {
  1038. /*var_dump($tabpay[$key]);
  1039. var_dump($tabtype[$key]);
  1040. var_dump($tabbq[$key]);*/
  1041. //print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
  1042. if (!empty($tabcompany[$key]['code_compta']))
  1043. {
  1044. if (in_array($tabtype[$key], array('payment_various'))) {
  1045. // For such case, if subledger is not defined, we won't use subledger accounts.
  1046. print '<span class="warning">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknownSubledgerIgnored").'</span>';
  1047. } else {
  1048. print '<span class="warning">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknown", $tabcompany[$key]['code_compta']).'</span>';
  1049. }
  1050. }
  1051. else
  1052. {
  1053. print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknownBlocking").'</span>';
  1054. }
  1055. }
  1056. else print $accounttoshowsubledger;
  1057. }
  1058. }
  1059. print "</td>";
  1060. print "<td>".$reflabel."</td>";
  1061. print '<td class="center">'.$val["type_payment"]."</td>";
  1062. print '<td class="right nowraponall">'.($mt < 0 ? price(-$mt) : '')."</td>";
  1063. print '<td class="right nowraponall">'.($mt >= 0 ? price($mt) : '')."</td>";
  1064. print "</tr>";
  1065. }
  1066. }
  1067. } else { // Waiting account
  1068. foreach ($tabbq[$key] as $k => $mt) {
  1069. if ($mt)
  1070. {
  1071. $reflabel = '';
  1072. if (!empty($val['lib'])) $reflabel .= $val['lib']." - ";
  1073. $reflabel .= 'WaitingAccount';
  1074. print '<!-- Wait bank.rowid='.$key.' -->';
  1075. print '<tr class="oddeven">';
  1076. print "<td>".$date."</td>";
  1077. print "<td>".$ref."</td>";
  1078. // Ledger account
  1079. print "<td>";
  1080. /*if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
  1081. {
  1082. print '<span class="error">'.$langs->trans("WaitAccountNotDefined").'</span>';
  1083. }
  1084. else */ print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE);
  1085. print "</td>";
  1086. // Subledger account
  1087. print "<td>";
  1088. /*if (empty($accounttoshowsubledger) || $accounttoshowsubledger == 'NotDefined')
  1089. {
  1090. print '<span class="error">'.$langs->trans("WaitAccountNotDefined").'</span>';
  1091. }
  1092. else print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE);
  1093. */
  1094. print "</td>";
  1095. print "<td>".$reflabel."</td>";
  1096. print '<td class="center">'.$val["type_payment"]."</td>";
  1097. print '<td class="right nowraponall">'.($mt < 0 ? price(-$mt) : '')."</td>";
  1098. print '<td class="right nowraponall">'.($mt >= 0 ? price($mt) : '')."</td>";
  1099. print "</tr>";
  1100. }
  1101. }
  1102. }
  1103. }
  1104. print "</table>";
  1105. print '</div>';
  1106. llxFooter();
  1107. }
  1108. $db->close();
  1109. /**
  1110. * Return source for doc_ref of a bank transaction
  1111. *
  1112. * @param string $val Array of val
  1113. * @param string $typerecord Type of record ('payment', 'payment_supplier', 'payment_expensereport', 'payment_vat', ...)
  1114. * @return string A string label to describe a record into llx_bank_url
  1115. */
  1116. function getSourceDocRef($val, $typerecord)
  1117. {
  1118. global $db, $langs;
  1119. // Defined the docref into $ref (We start with $val['ref'] by default and we complete according to other data)
  1120. // WE MUST HAVE SAME REF FOR ALL LINES WE WILL RECORD INTO THE BOOKKEEPING
  1121. $ref = $val['ref'];
  1122. if ($ref == '(SupplierInvoicePayment)' || $ref == '(SupplierInvoicePaymentBack)') {
  1123. $ref = $langs->transnoentitiesnoconv('Supplier');
  1124. }
  1125. if ($ref == '(CustomerInvoicePayment)' || $ref == '(CustomerInvoicePaymentBack)') {
  1126. $ref = $langs->transnoentitiesnoconv('Customer');
  1127. }
  1128. if ($ref == '(SocialContributionPayment)') {
  1129. $ref = $langs->transnoentitiesnoconv('SocialContribution');
  1130. }
  1131. if ($ref == '(DonationPayment)') {
  1132. $ref = $langs->transnoentitiesnoconv('Donation');
  1133. }
  1134. if ($ref == '(SubscriptionPayment)') {
  1135. $ref = $langs->transnoentitiesnoconv('Subscription');
  1136. }
  1137. if ($ref == '(ExpenseReportPayment)') {
  1138. $ref = $langs->transnoentitiesnoconv('Employee');
  1139. }
  1140. if ($ref == '(LoanPayment)') {
  1141. $ref = $langs->transnoentitiesnoconv('Loan');
  1142. }
  1143. if ($ref == '(payment_salary)') {
  1144. $ref = $langs->transnoentitiesnoconv('Employee');
  1145. }
  1146. $sqlmid = '';
  1147. if ($typerecord == 'payment')
  1148. {
  1149. $sqlmid = 'SELECT payfac.fk_facture as id, f.ref as ref';
  1150. $sqlmid .= " FROM ".MAIN_DB_PREFIX."paiement_facture as payfac, ".MAIN_DB_PREFIX."facture as f";
  1151. $sqlmid .= " WHERE payfac.fk_facture = f.rowid AND payfac.fk_paiement=".$val["paymentid"];
  1152. $ref = $langs->transnoentitiesnoconv("Invoice");
  1153. }
  1154. elseif ($typerecord == 'payment_supplier')
  1155. {
  1156. $sqlmid = 'SELECT payfac.fk_facturefourn as id, f.ref';
  1157. $sqlmid .= " FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn as payfac, ".MAIN_DB_PREFIX."facture_fourn as f";
  1158. $sqlmid .= " WHERE payfac.fk_facturefourn = f.rowid AND payfac.fk_paiementfourn=".$val["paymentsupplierid"];
  1159. $ref = $langs->transnoentitiesnoconv("SupplierInvoice");
  1160. }
  1161. elseif ($typerecord == 'payment_expensereport')
  1162. {
  1163. $sqlmid = 'SELECT e.rowid as id, e.ref';
  1164. $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_expensereport as pe, ".MAIN_DB_PREFIX."expensereport as e";
  1165. $sqlmid .= " WHERE pe.rowid=".$val["paymentexpensereport"]." AND pe.fk_expensereport = e.rowid";
  1166. $ref = $langs->transnoentitiesnoconv("ExpenseReport");
  1167. }
  1168. elseif ($typerecord == 'payment_salary')
  1169. {
  1170. $sqlmid = 'SELECT s.rowid as ref';
  1171. $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_salary as s";
  1172. $sqlmid .= " WHERE s.rowid=".$val["paymentsalid"];
  1173. $ref = $langs->transnoentitiesnoconv("SalaryPayment");
  1174. }
  1175. elseif ($typerecord == 'sc')
  1176. {
  1177. $sqlmid = 'SELECT sc.rowid as ref';
  1178. $sqlmid .= " FROM ".MAIN_DB_PREFIX."paiementcharge as sc";
  1179. $sqlmid .= " WHERE sc.rowid=".$val["paymentscid"];
  1180. $ref = $langs->transnoentitiesnoconv("SocialContribution");
  1181. }
  1182. elseif ($typerecord == 'payment_vat')
  1183. {
  1184. $sqlmid = 'SELECT v.rowid as ref';
  1185. $sqlmid .= " FROM ".MAIN_DB_PREFIX."tva as v";
  1186. $sqlmid .= " WHERE v.rowid=".$val["paymentvatid"];
  1187. $ref = $langs->transnoentitiesnoconv("PaymentVat");
  1188. }
  1189. elseif ($typerecord == 'payment_donation')
  1190. {
  1191. $sqlmid = 'SELECT payd.fk_donation as ref';
  1192. $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_donation as payd";
  1193. $sqlmid .= " WHERE payd.fk_donation=".$val["paymentdonationid"];
  1194. $ref = $langs->transnoentitiesnoconv("Donation");
  1195. }
  1196. elseif ($typerecord == 'payment_loan')
  1197. {
  1198. $sqlmid = 'SELECT l.rowid as ref';
  1199. $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_loan as l";
  1200. $sqlmid .= " WHERE l.rowid=".$val["paymentloanid"];
  1201. $ref = $langs->transnoentitiesnoconv("LoanPayment");
  1202. }
  1203. elseif ($typerecord == 'payment_various')
  1204. {
  1205. $sqlmid = 'SELECT v.rowid as ref';
  1206. $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_various as v";
  1207. $sqlmid .= " WHERE v.rowid=".$val["paymentvariousid"];
  1208. $ref = $langs->transnoentitiesnoconv("VariousPayment");
  1209. }
  1210. // Add warning
  1211. if (empty($sqlmid))
  1212. {
  1213. dol_syslog("Found a typerecord=".$typerecord." not supported", LOG_WARNING);
  1214. }
  1215. if ($sqlmid)
  1216. {
  1217. dol_syslog("accountancy/journal/bankjournal.php::sqlmid=".$sqlmid, LOG_DEBUG);
  1218. $resultmid = $db->query($sqlmid);
  1219. if ($resultmid)
  1220. {
  1221. while ($objmid = $db->fetch_object($resultmid))
  1222. {
  1223. $ref .= ' '.$objmid->ref;
  1224. }
  1225. }
  1226. else dol_print_error($db);
  1227. }
  1228. $ref = dol_trunc($langs->transnoentitiesnoconv("BankId").' '.$val['fk_bank'].' - '.$ref, 295); // 295 + 3 dots (...) is < than max size of 300
  1229. return $ref;
  1230. }