bankjournal.php 64 KB

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