dolibarr  17.0.4
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-2021 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 (empty($user->rights->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 (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) {
152  $sql .= " AND b.dateo >= '".$db->idate($conf->global->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 = (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER != "") ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : 'NotDefined'); // NotDefined is a reserved word
200  $account_customer = (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER != "") ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : 'NotDefined'); // NotDefined is a reserved word
201  $account_employee = (!empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) ? $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT : 'NotDefined'); // NotDefined is a reserved word
202  $account_pay_vat = (!empty($conf->global->ACCOUNTING_VAT_PAY_ACCOUNT) ? $conf->global->ACCOUNTING_VAT_PAY_ACCOUNT : 'NotDefined'); // NotDefined is a reserved word
203  $account_pay_donation = (!empty($conf->global->DONATION_ACCOUNTINGACCOUNT) ? $conf->global->DONATION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word
204  $account_pay_subscription = (!empty($conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT) ? $conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word
205  $account_transfer = (!empty($conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH) ? $conf->global->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 = $conf->global->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 '"'.$conf->global->ACCOUNTING_ACCOUNT_SUPPLIER.'"'.$sep;
982  } elseif ($tabtype[$key] == 'payment') {
983  print '"'.$conf->global->ACCOUNTING_ACCOUNT_CUSTOMER.'"'.$sep;
984  } elseif ($tabtype[$key] == 'payment_expensereport') {
985  print '"'.$conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT.'"'.$sep;
986  } elseif ($tabtype[$key] == 'payment_salary') {
987  print '"'.$conf->global->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($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE).'"'.$sep;
1013  print '"'.length_accounta($conf->global->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 (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1'
1087  || ($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1'
1088  || empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) || $conf->global->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 (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1'
1104  || ($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->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  }
1211 
1212  // Third party
1213  if (is_array($tabtp[$key])) {
1214  foreach ($tabtp[$key] as $k => $mt) {
1215  if ($mt) {
1216  $reflabel = '';
1217  if (!empty($val['lib'])) {
1218  $reflabel .= $val['lib'].($val['soclib'] ? " - " : "");
1219  }
1220  if ($tabtype[$key] == 'banktransfert') {
1221  $reflabel .= $langs->trans('TransitionalAccount').' '.$account_transfer;
1222  } else {
1223  $reflabel .= $val['soclib'];
1224  }
1225 
1226  print '<!-- Thirdparty bank.rowid='.$key.' -->';
1227  print '<tr class="oddeven">';
1228 
1229  // Date
1230  print "<td>".$date."</td>";
1231 
1232  // Ref
1233  print "<td>".dol_escape_htmltag($ref)."</td>";
1234 
1235  // Ledger account
1236  $account_ledger = $k;
1237  // Try to force general ledger account depending on type
1238  if ($tabtype[$key] == 'payment') {
1239  $account_ledger = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER');
1240  }
1241  if ($tabtype[$key] == 'payment_supplier') {
1242  $account_ledger = getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER');
1243  }
1244  if ($tabtype[$key] == 'payment_expensereport') {
1245  $account_ledger = getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT');
1246  }
1247  if ($tabtype[$key] == 'payment_salary') {
1248  $account_ledger = getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT');
1249  }
1250  if ($tabtype[$key] == 'payment_vat') {
1251  $account_ledger = getDolGlobalString('ACCOUNTING_VAT_PAY_ACCOUNT');
1252  }
1253  if ($tabtype[$key] == 'member') {
1254  $account_ledger = getDolGlobalString('ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT');
1255  }
1256  if ($tabtype[$key] == 'payment_various') {
1257  $account_ledger = $tabpay[$key]["account_various"];
1258  }
1259  $accounttoshow = length_accountg($account_ledger);
1260  if (empty($accounttoshow) || $accounttoshow == 'NotDefined') {
1261  if ($tabtype[$key] == 'unknown') {
1262  // We will accept writing, but into a waiting account
1263  if (empty($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE) || $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE == '-1') {
1264  $accounttoshow = '<span class="error small">'.$langs->trans('UnknownAccountForThirdpartyAndWaitingAccountNotDefinedBlocking').'</span>';
1265  } else {
1266  $accounttoshow = '<span class="warning small">'.$langs->trans('UnknownAccountForThirdparty', length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE)).'</span>'; // We will use a waiting account
1267  }
1268  } else {
1269  // We will refuse writing
1270  $errorstring = 'UnknownAccountForThirdpartyBlocking';
1271  if ($tabtype[$key] == 'payment') {
1272  $errorstring = 'MainAccountForCustomersNotDefined';
1273  }
1274  if ($tabtype[$key] == 'payment_supplier') {
1275  $errorstring = 'MainAccountForSuppliersNotDefined';
1276  }
1277  if ($tabtype[$key] == 'payment_expensereport') {
1278  $errorstring = 'MainAccountForUsersNotDefined';
1279  }
1280  if ($tabtype[$key] == 'payment_salary') {
1281  $errorstring = 'MainAccountForUsersNotDefined';
1282  }
1283  if ($tabtype[$key] == 'payment_vat') {
1284  $errorstring = 'MainAccountForVatPaymentNotDefined';
1285  }
1286  if ($tabtype[$key] == 'member') {
1287  $errorstring = 'MainAccountForSubscriptionPaymentNotDefined';
1288  }
1289  $accounttoshow = '<span class="error small">'.$langs->trans($errorstring).'</span>';
1290  }
1291  }
1292  print '<td class="maxwidth300" title="'.dol_escape_htmltag(dol_string_nohtmltag($accounttoshow)).'">';
1293  print $accounttoshow; // This is a HTML string
1294  print "</td>";
1295 
1296  // Subledger account
1297  $accounttoshowsubledger = '';
1298  if (in_array($tabtype[$key], array('payment', 'payment_supplier', 'payment_expensereport', 'payment_salary', 'payment_various'))) { // Type of payments that uses a subledger
1299  $accounttoshowsubledger = length_accounta($k);
1300  if ($accounttoshow != $accounttoshowsubledger) {
1301  if (empty($accounttoshowsubledger) || $accounttoshowsubledger == 'NotDefined') {
1302  //var_dump($tabpay[$key]);
1303  //var_dump($tabtype[$key]);
1304  //var_dump($tabbq[$key]);
1305  //print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
1306  if (!empty($tabcompany[$key]['code_compta'])) {
1307  if (in_array($tabtype[$key], array('payment_various', 'payment_salary'))) {
1308  // For such case, if subledger is not defined, we won't use subledger accounts.
1309  $accounttoshowsubledger = '<span class="warning small">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknownSubledgerIgnored").'</span>';
1310  } else {
1311  $accounttoshowsubledger = '<span class="warning small">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknown", $tabcompany[$key]['code_compta']).'</span>';
1312  }
1313  } else {
1314  $accounttoshowsubledger = '<span class="error small">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknownBlocking").'</span>';
1315  }
1316  }
1317  } else {
1318  $accounttoshowsubledger = '';
1319  }
1320  }
1321  print '<td class="maxwidth300">';
1322  print $accounttoshowsubledger; // This is a html string
1323  print "</td>";
1324 
1325  print "<td>".$reflabel."</td>";
1326 
1327  print '<td class="center">'.$val["type_payment"]."</td>";
1328 
1329  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1330 
1331  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1332 
1333  print "</tr>";
1334  }
1335  }
1336  } else { // Waiting account
1337  foreach ($tabbq[$key] as $k => $mt) {
1338  if ($mt) {
1339  $reflabel = '';
1340  if (!empty($val['lib'])) {
1341  $reflabel .= $val['lib']." - ";
1342  }
1343  $reflabel .= 'WaitingAccount';
1344 
1345  print '<!-- Wait bank.rowid='.$key.' -->';
1346  print '<tr class="oddeven">';
1347  print "<td>".$date."</td>";
1348  print "<td>".$ref."</td>";
1349  // Ledger account
1350  print "<td>";
1351  /*if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
1352  {
1353  print '<span class="error">'.$langs->trans("WaitAccountNotDefined").'</span>';
1354  }
1355  else */ print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE);
1356  print "</td>";
1357  // Subledger account
1358  print "<td>";
1359  /*if (empty($accounttoshowsubledger) || $accounttoshowsubledger == 'NotDefined')
1360  {
1361  print '<span class="error">'.$langs->trans("WaitAccountNotDefined").'</span>';
1362  }
1363  else print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE);
1364  */
1365  print "</td>";
1366  print "<td>".$reflabel."</td>";
1367  print '<td class="center">'.$val["type_payment"]."</td>";
1368  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1369  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1370  print "</tr>";
1371  }
1372  }
1373  }
1374  }
1375 
1376  print "</table>";
1377  print '</div>';
1378 
1379  llxFooter();
1380 }
1381 
1382 $db->close();
1383 
1384 
1385 
1393 function getSourceDocRef($val, $typerecord)
1394 {
1395  global $db, $langs;
1396 
1397  // Defined the docref into $ref (We start with $val['ref'] by default and we complete according to other data)
1398  // WE MUST HAVE SAME REF FOR ALL LINES WE WILL RECORD INTO THE BOOKKEEPING
1399  $ref = $val['ref'];
1400  if ($ref == '(SupplierInvoicePayment)' || $ref == '(SupplierInvoicePaymentBack)') {
1401  $ref = $langs->transnoentitiesnoconv('Supplier');
1402  }
1403  if ($ref == '(CustomerInvoicePayment)' || $ref == '(CustomerInvoicePaymentBack)') {
1404  $ref = $langs->transnoentitiesnoconv('Customer');
1405  }
1406  if ($ref == '(SocialContributionPayment)') {
1407  $ref = $langs->transnoentitiesnoconv('SocialContribution');
1408  }
1409  if ($ref == '(DonationPayment)') {
1410  $ref = $langs->transnoentitiesnoconv('Donation');
1411  }
1412  if ($ref == '(SubscriptionPayment)') {
1413  $ref = $langs->transnoentitiesnoconv('Subscription');
1414  }
1415  if ($ref == '(ExpenseReportPayment)') {
1416  $ref = $langs->transnoentitiesnoconv('Employee');
1417  }
1418  if ($ref == '(LoanPayment)') {
1419  $ref = $langs->transnoentitiesnoconv('Loan');
1420  }
1421  if ($ref == '(payment_salary)') {
1422  $ref = $langs->transnoentitiesnoconv('Employee');
1423  }
1424 
1425  $sqlmid = '';
1426  if ($typerecord == 'payment') {
1427  if (getDolGlobalInt('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
1428  $sqlmid = "SELECT payfac.fk_facture as id, ".$db->ifsql('f1.rowid IS NULL', 'f.ref', 'f1.ref')." as ref";
1429  $sqlmid .= " FROM ".$db->prefix()."paiement_facture as payfac";
1430  $sqlmid .= " LEFT JOIN ".$db->prefix()."facture as f ON f.rowid = payfac.fk_facture";
1431  $sqlmid .= " LEFT JOIN ".$db->prefix()."societe_remise_except as sre ON sre.fk_facture_source = payfac.fk_facture";
1432  $sqlmid .= " LEFT JOIN ".$db->prefix()."facture as f1 ON f1.rowid = sre.fk_facture";
1433  $sqlmid .= " WHERE payfac.fk_paiement=".((int) $val['paymentid']);
1434  } else {
1435  $sqlmid = "SELECT payfac.fk_facture as id, f.ref as ref";
1436  $sqlmid .= " FROM ".$db->prefix()."paiement_facture as payfac";
1437  $sqlmid .= " INNER JOIN ".$db->prefix()."facture as f ON f.rowid = payfac.fk_facture";
1438  $sqlmid .= " WHERE payfac.fk_paiement=".((int) $val['paymentid']);
1439  }
1440  $ref = $langs->transnoentitiesnoconv("Invoice");
1441  } elseif ($typerecord == 'payment_supplier') {
1442  $sqlmid = 'SELECT payfac.fk_facturefourn as id, f.ref';
1443  $sqlmid .= " FROM ".MAIN_DB_PREFIX."paiementfourn_facturefourn as payfac, ".MAIN_DB_PREFIX."facture_fourn as f";
1444  $sqlmid .= " WHERE payfac.fk_facturefourn = f.rowid AND payfac.fk_paiementfourn=".((int) $val["paymentsupplierid"]);
1445  $ref = $langs->transnoentitiesnoconv("SupplierInvoice");
1446  } elseif ($typerecord == 'payment_expensereport') {
1447  $sqlmid = 'SELECT e.rowid as id, e.ref';
1448  $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_expensereport as pe, ".MAIN_DB_PREFIX."expensereport as e";
1449  $sqlmid .= " WHERE pe.rowid=".((int) $val["paymentexpensereport"])." AND pe.fk_expensereport = e.rowid";
1450  $ref = $langs->transnoentitiesnoconv("ExpenseReport");
1451  } elseif ($typerecord == 'payment_salary') {
1452  $sqlmid = 'SELECT s.rowid as ref';
1453  $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_salary as s";
1454  $sqlmid .= " WHERE s.rowid=".((int) $val["paymentsalid"]);
1455  $ref = $langs->transnoentitiesnoconv("SalaryPayment");
1456  } elseif ($typerecord == 'sc') {
1457  $sqlmid = 'SELECT sc.rowid as ref';
1458  $sqlmid .= " FROM ".MAIN_DB_PREFIX."paiementcharge as sc";
1459  $sqlmid .= " WHERE sc.rowid=".((int) $val["paymentscid"]);
1460  $ref = $langs->transnoentitiesnoconv("SocialContribution");
1461  } elseif ($typerecord == 'payment_vat') {
1462  $sqlmid = 'SELECT v.rowid as ref';
1463  $sqlmid .= " FROM ".MAIN_DB_PREFIX."tva as v";
1464  $sqlmid .= " WHERE v.rowid=".((int) $val["paymentvatid"]);
1465  $ref = $langs->transnoentitiesnoconv("PaymentVat");
1466  } elseif ($typerecord == 'payment_donation') {
1467  $sqlmid = 'SELECT payd.fk_donation as ref';
1468  $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_donation as payd";
1469  $sqlmid .= " WHERE payd.fk_donation=".((int) $val["paymentdonationid"]);
1470  $ref = $langs->transnoentitiesnoconv("Donation");
1471  } elseif ($typerecord == 'payment_loan') {
1472  $sqlmid = 'SELECT l.rowid as ref';
1473  $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_loan as l";
1474  $sqlmid .= " WHERE l.rowid=".((int) $val["paymentloanid"]);
1475  $ref = $langs->transnoentitiesnoconv("LoanPayment");
1476  } elseif ($typerecord == 'payment_various') {
1477  $sqlmid = 'SELECT v.rowid as ref';
1478  $sqlmid .= " FROM ".MAIN_DB_PREFIX."payment_various as v";
1479  $sqlmid .= " WHERE v.rowid=".((int) $val["paymentvariousid"]);
1480  $ref = $langs->transnoentitiesnoconv("VariousPayment");
1481  }
1482  // Add warning
1483  if (empty($sqlmid)) {
1484  dol_syslog("Found a typerecord=".$typerecord." not supported", LOG_WARNING);
1485  }
1486 
1487  if ($sqlmid) {
1488  dol_syslog("accountancy/journal/bankjournal.php::sqlmid=".$sqlmid, LOG_DEBUG);
1489  $resultmid = $db->query($sqlmid);
1490  if ($resultmid) {
1491  while ($objmid = $db->fetch_object($resultmid)) {
1492  $ref .= ' '.$objmid->ref;
1493  }
1494  } else {
1495  dol_print_error($db);
1496  }
1497  }
1498 
1499  $ref = dol_trunc($langs->transnoentitiesnoconv("BankId").' '.$val['fk_bank'].' - '.$ref, 295); // 295 + 3 dots (...) is < than max size of 300
1500  return $ref;
1501 }
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:39
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.
Definition: loan.class.php:31
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.
Definition: user.class.php:47
if(isModEnabled('facture') &&!empty($user->rights->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') &&!empty($user->rights->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)) $resql
Social contributions to pay.
Definition: index.php:745
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:143
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:575
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:594
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...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
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.
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
isModEnabled($module)
Is Dolibarr module enabled.
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.