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