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