bankjournal.php 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364
  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-2018 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->societe_id > 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->lib = $langs->trans($reg[1]);
  290. } else {
  291. $chargestatic->lib = $links[$key]['label'];
  292. }
  293. $chargestatic->ref = $chargestatic->lib;
  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. $tabtp[$obj->rowid][$account_various] += $obj->amount;
  349. } elseif ($links[$key]['type'] == 'payment_loan') {
  350. $paymentloanstatic->id = $links[$key]['url_id'];
  351. $paymentloanstatic->ref = $links[$key]['url_id'];
  352. $paymentloanstatic->fk_loan = $links[$key]['url_id'];
  353. $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentloanstatic->getNomUrl(2);
  354. $tabpay[$obj->rowid]["paymentloanid"] = $paymentloanstatic->id;
  355. //$tabtp[$obj->rowid][$account_pay_loan] += $obj->amount;
  356. $sqlmid = 'SELECT pl.amount_capital, pl.amount_insurance, pl.amount_interest, l.accountancy_account_capital, l.accountancy_account_insurance, l.accountancy_account_interest';
  357. $sqlmid.= ' FROM '.MAIN_DB_PREFIX.'payment_loan as pl, '.MAIN_DB_PREFIX.'loan as l';
  358. $sqlmid.= ' WHERE l.rowid = pl.fk_loan AND pl.fk_bank = '.$obj->rowid;
  359. dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG);
  360. $resultmid = $db->query($sqlmid);
  361. if ($resultmid) {
  362. $objmid = $db->fetch_object($resultmid);
  363. $tabtp[$obj->rowid][$objmid->accountancy_account_capital] -= $objmid->amount_capital;
  364. $tabtp[$obj->rowid][$objmid->accountancy_account_insurance] -= $objmid->amount_insurance;
  365. $tabtp[$obj->rowid][$objmid->accountancy_account_interest] -= $objmid->amount_interest;
  366. }
  367. } elseif ($links[$key]['type'] == 'banktransfert') {
  368. $accountLinestatic->fetch($links[$key]['url_id']);
  369. $tabpay[$obj->rowid]["lib"] .= ' '.$langs->trans("BankTransfer").'- ' .$accountLinestatic ->getNomUrl(1);
  370. $tabtp[$obj->rowid][$account_transfer] += $obj->amount;
  371. $bankaccountstatic->fetch($tabpay[$obj->rowid]['fk_bank_account']);
  372. $tabpay[$obj->rowid]["soclib"] = $bankaccountstatic->getNomUrl(2);
  373. }
  374. }
  375. }
  376. $tabbq[$obj->rowid][$compta_bank] += $obj->amount;
  377. // If no links were found to know the amount on thirdparty, we try to guess it.
  378. // This may happens on bank entries without the links lines to 'company'.
  379. if (empty($tabtp[$obj->rowid]) && ! empty($tabmoreinfo[$obj->rowid]['withdraw'])) // If we dont find 'company' link because it is an old 'withdraw' record
  380. {
  381. foreach ($links as $key => $val) {
  382. if ($links[$key]['type'] == 'payment') {
  383. // Get thirdparty
  384. $tmppayment->fetch($links[$key]['url_id']);
  385. $arrayofamounts = $tmppayment->getAmountsArray();
  386. foreach($arrayofamounts as $invoiceid => $amount)
  387. {
  388. $tmpinvoice->fetch($invoiceid);
  389. $tmpinvoice->fetch_thirdparty();
  390. if ($tmpinvoice->thirdparty->code_compta)
  391. {
  392. $tabtp[$obj->rowid][$tmpinvoice->thirdparty->code_compta] += $amount;
  393. }
  394. }
  395. }
  396. }
  397. }
  398. // If no links were found to know the amount on thirdparty, we init it to account 'NotDefined'.
  399. if (empty($tabtp[$obj->rowid])) $tabtp[$obj->rowid]['NotDefined'] = $tabbq[$obj->rowid][$compta_bank];
  400. // Check account number is ok
  401. /*if ($action == 'writebookkeeping') // Make test now in such a case
  402. {
  403. reset($tabbq[$obj->rowid]);
  404. $first_key_tabbq = key($tabbq[$obj->rowid]);
  405. if (empty($first_key_tabbq))
  406. {
  407. $error++;
  408. setEventMessages($langs->trans('ErrorAccountancyCodeOnBankAccountNotDefined', $obj->baref), null, 'errors');
  409. }
  410. reset($tabtp[$obj->rowid]);
  411. $first_key_tabtp = key($tabtp[$obj->rowid]);
  412. if (empty($first_key_tabtp))
  413. {
  414. $error++;
  415. setEventMessages($langs->trans('ErrorAccountancyCodeOnThirdPartyNotDefined'), null, 'errors');
  416. }
  417. }*/
  418. // if($obj->socid)$tabtp[$obj->rowid][$compta_soc] += $obj->amount;
  419. $i++;
  420. }
  421. } else {
  422. dol_print_error($db);
  423. }
  424. /*var_dump($tabpay);
  425. var_dump($tabcompany);
  426. var_dump($tabbq);
  427. var_dump($tabtp);
  428. var_dump($tabtype);*/
  429. // Write bookkeeping
  430. if (! $error && $action == 'writebookkeeping') {
  431. $now = dol_now();
  432. $error = 0;
  433. foreach ($tabpay as $key => $val) // $key is rowid into llx_bank
  434. {
  435. $date = dol_print_date($db->jdate($val["date"]), 'day');
  436. $ref = getSourceDocRef($val, $tabtype[$key]);
  437. $errorforline = 0;
  438. $totalcredit = 0;
  439. $totaldebit = 0;
  440. $db->begin();
  441. // Introduce a protection. Total of tabtp must be total of tabbq
  442. /*var_dump($tabpay);
  443. var_dump($tabtp);
  444. var_dump($tabbq);exit;*/
  445. // Bank
  446. if (! $errorforline && is_array($tabbq[$key]))
  447. {
  448. // Line into bank account
  449. foreach ($tabbq[$key] as $k => $mt)
  450. {
  451. if ($mt)
  452. {
  453. $reflabel = '';
  454. if (! empty($val['lib'])) $reflabel .= dol_string_nohtmltag($val['lib']) . " - ";
  455. $reflabel.= $langs->trans("Bank").' '.dol_string_nohtmltag($val['bank_account_ref']);
  456. if (! empty($val['soclib'])) $reflabel .= " - " . dol_string_nohtmltag($val['soclib']);
  457. $bookkeeping = new BookKeeping($db);
  458. $bookkeeping->doc_date = $val["date"];
  459. $bookkeeping->doc_ref = $ref;
  460. $bookkeeping->doc_type = 'bank';
  461. $bookkeeping->fk_doc = $key;
  462. $bookkeeping->fk_docdet = $val["fk_bank"];
  463. $bookkeeping->numero_compte = $k;
  464. $accountingaccount->fetch(null, $k, true);
  465. $bookkeeping->label_compte = $accountingaccount->label;
  466. $bookkeeping->label_operation = $reflabel;
  467. $bookkeeping->montant = $mt;
  468. $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
  469. $bookkeeping->debit = ($mt >= 0 ? $mt : 0);
  470. $bookkeeping->credit = ($mt < 0 ? - $mt : 0);
  471. $bookkeeping->code_journal = $journal;
  472. $bookkeeping->journal_label = $journal_label;
  473. $bookkeeping->fk_user_author = $user->id;
  474. $bookkeeping->date_creation = $now;
  475. // No subledger_account value for the bank line but add a specific label_operation
  476. $bookkeeping->subledger_account = '';
  477. $bookkeeping->label_operation = $reflabel;
  478. $bookkeeping->entity = $conf->entity;
  479. $totaldebit += $bookkeeping->debit;
  480. $totalcredit += $bookkeeping->credit;
  481. $result = $bookkeeping->create($user);
  482. if ($result < 0) {
  483. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  484. {
  485. $error++;
  486. $errorforline++;
  487. setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  488. }
  489. else
  490. {
  491. $error++;
  492. $errorforline++;
  493. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  494. }
  495. }
  496. }
  497. }
  498. }
  499. // Third party
  500. if (! $errorforline)
  501. {
  502. if (is_array($tabtp[$key]))
  503. {
  504. // Line into thirdparty account
  505. foreach ($tabtp[$key] as $k => $mt) {
  506. if ($mt)
  507. {
  508. $reflabel = '';
  509. if (! empty($val['lib'])) $reflabel .= dol_string_nohtmltag($val['lib']) . ($val['soclib']?" - ":"");
  510. if ($tabtype[$key] == 'banktransfert')
  511. {
  512. $reflabel.= dol_string_nohtmltag($langs->transnoentitiesnoconv('TransitionalAccount').' '.$account_transfer);
  513. }
  514. else
  515. {
  516. $reflabel.= dol_string_nohtmltag($val['soclib']);
  517. }
  518. $bookkeeping = new BookKeeping($db);
  519. $bookkeeping->doc_date = $val["date"];
  520. $bookkeeping->doc_ref = $ref;
  521. $bookkeeping->doc_type = 'bank';
  522. $bookkeeping->fk_doc = $key;
  523. $bookkeeping->fk_docdet = $val["fk_bank"];
  524. $bookkeeping->label_operation = $reflabel;
  525. $bookkeeping->montant = $mt;
  526. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  527. $bookkeeping->debit = ($mt < 0 ? - $mt : 0);
  528. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  529. $bookkeeping->code_journal = $journal;
  530. $bookkeeping->journal_label = $journal_label;
  531. $bookkeeping->fk_user_author = $user->id;
  532. $bookkeeping->date_creation = $now;
  533. if ($tabtype[$key] == 'payment') { // If payment is payment of customer invoice, we get ref of invoice
  534. $bookkeeping->subledger_account = $k; // For payment, the subledger account is stored as $key of $tabtp
  535. $bookkeeping->subledger_label = $tabcompany[$key]['name']; // $tabcompany is defined only if we are sure there is 1 thirdparty for the bank transaction
  536. $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
  537. $accountingaccount->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER, true);
  538. $bookkeeping->label_compte = $accountingaccount->label;
  539. } elseif ($tabtype[$key] == 'payment_supplier') { // If payment is payment of supplier invoice, we get ref of invoice
  540. $bookkeeping->subledger_account = $k; // For payment, the subledger account is stored as $key of $tabtp
  541. $bookkeeping->subledger_label = $tabcompany[$key]['name']; // $tabcompany is defined only if we are sure there is 1 thirdparty for the bank transaction
  542. $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER;
  543. $accountingaccount->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER, true);
  544. $bookkeeping->label_compte = $accountingaccount->label;
  545. } elseif ($tabtype[$key] == 'payment_expensereport') {
  546. $bookkeeping->subledger_account = $tabuser[$key]['accountancy_code'];
  547. $bookkeeping->subledger_label = $tabuser[$key]['name'];
  548. $bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
  549. $accountingaccount->fetch(null, $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT, true);
  550. $bookkeeping->label_compte = $accountingaccount->label;
  551. } elseif ($tabtype[$key] == 'payment_salary') {
  552. $bookkeeping->subledger_account = $tabuser[$key]['accountancy_code'];
  553. $bookkeeping->subledger_label = $tabuser[$key]['name'];
  554. $bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
  555. $accountingaccount->fetch(null, $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT, true);
  556. $bookkeeping->label_compte = $accountingaccount->label;
  557. } elseif (in_array($tabtype[$key], array('sc', 'payment_sc'))) { // If payment is payment of social contribution
  558. $bookkeeping->subledger_account = '';
  559. $bookkeeping->subledger_label = '';
  560. $bookkeeping->numero_compte = $k;
  561. $bookkeeping->label_compte = $objmid->labelc;
  562. } elseif ($tabtype[$key] == 'payment_vat') {
  563. $bookkeeping->subledger_account = '';
  564. $bookkeeping->subledger_label = '';
  565. $bookkeeping->numero_compte = $k;
  566. $accountingaccount->fetch(null, $k, true);
  567. $bookkeeping->label_compte = $accountingaccount->label;
  568. } elseif ($tabtype[$key] == 'payment_donation') {
  569. $bookkeeping->subledger_account = '';
  570. $bookkeeping->subledger_label = '';
  571. $bookkeeping->numero_compte = $k;
  572. $accountingaccount->fetch(null, $k, true);
  573. $bookkeeping->label_compte = $accountingaccount->label;
  574. } elseif ($tabtype[$key] == 'member') {
  575. $bookkeeping->subledger_account = '';
  576. $bookkeeping->subledger_label = '';
  577. $bookkeeping->numero_compte = $k;
  578. $accountingaccount->fetch(null, $k, true);
  579. $bookkeeping->label_compte = $accountingaccount->label;
  580. } elseif ($tabtype[$key] == 'payment_loan') {
  581. $bookkeeping->subledger_account = '';
  582. $bookkeeping->subledger_label = '';
  583. $bookkeeping->numero_compte = $k;
  584. $accountingaccount->fetch(null, $k, true);
  585. $bookkeeping->label_compte = $accountingaccount->label;
  586. } elseif ($tabtype[$key] == 'payment_various') {
  587. $bookkeeping->subledger_account = '';
  588. $bookkeeping->subledger_label = '';
  589. $bookkeeping->numero_compte = $k;
  590. $accountingaccount->fetch(null, $k, true);
  591. $bookkeeping->label_compte = $accountingaccount->label;
  592. } elseif ($tabtype[$key] == 'banktransfert') {
  593. $bookkeeping->subledger_account = '';
  594. $bookkeeping->subledger_label = '';
  595. $bookkeeping->numero_compte = $k;
  596. $accountingaccount->fetch(null, $k, true);
  597. $bookkeeping->label_compte = $accountingaccount->label;
  598. } else {
  599. if ($tabtype[$key] == 'unknown') // Unknown transaction, we will use a waiting account for thirdparty.
  600. {
  601. // Temporary account
  602. $bookkeeping->subledger_account = '';
  603. $bookkeeping->subledger_label = '';
  604. $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE;
  605. $accountingaccount->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE, true);
  606. $bookkeeping->label_compte = $accountingaccount->label;
  607. }
  608. }
  609. $bookkeeping->label_operation = $reflabel;
  610. $bookkeeping->entity = $conf->entity;
  611. $totaldebit += $bookkeeping->debit;
  612. $totalcredit += $bookkeeping->credit;
  613. $result = $bookkeeping->create($user);
  614. if ($result < 0) {
  615. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  616. {
  617. $error++;
  618. $errorforline++;
  619. setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  620. }
  621. else
  622. {
  623. $error++;
  624. $errorforline++;
  625. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  626. }
  627. }
  628. }
  629. }
  630. }
  631. else { // If thirdparty unknown, output the waiting account
  632. foreach ($tabbq[$key] as $k => $mt) {
  633. if ($mt)
  634. {
  635. $reflabel = '';
  636. if (! empty($val['lib'])) $reflabel .= dol_string_nohtmltag($val['lib']) . " - ";
  637. $reflabel.= dol_string_nohtmltag('WaitingAccount');
  638. $bookkeeping = new BookKeeping($db);
  639. $bookkeeping->doc_date = $val["date"];
  640. $bookkeeping->doc_ref = $ref;
  641. $bookkeeping->doc_type = 'bank';
  642. $bookkeeping->fk_doc = $key;
  643. $bookkeeping->fk_docdet = $val["fk_bank"];
  644. $bookkeeping->montant = $mt;
  645. $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
  646. $bookkeeping->debit = ($mt < 0 ? - $mt : 0);
  647. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  648. $bookkeeping->code_journal = $journal;
  649. $bookkeeping->journal_label = $journal_label;
  650. $bookkeeping->fk_user_author = $user->id;
  651. $bookkeeping->date_creation = $now;
  652. $bookkeeping->label_compte = '';
  653. $bookkeeping->label_operation = $reflabel;
  654. $bookkeeping->entity = $conf->entity;
  655. $totaldebit += $bookkeeping->debit;
  656. $totalcredit += $bookkeeping->credit;
  657. $result = $bookkeeping->create($user);
  658. if ($result < 0) {
  659. if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
  660. {
  661. $error++;
  662. $errorforline++;
  663. setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
  664. }
  665. else
  666. {
  667. $error++;
  668. $errorforline++;
  669. setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
  670. }
  671. }
  672. }
  673. }
  674. }
  675. }
  676. if (price2num($totaldebit) != price2num($totalcredit))
  677. {
  678. $error++;
  679. $errorforline++;
  680. setEventMessages('Try to insert a non balanced transaction in book for '.$ref.'. Canceled. Surely a bug.', null, 'errors');
  681. }
  682. if (! $errorforline)
  683. {
  684. $db->commit();
  685. }
  686. else
  687. {
  688. //print 'KO for line '.$key.' '.$error.'<br>';
  689. $db->rollback();
  690. $MAXNBERRORS=5;
  691. if ($error >= $MAXNBERRORS)
  692. {
  693. setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped").' (>'.$MAXNBERRORS.')', null, 'errors');
  694. break; // Break in the foreach
  695. }
  696. }
  697. }
  698. if (empty($error) && count($tabpay) > 0) {
  699. setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
  700. }
  701. elseif (count($tabpay) == $error)
  702. {
  703. setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
  704. }
  705. else
  706. {
  707. setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
  708. }
  709. $action = '';
  710. // Must reload data, so we make a redirect
  711. if (count($tabpay) != $error)
  712. {
  713. $param='id_journal='.$id_journal;
  714. $param.='&date_startday='.$date_startday;
  715. $param.='&date_startmonth='.$date_startmonth;
  716. $param.='&date_startyear='.$date_startyear;
  717. $param.='&date_endday='.$date_endday;
  718. $param.='&date_endmonth='.$date_endmonth;
  719. $param.='&date_endyear='.$date_endyear;
  720. $param.='&in_bookkeeping='.$in_bookkeeping;
  721. header("Location: ".$_SERVER['PHP_SELF'].($param?'?'.$param:''));
  722. exit;
  723. }
  724. }
  725. // Export
  726. if ($action == 'exportcsv') { // ISO and not UTF8 !
  727. $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
  728. $filename = 'journal';
  729. $type_export = 'journal';
  730. include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php';
  731. // CSV header line
  732. print '"' . $langs->transnoentitiesnoconv("BankId").'"' . $sep;
  733. print '"' . $langs->transnoentitiesnoconv("Date") . '"' . $sep;
  734. print '"' . $langs->transnoentitiesnoconv("PaymentMode") . '"' . $sep;
  735. print '"' . $langs->transnoentitiesnoconv("AccountAccounting") . '"' . $sep;
  736. print '"' . $langs->transnoentitiesnoconv("LedgerAccount") . '"' . $sep;
  737. print '"' . $langs->transnoentitiesnoconv("SubledgerAccount") . '"' . $sep;
  738. print '"' . $langs->transnoentitiesnoconv("Label"). '"' . $sep;
  739. print '"' . $langs->transnoentitiesnoconv("Debit") . '"' . $sep;
  740. print '"' . $langs->transnoentitiesnoconv("Credit") . '"' . $sep;
  741. print '"' . $langs->transnoentitiesnoconv("Journal") . '"' . $sep;
  742. print '"' . $langs->transnoentitiesnoconv("Note") . '"' . $sep;
  743. print "\n";
  744. foreach ($tabpay as $key => $val)
  745. {
  746. $date = dol_print_date($db->jdate($val["date"]), 'day');
  747. $ref = getSourceDocRef($val, $tabtype[$key]);
  748. // Bank
  749. foreach ($tabbq[$key] as $k => $mt) {
  750. if ($mt)
  751. {
  752. $reflabel = '';
  753. if (! empty($val['lib'])) $reflabel .= dol_string_nohtmltag($val['lib']) . " - ";
  754. $reflabel.= $langs->trans("Bank").' '.dol_string_nohtmltag($val['bank_account_ref']);
  755. if (! empty($val['soclib'])) $reflabel .= " - " . dol_string_nohtmltag($val['soclib']);
  756. print '"' . $key . '"' . $sep;
  757. print '"' . $date . '"' . $sep;
  758. print '"' . $val["type_payment"] . '"' . $sep;
  759. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  760. print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
  761. print " " . $sep;
  762. print '"' . $reflabel . '"' . $sep;
  763. print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
  764. print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
  765. print '"' . $journal . '"' . $sep;
  766. print '"' . dol_string_nohtmltag($ref) . '"' . $sep;
  767. print "\n";
  768. }
  769. }
  770. // Third party
  771. if (is_array($tabtp[$key])) {
  772. foreach ($tabtp[$key] as $k => $mt) {
  773. if ($mt)
  774. {
  775. $reflabel = '';
  776. if (! empty($val['lib'])) $reflabel .= dol_string_nohtmltag($val['lib']) . ($val['soclib']?" - ":"");
  777. if ($tabtype[$key] == 'banktransfert')
  778. {
  779. $reflabel.= dol_string_nohtmltag($langs->transnoentitiesnoconv('TransitionalAccount').' '.$account_transfer);
  780. }
  781. else
  782. {
  783. $reflabel.= dol_string_nohtmltag($val['soclib']);
  784. }
  785. print '"' . $key . '"' . $sep;
  786. print '"' . $date . '"' . $sep;
  787. print '"' . $val["type_payment"] . '"' . $sep;
  788. print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
  789. if ($tabtype[$key] == 'payment_supplier') {
  790. print '"' . $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER . '"' . $sep;
  791. } elseif($tabtype[$key] == 'payment') {
  792. print '"' . $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER . '"' . $sep;
  793. } elseif($tabtype[$key] == 'payment_expensereport') {
  794. print '"' . $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT . '"' . $sep;
  795. } elseif($tabtype[$key] == 'payment_salary') {
  796. print '"' . $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT . '"' . $sep;
  797. } else {
  798. print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
  799. }
  800. print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
  801. print '"' . $reflabel . '"' . $sep;
  802. print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
  803. print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
  804. print '"' . $journal . '"' . $sep;
  805. print '"' . dol_string_nohtmltag($ref) . '"' . $sep;
  806. print "\n";
  807. }
  808. }
  809. } else { // If thirdparty unkown, output the waiting account
  810. foreach ($tabbq[$key] as $k => $mt) {
  811. if ($mt)
  812. {
  813. $reflabel = '';
  814. if (! empty($val['lib'])) $reflabel .= dol_string_nohtmltag($val['lib']) . " - ";
  815. $reflabel.= dol_string_nohtmltag('WaitingAccount');
  816. print '"' . $key . '"' . $sep;
  817. print '"' . $date . '"' . $sep;
  818. print '"' . $val["type_payment"] . '"' . $sep;
  819. print '"' . length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE) . '"' . $sep;
  820. print '"' . length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE) . '"' . $sep;
  821. print "" . $sep;
  822. print '"' . $reflabel . '"' . $sep;
  823. print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
  824. print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
  825. print '"' . $journal . '"' . $sep;
  826. print '"' . dol_string_nohtmltag($ref) . '"' . $sep;
  827. print "\n";
  828. }
  829. }
  830. }
  831. }
  832. }
  833. /*
  834. * View
  835. */
  836. $form = new Form($db);
  837. if (empty($action) || $action == 'view') {
  838. $invoicestatic = new Facture($db);
  839. $invoicesupplierstatic = new FactureFournisseur($db);
  840. $expensereportstatic = new ExpenseReport($db);
  841. $vatstatic = new Tva($db);
  842. $donationstatic = new Don($db);
  843. $loanstatic = new Loan($db);
  844. $salarystatic = new PaymentSalary($db);
  845. $variousstatic = new PaymentVarious($db);
  846. llxHeader('', $langs->trans("FinanceJournal"));
  847. $nom = $langs->trans("FinanceJournal") . ' | ' . $accountingjournalstatic->getNomUrl(0, 1, 1, '', 1);
  848. $builddate=dol_now();
  849. //$description = $langs->trans("DescFinanceJournal") . '<br>';
  850. $description.= $langs->trans("DescJournalOnlyBindedVisible").'<br>';
  851. $listofchoices=array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
  852. $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);
  853. $period .= ' - ' .$langs->trans("JournalizationInLedgerStatus").' '. $form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
  854. $varlink = 'id_journal=' . $id_journal;
  855. journalHead($nom, '', $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
  856. // Test that setup is complete
  857. $sql = 'SELECT COUNT(rowid) as nb FROM '.MAIN_DB_PREFIX.'bank_account WHERE fk_accountancy_journal IS NULL AND clos=0';
  858. $resql = $db->query($sql);
  859. if ($resql)
  860. {
  861. $obj = $db->fetch_object($resql);
  862. if ($obj->nb > 0)
  863. {
  864. print '<br>'.img_warning().' '.$langs->trans("TheJournalCodeIsNotDefinedOnSomeBankAccount");
  865. print ' : '.$langs->trans("AccountancyAreaDescBank", 9, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("BankAccounts").'</strong>');
  866. }
  867. }
  868. else dol_print_error($db);
  869. // Button to write into Ledger
  870. if (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1'
  871. || ($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1'
  872. || empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) || $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT == '-1') {
  873. print '<br>'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
  874. print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>');
  875. }
  876. print '<div class="tabsAction tabsActionNoBottom">';
  877. if (! empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL)) print '<input type="button" class="butAction" name="exportcsv" value="' . $langs->trans("ExportDraftJournal") . '" onclick="launch_export();" />';
  878. if (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1'
  879. || ($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1') {
  880. print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="' . $langs->trans("WriteBookKeeping") . '" />';
  881. }
  882. else {
  883. if ($in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="writebookkeeping" value="' . $langs->trans("WriteBookKeeping") . '" onclick="writebookkeeping();" />';
  884. else print '<a class="butActionRefused classfortooltip" name="writebookkeeping">' . $langs->trans("WriteBookKeeping") . '</a>';
  885. }
  886. print '</div>';
  887. // TODO Avoid using js. We can use a direct link with $param
  888. print '
  889. <script type="text/javascript">
  890. function launch_export() {
  891. console.log("Set value into form and submit");
  892. $("div.fiche form input[name=\"action\"]").val("exportcsv");
  893. $("div.fiche form input[type=\"submit\"]").click();
  894. $("div.fiche form input[name=\"action\"]").val("");
  895. }
  896. function writebookkeeping() {
  897. console.log("Set value into form and submit");
  898. $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
  899. $("div.fiche form input[type=\"submit\"]").click();
  900. $("div.fiche form input[name=\"action\"]").val("");
  901. }
  902. </script>';
  903. /*
  904. * Show result array
  905. */
  906. print '<br>';
  907. $i = 0;
  908. print '<div class="div-table-responsive">';
  909. print "<table class=\"noborder\" width=\"100%\">";
  910. print "<tr class=\"liste_titre\">";
  911. print "<td>" . $langs->trans("Date") . "</td>";
  912. print "<td>" . $langs->trans("Piece") . ' (' . $langs->trans("ObjectsRef") . ")</td>";
  913. print "<td>" . $langs->trans("AccountAccounting") . "</td>";
  914. print "<td>" . $langs->trans("SubledgerAccount") . "</td>";
  915. print "<td>" . $langs->trans("LabelOperation") . "</td>";
  916. print '<td class="center">' . $langs->trans("PaymentMode") . "</td>";
  917. print '<td class="right">' . $langs->trans("Debit") . "</td>";
  918. print '<td class="right">' . $langs->trans("Credit") . "</td>";
  919. print "</tr>\n";
  920. $r = '';
  921. foreach ($tabpay as $key => $val) // $key is rowid in llx_bank
  922. {
  923. $date = dol_print_date($db->jdate($val["date"]), 'day');
  924. $ref = getSourceDocRef($val, $tabtype[$key]);
  925. // Bank
  926. foreach ($tabbq[$key] as $k => $mt)
  927. {
  928. if ($mt)
  929. {
  930. $reflabel = '';
  931. if (! empty($val['lib'])) $reflabel .= $val['lib'] . " - ";
  932. $reflabel.= $langs->trans("Bank").' '.$val['bank_account_ref'];
  933. if (! empty($val['soclib'])) $reflabel .= " - " . $val['soclib'];
  934. //var_dump($tabpay[$key]);
  935. print '<!-- Bank bank.rowid='.$key.' type='.$tabpay[$key]['type'].' ref='.$tabpay[$key]['ref'].'-->';
  936. print '<tr class="oddeven">';
  937. print "<td>" . $date . "</td>";
  938. print "<td>" . $ref . "</td>";
  939. // Ledger account
  940. print "<td>";
  941. $accounttoshow = length_accountg($k);
  942. if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
  943. {
  944. print '<span class="error">'.$langs->trans("BankAccountNotDefined").'</span>';
  945. }
  946. else print $accounttoshow;
  947. print "</td>";
  948. // Subledger account
  949. print "<td>";
  950. /*$accounttoshow = length_accountg($k);
  951. if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
  952. {
  953. print '<span class="error">'.$langs->trans("BankAccountNotDefined").'</span>';
  954. }
  955. else print $accounttoshow;*/
  956. print "</td>";
  957. print "<td>";
  958. print $reflabel;
  959. print "</td>";
  960. print '<td class="center">' . $val["type_payment"] . "</td>";
  961. print '<td class="right nowraponall">' . ($mt >= 0 ? price($mt) : '') . "</td>";
  962. print '<td class="right nowraponall">' . ($mt < 0 ? price(- $mt) : '') . "</td>";
  963. print "</tr>";
  964. }
  965. }
  966. // Third party
  967. if (is_array($tabtp[$key])) {
  968. foreach ($tabtp[$key] as $k => $mt) {
  969. if ($mt)
  970. {
  971. $reflabel = '';
  972. if (! empty($val['lib'])) $reflabel .= $val['lib'] . ($val['soclib']?" - ":"");
  973. if ($tabtype[$key] == 'banktransfert')
  974. {
  975. $reflabel.= $langs->trans('TransitionalAccount').' '.$account_transfer;
  976. }
  977. else
  978. {
  979. $reflabel.= $val['soclib'];
  980. }
  981. print '<!-- Thirdparty bank.rowid='.$key.' -->';
  982. print '<tr class="oddeven">';
  983. print "<td>" . $date . "</td>";
  984. print "<td>" . $ref . "</td>";
  985. // Ledger account
  986. print "<td>";
  987. $account_ledger = $k;
  988. // Try to force general ledger account depending on type
  989. if ($tabtype[$key] == 'payment') $account_ledger = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
  990. if ($tabtype[$key] == 'payment_supplier') $account_ledger = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER;
  991. if ($tabtype[$key] == 'payment_expensereport') $account_ledger = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
  992. if ($tabtype[$key] == 'payment_salary') $account_ledger = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
  993. if ($tabtype[$key] == 'payment_vat') $account_ledger = $conf->global->ACCOUNTING_VAT_PAY_ACCOUNT;
  994. if ($tabtype[$key] == 'member') $account_ledger = $conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT;
  995. $accounttoshow = length_accounta($account_ledger);
  996. if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
  997. {
  998. if ($tabtype[$key] == 'unknown')
  999. {
  1000. // We will accept writing, but into a waiting account
  1001. if (empty($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE) || $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE == '-1')
  1002. {
  1003. print '<span class="error">'.$langs->trans('UnknownAccountForThirdpartyAndWaitingAccountNotDefinedBlocking').'</span>';
  1004. }
  1005. else
  1006. {
  1007. print '<span class="warning">'.$langs->trans('UnknownAccountForThirdparty', length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE)).'</span>'; // We will use a waiting account
  1008. }
  1009. }
  1010. else
  1011. {
  1012. // We will refuse writing
  1013. $errorstring='UnknownAccountForThirdpartyBlocking';
  1014. if ($tabtype[$key] == 'payment') $errorstring='MainAccountForCustomersNotDefined';
  1015. if ($tabtype[$key] == 'payment_supplier') $errorstring='MainAccountForSuppliersNotDefined';
  1016. if ($tabtype[$key] == 'payment_expensereport') $errorstring='MainAccountForUsersNotDefined';
  1017. if ($tabtype[$key] == 'payment_salary') $errorstring='MainAccountForUsersNotDefined';
  1018. if ($tabtype[$key] == 'payment_vat') $errorstring='MainAccountForVatPaymentNotDefined';
  1019. if ($tabtype[$key] == 'member') $errorstring='MainAccountForSubscriptionPaymentNotDefined';
  1020. print '<span class="error">'.$langs->trans($errorstring).'</span>';
  1021. }
  1022. }
  1023. else print $accounttoshow;
  1024. print "</td>";
  1025. // Subledger account
  1026. print "<td>";
  1027. if (in_array($tabtype[$key], array('payment', 'payment_supplier', 'payment_expensereport', 'payment_salary'))) // Type of payment with subledger
  1028. {
  1029. $accounttoshowsubledger = length_accounta($k);
  1030. if ($accounttoshow != $accounttoshowsubledger)
  1031. {
  1032. if (empty($accounttoshowsubledger) || $accounttoshowsubledger == 'NotDefined')
  1033. {
  1034. /*var_dump($tabpay[$key]);
  1035. var_dump($tabtype[$key]);
  1036. var_dump($tabbq[$key]);*/
  1037. //print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
  1038. if (! empty($tabcompany[$key]['code_compta']))
  1039. {
  1040. print '<span class="warning">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknown", $tabcompany[$key]['code_compta']).'</span>';
  1041. }
  1042. else
  1043. {
  1044. print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknownBlocking").'</span>';
  1045. }
  1046. }
  1047. else print $accounttoshowsubledger;
  1048. }
  1049. }
  1050. print "</td>";
  1051. print "<td>" . $reflabel . "</td>";
  1052. print '<td class="center">' . $val["type_payment"] . "</td>";
  1053. print '<td class="right nowraponall">' . ($mt < 0 ? price(- $mt) : '') . "</td>";
  1054. print '<td class="right nowraponall">' . ($mt >= 0 ? price($mt) : '') . "</td>";
  1055. print "</tr>";
  1056. }
  1057. }
  1058. } else { // Waiting account
  1059. foreach ($tabbq[$key] as $k => $mt) {
  1060. if ($mt)
  1061. {
  1062. $reflabel = '';
  1063. if (! empty($val['lib'])) $reflabel .= $val['lib'] . " - ";
  1064. $reflabel.= 'WaitingAccount';
  1065. print '<!-- Wait bank.rowid='.$key.' -->';
  1066. print '<tr class="oddeven">';
  1067. print "<td>" . $date . "</td>";
  1068. print "<td>" . $ref . "</td>";
  1069. // Ledger account
  1070. print "<td>";
  1071. /*if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
  1072. {
  1073. print '<span class="error">'.$langs->trans("WaitAccountNotDefined").'</span>';
  1074. }
  1075. else */ print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE);
  1076. print "</td>";
  1077. // Subledger account
  1078. print "<td>";
  1079. /*if (empty($accounttoshowsubledger) || $accounttoshowsubledger == 'NotDefined')
  1080. {
  1081. print '<span class="error">'.$langs->trans("WaitAccountNotDefined").'</span>';
  1082. }
  1083. else print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE);
  1084. */
  1085. print "</td>";
  1086. print "<td>" . $reflabel . "</td>";
  1087. print '<td class="center">' . $val["type_payment"] . "</td>";
  1088. print '<td class="right nowraponall">' . ($mt < 0 ? price(- $mt) : '') . "</td>";
  1089. print '<td class="right nowraponall">' . ($mt >= 0 ? price($mt) : '') . "</td>";
  1090. print "</tr>";
  1091. }
  1092. }
  1093. }
  1094. }
  1095. print "</table>";
  1096. print '</div>';
  1097. llxFooter();
  1098. }
  1099. $db->close();
  1100. /**
  1101. * Return source for doc_ref of a bank transaction
  1102. *
  1103. * @param string $val Array of val
  1104. * @param string $typerecord Type of record ('payment', 'payment_supplier', 'payment_expensereport', 'payment_vat', ...)
  1105. * @return string A string label to describe a record into llx_bank_url
  1106. */
  1107. function getSourceDocRef($val, $typerecord)
  1108. {
  1109. global $db, $langs;
  1110. // Defined the docref into $ref (We start with $val['ref'] by default and we complete according to other data)
  1111. // WE MUST HAVE SAME REF FOR ALL LINES WE WILL RECORD INTO THE BOOKKEEPING
  1112. $ref = $val['ref'];
  1113. if ($ref == '(SupplierInvoicePayment)' || $ref == '(SupplierInvoicePaymentBack)') {
  1114. $ref = $langs->transnoentitiesnoconv('Supplier');
  1115. }
  1116. if ($ref == '(CustomerInvoicePayment)' || $ref == '(CustomerInvoicePaymentBack)') {
  1117. $ref = $langs->transnoentitiesnoconv('Customer');
  1118. }
  1119. if ($ref == '(SocialContributionPayment)') {
  1120. $ref = $langs->transnoentitiesnoconv('SocialContribution');
  1121. }
  1122. if ($ref == '(DonationPayment)') {
  1123. $ref = $langs->transnoentitiesnoconv('Donation');
  1124. }
  1125. if ($ref == '(SubscriptionPayment)') {
  1126. $ref = $langs->transnoentitiesnoconv('Subscription');
  1127. }
  1128. if ($ref == '(ExpenseReportPayment)') {
  1129. $ref = $langs->transnoentitiesnoconv('Employee');
  1130. }
  1131. if ($ref == '(LoanPayment)') {
  1132. $ref = $langs->transnoentitiesnoconv('Loan');
  1133. }
  1134. if ($ref == '(payment_salary)') {
  1135. $ref = $langs->transnoentitiesnoconv('Employee');
  1136. }
  1137. $sqlmid = '';
  1138. if ($typerecord == 'payment')
  1139. {
  1140. $sqlmid = 'SELECT payfac.fk_facture as id, f.ref as ref';
  1141. $sqlmid .= " FROM ".MAIN_DB_PREFIX."paiement_facture as payfac, ".MAIN_DB_PREFIX."facture as f";
  1142. $sqlmid .= " WHERE payfac.fk_facture = f.rowid AND payfac.fk_paiement=" . $val["paymentid"];
  1143. $ref = $langs->transnoentitiesnoconv("Invoice");
  1144. }
  1145. elseif ($typerecord == 'payment_supplier')
  1146. {
  1147. $sqlmid = 'SELECT payfac.fk_facturefourn as id, f.ref';
  1148. $sqlmid .= " FROM " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfac, ".MAIN_DB_PREFIX."facture_fourn as f";
  1149. $sqlmid .= " WHERE payfac.fk_facturefourn = f.rowid AND payfac.fk_paiementfourn=" . $val["paymentsupplierid"];
  1150. $ref = $langs->transnoentitiesnoconv("SupplierInvoice");
  1151. }
  1152. elseif ($typerecord == 'payment_expensereport')
  1153. {
  1154. $sqlmid = 'SELECT e.rowid as id, e.ref';
  1155. $sqlmid .= " FROM " . MAIN_DB_PREFIX . "payment_expensereport as pe, " . MAIN_DB_PREFIX . "expensereport as e";
  1156. $sqlmid .= " WHERE pe.rowid=" . $val["paymentexpensereport"]." AND pe.fk_expensereport = e.rowid";
  1157. $ref = $langs->transnoentitiesnoconv("ExpenseReport");
  1158. }
  1159. elseif ($typerecord == 'payment_salary')
  1160. {
  1161. $sqlmid = 'SELECT s.rowid as ref';
  1162. $sqlmid .= " FROM " . MAIN_DB_PREFIX . "payment_salary as s";
  1163. $sqlmid .= " WHERE s.rowid=" . $val["paymentsalid"];
  1164. $ref = $langs->transnoentitiesnoconv("SalaryPayment");
  1165. }
  1166. elseif ($typerecord == 'sc')
  1167. {
  1168. $sqlmid = 'SELECT sc.rowid as ref';
  1169. $sqlmid .= " FROM " . MAIN_DB_PREFIX . "paiementcharge as sc";
  1170. $sqlmid .= " WHERE sc.rowid=" . $val["paymentscid"];
  1171. $ref = $langs->transnoentitiesnoconv("SocialContribution");
  1172. }
  1173. elseif ($typerecord == 'payment_vat')
  1174. {
  1175. $sqlmid = 'SELECT v.rowid as ref';
  1176. $sqlmid .= " FROM " . MAIN_DB_PREFIX . "tva as v";
  1177. $sqlmid .= " WHERE v.rowid=" . $val["paymentvatid"];
  1178. $ref = $langs->transnoentitiesnoconv("PaymentVat");
  1179. }
  1180. elseif ($typerecord == 'payment_donation')
  1181. {
  1182. $sqlmid = 'SELECT payd.fk_donation as ref';
  1183. $sqlmid .= " FROM " . MAIN_DB_PREFIX . "payment_donation as payd";
  1184. $sqlmid .= " WHERE payd.fk_donation=" . $val["paymentdonationid"];
  1185. $ref = $langs->transnoentitiesnoconv("Donation");
  1186. }
  1187. elseif ($typerecord == 'payment_loan')
  1188. {
  1189. $sqlmid = 'SELECT l.rowid as ref';
  1190. $sqlmid .= " FROM " . MAIN_DB_PREFIX . "payment_loan as l";
  1191. $sqlmid .= " WHERE l.rowid=" . $val["paymentloanid"];
  1192. $ref = $langs->transnoentitiesnoconv("LoanPayment");
  1193. }
  1194. elseif ($typerecord == 'payment_various')
  1195. {
  1196. $sqlmid = 'SELECT v.rowid as ref';
  1197. $sqlmid .= " FROM " . MAIN_DB_PREFIX . "payment_various as v";
  1198. $sqlmid .= " WHERE v.rowid=" . $val["paymentvariousid"];
  1199. $ref = $langs->transnoentitiesnoconv("VariousPayment");
  1200. }
  1201. // Add warning
  1202. if (empty($sqlmid))
  1203. {
  1204. dol_syslog("Found a typerecord=".$typerecord." not supported", LOG_WARNING);
  1205. }
  1206. if ($sqlmid)
  1207. {
  1208. dol_syslog("accountancy/journal/bankjournal.php::sqlmid=" . $sqlmid, LOG_DEBUG);
  1209. $resultmid = $db->query($sqlmid);
  1210. if ($resultmid)
  1211. {
  1212. while ($objmid = $db->fetch_object($resultmid))
  1213. {
  1214. $ref.=' '.$objmid->ref;
  1215. }
  1216. }
  1217. else dol_print_error($db);
  1218. }
  1219. $ref = dol_trunc($langs->transnoentitiesnoconv("BankId").' '.$val['fk_bank'].' - '.$ref, 295); // 295 + 3 dots (...) is < than max size of 300
  1220. return $ref;
  1221. }