dolibarr  7.0.0-beta
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@capnetworks.com>
6  * Copyright (C) 2013 Christophe Battarel <christophe.battarel@altairis.fr>
7  * Copyright (C) 2013-2017 Alexandre Spangaro <aspangaro@zendsi.com>
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 Frédéric France <frederic.france@netlogic.fr>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 3 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program. If not, see <http://www.gnu.org/licenses/>.
24  */
25 
31 require '../../main.inc.php';
32 require_once DOL_DOCUMENT_ROOT . '/core/lib/report.lib.php';
33 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
34 require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php';
35 require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
36 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
37 require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
38 require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
39 require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
40 require_once DOL_DOCUMENT_ROOT . '/compta/sociales/class/chargesociales.class.php';
41 require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
42 require_once DOL_DOCUMENT_ROOT . '/don/class/don.class.php';
43 require_once DOL_DOCUMENT_ROOT . '/don/class/paymentdonation.class.php';
44 require_once DOL_DOCUMENT_ROOT . '/compta/tva/class/tva.class.php';
45 require_once DOL_DOCUMENT_ROOT . '/compta/salaries/class/paymentsalary.class.php';
46 require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
47 require_once DOL_DOCUMENT_ROOT . '/fourn/class/paiementfourn.class.php';
48 require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php';
49 require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.class.php';
50 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php';
51 require_once DOL_DOCUMENT_ROOT . '/societe/class/client.class.php';
52 require_once DOL_DOCUMENT_ROOT . '/expensereport/class/expensereport.class.php';
53 require_once DOL_DOCUMENT_ROOT . '/expensereport/class/paymentexpensereport.class.php';
54 require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/paymentvarious.class.php';
55 require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
56 
57 $langs->loadLangs(array("companies","other","compta","banks",'bills','donations',"accountancy","trips","salaries","hrm"));
58 
59 // Multi journal
60 $id_journal = GETPOST('id_journal', 'int');
61 
62 $date_startmonth = GETPOST('date_startmonth','int');
63 $date_startday = GETPOST('date_startday','int');
64 $date_startyear = GETPOST('date_startyear','int');
65 $date_endmonth = GETPOST('date_endmonth','int');
66 $date_endday = GETPOST('date_endday','int');
67 $date_endyear = GETPOST('date_endyear','int');
68 $in_bookkeeping = GETPOST('in_bookkeeping','aZ09');
69 if ($in_bookkeeping == '') $in_bookkeeping = 'notyet';
70 
71 $now = dol_now();
72 
73 $action = GETPOST('action','aZ09');
74 
75 // Security check
76 if ($user->societe_id > 0 && empty($id_journal))
78 
79 
80 /*
81  * Actions
82  */
83 
84 $error = 0;
85 
86 $year_current = strftime("%Y", dol_now());
87 $pastmonth = strftime("%m", dol_now()) - 1;
88 $pastmonthyear = $year_current;
89 if ($pastmonth == 0) {
90  $pastmonth = 12;
91  $pastmonthyear --;
92 }
93 
94 $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
95 $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
96 
97 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
98 {
99  $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
100  $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
101 }
102 
103 $idpays = $mysoc->country_id;
104 
105 $sql = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type, b.fk_account,";
106 $sql .= " ba.courant, ba.ref as baref, ba.account_number, ba.fk_accountancy_journal,";
107 $sql .= " soc.code_compta, soc.code_compta_fournisseur, soc.rowid as socid, soc.nom as name, bu1.type as typeop_company,";
108 $sql .= " u.accountancy_code, u.rowid as userid, u.lastname as lastname, u.firstname as firstname, bu2.type as typeop_user,";
109 $sql .= " bu3.type as typeop_payment, bu4.type as typeop_payment_supplier";
110 $sql .= " FROM " . MAIN_DB_PREFIX . "bank as b";
111 $sql .= " JOIN " . MAIN_DB_PREFIX . "bank_account as ba on b.fk_account=ba.rowid";
112 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "bank_url as bu1 ON bu1.fk_bank = b.rowid AND bu1.type='company'";
113 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "bank_url as bu2 ON bu2.fk_bank = b.rowid AND bu2.type='user'";
114 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "bank_url as bu3 ON bu3.fk_bank = b.rowid AND bu3.type='payment'";
115 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "bank_url as bu4 ON bu4.fk_bank = b.rowid AND bu4.type='payment_supplier'";
116 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as soc on bu1.url_id=soc.rowid";
117 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "user as u on bu2.url_id=u.rowid";
118 $sql .= " WHERE ba.fk_accountancy_journal=" . $id_journal;
119 $sql .= ' AND b.amount != 0 AND ba.entity IN ('.getEntity('bank_account', 0).')'; // We don't share object for accountancy
120 if ($date_start && $date_end)
121  $sql .= " AND b.dateo >= '" . $db->idate($date_start) . "' AND b.dateo <= '" . $db->idate($date_end) . "'";
122 // Already in bookkeeping or not
123 if ($in_bookkeeping == 'already')
124 {
125  $sql .= " AND (b.rowid IN (SELECT fk_doc FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='bank') )";
126 }
127 if ($in_bookkeeping == 'notyet')
128 {
129  $sql .= " AND (b.rowid NOT IN (SELECT fk_doc FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='bank') )";
130 }
131 $sql .= " ORDER BY b.datev";
132 //print $sql;
133 
134 $object = new Account($db);
135 $paymentstatic = new Paiement($db);
136 $paymentsupplierstatic = new PaiementFourn($db);
137 $societestatic = new Societe($db);
138 $userstatic = new User($db);
139 $bankaccountstatic = new Account($db);
140 $chargestatic = new ChargeSociales($db);
141 $paymentdonstatic = new PaymentDonation($db);
142 $paymentvatstatic = new TVA($db);
143 $paymentsalstatic = new PaymentSalary($db);
144 $paymentexpensereportstatic = new PaymentExpenseReport($db);
145 $paymentvariousstatic = new PaymentVarious($db);
146 
147 // Get code of finance journal
148 $accountingjournalstatic = new AccountingJournal($db);
149 $accountingjournalstatic->fetch($id_journal);
150 $journal = $accountingjournalstatic->code;
151 $journal_label = $accountingjournalstatic->label;
152 
153 dol_syslog("accountancy/journal/bankjournal.php", LOG_DEBUG);
154 $result = $db->query($sql);
155 if ($result) {
156 
157  $num = $db->num_rows($result);
158  //print $sql;
159 
160  // Variables
161  $account_supplier = (! empty($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER) ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : 'NotDefined'); // NotDefined is a reserved word
162  $account_customer = (! empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : 'NotDefined'); // NotDefined is a reserved word
163  $account_employee = (! empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) ? $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT : 'NotDefined'); // NotDefined is a reserved word
164  $account_pay_vat = (! empty($conf->global->ACCOUNTING_VAT_PAY_ACCOUNT) ? $conf->global->ACCOUNTING_VAT_PAY_ACCOUNT : 'NotDefined'); // NotDefined is a reserved word
165  $account_pay_donation = (! empty($conf->global->DONATION_ACCOUNTINGACCOUNT) ? $conf->global->DONATION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word
166  $account_transfer = (! empty($conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH) ? $conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH : 'NotDefined'); // NotDefined is a reserved word
167 
168  $tabcompany = array();
169  $tabuser = array();
170  $tabpay = array ();
171  $tabbq = array ();
172  $tabtp = array ();
173  $tabtype = array ();
174 
175  // Loop on each line into llx_bank table. For each line, we should get:
176  // one line tabpay = line into bank
177  // one line for bank record = tabbq
178  // one line for thirdparty record = tabtp
179  $i = 0;
180  while ( $i < $num )
181  {
182  $obj = $db->fetch_object($result);
183 
184  $lineisapurchase = -1;
185  $lineisasale = -1;
186  // Old method to detect if it's a sale or purchase
187  if ($obj->label == '(SupplierInvoicePayment)' || $obj->label == '(SupplierInvoicePaymentBack)') $lineisapurchase=1;
188  if ($obj->label == '(CustomerInvoicePayment)' || $obj->label == '(CustomerInvoicePaymentBack)') $lineisasale=1;
189  // Try a more reliable method to detect if record is a supplier payment or a customer payment
190  if ($lineisapurchase < 0)
191  {
192  if ($obj->typeop_payment_supplier == 'payment_supplier') $lineisapurchase = 1;
193  }
194  if ($lineisasale < 0)
195  {
196  if ($obj->typeop_payment == 'payment') $lineisasale = 1;
197  }
198  //var_dump($obj->type_payment); var_dump($obj->type_payment_supplier);
199  //var_dump($lineisapurchase); //var_dump($lineisasale);
200 
201  // Set accountancy code for bank
202  $compta_bank = $obj->account_number;
203 
204  // Set accountancy code for thirdparty
205  $compta_soc = 'NotDefined';
206  if ($lineisapurchase > 0)
207  $compta_soc = (! empty($obj->code_compta_fournisseur) ? $obj->code_compta_fournisseur : $account_supplier);
208  if ($lineisasale > 0)
209  $compta_soc = (! empty($obj->code_compta) ? $obj->code_compta : $account_customer);
210 
211  $tabcompany[$obj->rowid] = array (
212  'id' => $obj->socid,
213  'name' => $obj->name,
214  'code_compta' => $compta_soc,
215  );
216 
217  // Set accountancy code for user
218  $compta_user = (! empty($obj->accountancy_code) ? $obj->accountancy_code : $account_employee);
219 
220  $tabuser[$obj->rowid] = array (
221  'id' => $obj->userid,
222  'name' => dolGetFirstLastname($obj->firstname, $obj->lastname),
223  'lastname' => $obj->lastname,
224  'firstname' => $obj->firstname,
225  'accountancy_code' => $compta_user,
226  );
227 
228  // Variable bookkeeping
229  $tabpay[$obj->rowid]["date"] = $obj->do;
230  $tabpay[$obj->rowid]["type_payment"] = $obj->fk_type; // CHQ, VIR, LIQ, CB, ...
231  $tabpay[$obj->rowid]["ref"] = $obj->label; // By default. Not unique. May be changed later
232  $tabpay[$obj->rowid]["fk_bank"] = $obj->rowid;
233  $tabpay[$obj->rowid]["bank_account_ref"] = $obj->baref;
234  $tabpay[$obj->rowid]["fk_bank_account"] = $obj->fk_account;
235  if (preg_match('/^\((.*)\)$/i', $obj->label, $reg)) {
236  $tabpay[$obj->rowid]["lib"] = $langs->trans($reg[1]);
237  } else {
238  $tabpay[$obj->rowid]["lib"] = dol_trunc($obj->label, 60);
239  }
240  $links = $object->get_url($obj->rowid);
241 
242  //var_dump($i);
243  //var_dump($tabpay);
244 
245  // By default
246  $tabpay[$obj->rowid]['type'] = 'unknown'; // Can be SOLD, miscellaneous entry, payment of patient, or any old record with no links in bank_url.
247  $tabtype[$obj->rowid] = 'unknown';
248 
249  // get_url may return -1 which is not traversable
250  if (is_array($links) && count($links) > 0) {
251 
252  // Now loop on each link of record in bank.
253  foreach ($links as $key => $val) {
254 
255  if (in_array($links[$key]['type'], array('sc', 'payment_sc', 'payment', 'payment_supplier', 'payment_vat', 'payment_expensereport', 'banktransfert', 'payment_donation', 'payment_salary', 'payment_various')))
256  {
257  // So we excluded 'company' and 'user' here. We want only payment lines
258 
259  // We save tabtype for a future use, to remember what kind of payment it is
260  $tabpay[$obj->rowid]['type'] = $links[$key]['type'];
261  $tabtype[$obj->rowid] = $links[$key]['type'];
262  }
263  elseif (in_array($links[$key]['type'], array('company', 'user')))
264  {
265  if ($tabpay[$obj->rowid]['type'] == 'unknown')
266  {
267  // We can guess here it is a bank record for a thirdparty company or a user.
268  // 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.
269  }
270  }
271 
272  if ($links[$key]['type'] == 'payment') {
273  $paymentstatic->id = $links[$key]['url_id'];
274  $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentstatic->getNomUrl(2);
275  $tabpay[$obj->rowid]["paymentid"] = $paymentstatic->id;
276  } else if ($links[$key]['type'] == 'payment_supplier') {
277  $paymentsupplierstatic->id = $links[$key]['url_id'];
278  $paymentsupplierstatic->ref = $links[$key]['url_id'];
279  $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentsupplierstatic->getNomUrl(2);
280  $tabpay[$obj->rowid]["paymentsupplierid"] = $paymentsupplierstatic->id;
281  } else if ($links[$key]['type'] == 'company') {
282  $societestatic->id = $links[$key]['url_id'];
283  $societestatic->name = $links[$key]['label'];
284  $tabpay[$obj->rowid]["soclib"] = $societestatic->getNomUrl(1, '', 30);
285  if ($compta_soc) $tabtp[$obj->rowid][$compta_soc] += $obj->amount;
286  } else if ($links[$key]['type'] == 'user') {
287  $userstatic->id = $links[$key]['url_id'];
288  $userstatic->name = $links[$key]['label'];
289  if ($userstatic->id > 0) $tabpay[$obj->rowid]["soclib"] = $userstatic->getNomUrl(1, '', 30);
290  else $tabpay[$obj->rowid]["soclib"] = '???'; // Should not happen, but happens with old data when id of user was not saved on expense report payment.
291  if ($compta_user) $tabtp[$obj->rowid][$compta_user] += $obj->amount;
292  } else if ($links[$key]['type'] == 'sc') {
293  $chargestatic->id = $links[$key]['url_id'];
294  $chargestatic->ref = $links[$key]['url_id'];
295 
296  $tabpay[$obj->rowid]["lib"] .= ' ' . $chargestatic->getNomUrl(2);
297  if (preg_match('/^\((.*)\)$/i', $links[$key]['label'], $reg)) {
298  if ($reg[1] == 'socialcontribution')
299  $reg[1] = 'SocialContribution';
300  $chargestatic->lib = $langs->trans($reg[1]);
301  } else {
302  $chargestatic->lib = $links[$key]['label'];
303  }
304  $chargestatic->ref = $chargestatic->lib;
305  $tabpay[$obj->rowid]["soclib"] = $chargestatic->getNomUrl(1, 30);
306 
307  $sqlmid = 'SELECT cchgsoc.accountancy_code';
308  $sqlmid .= " FROM " . MAIN_DB_PREFIX . "c_chargesociales cchgsoc ";
309  $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "chargesociales as chgsoc ON chgsoc.fk_type=cchgsoc.id";
310  $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementcharge as paycharg ON paycharg.fk_charge=chgsoc.rowid";
311  $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "bank_url as bkurl ON bkurl.url_id=paycharg.rowid";
312  $sqlmid .= " WHERE bkurl.fk_bank=" . $obj->rowid;
313 
314  dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG);
315  $resultmid = $db->query($sqlmid);
316  if ($resultmid) {
317  $objmid = $db->fetch_object($resultmid);
318  $tabtp[$obj->rowid][$objmid->accountancy_code] += $obj->amount;
319  }
320  } else if ($links[$key]['type'] == 'payment_donation') {
321  $paymentdonstatic->id = $links[$key]['url_id'];
322  $paymentdonstatic->fk_donation = $links[$key]['url_id'];
323  $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentdonstatic->getNomUrl(2);
324  $tabpay[$obj->rowid]["paymentdonationid"] = $paymentdonstatic->id;
325  $tabtp[$obj->rowid][$account_pay_donation] += $obj->amount;
326  } else if ($links[$key]['type'] == 'payment_vat') {
327  $paymentvatstatic->id = $links[$key]['url_id'];
328  $paymentvatstatic->ref = $links[$key]['url_id'];
329  $paymentvatstatic->label = $links[$key]['label'];
330  $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentvatstatic->getNomUrl(2);
331  $tabpay[$obj->rowid]["paymentvatid"] = $paymentvatstatic->id;
332  $tabtp[$obj->rowid][$account_pay_vat] += $obj->amount;
333  } else if ($links[$key]['type'] == 'payment_salary') {
334  $paymentsalstatic->id = $links[$key]['url_id'];
335  $paymentsalstatic->ref = $links[$key]['url_id'];
336  $paymentsalstatic->label = $links[$key]['label'];
337  $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentsalstatic->getNomUrl(2);
338  $tabpay[$obj->rowid]["paymentsalid"] = $paymentsalstatic->id;
339  } else if ($links[$key]['type'] == 'payment_expensereport') {
340  $paymentexpensereportstatic->id = $links[$key]['url_id'];
341  $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentexpensereportstatic->getNomUrl(2);
342  $tabpay[$obj->rowid]["paymentexpensereport"] = $paymentexpensereportstatic->id;
343  } else if ($links[$key]['type'] == 'payment_various') {
344  $paymentvariousstatic->id = $links[$key]['url_id'];
345  $paymentvariousstatic->ref = $links[$key]['url_id'];
346  $paymentvariousstatic->label = $links[$key]['label'];
347  $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentvariousstatic->getNomUrl(2);
348  $tabpay[$obj->rowid]["paymentvariousid"] = $paymentvariousstatic->id;
349  $paymentvariousstatic->fetch($paymentvariousstatic->id);
350  $account_various = (! empty($paymentvariousstatic->accountancy_code) ? $paymentvariousstatic->accountancy_code : 'NotDefined'); // NotDefined is a reserved word
351  $tabtp[$obj->rowid][$account_various] += $obj->amount;
352  } else if ($links[$key]['type'] == 'banktransfert') {
353  $tabpay[$obj->rowid]["lib"] .= ' ' . $langs->trans("BankTransfer");
354  $tabtp[$obj->rowid][$account_transfer] += $obj->amount;
355  $bankaccountstatic->fetch($tabpay[$obj->rowid]['fk_bank_account']);
356  $tabpay[$obj->rowid]["soclib"] = $bankaccountstatic->getNomUrl(2);
357  }
358  }
359  }
360 
361  $tabbq[$obj->rowid][$compta_bank] += $obj->amount;
362 
363  // If not links were found to know amount on thirdparty, we init it.
364  if (empty($tabtp[$obj->rowid])) $tabtp[$obj->rowid]['NotDefined']= $tabbq[$obj->rowid][$compta_bank];
365 
366  // Check account number is ok
367  /*if ($action == 'writebookkeeping') // Make test now in such a case
368  {
369  reset($tabbq[$obj->rowid]);
370  $first_key_tabbq = key($tabbq[$obj->rowid]);
371  if (empty($first_key_tabbq))
372  {
373  $error++;
374  setEventMessages($langs->trans('ErrorAccountancyCodeOnBankAccountNotDefined', $obj->baref), null, 'errors');
375  }
376  reset($tabtp[$obj->rowid]);
377  $first_key_tabtp = key($tabtp[$obj->rowid]);
378  if (empty($first_key_tabtp))
379  {
380  $error++;
381  setEventMessages($langs->trans('ErrorAccountancyCodeOnThirdPartyNotDefined'), null, 'errors');
382  }
383  }*/
384 
385  // if($obj->socid)$tabtp[$obj->rowid][$compta_soc] += $obj->amount;
386 
387  $i++;
388  }
389 } else {
390  dol_print_error($db);
391 }
392 
393 /*
394 var_dump($tabpay);
395 var_dump($tabbq);
396 var_dump($tabtp);
397 */
398 
399 // Write bookkeeping
400 if (! $error && $action == 'writebookkeeping') {
401  $now = dol_now();
402 
403  $error = 0;
404  foreach ( $tabpay as $key => $val ) { // $key is rowid into llx_bank
405 
406  $ref = getSourceDocRef($val, $tabtype[$key]);
407 
408  $errorforline = 0;
409 
410  $totalcredit = 0;
411  $totaldebit = 0;
412 
413  $db->begin();
414 
415  // Introduce a protection. Total of tabtp must be total of tabbq
416  /*var_dump($tabpay);
417  var_dump($tabtp);
418  var_dump($tabbq);exit;*/
419 
420  // Bank
421  if (! $errorforline && is_array($tabbq[$key]))
422  {
423  // Line into bank account
424  foreach ( $tabbq[$key] as $k => $mt )
425  {
426  if ($mt) {
427  $bookkeeping = new BookKeeping($db);
428  $bookkeeping->doc_date = $val["date"];
429  $bookkeeping->doc_ref = $ref;
430  $bookkeeping->doc_type = 'bank';
431  $bookkeeping->fk_doc = $key;
432  $bookkeeping->fk_docdet = $val["fk_bank"];
433  $bookkeeping->numero_compte = $k;
434  $bookkeeping->label_compte = $langs->trans("Bank");
435  $bookkeeping->montant = $mt;
436  $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
437  $bookkeeping->debit = ($mt >= 0 ? $mt : 0);
438  $bookkeeping->credit = ($mt < 0 ? - $mt : 0);
439  $bookkeeping->code_journal = $journal;
440  $bookkeeping->journal_label = $journal_label;
441  $bookkeeping->fk_user_author = $user->id;
442  $bookkeeping->date_create = $now;
443 
444  // No subledger_account value for the bank line but add a specific label_operation
445  if ($tabtype[$key] == 'payment') {
446  $bookkeeping->subledger_account = '';
447  $bookkeeping->label_operation = $tabcompany[$key]['name'] . ' - ' . $ref;
448  } else if ($tabtype[$key] == 'payment_supplier') {
449  $bookkeeping->subledger_account = '';
450  $bookkeeping->label_operation = $tabcompany[$key]['name'] . ' - ' . $ref;
451  } else if ($tabtype[$key] == 'payment_expensereport') {
452  $bookkeeping->subledger_account = '';
453  $bookkeeping->label_operation = $tabuser[$key]['name'] . ' - ' . $ref;
454  } else if ($tabtype[$key] == 'payment_salary') {
455  $bookkeeping->subledger_account = '';
456  $bookkeeping->label_operation = $tabuser[$key]['name'] . ' - ' . $ref;
457  } else if ($tabtype[$key] == 'payment_vat') {
458  $bookkeeping->subledger_account = '';
459  $bookkeeping->label_operation = $ref;
460  } else if ($tabtype[$key] == 'payment_donation') {
461  $bookkeeping->subledger_account = '';
462  $bookkeeping->label_operation = $ref;
463  } else if ($tabtype[$key] == 'payment_various') {
464  $bookkeeping->subledger_account = '';
465  $bookkeeping->label_operation = $ref;
466  } else if ($tabtype[$key] == 'unknown') {
467  // ???
468  $bookkeeping->subledger_account = '';
469  }
470 
471  $totaldebit += $bookkeeping->debit;
472  $totalcredit += $bookkeeping->credit;
473 
474  $result = $bookkeeping->create($user);
475  if ($result < 0) {
476  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
477  {
478  $error++;
479  $errorforline++;
480  setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
481  }
482  else
483  {
484  $error++;
485  $errorforline++;
486  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
487  }
488  }
489  }
490  }
491  }
492 
493  // Third party
494  if (! $errorforline && is_array($tabtp[$key]))
495  {
496  // Line into thirdparty account
497  foreach ( $tabtp[$key] as $k => $mt ) {
498  if ($mt) {
499  $bookkeeping = new BookKeeping($db);
500  $bookkeeping->doc_date = $val["date"];
501  $bookkeeping->doc_ref = $ref;
502  $bookkeeping->doc_type = 'bank';
503  $bookkeeping->fk_doc = $key;
504  $bookkeeping->fk_docdet = $val["fk_bank"];
505  $bookkeeping->montant = $mt;
506  $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
507  $bookkeeping->debit = ($mt < 0 ? - $mt : 0);
508  $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
509  $bookkeeping->code_journal = $journal;
510  $bookkeeping->journal_label = $journal_label;
511  $bookkeeping->fk_user_author = $user->id;
512  $bookkeeping->date_create = $now;
513 
514  if ($tabtype[$key] == 'payment') { // If payment is payment of customer invoice, we get ref of invoice
515  $bookkeeping->label_operation = $tabcompany[$key]['name'] . ' - ' . $ref;
516  $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
517  $bookkeeping->subledger_label = $tabcompany[$key]['name'];
518  $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
519  $bookkeeping->label_compte = '';
520  } else if ($tabtype[$key] == 'payment_supplier') { // If payment is payment of supplier invoice, we get ref of invoice
521  $bookkeeping->label_operation = $tabcompany[$key]['name'] . ' - ' . $ref;
522  $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
523  $bookkeeping->subledger_label = $tabcompany[$key]['name'];
524  $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER;
525  $bookkeeping->label_compte = '';
526  } else if ($tabtype[$key] == 'payment_expensereport') {
527  $bookkeeping->label_operation = $tabuser[$key]['name'] . ' - ' . $ref;
528  $bookkeeping->subledger_account = $tabuser[$key]['accountancy_code'];
529  $bookkeeping->subledger_label = $tabuser[$key]['name'];
530  $bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
531  $bookkeeping->label_compte = '';
532  } else if ($tabtype[$key] == 'payment_salary') {
533  $bookkeeping->label_operation = $tabuser[$key]['name'] . ' - ' . $ref;
534  $bookkeeping->subledger_account = $tabuser[$key]['accountancy_code'];
535  $bookkeeping->subledger_label = $tabuser[$key]['name'];
536  $bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
537  $bookkeeping->label_compte = '';
538  } else if (in_array($tabtype[$key], array('sc', 'payment_sc'))) { // If payment is payment of social contribution
539  $bookkeeping->label_operation = $ref;
540  $bookkeeping->subledger_account = '';
541  $bookkeeping->subledger_label = '';
542  $bookkeeping->numero_compte = $k;
543  $bookkeeping->label_compte = $objmid->labelc;
544  } else if ($tabtype[$key] == 'payment_vat') {
545  $bookkeeping->label_operation = $ref;
546  $bookkeeping->subledger_account = '';
547  $bookkeeping->subledger_label = '';
548  $bookkeeping->numero_compte = $k;
549  $bookkeeping->label_compte = '';
550  } else if ($tabtype[$key] == 'payment_donation') {
551  $bookkeeping->label_operation = $ref;
552  $bookkeeping->subledger_account = '';
553  $bookkeeping->subledger_label = '';
554  $bookkeeping->numero_compte = $k;
555  $bookkeeping->label_compte = '';
556  } else if ($tabtype[$key] == 'payment_various') {
557  $bookkeeping->label_operation = $ref;
558  $bookkeeping->subledger_account = '';
559  $bookkeeping->subledger_label = '';
560  $bookkeeping->numero_compte = $k;
561  $bookkeeping->label_compte = '';
562  } else if ($tabtype[$key] == 'banktransfert') {
563  $bookkeeping->label_operation = $ref;
564  $bookkeeping->subledger_account = '';
565  $bookkeeping->subledger_label = '';
566  $bookkeeping->numero_compte = $k;
567  $bookkeeping->label_compte = '';
568  } else {
569  if ($tabtype[$key] == 'unknown') // Unknown transaction, we will use a waiting account for thirdparty.
570  {
571  // Temporary account
572  $bookkeeping->label_operation = '';
573  $bookkeeping->subledger_account = '';
574  $bookkeeping->subledger_label = '';
575  $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE;
576  $bookkeeping->label_compte = '';
577  }
578  }
579 
580  $totaldebit += $bookkeeping->debit;
581  $totalcredit += $bookkeeping->credit;
582 
583  $result = $bookkeeping->create($user);
584  if ($result < 0) {
585  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
586  {
587  $error++;
588  $errorforline++;
589  setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
590  }
591  else
592  {
593  $error++;
594  $errorforline++;
595  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
596  }
597  }
598  }
599  }
600  }
601 
602  if ($totaldebit != $totalcredit)
603  {
604  $error++;
605  $errorforline++;
606  setEventMessages('Try to insert a non balanced transaction in book for '.$ref.'. Canceled. Surely a bug.', null, 'errors');
607  }
608 
609  if (! $errorforline)
610  {
611  $db->commit();
612  }
613  else
614  {
615  //print 'KO for line '.$key.' '.$error.'<br>';
616  $db->rollback();
617 
618  $MAXNBERRORS=5;
619  if ($error >= $MAXNBERRORS)
620  {
621  setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped").' (>'.$MAXNBERRORS.')', null, 'errors');
622  break; // Break in the foreach
623  }
624  }
625  }
626 
627  if (empty($error) && count($tabpay) > 0) {
628  setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
629  }
630  elseif (count($tabpay) == $error)
631  {
632  setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
633  }
634  else
635  {
636  setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
637  }
638 
639  $action = '';
640 
641  // Must reload data, so we make a redirect
642  if (count($tabpay) != $error)
643  {
644  $param='id_journal='.$id_journal;
645  $param.='&date_startday='.$date_startday;
646  $param.='&date_startmonth='.$date_startmonth;
647  $param.='&date_startyear='.$date_startyear;
648  $param.='&date_endday='.$date_endday;
649  $param.='&date_endmonth='.$date_endmonth;
650  $param.='&date_endyear='.$date_endyear;
651  $param.='&in_bookkeeping='.$in_bookkeeping;
652  header("Location: ".$_SERVER['PHP_SELF'].($param?'?'.$param:''));
653  exit;
654  }
655 }
656 
657 
658 
659 // Export
660 if ($action == 'exportcsv') { // ISO and not UTF8 !
661  $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
662 
663  include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php';
664 
665  $companystatic = new Client($db);
666  $userstatic = new User($db);
667 
668  foreach ( $tabpay as $key => $val ) {
669  $date = dol_print_date($db->jdate($val["date"]), 'day');
670 
671  $ref = getSourceDocRef($val, $tabtype[$key]);
672 
673  //
674  if (! empty($tabcompany[$key]['id']))
675  {
676  $companystatic->id = $tabcompany[$key]['id'];
677  $companystatic->name = $tabcompany[$key]['name'];
678  }
679  else
680  {
681  $companystatic->id = 0;
682  $companystatic->name = '';
683  }
684  if (! empty($tabuser[$key]['id']))
685  {
686  $userstatic->id = $tabuser[$key]['id'];
687  $userstatic->lastname = $tabuser[$key]['lastname'];
688  $userstatic->firstname = $tabuser[$key]['firstname'];
689  }
690  else
691  {
692  $userstatic->id = 0;
693  $userstatic->lastname = '';
694  $userstatic->firstname = '';
695  }
696 
697  // Bank
698  foreach ( $tabbq[$key] as $k => $mt ) {
699  print '"' . $key . '"' . $sep;
700  print '"' . $date . '"' . $sep;
701  print '"' . $val["type_payment"] . '"' . $sep;
702  print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
703  print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
704  print " " . $sep;
705  if ($companystatic->name == '') {
706  print '"' . $val['bank_account_ref'] . " - " . utf8_decode($reflabel) . '"' . $sep;
707  } else {
708  print '"' . $val['bank_account_ref'] . ' - ' . utf8_decode($companystatic->name) . '"' . $sep;
709  }
710  print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
711  print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
712  print '"' . $journal . '"' . $sep;
713  print "\n";
714  }
715 
716  // Third party
717  if (is_array($tabtp[$key])) {
718  foreach ( $tabtp[$key] as $k => $mt ) {
719  if ($mt) {
720  print '"' . $key . '"' . $sep;
721  print '"' . $date . '"' . $sep;
722  print '"' . $val["type_payment"] . '"' . $sep;
723  print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
724  if ($tabtype[$key] == 'payment_supplier') {
725  print '"' . $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER . '"' . $sep;
726  } else if($tabtype[$key] == 'payment') {
727  print '"' . $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER . '"' . $sep;
728  } else {
729  print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
730  }
731  print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
732  if ($companystatic->name == '') {
733  print '"' . $langs->trans('ThirdParty') . " - " . utf8_decode($reflabel) . '"' . $sep;
734  } else {
735  print '"' . $langs->trans('ThirdParty') . " - " . utf8_decode($companystatic->name) . '"' . $sep;
736  }
737  print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
738  print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
739  print '"' . $journal . '"' . $sep;
740  print "\n";
741  }
742  }
743  } else {
744  foreach ( $tabbq[$key] as $k => $mt ) {
745  print '"' . $key . '"' . $sep;
746  print '"' . $date . '"' . $sep;
747  print '"' . $val["type_payment"] . '"' . $sep;
748  print '"' . length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE) . '"' . $sep;
749  print '"' . length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE) . '"' . $sep;
750  print " " . $sep;
751  if ($companystatic->name == '') {
752  print '"' . $val['bank_account_ref'] . ' - ' . utf8_decode($reflabel) . '"' . $sep;
753  } else {
754  print '"' . $val['bank_account_ref'] . ' - ' . utf8_decode($companystatic->name) . '"' . $sep;
755  }
756  print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
757  print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
758  print '"' . $journal . '"' . $sep;
759  print "\n";
760  }
761  }
762  }
763 }
764 
765 
766 /*
767  * View
768  */
769 
770 $form = new Form($db);
771 
772 if (empty($action) || $action == 'view') {
773  $invoicestatic = new Facture($db);
774  $invoicesupplierstatic = new FactureFournisseur($db);
775  $expensereportstatic = new ExpenseReport($db);
776  $vatstatic = new Tva($db);
777  $donationstatic = new Don($db);
778  $salarystatic = new PaymentSalary($db);
779  $variousstatic = new PaymentVarious($db);
780 
781  llxHeader('', $langs->trans("FinanceJournal"));
782 
783  $nom = $langs->trans("FinanceJournal") . ' - ' . $accountingjournalstatic->getNomUrl(1);
784  $builddate=dol_now();
785  //$description = $langs->trans("DescFinanceJournal") . '<br>';
786  $description.= $langs->trans("DescJournalOnlyBindedVisible").'<br>';
787 
788  $listofchoices=array('already'=>$langs->trans("AlreadyInGeneralLedger"), 'notyet'=>$langs->trans("NotYetInGeneralLedger"));
789  $period = $form->select_date($date_start?$date_start:-1, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end?$date_end:-1, 'date_end', 0, 0, 0, '', 1, 0, 1). ' - ' .$langs->trans("JournalizationInLedgerStatus").' '. $form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
790 
791  $varlink = 'id_journal=' . $id_journal;
792 
793  journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
794 
795 
796  // Test that setup is complete
797  $sql = 'SELECT COUNT(rowid) as nb FROM '.MAIN_DB_PREFIX.'bank_account WHERE fk_accountancy_journal IS NULL';
798  $resql = $db->query($sql);
799  if ($resql)
800  {
801  $obj = $db->fetch_object($resql);
802  if ($obj->nb > 0)
803  {
804  print '<br>'.img_warning().' '.$langs->trans("TheJournalCodeIsNotDefinedOnSomeBankAccount");
805  print ' : '.$langs->trans("AccountancyAreaDescBank", 9, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("BankAccounts").'</strong>');
806  }
807  }
808  else dol_print_error($db);
809 
810 
811  // Button to write into Ledger
812  if (empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1'
813  || empty($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER) || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1'
814  || empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) || $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT == '-1') {
815  print '<br>'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
816  print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>');
817  }
818 
819 
820  print '<div class="tabsAction tabsActionNoBottom">';
821  print '<input type="button" class="butAction" name="exportcsv" value="' . $langs->trans("ExportDraftJournal") . '" onclick="launch_export();" />';
822  if ($in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="writebookkeeping" value="' . $langs->trans("WriteBookKeeping") . '" onclick="writebookkeeping();" />';
823  else print '<a class="butActionRefused" name="writebookkeeping">' . $langs->trans("WriteBookKeeping") . '</a>';
824  print '</div>';
825 
826  // TODO Avoid using js. We can use a direct link with $param
827  print '
828  <script type="text/javascript">
829  function launch_export() {
830  console.log("Set value into form and submit");
831  $("div.fiche form input[name=\"action\"]").val("exportcsv");
832  $("div.fiche form input[type=\"submit\"]").click();
833  $("div.fiche form input[name=\"action\"]").val("");
834  }
835  function writebookkeeping() {
836  console.log("Set value into form and submit");
837  $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
838  $("div.fiche form input[type=\"submit\"]").click();
839  $("div.fiche form input[name=\"action\"]").val("");
840  }
841  </script>';
842 
843  /*
844  * Show result array
845  */
846  print '<br>';
847 
848  $i = 0;
849  print '<div class="div-table-responsive">';
850  print "<table class=\"noborder\" width=\"100%\">";
851  print "<tr class=\"liste_titre\">";
852  print "<td></td>";
853  print "<td>" . $langs->trans("Date") . "</td>";
854  print "<td>" . $langs->trans("Piece") . ' (' . $langs->trans("ObjectsRef") . ")</td>";
855  print "<td>" . $langs->trans("AccountAccounting") . "</td>";
856  print "<td>" . $langs->trans("SubledgerAccount") . "</td>";
857  print "<td>" . $langs->trans("LabelOperation") . "</td>";
858  print "<td>" . $langs->trans("PaymentMode") . "</td>";
859  print "<td align='right'>" . $langs->trans("Debit") . "</td>";
860  print "<td align='right'>" . $langs->trans("Credit") . "</td>";
861  print "</tr>\n";
862 
863  $r = '';
864 
865  foreach ( $tabpay as $key => $val ) { // $key is rowid in llx_bank
866  $date = dol_print_date($db->jdate($val["date"]), 'day');
867 
868  $ref = getSourceDocRef($val, $tabtype[$key]);
869 
870  // Bank
871  foreach ( $tabbq[$key] as $k => $mt )
872  {
873  //var_dump($tabpay[$key]);
874  print '<!-- Bank bank.rowid='.$key.' type='.$tabpay[$key]['type'].' ref='.$tabpay[$key]['ref'].'-->';
875  print '<tr class="oddeven">';
876  print "<td></td>";
877  print "<td>" . $date . "</td>";
878  print "<td>" . $ref . "</td>";
879  // Ledger account
880  print "<td>";
881  $accounttoshow = length_accountg($k);
882  if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
883  {
884  print '<span class="error">'.$langs->trans("BankAccountNotDefined").'</span>';
885  }
886  else print $accounttoshow;
887  print "</td>";
888  // Subledger account
889  print "<td>";
890  /*$accounttoshow = length_accountg($k);
891  if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
892  {
893  print '<span class="error">'.$langs->trans("BankAccountNotDefined").'</span>';
894  }
895  else print $accounttoshow;*/
896  print "</td>";
897  print "<td>";
898  //var_dump($tabpay[$key]);
899  print $langs->trans("Bank");
900  print ' '.$val['bank_account_ref'];
901  if (! empty($val['soclib'])) {
902  print " - " . $val['soclib'];
903  }
904  print "</td>";
905  print "<td>" . $val["type_payment"] . "</td>";
906  print "<td align='right'>" . ($mt >= 0 ? price($mt) : '') . "</td>";
907  print "<td align='right'>" . ($mt < 0 ? price(- $mt) : '') . "</td>";
908  print "</tr>";
909  }
910 
911  // Third party
912  if (is_array($tabtp[$key])) {
913  foreach ( $tabtp[$key] as $k => $mt ) {
914  if ($k != 'type') {
915  print '<!-- Thirdparty bank.rowid='.$key.' -->';
916  print '<tr class="oddeven">';
917  print "<td></td>";
918  print "<td>" . $date . "</td>";
919  print "<td>" . $ref . "</td>";
920  // Ledger account
921  print "<td>";
922  $account_ledger = $k;
923  // Try to force general ledger account depending on type
924  if ($tabtype[$key] == 'payment') $account_ledger = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
925  if ($tabtype[$key] == 'payment_supplier') $account_ledger = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER;
926  if ($tabtype[$key] == 'payment_expensereport') $account_ledger = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
927  if ($tabtype[$key] == 'payment_salary') $account_ledger = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT;
928  if ($tabtype[$key] == 'payment_vat') $account_ledger = $conf->global->ACCOUNTING_VAT_PAY_ACCOUNT;
929  $accounttoshow = length_accounta($account_ledger);
930  if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
931  {
932  if ($tabtype[$key] == 'unknown')
933  {
934  // We will accept writing, but into a waiting account
935  if (empty($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE) || $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE == '-1')
936  {
937  print '<span class="error">'.$langs->trans('UnknownAccountForThirdpartyAndWaitingAccountNotDefinedBlocking').'</span>';
938  }
939  else
940  {
941  print '<span class="warning">'.$langs->trans('UnknownAccountForThirdparty', length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE)).'</span>'; // We will a waiting account
942  }
943  }
944  else
945  {
946  // We will refuse writing
947  $errorstring='UnknownAccountForThirdpartyBlocking';
948  if ($tabtype[$key] == 'payment') $errorstring='MainAccountForCustomersNotDefined';
949  if ($tabtype[$key] == 'payment_supplier') $errorstring='MainAccountForSuppliersNotDefined';
950  if ($tabtype[$key] == 'payment_expensereport') $errorstring='MainAccountForUsersNotDefined';
951  if ($tabtype[$key] == 'payment_salary') $errorstring='MainAccountForUsersNotDefined';
952  if ($tabtype[$key] == 'payment_vat') $errorstring='MainAccountForVatPaymentNotDefined';
953  print '<span class="error">'.$langs->trans($errorstring).'</span>';
954  }
955  }
956  else print $accounttoshow;
957  print "</td>";
958  // Subledger account
959  print "<td>";
960  if (in_array($tabtype[$key], array('payment', 'payment_supplier', 'payment_expensereport', 'payment_salary'))) // Type of payment with subledger
961  {
962  $accounttoshowsubledger = length_accounta($k);
963  if ($accounttoshow != $accounttoshowsubledger)
964  {
965  if (empty($accounttoshowsubledger) || $accounttoshowsubledger == 'NotDefined')
966  {
967  /*var_dump($tabpay[$key]);
968  var_dump($tabtype[$key]);
969  var_dump($tabbq[$key]);*/
970  //print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
971  print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefinedOrThirdPartyUnknown").'</span>';
972  }
973  else print $accounttoshowsubledger;
974  }
975  }
976  print "</td>";
977  print "<td>" . $reflabel . ' ' . $val['soclib'] . "</td>";
978  print "<td>" . $val["type_payment"] . "</td>";
979  print "<td align='right'>" . ($mt < 0 ? price(- $mt) : '') . "</td>";
980  print "<td align='right'>" . ($mt >= 0 ? price($mt) : '') . "</td>";
981  print "</tr>";
982  }
983  }
984  } else {
985  foreach ( $tabbq[$key] as $k => $mt ) {
986  print '<!-- Wait bank.rowid='.$key.' -->';
987  print '<tr class="oddeven">';
988  print "<td></td>";
989  print "<td>" . $date . "</td>";
990  print "<td>" . $ref . "</td>";
991  // Ledger account
992  print "<td>";
993  /*if (empty($accounttoshow) || $accounttoshow == 'NotDefined')
994  {
995  print '<span class="error">'.$langs->trans("WaitAccountNotDefined").'</span>';
996  }
997  else */ print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE);
998  print "</td>";
999  // Subledger account
1000  print "<td>";
1001  /*if (empty($accounttoshowsubledger) || $accounttoshowsubledger == 'NotDefined')
1002  {
1003  print '<span class="error">'.$langs->trans("WaitAccountNotDefined").'</span>';
1004  }
1005  else print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE);
1006  */
1007  print "</td>";
1008  print "<td>" . $reflabel . "</td>";
1009  print "<td>" . $val["type_payment"] . "</td>";
1010  print "<td align='right'>" . ($mt < 0 ? price(- $mt) : '') . "</td>";
1011  print "<td align='right'>" . ($mt >= 0 ? price($mt) : '') . "</td>";
1012  print "</tr>";
1013  }
1014  }
1015  }
1016 
1017  print "</table>";
1018  print '</div>';
1019 
1020  llxFooter();
1021 }
1022 
1023 $db->close();
1024 
1025 
1026 
1034 function getSourceDocRef($val, $typerecord)
1035 {
1036  global $db, $langs;
1037 
1038  // Defined the docref into $ref (We start with $val['ref'] by default and we complete according to other data)
1039  // WE MUST HAVE SAME REF FOR ALL LINES WE WILL RECORD INTO THE BOOKKEEPING
1040  $ref = $val['ref'];
1041  if ($ref == '(SupplierInvoicePayment)' || $ref == '(SupplierInvoicePaymentBack)') {
1042  $ref = $langs->trans('Supplier');
1043  }
1044  if ($ref == '(CustomerInvoicePayment)' || $ref == '(CustomerInvoicePaymentBack)') {
1045  $ref = $langs->trans('Customer');
1046  }
1047  if ($ref == '(SocialContributionPayment)') {
1048  $ref = $langs->trans('SocialContribution');
1049  }
1050  if ($ref == '(DonationPayment)') {
1051  $ref = $langs->trans('Donation');
1052  }
1053  if ($ref == '(SubscriptionPayment)') {
1054  $ref = $langs->trans('Subscription');
1055  }
1056  if ($ref == '(ExpenseReportPayment)') {
1057  $ref = $langs->trans('Employee');
1058  }
1059  if ($ref == '(payment_salary)') {
1060  $ref = $langs->trans('Employee');
1061  }
1062 
1063  $sqlmid = '';
1064  if ($typerecord == 'payment')
1065  {
1066  $sqlmid = 'SELECT payfac.fk_facture as id, f.facnumber as ref';
1067  $sqlmid .= " FROM ".MAIN_DB_PREFIX."paiement_facture as payfac, ".MAIN_DB_PREFIX."facture as f";
1068  $sqlmid .= " WHERE payfac.fk_facture = f.rowid AND payfac.fk_paiement=" . $val["paymentid"];
1069  $ref = $langs->trans("Invoice");
1070  }
1071  elseif ($typerecord == 'payment_supplier')
1072  {
1073  $sqlmid = 'SELECT payfac.fk_facturefourn as id, f.ref';
1074  $sqlmid .= " FROM " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfac, ".MAIN_DB_PREFIX."facture_fourn as f";
1075  $sqlmid .= " WHERE payfac.fk_facturefourn = f.rowid AND payfac.fk_paiementfourn=" . $val["paymentsupplierid"];
1076  $ref = $langs->trans("SupplierInvoice");
1077  }
1078  elseif ($typerecord == 'payment_expensereport')
1079  {
1080  $sqlmid = 'SELECT e.rowid as id, e.ref';
1081  $sqlmid .= " FROM " . MAIN_DB_PREFIX . "payment_expensereport as pe, " . MAIN_DB_PREFIX . "expensereport as e";
1082  $sqlmid .= " WHERE pe.rowid=" . $val["paymentexpensereport"]." AND pe.fk_expensereport = e.rowid";
1083  $ref = $langs->trans("ExpenseReport");
1084  }
1085  elseif ($typerecord == 'payment_salary')
1086  {
1087  $sqlmid = 'SELECT s.rowid as ref';
1088  $sqlmid .= " FROM " . MAIN_DB_PREFIX . "payment_salary as s";
1089  $sqlmid .= " WHERE s.rowid=" . $val["paymentsalid"];
1090  $ref = $langs->trans("SalaryPayment");
1091  }
1092  elseif ($typerecord == 'payment_vat')
1093  {
1094  $sqlmid = 'SELECT v.rowid as ref';
1095  $sqlmid .= " FROM " . MAIN_DB_PREFIX . "tva as v";
1096  $sqlmid .= " WHERE v.rowid=" . $val["paymentvatid"];
1097  $ref = $langs->trans("PaymentVat");
1098  }
1099  elseif ($typerecord == 'payment_donation')
1100  {
1101  $sqlmid = 'SELECT payd.fk_donation as ref';
1102  $sqlmid .= " FROM " . MAIN_DB_PREFIX . "payment_donation as payd";
1103  $sqlmid .= " WHERE payd.fk_donation=" . $val["paymentdonationid"];
1104  $ref = $langs->trans("Donation").' ';
1105  }
1106  elseif ($typerecord == 'payment_various')
1107  {
1108  $sqlmid = 'SELECT v.rowid as ref';
1109  $sqlmid .= " FROM " . MAIN_DB_PREFIX . "payment_various as v";
1110  $sqlmid .= " WHERE v.rowid=" . $val["paymentvariousid"];
1111  $ref = $langs->trans("VariousPayment");
1112  }
1113  // Add warning
1114  if (empty($sqlmid))
1115  {
1116  dol_syslog("Found a typerecord=".$typerecord." not supported", LOG_WARNING);
1117  }
1118 
1119  if ($sqlmid)
1120  {
1121  dol_syslog("accountancy/journal/bankjournal.php::sqlmid=" . $sqlmid, LOG_DEBUG);
1122  $resultmid = $db->query($sqlmid);
1123  if ($resultmid) {
1124  while ($objmid = $db->fetch_object($resultmid))
1125  {
1126  $ref.=' '.$objmid->ref;
1127  }
1128  }
1129  else dol_print_error($db);
1130  }
1131 
1132  return $ref;
1133 }
llxFooter()
Empty footer.
Definition: wrapper.php:58
setEventMessages($mesg, $mesgs, $style='mesgs')
Set event messages in dol_events session object.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
Class to manage various payments.
Class to manage salary payments.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm=false, $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
Class to manage Dolibarr users.
Definition: user.class.php:39
Class to manage customers or prospects.
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:445
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
Class to manage suppliers invoices.
if(empty($reshook)) $form
View.
Definition: perms.php:103
Class to manage bank accounts.
Put here description of your class.
Definition: tva.class.php:33
GETPOST($paramname, $check='none', $method=0, $filter=NULL, $options=NULL, $noreplace=0)
Return value of a param into GET or POST supervariable.
Class to manage Ledger (General Ledger and Subledger)
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
Class to manage generation of HTML components Only common components must be here.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting a parameter.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage payments of customer invoices.
llxHeader()
Empty header.
Definition: wrapper.php:46
length_accounta($accounta)
Return Auxiliary accounting account of thirdparties with defined length.
getSourceDocRef($val, $typerecord)
Return source for doc_ref of a bank transaction.
dol_now($mode='gmt')
Return date for now.
Class to manage Trips and Expenses.
Class to manage payments of donations.
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='tzserver', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:459
print
Draft customers invoices.
Definition: index.php:91
Class to manage donations.
Definition: don.class.php:35
Class to manage payments of expense report.
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if(!empty($conf->fournisseur->enabled)&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->societe->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if(!empty($conf->fournisseur->enabled)&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1013
Class to manage accounting accounts.
Class to manage invoices.
Class to manage payments for supplier invoices.
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous) ...
Classe permettant la gestion des paiements des charges La tva collectee n'est calculee que sur les fa...
journalHead($nom, $variante, $period, $periodlink, $description, $builddate, $exportlink='', $moreparam=array(), $calcmode='', $varlink='')
Show header of a VAT report.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.