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