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