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