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