dolibarr 21.0.0-alpha
bankjournal.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2007-2010 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2007-2010 Jean Heimburger <jean@tiaris.info>
4 * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
6 * Copyright (C) 2013 Christophe Battarel <christophe.battarel@altairis.fr>
7 * Copyright (C) 2013-2022 Open-DSI <support@open-dsi.fr>
8 * Copyright (C) 2013-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
9 * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
10 * Copyright (C) 2013-2014 Olivier Geffroy <jeff@jeffinfo.com>
11 * Copyright (C) 2017-2024 Frédéric France <frederic.france@free.fr>
12 * Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es>
13 * Copyright (C) 2018-2024 Eric Seigne <eric.seigne@cap-rel.fr>
14 * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
15 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
16 *
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 3 of the License, or
20 * (at your option) any later version.
21 *
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <https://www.gnu.org/licenses/>.
29 */
30
36require '../../main.inc.php';
37require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
38require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
39require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
40require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
41require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
42require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
43require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
44require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
45require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
46require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
47require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
48require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
49require_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php';
50require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
51require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php';
52require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
53require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
54require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
55require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
56require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
57require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
58require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
59require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php';
60require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php';
61require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
62require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php';
63require_once DOL_DOCUMENT_ROOT.'/loan/class/paymentloan.class.php';
64require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
65
66// Load translation files required by the page
67$langs->loadLangs(array("companies", "other", "compta", "banks", "bills", "donations", "loan", "accountancy", "trips", "salaries", "hrm", "members"));
68
69// Multi journal&search_status=-1
70$id_journal = GETPOSTINT('id_journal');
71
72$date_startmonth = GETPOSTINT('date_startmonth');
73$date_startday = GETPOSTINT('date_startday');
74$date_startyear = GETPOSTINT('date_startyear');
75$date_endmonth = GETPOSTINT('date_endmonth');
76$date_endday = GETPOSTINT('date_endday');
77$date_endyear = GETPOSTINT('date_endyear');
78$in_bookkeeping = GETPOST('in_bookkeeping', 'aZ09');
79
80$only_rappro = GETPOSTINT('only_rappro');
81if ($only_rappro == 0) {
82 //GET page for the first time, use default settings
83 $only_rappro = getDolGlobalInt('ACCOUNTING_BANK_CONCILIATED');
84}
85
86$now = dol_now();
87
88$action = GETPOST('action', 'aZ09');
89
90if ($in_bookkeeping == '') {
91 $in_bookkeeping = 'notyet';
92}
93
94
95// Security check
96if (!isModEnabled('accounting')) {
98}
99if ($user->socid > 0) {
101}
102if (!$user->hasRight('accounting', 'bind', 'write')) {
104}
105
106
107/*
108 * Actions
109 */
110
111$error = 0;
112
113$date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
114$date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
115
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
417 // For a payment of social contribution, we have a link sc + user.
418 // but we already fill the $tabpay[$obj->rowid]["soclib"] in the line 'sc'.
419 // If we fill it here to, we must concat.
420 if ($userstatic->id > 0) {
421 if ($is_sc) {
422 $tabpay[$obj->rowid]["soclib"] .= ' '.$userstatic->getNomUrl(1, 'accountancy', 0);
423 } else {
424 $tabpay[$obj->rowid]["soclib"] = $userstatic->getNomUrl(1, 'accountancy', 0);
425 }
426 } else {
427 $tabpay[$obj->rowid]["soclib"] = '???'; // Should not happen, but happens with old data when id of user was not saved on expense report payment.
428 }
429
430 if ($compta_user) {
431 if ($is_sc) {
432 //$tabcompany[$obj->rowid][$compta_user] += $amounttouse;
433 } else {
434 $tabtp[$obj->rowid][$compta_user] += $amounttouse;
435 }
436 }
437 } elseif ($links[$key]['type'] == 'sc') {
438 $chargestatic->id = $links[$key]['url_id'];
439 $chargestatic->ref = $links[$key]['url_id'];
440
441 $tabpay[$obj->rowid]["lib"] .= ' '.$chargestatic->getNomUrl(2);
442 $reg = array();
443 if (preg_match('/^\‍((.*)\‍)$/i', $links[$key]['label'], $reg)) {
444 if ($reg[1] == 'socialcontribution') {
445 $reg[1] = 'SocialContribution';
446 }
447 $chargestatic->label = $langs->trans($reg[1]);
448 } else {
449 $chargestatic->label = $links[$key]['label'];
450 }
451 $chargestatic->ref = $chargestatic->label;
452 //$chargestatic->fetch($chargestatic->id);
453
454 $tabpay[$obj->rowid]["soclib"] = $chargestatic->getNomUrl(1, 30);
455 $tabpay[$obj->rowid]["paymentscid"] = $chargestatic->id;
456
457 // Retrieve the accounting code of the social contribution of the payment from link of payment.
458 // Note: We have the social contribution id, it can be faster to get accounting code from social contribution id.
459 $sqlmid = "SELECT cchgsoc.accountancy_code";
460 $sqlmid .= " FROM ".MAIN_DB_PREFIX."c_chargesociales cchgsoc";
461 $sqlmid .= " INNER JOIN ".MAIN_DB_PREFIX."chargesociales as chgsoc ON chgsoc.fk_type = cchgsoc.id";
462 $sqlmid .= " INNER JOIN ".MAIN_DB_PREFIX."paiementcharge as paycharg ON paycharg.fk_charge = chgsoc.rowid";
463 $sqlmid .= " INNER JOIN ".MAIN_DB_PREFIX."bank_url as bkurl ON bkurl.url_id=paycharg.rowid AND bkurl.type = 'payment_sc'";
464 $sqlmid .= " WHERE bkurl.fk_bank = ".((int) $obj->rowid);
465
466 dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=".$sqlmid, LOG_DEBUG);
467 $resultmid = $db->query($sqlmid);
468 if ($resultmid) {
469 $objmid = $db->fetch_object($resultmid);
470 $tabtp[$obj->rowid][$objmid->accountancy_code] = isset($tabtp[$obj->rowid][$objmid->accountancy_code]) ? $tabtp[$obj->rowid][$objmid->accountancy_code] + $amounttouse : $amounttouse;
471 }
472 } elseif ($links[$key]['type'] == 'payment_donation') {
473 $paymentdonstatic->id = $links[$key]['url_id'];
474 $paymentdonstatic->ref = $links[$key]['url_id'];
475 $paymentdonstatic->fk_donation = $links[$key]['url_id'];
476 $tabpay[$obj->rowid]["lib"] .= ' '.$paymentdonstatic->getNomUrl(2);
477 $tabpay[$obj->rowid]["paymentdonationid"] = $paymentdonstatic->id;
478 $tabtp[$obj->rowid][$account_pay_donation] = isset($tabtp[$obj->rowid][$account_pay_donation]) ? $tabtp[$obj->rowid][$account_pay_donation] + $amounttouse : $amounttouse;
479 } elseif ($links[$key]['type'] == 'member') {
480 $paymentsubscriptionstatic->id = $links[$key]['url_id'];
481 $paymentsubscriptionstatic->ref = $links[$key]['url_id'];
482 $paymentsubscriptionstatic->label = $links[$key]['label'];
483 $tabpay[$obj->rowid]["lib"] .= ' '.$paymentsubscriptionstatic->getNomUrl(2);
484 $tabpay[$obj->rowid]["paymentsubscriptionid"] = $paymentsubscriptionstatic->id;
485 $paymentsubscriptionstatic->fetch($paymentsubscriptionstatic->id);
486 $tabtp[$obj->rowid][$account_pay_subscription] = isset($tabtp[$obj->rowid][$account_pay_subscription]) ? $tabtp[$obj->rowid][$account_pay_subscription] + $amounttouse : $amounttouse;
487 } elseif ($links[$key]['type'] == 'payment_vat') { // Payment VAT
488 $paymentvatstatic->id = $links[$key]['url_id'];
489 $paymentvatstatic->ref = $links[$key]['url_id'];
490 $paymentvatstatic->label = $links[$key]['label'];
491 $tabpay[$obj->rowid]["lib"] .= ' '.$paymentvatstatic->getNomUrl(2);
492 $tabpay[$obj->rowid]["paymentvatid"] = $paymentvatstatic->id;
493 $tabtp[$obj->rowid][$account_pay_vat] = isset($tabtp[$obj->rowid][$account_pay_vat]) ? $tabtp[$obj->rowid][$account_pay_vat] + $amounttouse : $amounttouse;
494 } elseif ($links[$key]['type'] == 'payment_salary') {
495 $paymentsalstatic->id = $links[$key]['url_id'];
496 $paymentsalstatic->ref = $links[$key]['url_id'];
497 $paymentsalstatic->label = $links[$key]['label'];
498 $tabpay[$obj->rowid]["lib"] .= ' '.$paymentsalstatic->getNomUrl(2);
499 $tabpay[$obj->rowid]["paymentsalid"] = $paymentsalstatic->id;
500
501 // 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.
502 // Note: A better way to fix this is to delete payment of salary and recreate it, or to fix the bookkeeping table manually after.
503 if (getDolGlobalString('ACCOUNTANCY_AUTOFIX_MISSING_LINK_TO_USER_ON_SALARY_BANK_PAYMENT')) {
504 $tmpsalary = new Salary($db);
505 $tmpsalary->fetch($paymentsalstatic->id);
506 $tmpsalary->fetch_user($tmpsalary->fk_user);
507
508 $userstatic->id = $tmpsalary->user->id;
509 $userstatic->name = $tmpsalary->user->name;
510 $userstatic->email = $tmpsalary->user->email;
511 $userstatic->firstname = $tmpsalary->user->firstname;
512 $userstatic->lastname = $tmpsalary->user->lastname;
513 $userstatic->status = $tmpsalary->user->status;
514 $userstatic->accountancy_code = $tmpsalary->user->accountancy_code;
515
516 if ($userstatic->id > 0) {
517 $tabpay[$obj->rowid]["soclib"] = $userstatic->getNomUrl(1, 'accountancy', 0);
518 } else {
519 $tabpay[$obj->rowid]["soclib"] = '???'; // Should not happen
520 }
521
522 if (empty($obj->typeop_user)) { // Add test to avoid to add amount twice if a link already exists also on user.
523 $compta_user = $userstatic->accountancy_code;
524 if ($compta_user) {
525 $tabtp[$obj->rowid][$compta_user] += $amounttouse;
526 $tabuser[$obj->rowid] = array(
527 'id' => $userstatic->id,
528 'name' => dolGetFirstLastname($userstatic->firstname, $userstatic->lastname),
529 'lastname' => $userstatic->lastname,
530 'firstname' => $userstatic->firstname,
531 'email' => $userstatic->email,
532 'accountancy_code' => $compta_user,
533 'status' => $userstatic->status
534 );
535 }
536 }
537 }
538 } elseif ($links[$key]['type'] == 'payment_expensereport') {
539 $paymentexpensereportstatic->id = $links[$key]['url_id'];
540 $tabpay[$obj->rowid]["lib"] .= $paymentexpensereportstatic->getNomUrl(2);
541 $tabpay[$obj->rowid]["paymentexpensereport"] = $paymentexpensereportstatic->id;
542 } elseif ($links[$key]['type'] == 'payment_various') {
543 $paymentvariousstatic->id = $links[$key]['url_id'];
544 $paymentvariousstatic->ref = $links[$key]['url_id'];
545 $paymentvariousstatic->label = $links[$key]['label'];
546 $tabpay[$obj->rowid]["lib"] .= ' '.$paymentvariousstatic->getNomUrl(2);
547 $tabpay[$obj->rowid]["paymentvariousid"] = $paymentvariousstatic->id;
548 $paymentvariousstatic->fetch($paymentvariousstatic->id);
549 $account_various = (!empty($paymentvariousstatic->accountancy_code) ? $paymentvariousstatic->accountancy_code : 'NotDefined'); // NotDefined is a reserved word
550 $account_subledger = (!empty($paymentvariousstatic->subledger_account) ? $paymentvariousstatic->subledger_account : ''); // NotDefined is a reserved word
551 $tabpay[$obj->rowid]["account_various"] = $account_various;
552 $tabtp[$obj->rowid][$account_subledger] = isset($tabtp[$obj->rowid][$account_subledger]) ? $tabtp[$obj->rowid][$account_subledger] + $amounttouse : $amounttouse;
553 } elseif ($links[$key]['type'] == 'payment_loan') {
554 $paymentloanstatic->id = $links[$key]['url_id'];
555 $paymentloanstatic->ref = $links[$key]['url_id'];
556 $paymentloanstatic->fk_loan = $links[$key]['url_id'];
557 $tabpay[$obj->rowid]["lib"] .= ' '.$paymentloanstatic->getNomUrl(2);
558 $tabpay[$obj->rowid]["paymentloanid"] = $paymentloanstatic->id;
559 //$tabtp[$obj->rowid][$account_pay_loan] += $amounttouse;
560 $sqlmid = 'SELECT pl.amount_capital, pl.amount_insurance, pl.amount_interest, l.accountancy_account_capital, l.accountancy_account_insurance, l.accountancy_account_interest';
561 $sqlmid .= ' FROM '.MAIN_DB_PREFIX.'payment_loan as pl, '.MAIN_DB_PREFIX.'loan as l';
562 $sqlmid .= ' WHERE l.rowid = pl.fk_loan AND pl.fk_bank = '.((int) $obj->rowid);
563
564 dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=".$sqlmid, LOG_DEBUG);
565 $resultmid = $db->query($sqlmid);
566 if ($resultmid) {
567 $objmid = $db->fetch_object($resultmid);
568 $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;
569 $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;
570 $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;
571 }
572 } elseif ($links[$key]['type'] == 'banktransfert') {
573 $accountLinestatic->fetch($links[$key]['url_id']);
574 $tabpay[$obj->rowid]["lib"] .= ' '.$langs->trans("BankTransfer").'- '.$accountLinestatic ->getNomUrl(1);
575 $tabtp[$obj->rowid][$account_transfer] = isset($tabtp[$obj->rowid][$account_transfer]) ? $tabtp[$obj->rowid][$account_transfer] + $amounttouse : $amounttouse;
576 $bankaccountstatic->fetch($tabpay[$obj->rowid]['fk_bank_account']);
577 $tabpay[$obj->rowid]["soclib"] = $bankaccountstatic->getNomUrl(2);
578 }
579 }
580 }
581
582 if (empty($tabbq[$obj->rowid][$compta_bank])) {
583 $tabbq[$obj->rowid][$compta_bank] = $amounttouse;
584 } else {
585 $tabbq[$obj->rowid][$compta_bank] += $amounttouse;
586 }
587
588 // If no links were found to know the amount on thirdparty, we try to guess it.
589 // This may happens on bank entries without the links lines to 'company'.
590 if (empty($tabtp[$obj->rowid]) && !empty($tabmoreinfo[$obj->rowid]['withdraw'])) { // If we don't find 'company' link because it is an old 'withdraw' record
591 foreach ($links as $key => $val) {
592 if ($links[$key]['type'] == 'payment') {
593 // Get thirdparty
594 $tmppayment->fetch($links[$key]['url_id']);
595 $arrayofamounts = $tmppayment->getAmountsArray();
596 if (is_array($arrayofamounts)) {
597 foreach ($arrayofamounts as $invoiceid => $amount) {
598 $tmpinvoice->fetch($invoiceid);
599 $tmpinvoice->fetch_thirdparty();
600 if ($tmpinvoice->thirdparty->code_compta_client) {
601 $tabtp[$obj->rowid][$tmpinvoice->thirdparty->code_compta_client] += $amount;
602 }
603 }
604 }
605 }
606 }
607 }
608
609 // If no links were found to know the amount on thirdparty/user, we init it to account 'NotDefined'.
610 if (empty($tabtp[$obj->rowid])) {
611 $tabtp[$obj->rowid]['NotDefined'] = $tabbq[$obj->rowid][$compta_bank];
612 }
613
614 // Check account number is ok
615 /*if ($action == 'writebookkeeping') // Make test now in such a case
616 {
617 reset($tabbq[$obj->rowid]);
618 $first_key_tabbq = key($tabbq[$obj->rowid]);
619 if (empty($first_key_tabbq))
620 {
621 $error++;
622 setEventMessages($langs->trans('ErrorAccountancyCodeOnBankAccountNotDefined', $obj->baref), null, 'errors');
623 }
624 reset($tabtp[$obj->rowid]);
625 $first_key_tabtp = key($tabtp[$obj->rowid]);
626 if (empty($first_key_tabtp))
627 {
628 $error++;
629 setEventMessages($langs->trans('ErrorAccountancyCodeOnThirdPartyNotDefined'), null, 'errors');
630 }
631 }*/
632
633 // if($obj->socid)$tabtp[$obj->rowid][$compta_soc] += $amounttouse;
634
635 $i++;
636 }
637} else {
638 dol_print_error($db);
639}
640
641
642//var_dump($tabpay);
643//var_dump($tabcompany);
644//var_dump($tabbq);
645//var_dump($tabtp);
646//var_dump($tabtype);
647
648// Write bookkeeping
649if (!$error && $action == 'writebookkeeping') {
650 $now = dol_now();
651
652 $accountingaccountcustomer = new AccountingAccount($db);
653 $accountingaccountcustomer->fetch(null, getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'), true);
654
655 $accountingaccountsupplier = new AccountingAccount($db);
656 $accountingaccountsupplier->fetch(null, getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER'), true);
657
658 $accountingaccountpayment = new AccountingAccount($db);
659 $accountingaccountpayment->fetch(null, getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT'), true);
660
661 $accountingaccountexpensereport = new AccountingAccount($db);
662 $accountingaccountexpensereport->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_EXPENSEREPORT, true);
663
664 $accountingaccountsuspense = new AccountingAccount($db);
665 $accountingaccountsuspense->fetch(null, getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE'), true);
666
667 $error = 0;
668 foreach ($tabpay as $key => $val) { // $key is rowid into llx_bank
669 $date = dol_print_date($val["date"], 'day');
670
671 $ref = getSourceDocRef($val, $tabtype[$key]);
672
673 $errorforline = 0;
674
675 $totalcredit = 0;
676 $totaldebit = 0;
677
678 $db->begin();
679
680 // Introduce a protection. Total of tabtp must be total of tabbq
681 //var_dump($tabpay);
682 //var_dump($tabtp);
683 //var_dump($tabbq);exit;
684
685 // Bank
686 if (!$errorforline && is_array($tabbq[$key])) {
687 // Line into bank account
688 foreach ($tabbq[$key] as $k => $mt) {
689 if ($mt) {
690 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
691 $accountingaccount = new AccountingAccount($db);
692 $accountingaccount->fetch(0, $k, true); // $k is accounting account of the bank.
693 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
694 } else {
695 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
696 }
697
698 $account_label = $accountingaccount->label;
699
700 $reflabel = '';
701 if (!empty($val['lib'])) {
702 $reflabel .= dol_string_nohtmltag($val['lib'])." - ";
703 }
704 $reflabel .= $langs->trans("Bank").' '.dol_string_nohtmltag($val['bank_account_ref']);
705 if (!empty($val['soclib'])) {
706 $reflabel .= " - ".dol_string_nohtmltag($val['soclib']);
707 }
708
709 $bookkeeping = new BookKeeping($db);
710 $bookkeeping->doc_date = $val["date"];
711 $bookkeeping->doc_ref = $ref;
712 $bookkeeping->doc_type = 'bank';
713 $bookkeeping->fk_doc = $key;
714 $bookkeeping->fk_docdet = $val["fk_bank"];
715
716 $bookkeeping->numero_compte = $k;
717 $bookkeeping->label_compte = $account_label;
718
719 $bookkeeping->label_operation = $reflabel;
720 $bookkeeping->montant = $mt;
721 $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
722 $bookkeeping->debit = ($mt >= 0 ? $mt : 0);
723 $bookkeeping->credit = ($mt < 0 ? -$mt : 0);
724 $bookkeeping->code_journal = $journal;
725 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
726 $bookkeeping->fk_user_author = $user->id;
727 $bookkeeping->date_creation = $now;
728
729 // No subledger_account value for the bank line but add a specific label_operation
730 $bookkeeping->subledger_account = '';
731 $bookkeeping->label_operation = $reflabel;
732 $bookkeeping->entity = $conf->entity;
733
734 $totaldebit += $bookkeeping->debit;
735 $totalcredit += $bookkeeping->credit;
736
737 $result = $bookkeeping->create($user);
738 if ($result < 0) {
739 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
740 $error++;
741 $errorforline++;
742 setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
743 } else {
744 $error++;
745 $errorforline++;
746 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
747 }
748 }
749 }
750 }
751 }
752
753 // Third party
754 if (!$errorforline) {
755 if (is_array($tabtp[$key])) {
756 // Line into thirdparty account
757 foreach ($tabtp[$key] as $k => $mt) {
758 if ($mt) {
759 $lettering = false;
760
761 $reflabel = '';
762 if (!empty($val['lib'])) {
763 $reflabel .= dol_string_nohtmltag($val['lib']).($val['soclib'] ? " - " : "");
764 }
765 if ($tabtype[$key] == 'banktransfert') {
766 $reflabel .= dol_string_nohtmltag($langs->transnoentitiesnoconv('TransitionalAccount').' '.$account_transfer);
767 } else {
768 $reflabel .= dol_string_nohtmltag($val['soclib']);
769 }
770
771 $bookkeeping = new BookKeeping($db);
772 $bookkeeping->doc_date = $val["date"];
773 $bookkeeping->doc_ref = $ref;
774 $bookkeeping->doc_type = 'bank';
775 $bookkeeping->fk_doc = $key;
776 $bookkeeping->fk_docdet = $val["fk_bank"];
777
778 $bookkeeping->label_operation = $reflabel;
779 $bookkeeping->montant = $mt;
780 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
781 $bookkeeping->debit = ($mt < 0 ? -$mt : 0);
782 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
783 $bookkeeping->code_journal = $journal;
784 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
785 $bookkeeping->fk_user_author = $user->id;
786 $bookkeeping->date_creation = $now;
787
788 if ($tabtype[$key] == 'payment') { // If payment is payment of customer invoice, we get ref of invoice
789 $lettering = true;
790 $bookkeeping->subledger_account = $k; // For payment, the subledger account is stored as $key of $tabtp
791 $bookkeeping->subledger_label = $tabcompany[$key]['name']; // $tabcompany is defined only if we are sure there is 1 thirdparty for the bank transaction
792 $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER');
793 $bookkeeping->label_compte = $accountingaccountcustomer->label;
794 } elseif ($tabtype[$key] == 'payment_supplier') { // If payment is payment of supplier invoice, we get ref of invoice
795 $lettering = true;
796 $bookkeeping->subledger_account = $k; // For payment, the subledger account is stored as $key of $tabtp
797 $bookkeeping->subledger_label = $tabcompany[$key]['name']; // $tabcompany is defined only if we are sure there is 1 thirdparty for the bank transaction
798 $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER');
799 $bookkeeping->label_compte = $accountingaccountsupplier->label;
800 } elseif ($tabtype[$key] == 'payment_expensereport') {
801 $bookkeeping->subledger_account = $tabuser[$key]['accountancy_code'];
802 $bookkeeping->subledger_label = $tabuser[$key]['name'];
803 $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT');
804 $bookkeeping->label_compte = $accountingaccountexpensereport->label;
805 } elseif ($tabtype[$key] == 'payment_salary') {
806 $bookkeeping->subledger_account = $tabuser[$key]['accountancy_code'];
807 $bookkeeping->subledger_label = $tabuser[$key]['name'];
808 $bookkeeping->numero_compte = getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT');
809 $bookkeeping->label_compte = $accountingaccountpayment->label;
810 } elseif (in_array($tabtype[$key], array('sc', 'payment_sc'))) { // If payment is payment of social contribution
811 $bookkeeping->subledger_account = '';
812 $bookkeeping->subledger_label = '';
813 $accountingaccount->fetch(null, $k, true); // TODO Use a cache
814 $bookkeeping->numero_compte = $k;
815 $bookkeeping->label_compte = $accountingaccount->label;
816 } elseif ($tabtype[$key] == 'payment_vat') {
817 $bookkeeping->subledger_account = '';
818 $bookkeeping->subledger_label = '';
819 $accountingaccount->fetch(null, $k, true); // TODO Use a cache
820 $bookkeeping->numero_compte = $k;
821 $bookkeeping->label_compte = $accountingaccount->label;
822 } elseif ($tabtype[$key] == 'payment_donation') {
823 $bookkeeping->subledger_account = '';
824 $bookkeeping->subledger_label = '';
825 $accountingaccount->fetch(null, $k, true); // TODO Use a cache
826 $bookkeeping->numero_compte = $k;
827 $bookkeeping->label_compte = $accountingaccount->label;
828 } elseif ($tabtype[$key] == 'member') {
829 $bookkeeping->subledger_account = '';
830 $bookkeeping->subledger_label = '';
831 $accountingaccount->fetch(null, $k, true); // TODO Use a cache
832 $bookkeeping->numero_compte = $k;
833 $bookkeeping->label_compte = $accountingaccount->label;
834 } elseif ($tabtype[$key] == 'payment_loan') {
835 $bookkeeping->subledger_account = '';
836 $bookkeeping->subledger_label = '';
837 $accountingaccount->fetch(null, $k, true); // TODO Use a cache
838 $bookkeeping->numero_compte = $k;
839 $bookkeeping->label_compte = $accountingaccount->label;
840 } elseif ($tabtype[$key] == 'payment_various') {
841 $bookkeeping->subledger_account = $k;
842 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
843 $accountingaccount->fetch(null, $tabpay[$key]["account_various"], true); // TODO Use a cache
844 $bookkeeping->numero_compte = $tabpay[$key]["account_various"];
845 $bookkeeping->label_compte = $accountingaccount->label;
846 } elseif ($tabtype[$key] == 'banktransfert') {
847 $bookkeeping->subledger_account = '';
848 $bookkeeping->subledger_label = '';
849 $accountingaccount->fetch(null, $k, true); // TODO Use a cache
850 $bookkeeping->numero_compte = $k;
851 $bookkeeping->label_compte = $accountingaccount->label;
852 } else {
853 if ($tabtype[$key] == 'unknown') { // Unknown transaction, we will use a waiting account for thirdparty.
854 // Temporary account
855 $bookkeeping->subledger_account = '';
856 $bookkeeping->subledger_label = '';
857 $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE');
858 $bookkeeping->label_compte = $accountingaccountsuspense->label;
859 }
860 }
861 $bookkeeping->label_operation = $reflabel;
862 $bookkeeping->entity = $conf->entity;
863
864 $totaldebit += $bookkeeping->debit;
865 $totalcredit += $bookkeeping->credit;
866
867 $result = $bookkeeping->create($user);
868 if ($result < 0) {
869 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
870 $error++;
871 $errorforline++;
872 setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
873 } else {
874 $error++;
875 $errorforline++;
876 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
877 }
878 } else {
879 if ($lettering && getDolGlobalInt('ACCOUNTING_ENABLE_LETTERING') && getDolGlobalInt('ACCOUNTING_ENABLE_AUTOLETTERING')) {
880 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php';
881 $lettering_static = new Lettering($db);
882 $nb_lettering = $lettering_static->bookkeepingLetteringAll(array($bookkeeping->id));
883 }
884 }
885 }
886 }
887 } else { // If thirdparty unknown, output the waiting account
888 foreach ($tabbq[$key] as $k => $mt) {
889 if ($mt) {
890 $reflabel = '';
891 if (!empty($val['lib'])) {
892 $reflabel .= dol_string_nohtmltag($val['lib'])." - ";
893 }
894 $reflabel .= dol_string_nohtmltag('WaitingAccount');
895
896 $bookkeeping = new BookKeeping($db);
897 $bookkeeping->doc_date = $val["date"];
898 $bookkeeping->doc_ref = $ref;
899 $bookkeeping->doc_type = 'bank';
900 $bookkeeping->fk_doc = $key;
901 $bookkeeping->fk_docdet = $val["fk_bank"];
902 $bookkeeping->montant = $mt;
903 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
904 $bookkeeping->debit = ($mt < 0 ? -$mt : 0);
905 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
906 $bookkeeping->code_journal = $journal;
907 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
908 $bookkeeping->fk_user_author = $user->id;
909 $bookkeeping->date_creation = $now;
910 $bookkeeping->label_compte = '';
911 $bookkeeping->label_operation = $reflabel;
912 $bookkeeping->entity = $conf->entity;
913
914 $totaldebit += $bookkeeping->debit;
915 $totalcredit += $bookkeeping->credit;
916
917 $result = $bookkeeping->create($user);
918
919 if ($result < 0) {
920 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
921 $error++;
922 $errorforline++;
923 setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
924 } else {
925 $error++;
926 $errorforline++;
927 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
928 }
929 }
930 }
931 }
932 }
933 }
934
935 if (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT')) {
936 $error++;
937 $errorforline++;
938 setEventMessages('We tried to insert a non balanced transaction in book for '.$ref.'. Canceled. Surely a bug.', null, 'errors');
939 }
940
941 if (!$errorforline) {
942 $db->commit();
943 } else {
944 //print 'KO for line '.$key.' '.$error.'<br>';
945 $db->rollback();
946
947 $MAXNBERRORS = 5;
948 if ($error >= $MAXNBERRORS) {
949 setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped").' (>'.$MAXNBERRORS.')', null, 'errors');
950 break; // Break in the foreach
951 }
952 }
953 }
954
955 if (empty($error) && count($tabpay) > 0) {
956 setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
957 } elseif (count($tabpay) == $error) {
958 setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
959 } else {
960 setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
961 }
962
963 $action = '';
964
965 // Must reload data, so we make a redirect
966 if (count($tabpay) != $error) {
967 $param = 'id_journal='.$id_journal;
968 $param .= '&date_startday='.$date_startday;
969 $param .= '&date_startmonth='.$date_startmonth;
970 $param .= '&date_startyear='.$date_startyear;
971 $param .= '&date_endday='.$date_endday;
972 $param .= '&date_endmonth='.$date_endmonth;
973 $param .= '&date_endyear='.$date_endyear;
974 $param .= '&in_bookkeeping='.$in_bookkeeping;
975 header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
976 exit;
977 }
978}
979
980
981
982// Export
983if ($action == 'exportcsv') { // ISO and not UTF8 !
984 $sep = getDolGlobalString('ACCOUNTING_EXPORT_SEPARATORCSV');
985
986 $filename = 'journal';
987 $type_export = 'journal';
988 include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
989
990 // CSV header line
991 print '"'.$langs->transnoentitiesnoconv("BankId").'"'.$sep;
992 print '"'.$langs->transnoentitiesnoconv("Date").'"'.$sep;
993 print '"'.$langs->transnoentitiesnoconv("PaymentMode").'"'.$sep;
994 print '"'.$langs->transnoentitiesnoconv("AccountAccounting").'"'.$sep;
995 print '"'.$langs->transnoentitiesnoconv("LedgerAccount").'"'.$sep;
996 print '"'.$langs->transnoentitiesnoconv("SubledgerAccount").'"'.$sep;
997 print '"'.$langs->transnoentitiesnoconv("Label").'"'.$sep;
998 print '"'.$langs->transnoentitiesnoconv("AccountingDebit").'"'.$sep;
999 print '"'.$langs->transnoentitiesnoconv("AccountingCredit").'"'.$sep;
1000 print '"'.$langs->transnoentitiesnoconv("Journal").'"'.$sep;
1001 print '"'.$langs->transnoentitiesnoconv("Note").'"'.$sep;
1002 print "\n";
1003
1004 foreach ($tabpay as $key => $val) {
1005 $date = dol_print_date($val["date"], 'day');
1006
1007 $ref = getSourceDocRef($val, $tabtype[$key]);
1008
1009 // Bank
1010 foreach ($tabbq[$key] as $k => $mt) {
1011 if ($mt) {
1012 $reflabel = '';
1013 if (!empty($val['lib'])) {
1014 $reflabel .= dol_string_nohtmltag($val['lib'])." - ";
1015 }
1016 $reflabel .= $langs->trans("Bank").' '.dol_string_nohtmltag($val['bank_account_ref']);
1017 if (!empty($val['soclib'])) {
1018 $reflabel .= " - ".dol_string_nohtmltag($val['soclib']);
1019 }
1020
1021 print '"'.$key.'"'.$sep;
1022 print '"'.$date.'"'.$sep;
1023 print '"'.$val["type_payment"].'"'.$sep;
1024 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1025 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1026 print " ".$sep;
1027 print '"'.$reflabel.'"'.$sep;
1028 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1029 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1030 print '"'.$journal.'"'.$sep;
1031 print '"'.dol_string_nohtmltag($ref).'"'.$sep;
1032 print "\n";
1033 }
1034 }
1035
1036 // Third party
1037 if (is_array($tabtp[$key])) {
1038 foreach ($tabtp[$key] as $k => $mt) {
1039 if ($mt) {
1040 $reflabel = '';
1041 if (!empty($val['lib'])) {
1042 $reflabel .= dol_string_nohtmltag($val['lib']).($val['soclib'] ? " - " : "");
1043 }
1044 if ($tabtype[$key] == 'banktransfert') {
1045 $reflabel .= dol_string_nohtmltag($langs->transnoentitiesnoconv('TransitionalAccount').' '.$account_transfer);
1046 } else {
1047 $reflabel .= dol_string_nohtmltag($val['soclib']);
1048 }
1049
1050 print '"'.$key.'"'.$sep;
1051 print '"'.$date.'"'.$sep;
1052 print '"'.$val["type_payment"].'"'.$sep;
1053 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1054 if ($tabtype[$key] == 'payment_supplier') {
1055 print '"'.getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER').'"'.$sep;
1056 } elseif ($tabtype[$key] == 'payment') {
1057 print '"'.getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER').'"'.$sep;
1058 } elseif ($tabtype[$key] == 'payment_expensereport') {
1059 print '"'.getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT').'"'.$sep;
1060 } elseif ($tabtype[$key] == 'payment_salary') {
1061 print '"'.getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT').'"'.$sep;
1062 } else {
1063 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1064 }
1065 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1066 print '"'.$reflabel.'"'.$sep;
1067 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1068 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1069 print '"'.$journal.'"'.$sep;
1070 print '"'.dol_string_nohtmltag($ref).'"'.$sep;
1071 print "\n";
1072 }
1073 }
1074 } else { // If thirdparty unknown, output the waiting account
1075 foreach ($tabbq[$key] as $k => $mt) {
1076 if ($mt) {
1077 $reflabel = '';
1078 if (!empty($val['lib'])) {
1079 $reflabel .= dol_string_nohtmltag($val['lib'])." - ";
1080 }
1081 $reflabel .= dol_string_nohtmltag('WaitingAccount');
1082
1083 print '"'.$key.'"'.$sep;
1084 print '"'.$date.'"'.$sep;
1085 print '"'.$val["type_payment"].'"'.$sep;
1086 print '"'.length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE')).'"'.$sep;
1087 print '"'.length_accounta(getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE')).'"'.$sep;
1088 print $sep;
1089 print '"'.$reflabel.'"'.$sep;
1090 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1091 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1092 print '"'.$journal.'"'.$sep;
1093 print '"'.dol_string_nohtmltag($ref).'"'.$sep;
1094 print "\n";
1095 }
1096 }
1097 }
1098 }
1099}
1100
1101
1102/*
1103 * View
1104 */
1105
1106$form = new Form($db);
1107
1108if (empty($action) || $action == 'view') {
1109 $invoicestatic = new Facture($db);
1110 $invoicesupplierstatic = new FactureFournisseur($db);
1111 $expensereportstatic = new ExpenseReport($db);
1112 $vatstatic = new Tva($db);
1113 $donationstatic = new Don($db);
1114 $loanstatic = new Loan($db);
1115 $salarystatic = new Salary($db);
1116 $variousstatic = new PaymentVarious($db);
1117
1118 $title = $langs->trans("GenerationOfAccountingEntries").' - '.$accountingjournalstatic->getNomUrl(0, 2, 1, '', 1);
1119 $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;';
1120 llxHeader('', dol_string_nohtmltag($title), $help_url, '', 0, 0, '', '', '', 'mod-accountancy accountancy-generation page-bankjournal');
1121
1122 $nom = $title;
1123 $builddate = dol_now();
1124 //$description = $langs->trans("DescFinanceJournal") . '<br>';
1125 $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
1126
1127 $listofchoices = array(
1128 'notyet' => $langs->trans("NotYetInGeneralLedger"),
1129 'already' => $langs->trans("AlreadyInGeneralLedger")
1130 );
1131 $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);
1132 $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
1133
1134 $varlink = 'id_journal='.$id_journal;
1135 $periodlink = '';
1136 $exportlink = '';
1137
1138 $listofchoices = array(
1139 1 => $langs->trans("TransfertAllBankLines"),
1140 2 => $langs->trans("TransfertOnlyConciliatedBankLine")
1141 );
1142 $moreoptions = [ "BankLineConciliated" => $form->selectarray('only_rappro', $listofchoices, $only_rappro)];
1143
1144 journalHead($nom, '', $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink, $moreoptions);
1145
1146 $desc = '';
1147
1148 if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') != 'blockedonclosed') {
1149 // Test that setup is complete (we are in accounting, so test on entity is always on $conf->entity only, no sharing allowed)
1150 // Fiscal period test
1151 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_fiscalyear WHERE entity = ".((int) $conf->entity);
1152 $resql = $db->query($sql);
1153 if ($resql) {
1154 $obj = $db->fetch_object($resql);
1155 if ($obj->nb == 0) {
1156 print '<br><div class="warning">'.img_warning().' '.$langs->trans("TheFiscalPeriodIsNotDefined");
1157 $desc = ' : '.$langs->trans("AccountancyAreaDescFiscalPeriod", 4, '{link}');
1158 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("FiscalPeriod").'</strong>', $desc);
1159 print $desc;
1160 print '</div>';
1161 }
1162 } else {
1163 dol_print_error($db);
1164 }
1165 }
1166
1167 // Bank test
1168 $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";
1169 $resql = $db->query($sql);
1170 if ($resql) {
1171 $obj = $db->fetch_object($resql);
1172 if ($obj->nb > 0) {
1173 print '<br><div class="warning">'.img_warning().' '.$langs->trans("TheJournalCodeIsNotDefinedOnSomeBankAccount");
1174 $desc = ' : '.$langs->trans("AccountancyAreaDescBank", 6, '{link}');
1175 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("BankAccounts").'</strong>', $desc);
1176 print $desc;
1177 print '</div>';
1178 }
1179 } else {
1180 dol_print_error($db);
1181 }
1182
1183
1184 // Button to write into Ledger
1185 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') == "" || getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') == '-1'
1186 || getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') == "" || getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') == '-1'
1187 || (isModEnabled("salaries") && (getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT') == "" || getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT') == '-1'))
1188 || (isModEnabled("expensereport") && (getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT') == "" || getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT') == '-1'))) {
1189
1190
1191 print($desc ? '' : '<br>').'<div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
1192 $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
1193 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
1194 print $desc;
1195 print '</div>';
1196 }
1197
1198
1199 print '<br><div class="tabsAction tabsActionNoBottom centerimp">';
1200
1201 if (getDolGlobalString('ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL') && $in_bookkeeping == 'notyet') {
1202 print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
1203 }
1204
1205 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') == "" || getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') == '-1'
1206 || getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') == "" || getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') == '-1') {
1207 print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
1208 } else {
1209 if ($in_bookkeeping == 'notyet') {
1210 print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
1211 } else {
1212 print '<a class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
1213 }
1214 }
1215
1216 print '</div>';
1217
1218 // TODO Avoid using js. We can use a direct link with $param
1219 print '
1220 <script type="text/javascript">
1221 function launch_export() {
1222 console.log("Set value into form and submit");
1223 $("div.fiche form input[name=\"action\"]").val("exportcsv");
1224 $("div.fiche form input[type=\"submit\"]").click();
1225 $("div.fiche form input[name=\"action\"]").val("");
1226 }
1227 function writebookkeeping() {
1228 console.log("Set value into form and submit");
1229 $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
1230 $("div.fiche form input[type=\"submit\"]").click();
1231 $("div.fiche form input[name=\"action\"]").val("");
1232 }
1233 </script>';
1234
1235 /*
1236 * Show result array
1237 */
1238 print '<br>';
1239
1240 $i = 0;
1241 print '<div class="div-table-responsive">';
1242 print '<table class="noborder centpercent">';
1243 print '<tr class="liste_titre">';
1244 print "<td>".$langs->trans("Date")."</td>";
1245 print "<td>".$langs->trans("Piece").' ('.$langs->trans("ObjectsRef").")</td>";
1246 print "<td>".$langs->trans("AccountAccounting")."</td>";
1247 print "<td>".$langs->trans("SubledgerAccount")."</td>";
1248 print "<td>".$langs->trans("LabelOperation")."</td>";
1249 print '<td class="center">'.$langs->trans("PaymentMode")."</td>";
1250 print '<td class="right">'.$langs->trans("AccountingDebit")."</td>";
1251 print '<td class="right">'.$langs->trans("AccountingCredit")."</td>";
1252 print "</tr>\n";
1253
1254 $r = '';
1255
1256 foreach ($tabpay as $key => $val) { // $key is rowid in llx_bank
1257 $date = dol_print_date($val["date"], 'day');
1258
1259 $ref = getSourceDocRef($val, $tabtype[$key]);
1260
1261 // Bank
1262 foreach ($tabbq[$key] as $k => $mt) {
1263 if ($mt) {
1264 $reflabel = '';
1265 if (!empty($val['lib'])) {
1266 $reflabel .= $val['lib']." - ";
1267 }
1268 $reflabel .= $langs->trans("Bank").' '.$val['bank_account_ref'];
1269 if (!empty($val['soclib'])) {
1270 $reflabel .= " - ".$val['soclib'];
1271 }
1272
1273 //var_dump($tabpay[$key]);
1274 print '<!-- Bank bank.rowid='.$key.' type='.$tabpay[$key]['type'].' ref='.$tabpay[$key]['ref'].'-->';
1275 print '<tr class="oddeven">';
1276
1277 // Date
1278 print "<td>".$date."</td>";
1279
1280 // Ref
1281 print "<td>".dol_escape_htmltag($ref)."</td>";
1282
1283 // Ledger account
1284 $accounttoshow = length_accountg($k);
1285 if (empty($accounttoshow) || $accounttoshow == 'NotDefined') {
1286 $accounttoshow = '<span class="error">'.$langs->trans("BankAccountNotDefined").'</span>';
1287 }
1288 print '<td class="maxwidth300" title="'.dol_escape_htmltag(dol_string_nohtmltag($accounttoshow)).'">';
1289 print $accounttoshow;
1290 print "</td>";
1291
1292 // Subledger account
1293 print '<td class="maxwidth300">';
1294 /*$accounttoshow = length_accountg($k);
1295 if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
1296 {
1297 print '<span class="error">'.$langs->trans("BankAccountNotDefined").'</span>';
1298 }
1299 else print $accounttoshow;*/
1300 print "</td>";
1301
1302 // Label operation
1303 print '<td>';
1304 print $reflabel; // This is already html escaped content
1305 print "</td>";
1306
1307 print '<td class="center">'.$val["type_payment"]."</td>";
1308 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1309 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1310 print "</tr>";
1311
1312 $i++;
1313 }
1314 }
1315
1316 // Third party
1317 if (is_array($tabtp[$key])) {
1318 foreach ($tabtp[$key] as $k => $mt) {
1319 if ($mt) {
1320 $reflabel = '';
1321 if (!empty($val['lib'])) {
1322 $reflabel .= $val['lib'].(isset($val['soclib']) ? " - " : "");
1323 }
1324 if ($tabtype[$key] == 'banktransfert') {
1325 $reflabel .= $langs->trans('TransitionalAccount').' '.$account_transfer;
1326 } else {
1327 $reflabel .= isset($val['soclib']) ? $val['soclib'] : "";
1328 }
1329
1330 print '<!-- Thirdparty bank.rowid='.$key.' -->';
1331 print '<tr class="oddeven">';
1332
1333 // Date
1334 print "<td>".$date."</td>";
1335
1336 // Ref
1337 print "<td>".dol_escape_htmltag($ref)."</td>";
1338
1339 // Ledger account
1340 $account_ledger = $k;
1341 // Try to force general ledger account depending on type
1342 if ($tabtype[$key] == 'payment') {
1343 $account_ledger = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER');
1344 }
1345 if ($tabtype[$key] == 'payment_supplier') {
1346 $account_ledger = getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER');
1347 }
1348 if ($tabtype[$key] == 'payment_expensereport') {
1349 $account_ledger = getDolGlobalString('ACCOUNTING_ACCOUNT_EXPENSEREPORT');
1350 }
1351 if ($tabtype[$key] == 'payment_salary') {
1352 $account_ledger = getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT');
1353 }
1354 if ($tabtype[$key] == 'payment_vat') {
1355 $account_ledger = getDolGlobalString('ACCOUNTING_VAT_PAY_ACCOUNT');
1356 }
1357 if ($tabtype[$key] == 'member') {
1358 $account_ledger = getDolGlobalString('ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT');
1359 }
1360 if ($tabtype[$key] == 'payment_various') {
1361 $account_ledger = $tabpay[$key]["account_various"];
1362 }
1363 $accounttoshow = length_accountg($account_ledger);
1364 if (empty($accounttoshow) || $accounttoshow == 'NotDefined') {
1365 if ($tabtype[$key] == 'unknown') {
1366 // We will accept writing, but into a waiting account
1367 if (!getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE') || getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE') == '-1') {
1368 $accounttoshow = '<span class="error small">'.$langs->trans('UnknownAccountForThirdpartyAndWaitingAccountNotDefinedBlocking').'</span>';
1369 } else {
1370 $accounttoshow = '<span class="warning small">'.$langs->trans('UnknownAccountForThirdparty', length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE'))).'</span>'; // We will use a waiting account
1371 }
1372 } else {
1373 // We will refuse writing
1374 $errorstring = 'UnknownAccountForThirdpartyBlocking';
1375 if ($tabtype[$key] == 'payment') {
1376 $errorstring = 'MainAccountForCustomersNotDefined';
1377 }
1378 if ($tabtype[$key] == 'payment_supplier') {
1379 $errorstring = 'MainAccountForSuppliersNotDefined';
1380 }
1381 if ($tabtype[$key] == 'payment_expensereport') {
1382 $errorstring = 'MainAccountForUsersNotDefined';
1383 }
1384 if ($tabtype[$key] == 'payment_salary') {
1385 $errorstring = 'MainAccountForUsersNotDefined';
1386 }
1387 if ($tabtype[$key] == 'payment_vat') {
1388 $errorstring = 'MainAccountForVatPaymentNotDefined';
1389 }
1390 if ($tabtype[$key] == 'member') {
1391 $errorstring = 'MainAccountForSubscriptionPaymentNotDefined';
1392 }
1393 $accounttoshow = '<span class="error small">'.$langs->trans($errorstring).'</span>';
1394 }
1395 }
1396 print '<td class="maxwidth300" title="'.dol_escape_htmltag(dol_string_nohtmltag($accounttoshow)).'">';
1397 print $accounttoshow; // This is a HTML string
1398 print "</td>";
1399
1400 // Subledger account
1401 $accounttoshowsubledger = '';
1402 if (in_array($tabtype[$key], array('payment', 'payment_supplier', 'payment_expensereport', 'payment_salary', 'payment_various'))) { // Type of payments that uses a subledger
1403 $accounttoshowsubledger = length_accounta($k);
1404 if ($accounttoshow != $accounttoshowsubledger) {
1405 if (empty($accounttoshowsubledger) || $accounttoshowsubledger == 'NotDefined') {
1406 //var_dump($tabpay[$key]);
1407 //var_dump($tabtype[$key]);
1408 //var_dump($tabbq[$key]);
1409 //print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
1410 if (!empty($tabcompany[$key]['code_compta'])) {
1411 if (in_array($tabtype[$key], array('payment_various', 'payment_salary'))) {
1412 // For such case, if subledger is not defined, we won't use subledger accounts.
1413 $accounttoshowsubledger = '<span class="warning small">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknownSubledgerIgnored").'</span>';
1414 } else {
1415 $accounttoshowsubledger = '<span class="warning small">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknown", $tabcompany[$key]['code_compta']).'</span>';
1416 }
1417 } else {
1418 $accounttoshowsubledger = '<span class="error small">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknownBlocking").'</span>';
1419 }
1420 }
1421 } else {
1422 $accounttoshowsubledger = '';
1423 }
1424 }
1425 print '<td class="maxwidth300">';
1426 print $accounttoshowsubledger; // This is a html string
1427 print "</td>";
1428
1429 print "<td>".$reflabel."</td>";
1430
1431 print '<td class="center">'.$val["type_payment"]."</td>";
1432
1433 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1434
1435 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1436
1437 print "</tr>";
1438
1439 $i++;
1440 }
1441 }
1442 } else { // Waiting account
1443 foreach ($tabbq[$key] as $k => $mt) {
1444 if ($mt) {
1445 $reflabel = '';
1446 if (!empty($val['lib'])) {
1447 $reflabel .= $val['lib']." - ";
1448 }
1449 $reflabel .= 'WaitingAccount';
1450
1451 print '<!-- Wait bank.rowid='.$key.' -->';
1452 print '<tr class="oddeven">';
1453 print "<td>".$date."</td>";
1454 print "<td>".$ref."</td>";
1455 // Ledger account
1456 print "<td>";
1457 /*if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
1458 {
1459 print '<span class="error">'.$langs->trans("WaitAccountNotDefined").'</span>';
1460 }
1461 else */
1462 print length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE'));
1463 print "</td>";
1464 // Subledger account
1465 print "<td>";
1466 print "</td>";
1467 print "<td>".dol_escape_htmltag($reflabel)."</td>";
1468 print '<td class="center">'.$val["type_payment"]."</td>";
1469 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1470 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1471 print "</tr>";
1472
1473 $i++;
1474 }
1475 }
1476 }
1477 }
1478
1479 if (!$i) {
1480 $colspan = 8;
1481 print '<tr class="oddeven"><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
1482 }
1483
1484 print "</table>";
1485 print '</div>';
1486
1487 llxFooter();
1488}
1489
1490$db->close();
1491
1492
1493
1501function getSourceDocRef($val, $typerecord)
1502{
1503 global $db, $langs;
1504
1505 // Defined the docref into $ref (We start with $val['ref'] by default and we complete according to other data)
1506 // WE MUST HAVE SAME REF FOR ALL LINES WE WILL RECORD INTO THE BOOKKEEPING
1507 $ref = $val['ref'];
1508 if ($ref == '(SupplierInvoicePayment)' || $ref == '(SupplierInvoicePaymentBack)') {
1509 $ref = $langs->transnoentitiesnoconv('Supplier');
1510 }
1511 if ($ref == '(CustomerInvoicePayment)' || $ref == '(CustomerInvoicePaymentBack)') {
1512 $ref = $langs->transnoentitiesnoconv('Customer');
1513 }
1514 if ($ref == '(SocialContributionPayment)') {
1515 $ref = $langs->transnoentitiesnoconv('SocialContribution');
1516 }
1517 if ($ref == '(DonationPayment)') {
1518 $ref = $langs->transnoentitiesnoconv('Donation');
1519 }
1520 if ($ref == '(SubscriptionPayment)') {
1521 $ref = $langs->transnoentitiesnoconv('Subscription');
1522 }
1523 if ($ref == '(ExpenseReportPayment)') {
1524 $ref = $langs->transnoentitiesnoconv('Employee');
1525 }
1526 if ($ref == '(LoanPayment)') {
1527 $ref = $langs->transnoentitiesnoconv('Loan');
1528 }
1529 if ($ref == '(payment_salary)') {
1530 $ref = $langs->transnoentitiesnoconv('Employee');
1531 }
1532
1533 $sqlmid = '';
1534 if ($typerecord == 'payment') {
1535 if (getDolGlobalInt('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
1536 $sqlmid = "SELECT payfac.fk_facture as id, ".$db->ifsql('f1.rowid IS NULL', 'f.ref', 'f1.ref')." as ref";
1537 $sqlmid .= " FROM ".$db->prefix()."paiement_facture as payfac";
1538 $sqlmid .= " LEFT JOIN ".$db->prefix()."facture as f ON f.rowid = payfac.fk_facture";
1539 $sqlmid .= " LEFT JOIN ".$db->prefix()."societe_remise_except as sre ON sre.fk_facture_source = payfac.fk_facture";
1540 $sqlmid .= " LEFT JOIN ".$db->prefix()."facture as f1 ON f1.rowid = sre.fk_facture";
1541 $sqlmid .= " WHERE payfac.fk_paiement=".((int) $val['paymentid']);
1542 } else {
1543 $sqlmid = "SELECT payfac.fk_facture as id, f.ref as ref";
1544 $sqlmid .= " FROM ".$db->prefix()."paiement_facture as payfac";
1545 $sqlmid .= " INNER JOIN ".$db->prefix()."facture as f ON f.rowid = payfac.fk_facture";
1546 $sqlmid .= " WHERE payfac.fk_paiement=".((int) $val['paymentid']);
1547 }
1548 $ref = $langs->transnoentitiesnoconv("Invoice");
1549 } elseif ($typerecord == 'payment_supplier') {
1550 $sqlmid = 'SELECT payfac.fk_facturefourn as id, f.ref';
1551 $sqlmid .= " FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn as payfac, ".MAIN_DB_PREFIX."facture_fourn as f";
1552 $sqlmid .= " WHERE payfac.fk_facturefourn = f.rowid AND payfac.fk_paiementfourn=".((int) $val["paymentsupplierid"]);
1553 $ref = $langs->transnoentitiesnoconv("SupplierInvoice");
1554 } elseif ($typerecord == 'payment_expensereport') {
1555 $sqlmid = 'SELECT e.rowid as id, e.ref';
1556 $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_expensereport as pe, ".MAIN_DB_PREFIX."expensereport as e";
1557 $sqlmid .= " WHERE pe.rowid=".((int) $val["paymentexpensereport"])." AND pe.fk_expensereport = e.rowid";
1558 $ref = $langs->transnoentitiesnoconv("ExpenseReport");
1559 } elseif ($typerecord == 'payment_salary') {
1560 $sqlmid = 'SELECT s.rowid as ref';
1561 $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_salary as s";
1562 $sqlmid .= " WHERE s.rowid=".((int) $val["paymentsalid"]);
1563 $ref = $langs->transnoentitiesnoconv("SalaryPayment");
1564 } elseif ($typerecord == 'sc') {
1565 $sqlmid = 'SELECT sc.rowid as ref';
1566 $sqlmid .= " FROM ".MAIN_DB_PREFIX."paiementcharge as sc";
1567 $sqlmid .= " WHERE sc.rowid=".((int) $val["paymentscid"]);
1568 $ref = $langs->transnoentitiesnoconv("SocialContribution");
1569 } elseif ($typerecord == 'payment_vat') {
1570 $sqlmid = 'SELECT v.rowid as ref';
1571 $sqlmid .= " FROM ".MAIN_DB_PREFIX."tva as v";
1572 $sqlmid .= " WHERE v.rowid=".((int) $val["paymentvatid"]);
1573 $ref = $langs->transnoentitiesnoconv("PaymentVat");
1574 } elseif ($typerecord == 'payment_donation') {
1575 $sqlmid = 'SELECT payd.fk_donation as ref';
1576 $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_donation as payd";
1577 $sqlmid .= " WHERE payd.fk_donation=".((int) $val["paymentdonationid"]);
1578 $ref = $langs->transnoentitiesnoconv("Donation");
1579 } elseif ($typerecord == 'payment_loan') {
1580 $sqlmid = 'SELECT l.rowid as ref';
1581 $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_loan as l";
1582 $sqlmid .= " WHERE l.rowid=".((int) $val["paymentloanid"]);
1583 $ref = $langs->transnoentitiesnoconv("LoanPayment");
1584 } elseif ($typerecord == 'payment_various') {
1585 $sqlmid = 'SELECT v.rowid as ref';
1586 $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_various as v";
1587 $sqlmid .= " WHERE v.rowid=".((int) $val["paymentvariousid"]);
1588 $ref = $langs->transnoentitiesnoconv("VariousPayment");
1589 }
1590 // Add warning
1591 if (empty($sqlmid)) {
1592 dol_syslog("Found a typerecord=".$typerecord." not supported", LOG_WARNING);
1593 }
1594
1595 if ($sqlmid) {
1596 dol_syslog("accountancy/journal/bankjournal.php::sqlmid=".$sqlmid, LOG_DEBUG);
1597 $resultmid = $db->query($sqlmid);
1598 if ($resultmid) {
1599 while ($objmid = $db->fetch_object($resultmid)) {
1600 $ref .= ' '.$objmid->ref;
1601 }
1602 } else {
1603 dol_print_error($db);
1604 }
1605 }
1606
1607 $ref = dol_trunc($langs->transnoentitiesnoconv("BankId").' '.$val['fk_bank'].' - '.$ref, 295); // 295 + 3 dots (...) is < than max size of 300
1608 return $ref;
1609}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous)
journalHead($nom, $variant, $period, $periodlink, $description, $builddate, $exportlink='', $moreparam=array(), $calcmode='', $varlink='', $moreoptions=array())
Show header of a page used to transfer/dispatch data in accounting.
getDefaultDatesForTransfer()
Return Default dates for transfer based on periodicity option in accountancy setup.
length_accounta($accounta)
Return Auxiliary accounting account of thirdparties with defined length.
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:70
getSourceDocRef($val, $typerecord)
Return source for doc_ref of a bank transaction.
Class to manage bank accounts.
Class to manage bank transaction lines.
Class to manage accounting accounts.
Class to manage accounting journals.
Class to manage Ledger (General Ledger and Subledger)
Class for managing the social charges.
Class to manage donations.
Definition don.class.php:41
Class to manage Trips and Expenses.
Class to manage suppliers invoices.
Class to manage invoices.
Class to manage generation of HTML components Only common components must be here.
Class Lettering.
Loan.
Class to manage payments for supplier invoices.
Class to manage payments of customer invoices.
Class to manage payments of donations.
Class to manage payments of expense report.
Class to manage payments of loans.
Class to manage payments of salaries.
Class to manage various payments.
Class to manage salary payments.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage subscriptions of foundation members.
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:594
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:613
llxFooter()
Footer empty.
Definition document.php:107
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
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.