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