bankjournal.php 64 KB

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