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