dolibarr 20.0.5
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($objmid->amount_capital) ? $tabtp[$obj->rowid][$objmid->accountancy_account_capital] - $objmid->amount_capital : 0;
566 $tabtp[$obj->rowid][$objmid->accountancy_account_insurance] = isset($objmid->amount_insurance) ? $tabtp[$obj->rowid][$objmid->accountancy_account_insurance] - $objmid->amount_insurance : 0;
567 $tabtp[$obj->rowid][$objmid->accountancy_account_interest] = isset($objmid->amount_interest) ? $tabtp[$obj->rowid][$objmid->accountancy_account_interest] - $objmid->amount_interest : 0;
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 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
792 $accountingaccount = new AccountingAccount($db);
793 $accountingaccount->fetch(0, $k, true);
794 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
795 } else {
796 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
797 }
798 $bookkeeping->numero_compte = $k;
799 $bookkeeping->label_compte = $accountingaccount->label;
800 } elseif ($tabtype[$key] == 'payment_vat') {
801 $bookkeeping->subledger_account = '';
802 $bookkeeping->subledger_label = '';
803 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
804 $accountingaccount = new AccountingAccount($db);
805 $accountingaccount->fetch(0, $k, true);
806 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
807 } else {
808 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
809 }
810 $bookkeeping->numero_compte = $k;
811 $bookkeeping->label_compte = $accountingaccount->label;
812 } elseif ($tabtype[$key] == 'payment_donation') {
813 $bookkeeping->subledger_account = '';
814 $bookkeeping->subledger_label = '';
815 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
816 $accountingaccount = new AccountingAccount($db);
817 $accountingaccount->fetch(0, $k, true);
818 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
819 } else {
820 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
821 }
822 $bookkeeping->numero_compte = $k;
823 $bookkeeping->label_compte = $accountingaccount->label;
824 } elseif ($tabtype[$key] == 'member') {
825 $bookkeeping->subledger_account = '';
826 $bookkeeping->subledger_label = '';
827 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
828 $accountingaccount = new AccountingAccount($db);
829 $accountingaccount->fetch(0, $k, true);
830 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
831 } else {
832 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
833 }
834 $bookkeeping->numero_compte = $k;
835 $bookkeeping->label_compte = $accountingaccount->label;
836 } elseif ($tabtype[$key] == 'payment_loan') {
837 $bookkeeping->subledger_account = '';
838 $bookkeeping->subledger_label = '';
839 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
840 $accountingaccount = new AccountingAccount($db);
841 $accountingaccount->fetch(0, $k, true);
842 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
843 } else {
844 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
845 }
846 $bookkeeping->numero_compte = $k;
847 $bookkeeping->label_compte = $accountingaccount->label;
848 } elseif ($tabtype[$key] == 'payment_various') {
849 $bookkeeping->subledger_account = $k;
850 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
851 if (empty($conf->cache['accountingaccountincurrententity'][$tabpay[$key]["account_various"]])) {
852 $accountingaccount = new AccountingAccount($db);
853 $accountingaccount->fetch(0, $tabpay[$key]["account_various"], true);
854 $conf->cache['accountingaccountincurrententity'][$tabpay[$key]["account_various"]] = $accountingaccount;
855 } else {
856 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$tabpay[$key]["account_various"]];
857 }
858 $bookkeeping->numero_compte = $tabpay[$key]["account_various"];
859 $bookkeeping->label_compte = $accountingaccount->label;
860 } elseif ($tabtype[$key] == 'banktransfert') {
861 $bookkeeping->subledger_account = '';
862 $bookkeeping->subledger_label = '';
863 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
864 $accountingaccount = new AccountingAccount($db);
865 $accountingaccount->fetch(0, $k, true);
866 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
867 } else {
868 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
869 }
870 $bookkeeping->numero_compte = $k;
871 $bookkeeping->label_compte = $accountingaccount->label;
872 } else {
873 if ($tabtype[$key] == 'unknown') { // Unknown transaction, we will use a waiting account for thirdparty.
874 // Temporary account
875 $bookkeeping->subledger_account = '';
876 $bookkeeping->subledger_label = '';
877 $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE');
878 $bookkeeping->label_compte = $accountingaccountsuspense->label;
879 }
880 }
881 $bookkeeping->label_operation = $reflabel;
882 $bookkeeping->entity = $conf->entity;
883
884 $totaldebit += $bookkeeping->debit;
885 $totalcredit += $bookkeeping->credit;
886
887 $result = $bookkeeping->create($user);
888 if ($result < 0) {
889 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
890 $error++;
891 $errorforline++;
892 setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
893 } else {
894 $error++;
895 $errorforline++;
896 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
897 }
898 } else {
899 if ($lettering && getDolGlobalInt('ACCOUNTING_ENABLE_LETTERING') && getDolGlobalInt('ACCOUNTING_ENABLE_AUTOLETTERING')) {
900 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php';
901 $lettering_static = new Lettering($db);
902 $nb_lettering = $lettering_static->bookkeepingLetteringAll(array($bookkeeping->id));
903 }
904 }
905 }
906 }
907 } else { // If thirdparty unknown, output the waiting account
908 foreach ($tabbq[$key] as $k => $mt) {
909 if ($mt) {
910 $reflabel = '';
911 if (!empty($val['lib'])) {
912 $reflabel .= dol_string_nohtmltag($val['lib'])." - ";
913 }
914 $reflabel .= dol_string_nohtmltag('WaitingAccount');
915
916 $bookkeeping = new BookKeeping($db);
917 $bookkeeping->doc_date = $val["date"];
918 $bookkeeping->doc_ref = $ref;
919 $bookkeeping->doc_type = 'bank';
920 $bookkeeping->fk_doc = $key;
921 $bookkeeping->fk_docdet = $val["fk_bank"];
922 $bookkeeping->montant = $mt;
923 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
924 $bookkeeping->debit = ($mt < 0 ? -$mt : 0);
925 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
926 $bookkeeping->code_journal = $journal;
927 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
928 $bookkeeping->fk_user_author = $user->id;
929 $bookkeeping->date_creation = $now;
930 $bookkeeping->label_compte = '';
931 $bookkeeping->label_operation = $reflabel;
932 $bookkeeping->entity = $conf->entity;
933
934 $totaldebit += $bookkeeping->debit;
935 $totalcredit += $bookkeeping->credit;
936
937 $result = $bookkeeping->create($user);
938
939 if ($result < 0) {
940 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
941 $error++;
942 $errorforline++;
943 setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
944 } else {
945 $error++;
946 $errorforline++;
947 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
948 }
949 }
950 }
951 }
952 }
953 }
954
955 if (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT')) {
956 $error++;
957 $errorforline++;
958 setEventMessages('We tried to insert a non balanced transaction in book for '.$ref.'. Canceled. Surely a bug.', null, 'errors');
959 }
960
961 if (!$errorforline) {
962 $db->commit();
963 } else {
964 //print 'KO for line '.$key.' '.$error.'<br>';
965 $db->rollback();
966
967 $MAXNBERRORS = 5;
968 if ($error >= $MAXNBERRORS) {
969 setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped").' (>'.$MAXNBERRORS.')', null, 'errors');
970 break; // Break in the foreach
971 }
972 }
973 }
974
975 if (empty($error) && count($tabpay) > 0) {
976 setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
977 } elseif (count($tabpay) == $error) {
978 setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
979 } else {
980 setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
981 }
982
983 $action = '';
984
985 // Must reload data, so we make a redirect
986 if (count($tabpay) != $error) {
987 $param = 'id_journal='.$id_journal;
988 $param .= '&date_startday='.$date_startday;
989 $param .= '&date_startmonth='.$date_startmonth;
990 $param .= '&date_startyear='.$date_startyear;
991 $param .= '&date_endday='.$date_endday;
992 $param .= '&date_endmonth='.$date_endmonth;
993 $param .= '&date_endyear='.$date_endyear;
994 $param .= '&in_bookkeeping='.$in_bookkeeping;
995 header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
996 exit;
997 }
998}
999
1000
1001
1002// Export
1003if ($action == 'exportcsv' && $user->hasRight('accounting', 'bind', 'write')) { // ISO and not UTF8 !
1004 $sep = getDolGlobalString('ACCOUNTING_EXPORT_SEPARATORCSV');
1005
1006 $filename = 'journal';
1007 $type_export = 'journal';
1008 include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
1009
1010 // CSV header line
1011 print '"'.$langs->transnoentitiesnoconv("BankId").'"'.$sep;
1012 print '"'.$langs->transnoentitiesnoconv("Date").'"'.$sep;
1013 print '"'.$langs->transnoentitiesnoconv("PaymentMode").'"'.$sep;
1014 print '"'.$langs->transnoentitiesnoconv("AccountAccounting").'"'.$sep;
1015 print '"'.$langs->transnoentitiesnoconv("LedgerAccount").'"'.$sep;
1016 print '"'.$langs->transnoentitiesnoconv("SubledgerAccount").'"'.$sep;
1017 print '"'.$langs->transnoentitiesnoconv("Label").'"'.$sep;
1018 print '"'.$langs->transnoentitiesnoconv("AccountingDebit").'"'.$sep;
1019 print '"'.$langs->transnoentitiesnoconv("AccountingCredit").'"'.$sep;
1020 print '"'.$langs->transnoentitiesnoconv("Journal").'"'.$sep;
1021 print '"'.$langs->transnoentitiesnoconv("Note").'"'.$sep;
1022 print "\n";
1023
1024 foreach ($tabpay as $key => $val) {
1025 $date = dol_print_date($val["date"], 'day');
1026
1027 $ref = getSourceDocRef($val, $tabtype[$key]);
1028
1029 // Bank
1030 foreach ($tabbq[$key] as $k => $mt) {
1031 if ($mt) {
1032 $reflabel = '';
1033 if (!empty($val['lib'])) {
1034 $reflabel .= dol_string_nohtmltag($val['lib'])." - ";
1035 }
1036 $reflabel .= $langs->trans("Bank").' '.dol_string_nohtmltag($val['bank_account_ref']);
1037 if (!empty($val['soclib'])) {
1038 $reflabel .= " - ".dol_string_nohtmltag($val['soclib']);
1039 }
1040
1041 print '"'.$key.'"'.$sep;
1042 print '"'.$date.'"'.$sep;
1043 print '"'.$val["type_payment"].'"'.$sep;
1044 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1045 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1046 print " ".$sep;
1047 print '"'.$reflabel.'"'.$sep;
1048 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1049 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1050 print '"'.$journal.'"'.$sep;
1051 print '"'.dol_string_nohtmltag($ref).'"'.$sep;
1052 print "\n";
1053 }
1054 }
1055
1056 // Third party
1057 if (is_array($tabtp[$key])) {
1058 foreach ($tabtp[$key] as $k => $mt) {
1059 if ($mt) {
1060 $reflabel = '';
1061 if (!empty($val['lib'])) {
1062 $reflabel .= dol_string_nohtmltag($val['lib']).($val['soclib'] ? " - " : "");
1063 }
1064 if ($tabtype[$key] == 'banktransfert') {
1065 $reflabel .= dol_string_nohtmltag($langs->transnoentitiesnoconv('TransitionalAccount').' '.$account_transfer);
1066 } else {
1067 $reflabel .= dol_string_nohtmltag($val['soclib']);
1068 }
1069
1070 print '"'.$key.'"'.$sep;
1071 print '"'.$date.'"'.$sep;
1072 print '"'.$val["type_payment"].'"'.$sep;
1073 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1074 if ($tabtype[$key] == 'payment_supplier') {
1075 print '"'.getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER').'"'.$sep;
1076 } elseif ($tabtype[$key] == 'payment') {
1077 print '"'.getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER').'"'.$sep;
1078 } elseif ($tabtype[$key] == 'payment_expensereport') {
1079 print '"'.getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT').'"'.$sep;
1080 } elseif ($tabtype[$key] == 'payment_salary') {
1081 print '"'.getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT').'"'.$sep;
1082 } else {
1083 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1084 }
1085 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1086 print '"'.$reflabel.'"'.$sep;
1087 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1088 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1089 print '"'.$journal.'"'.$sep;
1090 print '"'.dol_string_nohtmltag($ref).'"'.$sep;
1091 print "\n";
1092 }
1093 }
1094 } else { // If thirdparty unknown, output the waiting account
1095 foreach ($tabbq[$key] as $k => $mt) {
1096 if ($mt) {
1097 $reflabel = '';
1098 if (!empty($val['lib'])) {
1099 $reflabel .= dol_string_nohtmltag($val['lib'])." - ";
1100 }
1101 $reflabel .= dol_string_nohtmltag('WaitingAccount');
1102
1103 print '"'.$key.'"'.$sep;
1104 print '"'.$date.'"'.$sep;
1105 print '"'.$val["type_payment"].'"'.$sep;
1106 print '"'.length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE')).'"'.$sep;
1107 print '"'.length_accounta(getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE')).'"'.$sep;
1108 print $sep;
1109 print '"'.$reflabel.'"'.$sep;
1110 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1111 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1112 print '"'.$journal.'"'.$sep;
1113 print '"'.dol_string_nohtmltag($ref).'"'.$sep;
1114 print "\n";
1115 }
1116 }
1117 }
1118 }
1119}
1120
1121
1122/*
1123 * View
1124 */
1125
1126$form = new Form($db);
1127
1128if (empty($action) || $action == 'view') {
1129 $invoicestatic = new Facture($db);
1130 $invoicesupplierstatic = new FactureFournisseur($db);
1131 $expensereportstatic = new ExpenseReport($db);
1132 $vatstatic = new Tva($db);
1133 $donationstatic = new Don($db);
1134 $loanstatic = new Loan($db);
1135 $salarystatic = new Salary($db);
1136 $variousstatic = new PaymentVarious($db);
1137
1138 $title = $langs->trans("GenerationOfAccountingEntries").' - '.$accountingjournalstatic->getNomUrl(0, 2, 1, '', 1);
1139 $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;';
1140 llxHeader('', dol_string_nohtmltag($title), $help_url, '', 0, 0, '', '', '', 'mod-accountancy accountancy-generation page-bankjournal');
1141
1142 $nom = $title;
1143 $builddate = dol_now();
1144 //$description = $langs->trans("DescFinanceJournal") . '<br>';
1145 $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
1146
1147 $listofchoices = array(
1148 'notyet' => $langs->trans("NotYetInGeneralLedger"),
1149 'already' => $langs->trans("AlreadyInGeneralLedger")
1150 );
1151 $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);
1152 $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
1153
1154 $varlink = 'id_journal='.$id_journal;
1155 $periodlink = '';
1156 $exportlink = '';
1157
1158 $listofchoices = array(
1159 1 => $langs->trans("TransfertAllBankLines"),
1160 2 => $langs->trans("TransfertOnlyConciliatedBankLine")
1161 );
1162 $moreoptions = [ "BankLineConciliated" => $form->selectarray('only_rappro', $listofchoices, $only_rappro)];
1163
1164 journalHead($nom, '', $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink, $moreoptions);
1165
1166 $desc = '';
1167
1168 if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') != 'blockedonclosed') {
1169 // Test that setup is complete (we are in accounting, so test on entity is always on $conf->entity only, no sharing allowed)
1170 // Fiscal period test
1171 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_fiscalyear WHERE entity = ".((int) $conf->entity);
1172 $resql = $db->query($sql);
1173 if ($resql) {
1174 $obj = $db->fetch_object($resql);
1175 if ($obj->nb == 0) {
1176 print '<br><div class="warning">'.img_warning().' '.$langs->trans("TheFiscalPeriodIsNotDefined");
1177 $desc = ' : '.$langs->trans("AccountancyAreaDescFiscalPeriod", 4, '{link}');
1178 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("FiscalPeriod").'</strong>', $desc);
1179 print $desc;
1180 print '</div>';
1181 }
1182 } else {
1183 dol_print_error($db);
1184 }
1185 }
1186
1187 // Bank test
1188 $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";
1189 $resql = $db->query($sql);
1190 if ($resql) {
1191 $obj = $db->fetch_object($resql);
1192 if ($obj->nb > 0) {
1193 print '<br><div class="warning">'.img_warning().' '.$langs->trans("TheJournalCodeIsNotDefinedOnSomeBankAccount");
1194 $desc = ' : '.$langs->trans("AccountancyAreaDescBank", 6, '{link}');
1195 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("BankAccounts").'</strong>', $desc);
1196 print $desc;
1197 print '</div>';
1198 }
1199 } else {
1200 dol_print_error($db);
1201 }
1202
1203
1204 // Button to write into Ledger
1205 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') == "" || getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') == '-1'
1206 || getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') == "" || getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') == '-1'
1207 || (isModEnabled("salaries") && (getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT') == "" || getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT') == '-1'))
1208 || (isModEnabled("expensereport") && (getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT') == "" || getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT') == '-1'))) {
1209
1210
1211 print($desc ? '' : '<br>').'<div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
1212 $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
1213 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
1214 print $desc;
1215 print '</div>';
1216 }
1217
1218
1219 print '<br><div class="tabsAction tabsActionNoBottom centerimp">';
1220
1221 if (getDolGlobalString('ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL') && $in_bookkeeping == 'notyet') {
1222 print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
1223 }
1224
1225 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') == "" || getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') == '-1'
1226 || getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') == "" || getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') == '-1') {
1227 print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
1228 } else {
1229 if ($in_bookkeeping == 'notyet') {
1230 print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
1231 } else {
1232 print '<a class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
1233 }
1234 }
1235
1236 print '</div>';
1237
1238 // TODO Avoid using js. We can use a direct link with $param
1239 print '
1240 <script type="text/javascript">
1241 function launch_export() {
1242 console.log("Set value into form and submit");
1243 $("div.fiche form input[name=\"action\"]").val("exportcsv");
1244 $("div.fiche form input[type=\"submit\"]").click();
1245 $("div.fiche form input[name=\"action\"]").val("");
1246 }
1247 function writebookkeeping() {
1248 console.log("Set value into form and submit");
1249 $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
1250 $("div.fiche form input[type=\"submit\"]").click();
1251 $("div.fiche form input[name=\"action\"]").val("");
1252 }
1253 </script>';
1254
1255 /*
1256 * Show result array
1257 */
1258 print '<br>';
1259
1260 $i = 0;
1261 print '<div class="div-table-responsive">';
1262 print '<table class="noborder centpercent">';
1263 print '<tr class="liste_titre">';
1264 print "<td>".$langs->trans("Date")."</td>";
1265 print "<td>".$langs->trans("Piece").' ('.$langs->trans("ObjectsRef").")</td>";
1266 print "<td>".$langs->trans("AccountAccounting")."</td>";
1267 print "<td>".$langs->trans("SubledgerAccount")."</td>";
1268 print "<td>".$langs->trans("LabelOperation")."</td>";
1269 print '<td class="center">'.$langs->trans("PaymentMode")."</td>";
1270 print '<td class="right">'.$langs->trans("AccountingDebit")."</td>";
1271 print '<td class="right">'.$langs->trans("AccountingCredit")."</td>";
1272 print "</tr>\n";
1273
1274 $r = '';
1275
1276 foreach ($tabpay as $key => $val) { // $key is rowid in llx_bank
1277 $date = dol_print_date($val["date"], 'day');
1278
1279 $ref = getSourceDocRef($val, $tabtype[$key]);
1280
1281 // Bank
1282 foreach ($tabbq[$key] as $k => $mt) {
1283 if ($mt) {
1284 $reflabel = '';
1285 if (!empty($val['lib'])) {
1286 $reflabel .= $val['lib']." - ";
1287 }
1288 $reflabel .= $langs->trans("Bank").' '.$val['bank_account_ref'];
1289 if (!empty($val['soclib'])) {
1290 $reflabel .= " - ".$val['soclib'];
1291 }
1292
1293 //var_dump($tabpay[$key]);
1294 print '<!-- Bank bank.rowid='.$key.' type='.$tabpay[$key]['type'].' ref='.$tabpay[$key]['ref'].'-->';
1295 print '<tr class="oddeven">';
1296
1297 // Date
1298 print "<td>".$date."</td>";
1299
1300 // Ref
1301 print "<td>".dol_escape_htmltag($ref)."</td>";
1302
1303 // Ledger account
1304 $accounttoshow = length_accountg($k);
1305 if (empty($accounttoshow) || $accounttoshow == 'NotDefined') {
1306 $accounttoshow = '<span class="error">'.$langs->trans("BankAccountNotDefined").'</span>';
1307 }
1308 print '<td class="maxwidth300" title="'.dol_escape_htmltag(dol_string_nohtmltag($accounttoshow)).'">';
1309 print $accounttoshow;
1310 print "</td>";
1311
1312 // Subledger account
1313 print '<td class="maxwidth300">';
1314 /*$accounttoshow = length_accountg($k);
1315 if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
1316 {
1317 print '<span class="error">'.$langs->trans("BankAccountNotDefined").'</span>';
1318 }
1319 else print $accounttoshow;*/
1320 print "</td>";
1321
1322 // Label operation
1323 print '<td>';
1324 print $reflabel; // This is already html escaped content
1325 print "</td>";
1326
1327 print '<td class="center">'.$val["type_payment"]."</td>";
1328 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1329 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1330 print "</tr>";
1331
1332 $i++;
1333 }
1334 }
1335
1336 // Third party
1337 if (is_array($tabtp[$key])) {
1338 foreach ($tabtp[$key] as $k => $mt) {
1339 if ($mt) {
1340 $reflabel = '';
1341 if (!empty($val['lib'])) {
1342 $reflabel .= $val['lib'].(isset($val['soclib']) ? " - " : "");
1343 }
1344 if ($tabtype[$key] == 'banktransfert') {
1345 $reflabel .= $langs->trans('TransitionalAccount').' '.$account_transfer;
1346 } else {
1347 $reflabel .= isset($val['soclib']) ? $val['soclib'] : "";
1348 }
1349
1350 print '<!-- Thirdparty bank.rowid='.$key.' -->';
1351 print '<tr class="oddeven">';
1352
1353 // Date
1354 print "<td>".$date."</td>";
1355
1356 // Ref
1357 print "<td>".dol_escape_htmltag($ref)."</td>";
1358
1359 // Ledger account
1360 $account_ledger = $k;
1361 // Try to force general ledger account depending on type
1362 if ($tabtype[$key] == 'payment') {
1363 $account_ledger = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER');
1364 }
1365 if ($tabtype[$key] == 'payment_supplier') {
1366 $account_ledger = getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER');
1367 }
1368 if ($tabtype[$key] == 'payment_expensereport') {
1369 $account_ledger = getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT');
1370 }
1371 if ($tabtype[$key] == 'payment_salary') {
1372 $account_ledger = getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT');
1373 }
1374 if ($tabtype[$key] == 'payment_vat') {
1375 $account_ledger = getDolGlobalString('ACCOUNTING_VAT_PAY_ACCOUNT');
1376 }
1377 if ($tabtype[$key] == 'member') {
1378 $account_ledger = getDolGlobalString('ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT');
1379 }
1380 if ($tabtype[$key] == 'payment_various') {
1381 $account_ledger = $tabpay[$key]["account_various"];
1382 }
1383 $accounttoshow = length_accountg($account_ledger);
1384 if (empty($accounttoshow) || $accounttoshow == 'NotDefined') {
1385 if ($tabtype[$key] == 'unknown') {
1386 // We will accept writing, but into a waiting account
1387 if (!getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE') || getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE') == '-1') {
1388 $accounttoshow = '<span class="error small">'.$langs->trans('UnknownAccountForThirdpartyAndWaitingAccountNotDefinedBlocking').'</span>';
1389 } else {
1390 $accounttoshow = '<span class="warning small">'.$langs->trans('UnknownAccountForThirdparty', length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE'))).'</span>'; // We will use a waiting account
1391 }
1392 } else {
1393 // We will refuse writing
1394 $errorstring = 'UnknownAccountForThirdpartyBlocking';
1395 if ($tabtype[$key] == 'payment') {
1396 $errorstring = 'MainAccountForCustomersNotDefined';
1397 }
1398 if ($tabtype[$key] == 'payment_supplier') {
1399 $errorstring = 'MainAccountForSuppliersNotDefined';
1400 }
1401 if ($tabtype[$key] == 'payment_expensereport') {
1402 $errorstring = 'MainAccountForUsersNotDefined';
1403 }
1404 if ($tabtype[$key] == 'payment_salary') {
1405 $errorstring = 'MainAccountForUsersNotDefined';
1406 }
1407 if ($tabtype[$key] == 'payment_vat') {
1408 $errorstring = 'MainAccountForVatPaymentNotDefined';
1409 }
1410 if ($tabtype[$key] == 'member') {
1411 $errorstring = 'MainAccountForSubscriptionPaymentNotDefined';
1412 }
1413 $accounttoshow = '<span class="error small">'.$langs->trans($errorstring).'</span>';
1414 }
1415 }
1416 print '<td class="maxwidth300" title="'.dol_escape_htmltag(dol_string_nohtmltag($accounttoshow)).'">';
1417 print $accounttoshow; // This is a HTML string
1418 print "</td>";
1419
1420 // Subledger account
1421 $accounttoshowsubledger = '';
1422 if (in_array($tabtype[$key], array('payment', 'payment_supplier', 'payment_expensereport', 'payment_salary', 'payment_various'))) { // Type of payments that uses a subledger
1423 $accounttoshowsubledger = length_accounta($k);
1424 if ($accounttoshow != $accounttoshowsubledger) {
1425 if (empty($accounttoshowsubledger) || $accounttoshowsubledger == 'NotDefined') {
1426 //var_dump($tabpay[$key]);
1427 //var_dump($tabtype[$key]);
1428 //var_dump($tabbq[$key]);
1429 //print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
1430 if (!empty($tabcompany[$key]['code_compta'])) {
1431 if (in_array($tabtype[$key], array('payment_various', 'payment_salary'))) {
1432 // For such case, if subledger is not defined, we won't use subledger accounts.
1433 $accounttoshowsubledger = '<span class="warning small">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknownSubledgerIgnored").'</span>';
1434 } else {
1435 $accounttoshowsubledger = '<span class="warning small">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknown", $tabcompany[$key]['code_compta']).'</span>';
1436 }
1437 } else {
1438 $accounttoshowsubledger = '<span class="error small">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknownBlocking").'</span>';
1439 }
1440 }
1441 } else {
1442 $accounttoshowsubledger = '';
1443 }
1444 }
1445 print '<td class="maxwidth300">';
1446 print $accounttoshowsubledger; // This is a html string
1447 print "</td>";
1448
1449 print "<td>".$reflabel."</td>";
1450
1451 print '<td class="center">'.$val["type_payment"]."</td>";
1452
1453 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1454
1455 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1456
1457 print "</tr>";
1458
1459 $i++;
1460 }
1461 }
1462 } else { // Waiting account
1463 foreach ($tabbq[$key] as $k => $mt) {
1464 if ($mt) {
1465 $reflabel = '';
1466 if (!empty($val['lib'])) {
1467 $reflabel .= $val['lib']." - ";
1468 }
1469 $reflabel .= 'WaitingAccount';
1470
1471 print '<!-- Wait bank.rowid='.$key.' -->';
1472 print '<tr class="oddeven">';
1473 print "<td>".$date."</td>";
1474 print "<td>".$ref."</td>";
1475 // Ledger account
1476 print "<td>";
1477 /*if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
1478 {
1479 print '<span class="error">'.$langs->trans("WaitAccountNotDefined").'</span>';
1480 }
1481 else */
1482 print length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE'));
1483 print "</td>";
1484 // Subledger account
1485 print "<td>";
1486 print "</td>";
1487 print "<td>".dol_escape_htmltag($reflabel)."</td>";
1488 print '<td class="center">'.$val["type_payment"]."</td>";
1489 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1490 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1491 print "</tr>";
1492
1493 $i++;
1494 }
1495 }
1496 }
1497 }
1498
1499 if (!$i) {
1500 $colspan = 8;
1501 print '<tr class="oddeven"><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
1502 }
1503
1504 print "</table>";
1505 print '</div>';
1506
1507 llxFooter();
1508}
1509
1510$db->close();
1511
1512
1513
1521function getSourceDocRef($val, $typerecord)
1522{
1523 global $db, $langs;
1524
1525 // Defined the docref into $ref (We start with $val['ref'] by default and we complete according to other data)
1526 // WE MUST HAVE SAME REF FOR ALL LINES WE WILL RECORD INTO THE BOOKKEEPING
1527 $ref = $val['ref'];
1528 if ($ref == '(SupplierInvoicePayment)' || $ref == '(SupplierInvoicePaymentBack)') {
1529 $ref = $langs->transnoentitiesnoconv('Supplier');
1530 }
1531 if ($ref == '(CustomerInvoicePayment)' || $ref == '(CustomerInvoicePaymentBack)') {
1532 $ref = $langs->transnoentitiesnoconv('Customer');
1533 }
1534 if ($ref == '(SocialContributionPayment)') {
1535 $ref = $langs->transnoentitiesnoconv('SocialContribution');
1536 }
1537 if ($ref == '(DonationPayment)') {
1538 $ref = $langs->transnoentitiesnoconv('Donation');
1539 }
1540 if ($ref == '(SubscriptionPayment)') {
1541 $ref = $langs->transnoentitiesnoconv('Subscription');
1542 }
1543 if ($ref == '(ExpenseReportPayment)') {
1544 $ref = $langs->transnoentitiesnoconv('Employee');
1545 }
1546 if ($ref == '(LoanPayment)') {
1547 $ref = $langs->transnoentitiesnoconv('Loan');
1548 }
1549 if ($ref == '(payment_salary)') {
1550 $ref = $langs->transnoentitiesnoconv('Employee');
1551 }
1552
1553 $sqlmid = '';
1554 if ($typerecord == 'payment') {
1555 if (getDolGlobalInt('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
1556 $sqlmid = "SELECT payfac.fk_facture as id, ".$db->ifsql('f1.rowid IS NULL', 'f.ref', 'f1.ref')." as ref";
1557 $sqlmid .= " FROM ".$db->prefix()."paiement_facture as payfac";
1558 $sqlmid .= " LEFT JOIN ".$db->prefix()."facture as f ON f.rowid = payfac.fk_facture";
1559 $sqlmid .= " LEFT JOIN ".$db->prefix()."societe_remise_except as sre ON sre.fk_facture_source = payfac.fk_facture";
1560 $sqlmid .= " LEFT JOIN ".$db->prefix()."facture as f1 ON f1.rowid = sre.fk_facture";
1561 $sqlmid .= " WHERE payfac.fk_paiement=".((int) $val['paymentid']);
1562 } else {
1563 $sqlmid = "SELECT payfac.fk_facture as id, f.ref as ref";
1564 $sqlmid .= " FROM ".$db->prefix()."paiement_facture as payfac";
1565 $sqlmid .= " INNER JOIN ".$db->prefix()."facture as f ON f.rowid = payfac.fk_facture";
1566 $sqlmid .= " WHERE payfac.fk_paiement=".((int) $val['paymentid']);
1567 }
1568 $ref = $langs->transnoentitiesnoconv("Invoice");
1569 } elseif ($typerecord == 'payment_supplier') {
1570 $sqlmid = 'SELECT payfac.fk_facturefourn as id, f.ref';
1571 $sqlmid .= " FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn as payfac, ".MAIN_DB_PREFIX."facture_fourn as f";
1572 $sqlmid .= " WHERE payfac.fk_facturefourn = f.rowid AND payfac.fk_paiementfourn=".((int) $val["paymentsupplierid"]);
1573 $ref = $langs->transnoentitiesnoconv("SupplierInvoice");
1574 } elseif ($typerecord == 'payment_expensereport') {
1575 $sqlmid = 'SELECT e.rowid as id, e.ref';
1576 $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_expensereport as pe, ".MAIN_DB_PREFIX."expensereport as e";
1577 $sqlmid .= " WHERE pe.rowid=".((int) $val["paymentexpensereport"])." AND pe.fk_expensereport = e.rowid";
1578 $ref = $langs->transnoentitiesnoconv("ExpenseReport");
1579 } elseif ($typerecord == 'payment_salary') {
1580 $sqlmid = 'SELECT s.rowid as ref';
1581 $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_salary as s";
1582 $sqlmid .= " WHERE s.rowid=".((int) $val["paymentsalid"]);
1583 $ref = $langs->transnoentitiesnoconv("SalaryPayment");
1584 } elseif ($typerecord == 'sc') {
1585 $sqlmid = 'SELECT sc.rowid as ref';
1586 $sqlmid .= " FROM ".MAIN_DB_PREFIX."paiementcharge as sc";
1587 $sqlmid .= " WHERE sc.rowid=".((int) $val["paymentscid"]);
1588 $ref = $langs->transnoentitiesnoconv("SocialContribution");
1589 } elseif ($typerecord == 'payment_vat') {
1590 $sqlmid = 'SELECT v.rowid as ref';
1591 $sqlmid .= " FROM ".MAIN_DB_PREFIX."tva as v";
1592 $sqlmid .= " WHERE v.rowid=".((int) $val["paymentvatid"]);
1593 $ref = $langs->transnoentitiesnoconv("PaymentVat");
1594 } elseif ($typerecord == 'payment_donation') {
1595 $sqlmid = 'SELECT payd.fk_donation as ref';
1596 $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_donation as payd";
1597 $sqlmid .= " WHERE payd.fk_donation=".((int) $val["paymentdonationid"]);
1598 $ref = $langs->transnoentitiesnoconv("Donation");
1599 } elseif ($typerecord == 'payment_loan') {
1600 $sqlmid = 'SELECT l.rowid as ref';
1601 $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_loan as l";
1602 $sqlmid .= " WHERE l.rowid=".((int) $val["paymentloanid"]);
1603 $ref = $langs->transnoentitiesnoconv("LoanPayment");
1604 } elseif ($typerecord == 'payment_various') {
1605 $sqlmid = 'SELECT v.rowid as ref';
1606 $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_various as v";
1607 $sqlmid .= " WHERE v.rowid=".((int) $val["paymentvariousid"]);
1608 $ref = $langs->transnoentitiesnoconv("VariousPayment");
1609 }
1610 // Add warning
1611 if (empty($sqlmid)) {
1612 dol_syslog("Found a typerecord=".$typerecord." not supported", LOG_WARNING);
1613 }
1614
1615 if ($sqlmid) {
1616 dol_syslog("accountancy/journal/bankjournal.php::sqlmid=".$sqlmid, LOG_DEBUG);
1617 $resultmid = $db->query($sqlmid);
1618 if ($resultmid) {
1619 while ($objmid = $db->fetch_object($resultmid)) {
1620 $ref .= ' '.$objmid->ref;
1621 }
1622 } else {
1623 dol_print_error($db);
1624 }
1625 }
1626
1627 $ref = dol_trunc($langs->transnoentitiesnoconv("BankId").' '.$val['fk_bank'].' - '.$ref, 295); // 295 + 3 dots (...) is < than max size of 300
1628 return $ref;
1629}
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.