bankjournal.php 62 KB

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