dolibarr  18.0.0-alpha
sellsjournal.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 Alexandre Spangaro <aspangaro@open-dsi.fr>
8  * Copyright (C) 2013-2016 Florian Henry <florian.henry@open-concept.pro>
9  * Copyright (C) 2013-2016 Olivier Geffroy <jeff@jeffinfo.com>
10  * Copyright (C) 2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
11  * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 3 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program. If not, see <https://www.gnu.org/licenses/>.
25  */
26 
33 // Load Dolibarr environment
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/accounting.lib.php';
38 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
39 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
40 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
41 require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
42 require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
43 
44 // Load translation files required by the page
45 $langs->loadLangs(array("commercial", "compta", "bills", "other", "accountancy", "errors"));
46 
47 $id_journal = GETPOST('id_journal', 'int');
48 $action = GETPOST('action', 'aZ09');
49 
50 $date_startmonth = GETPOST('date_startmonth');
51 $date_startday = GETPOST('date_startday');
52 $date_startyear = GETPOST('date_startyear');
53 $date_endmonth = GETPOST('date_endmonth');
54 $date_endday = GETPOST('date_endday');
55 $date_endyear = GETPOST('date_endyear');
56 $in_bookkeeping = GETPOST('in_bookkeeping');
57 if ($in_bookkeeping == '') {
58  $in_bookkeeping = 'notyet';
59 }
60 
61 $now = dol_now();
62 
63 $hookmanager->initHooks(array('sellsjournal'));
64 $parameters = array();
65 
66 // Security check
67 if (!isModEnabled('accounting')) {
69 }
70 if ($user->socid > 0) {
72 }
73 if (empty($user->rights->accounting->mouvements->lire)) {
75 }
76 
77 
78 /*
79  * Actions
80  */
81 
82 $reshook = $hookmanager->executeHooks('doActions', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
83 
84 $accountingaccount = new AccountingAccount($db);
85 
86 // Get informations of journal
87 $accountingjournalstatic = new AccountingJournal($db);
88 $accountingjournalstatic->fetch($id_journal);
89 $journal = $accountingjournalstatic->code;
90 $journal_label = $accountingjournalstatic->label;
91 
92 $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
93 $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
94 
95 if (empty($date_startmonth) || empty($date_endmonth)) {
96  // Period by default on transfer
97  $dates = getDefaultDatesForTransfer();
98  $date_start = $dates['date_start'];
99  $date_end = $dates['date_end'];
100  $pastmonthyear = $dates['pastmonthyear'];
101  $pastmonth = $dates['pastmonth'];
102 }
103 
104 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
105  $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
106  $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
107 }
108 
109 $sql = "SELECT f.rowid, f.ref, f.type, f.datef as df, f.ref_client, f.date_lim_reglement as dlr, f.close_code, f.retained_warranty,";
110 $sql .= " fd.rowid as fdid, fd.description, fd.product_type, fd.total_ht, fd.total_tva, fd.total_localtax1, fd.total_localtax2, fd.tva_tx, fd.total_ttc, fd.situation_percent, fd.vat_src_code,";
111 $sql .= " s.rowid as socid, s.nom as name, s.code_client, s.code_fournisseur,";
112 if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
113  $sql .= " spe.accountancy_code_customer as code_compta,";
114  $sql .= " spe.accountancy_code_supplier as code_compta_fournisseur,";
115 } else {
116  $sql .= " s.code_compta as code_compta,";
117  $sql .= " s.code_compta_fournisseur,";
118 }
119 $sql .= " p.rowid as pid, p.ref as pref, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte,";
120 if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
121  $sql .= " ppe.accountancy_code_sell";
122 } else {
123  $sql .= " p.accountancy_code_sell";
124 }
125 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
126 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product";
127 if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
128  $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
129 }
130 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
131 $sql .= " JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
132 $sql .= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc";
133 if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
134  $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
135 }
136 $sql .= " WHERE fd.fk_code_ventilation > 0";
137 $sql .= " AND f.entity IN (".getEntity('invoice', 0).')'; // We don't share object for accountancy, we use source object sharing
138 $sql .= " AND f.fk_statut > 0";
139 if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Non common setup
140  $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")";
141 } else {
142  $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")";
143 }
144 $sql .= " AND fd.product_type IN (0,1)";
145 if ($date_start && $date_end) {
146  $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
147 }
148 // Define begin binding date
149 if (!empty($conf->global->ACCOUNTING_DATE_START_BINDING)) {
150  $sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'";
151 }
152 // Already in bookkeeping or not
153 if ($in_bookkeeping == 'already') {
154  $sql .= " AND f.rowid IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
155  // $sql .= " AND fd.rowid IN (SELECT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')"; // Useless, we save one line for all products with same account
156 }
157 if ($in_bookkeeping == 'notyet') {
158  $sql .= " AND f.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
159  // $sql .= " AND fd.rowid NOT IN (SELECT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')"; // Useless, we save one line for all products with same account
160 }
161 $sql .= " ORDER BY f.datef";
162 //print $sql; exit;
163 
164 dol_syslog('accountancy/journal/sellsjournal.php', LOG_DEBUG);
165 $result = $db->query($sql);
166 if ($result) {
167  $tabfac = array();
168  $tabht = array();
169  $tabtva = array();
170  $def_tva = array();
171  $tabwarranty = array();
172  $tabttc = array();
173  $tablocaltax1 = array();
174  $tablocaltax2 = array();
175  $tabcompany = array();
176 
177  $num = $db->num_rows($result);
178 
179  // Variables
180  $cptcli = (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER != "")) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : 'NotDefined';
181  $cpttva = (!empty($conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT : 'NotDefined';
182 
183  $i = 0;
184  while ($i < $num) {
185  $obj = $db->fetch_object($result);
186 
187  // Controls
188  $compta_soc = (!empty($obj->code_compta)) ? $obj->code_compta : $cptcli;
189 
190  $compta_prod = $obj->compte;
191  if (empty($compta_prod)) {
192  if ($obj->product_type == 0) {
193  $compta_prod = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : 'NotDefined';
194  } else {
195  $compta_prod = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : 'NotDefined';
196  }
197  }
198 
199  $vatdata = getTaxesFromId($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), $mysoc, $mysoc, 0);
200  $compta_tva = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
201  $compta_localtax1 = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
202  $compta_localtax2 = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
203 
204  // Define array to display all VAT rates that use this accounting account $compta_tva
205  if (price2num($obj->tva_tx) || !empty($obj->vat_src_code)) {
206  $def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : '')] = (vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''));
207  }
208 
209  $line = new FactureLigne($db);
210  $line->fetch($obj->fdid);
211 
212  // Situation invoices handling
213  $prev_progress = $line->get_prev_progress($obj->rowid);
214 
215  if ($obj->type == Facture::TYPE_SITUATION) {
216  // Avoid divide by 0
217  if ($obj->situation_percent == 0) {
218  $situation_ratio = 0;
219  } else {
220  $situation_ratio = ($obj->situation_percent - $prev_progress) / $obj->situation_percent;
221  }
222  } else {
223  $situation_ratio = 1;
224  }
225 
226  // Invoice lines
227  $tabfac[$obj->rowid]["date"] = $db->jdate($obj->df);
228  $tabfac[$obj->rowid]["datereg"] = $db->jdate($obj->dlr);
229  $tabfac[$obj->rowid]["ref"] = $obj->ref;
230  $tabfac[$obj->rowid]["type"] = $obj->type;
231  $tabfac[$obj->rowid]["description"] = $obj->label_compte;
232  $tabfac[$obj->rowid]["close_code"] = $obj->close_code; // close_code = 'replaced' for replacement invoices (not used in most european countries)
233  //$tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid;
234 
235  // Avoid warnings
236  if (!isset($tabttc[$obj->rowid][$compta_soc])) {
237  $tabttc[$obj->rowid][$compta_soc] = 0;
238  }
239  if (!isset($tabht[$obj->rowid][$compta_prod])) {
240  $tabht[$obj->rowid][$compta_prod] = 0;
241  }
242  if (!isset($tabtva[$obj->rowid][$compta_tva])) {
243  $tabtva[$obj->rowid][$compta_tva] = 0;
244  }
245  if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
246  $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
247  }
248  if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
249  $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
250  }
251 
252  $total_ttc = $obj->total_ttc * $situation_ratio;
253  if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY) && $obj->retained_warranty > 0) {
254  $retained_warranty = (double) price2num($total_ttc * $obj->retained_warranty / 100, 'MT');
255  $tabwarranty[$obj->rowid][$compta_soc] += $retained_warranty;
256  $total_ttc -= $retained_warranty;
257  }
258  $tabttc[$obj->rowid][$compta_soc] += $total_ttc;
259  $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
260  if (empty($line->tva_npr)) {
261  $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio; // We ignore line if VAT is a NPR
262  }
263  $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1 * $situation_ratio;
264  $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2 * $situation_ratio;
265  $tabcompany[$obj->rowid] = array(
266  'id' => $obj->socid,
267  'name' => $obj->name,
268  'code_client' => $obj->code_client,
269  'code_compta' => $compta_soc
270  );
271 
272  $i++;
273  }
274 } else {
275  dol_print_error($db);
276 }
277 
278 $errorforinvoice = array();
279 
280 // Loop in invoices to detect lines with not binding lines
281 foreach ($tabfac as $key => $val) { // Loop on each invoice
282  $sql = "SELECT COUNT(fd.rowid) as nb";
283  $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
284  $sql .= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
285  $sql .= " AND fd.total_ttc <> 0 AND fk_facture = ".((int) $key);
286  $resql = $db->query($sql);
287  if ($resql) {
288  $obj = $db->fetch_object($resql);
289  if ($obj->nb > 0) {
290  $errorforinvoice[$key] = 'somelinesarenotbound';
291  }
292  } else {
293  dol_print_error($db);
294  }
295 }
296 //var_dump($errorforinvoice);exit;
297 
298 
299 // Bookkeeping Write
300 if ($action == 'writebookkeeping') {
301  $now = dol_now();
302  $error = 0;
303 
304  $companystatic = new Societe($db);
305  $invoicestatic = new Facture($db);
306  $accountingaccountcustomer = new AccountingAccount($db);
307 
308  $accountingaccountcustomer->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER, true);
309 
310  $accountingaccountcustomerwarranty = new AccountingAccount($db);
311 
312  $accountingaccountcustomerwarranty->fetch(null, $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY, true);
313 
314  foreach ($tabfac as $key => $val) { // Loop on each invoice
315  $errorforline = 0;
316 
317  $totalcredit = 0;
318  $totaldebit = 0;
319 
320  $db->begin();
321 
322  $companystatic->id = $tabcompany[$key]['id'];
323  $companystatic->name = $tabcompany[$key]['name'];
324  $companystatic->code_compta = $tabcompany[$key]['code_compta'];
325  $companystatic->code_client = $tabcompany[$key]['code_client'];
326  $companystatic->client = 3;
327 
328  $invoicestatic->id = $key;
329  $invoicestatic->ref = (string) $val["ref"];
330  $invoicestatic->type = $val["type"];
331  $invoicestatic->close_code = $val["close_code"];
332 
333  $date = dol_print_date($val["date"], 'day');
334 
335  // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
336  $replacedinvoice = 0;
337  if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
338  $replacedinvoice = 1;
339  $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
340  if ($alreadydispatched) {
341  $replacedinvoice = 2;
342  }
343  }
344 
345  // If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
346  if ($replacedinvoice == 1) {
347  $db->rollback();
348  continue;
349  }
350 
351  // Error if some lines are not binded/ready to be journalized
352  if ($errorforinvoice[$key] == 'somelinesarenotbound') {
353  $error++;
354  $errorforline++;
355  setEventMessages($langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $val['ref']), null, 'errors');
356  }
357 
358  // Warranty
359  if (!$errorforline) {
360  foreach ($tabwarranty[$key] as $k => $mt) {
361  $bookkeeping = new BookKeeping($db);
362  $bookkeeping->doc_date = $val["date"];
363  $bookkeeping->date_lim_reglement = $val["datereg"];
364  $bookkeeping->doc_ref = $val["ref"];
365  $bookkeeping->date_creation = $now;
366  $bookkeeping->doc_type = 'customer_invoice';
367  $bookkeeping->fk_doc = $key;
368  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
369  $bookkeeping->thirdparty_code = $companystatic->code_client;
370 
371  $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
372  $bookkeeping->subledger_label = $tabcompany[$key]['name'];
373 
374  $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY;
375  $bookkeeping->label_compte = $accountingaccountcustomerwarranty->label;
376 
377  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$langs->trans("Retainedwarranty");
378  $bookkeeping->montant = $mt;
379  $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
380  $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
381  $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
382  $bookkeeping->code_journal = $journal;
383  $bookkeeping->journal_label = $langs->transnoentities($journal_label);
384  $bookkeeping->fk_user_author = $user->id;
385  $bookkeeping->entity = $conf->entity;
386 
387  $totaldebit += $bookkeeping->debit;
388  $totalcredit += $bookkeeping->credit;
389 
390  $result = $bookkeeping->create($user);
391  if ($result < 0) {
392  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
393  $error++;
394  $errorforline++;
395  $errorforinvoice[$key] = 'alreadyjournalized';
396  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
397  } else {
398  $error++;
399  $errorforline++;
400  $errorforinvoice[$key] = 'other';
401  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
402  }
403  }
404  }
405  }
406 
407  // Thirdparty
408  if (!$errorforline) {
409  foreach ($tabttc[$key] as $k => $mt) {
410  $bookkeeping = new BookKeeping($db);
411  $bookkeeping->doc_date = $val["date"];
412  $bookkeeping->date_lim_reglement = $val["datereg"];
413  $bookkeeping->doc_ref = $val["ref"];
414  $bookkeeping->date_creation = $now;
415  $bookkeeping->doc_type = 'customer_invoice';
416  $bookkeeping->fk_doc = $key;
417  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
418  $bookkeeping->thirdparty_code = $companystatic->code_client;
419 
420  $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
421  $bookkeeping->subledger_label = $tabcompany[$key]['name'];
422 
423  $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
424  $bookkeeping->label_compte = $accountingaccountcustomer->label;
425 
426  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$langs->trans("SubledgerAccount");
427  $bookkeeping->montant = $mt;
428  $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
429  $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
430  $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
431  $bookkeeping->code_journal = $journal;
432  $bookkeeping->journal_label = $langs->transnoentities($journal_label);
433  $bookkeeping->fk_user_author = $user->id;
434  $bookkeeping->entity = $conf->entity;
435 
436  $totaldebit += $bookkeeping->debit;
437  $totalcredit += $bookkeeping->credit;
438 
439  $result = $bookkeeping->create($user);
440  if ($result < 0) {
441  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
442  $error++;
443  $errorforline++;
444  $errorforinvoice[$key] = 'alreadyjournalized';
445  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
446  } else {
447  $error++;
448  $errorforline++;
449  $errorforinvoice[$key] = 'other';
450  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
451  }
452  } else {
453  if (getDolGlobalInt('ACCOUNTING_ENABLE_LETTERING') && getDolGlobalInt('ACCOUNTING_ENABLE_AUTOLETTERING')) {
454  require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php';
455  $lettering_static = new Lettering($db);
456  $nb_lettering = $lettering_static->bookkeepingLettering(array($bookkeeping->id));
457  }
458  }
459  }
460  }
461 
462  // Product / Service
463  if (!$errorforline) {
464  foreach ($tabht[$key] as $k => $mt) {
465  $resultfetch = $accountingaccount->fetch(null, $k, true); // TODO Use a cache
466  $label_account = $accountingaccount->label;
467 
468  // get compte id and label
469  if ($resultfetch > 0) {
470  $bookkeeping = new BookKeeping($db);
471  $bookkeeping->doc_date = $val["date"];
472  $bookkeeping->date_lim_reglement = $val["datereg"];
473  $bookkeeping->doc_ref = $val["ref"];
474  $bookkeeping->date_creation = $now;
475  $bookkeeping->doc_type = 'customer_invoice';
476  $bookkeeping->fk_doc = $key;
477  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
478  $bookkeeping->thirdparty_code = $companystatic->code_client;
479 
480  if (!empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT)) {
481  if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
482  $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
483  $bookkeeping->subledger_label = $tabcompany[$key]['name'];
484  } else {
485  $bookkeeping->subledger_account = '';
486  $bookkeeping->subledger_label = '';
487  }
488  } else {
489  $bookkeeping->subledger_account = '';
490  $bookkeeping->subledger_label = '';
491  }
492 
493  $bookkeeping->numero_compte = $k;
494  $bookkeeping->label_compte = $label_account;
495 
496  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$label_account;
497  $bookkeeping->montant = $mt;
498  $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
499  $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
500  $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
501  $bookkeeping->code_journal = $journal;
502  $bookkeeping->journal_label = $langs->transnoentities($journal_label);
503  $bookkeeping->fk_user_author = $user->id;
504  $bookkeeping->entity = $conf->entity;
505 
506  $totaldebit += $bookkeeping->debit;
507  $totalcredit += $bookkeeping->credit;
508 
509  $result = $bookkeeping->create($user);
510  if ($result < 0) {
511  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
512  $error++;
513  $errorforline++;
514  $errorforinvoice[$key] = 'alreadyjournalized';
515  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
516  } else {
517  $error++;
518  $errorforline++;
519  $errorforinvoice[$key] = 'other';
520  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
521  }
522  }
523  }
524  }
525  }
526 
527  // VAT
528  if (!$errorforline) {
529  $listoftax = array(0, 1, 2);
530  foreach ($listoftax as $numtax) {
531  $arrayofvat = $tabtva;
532  if ($numtax == 1) {
533  $arrayofvat = $tablocaltax1;
534  }
535  if ($numtax == 2) {
536  $arrayofvat = $tablocaltax2;
537  }
538 
539  foreach ($arrayofvat[$key] as $k => $mt) {
540  if ($mt) {
541  $accountingaccount->fetch(null, $k, true); // TODO Use a cache for label
542  $label_account = $accountingaccount->label;
543 
544  $bookkeeping = new BookKeeping($db);
545  $bookkeeping->doc_date = $val["date"];
546  $bookkeeping->date_lim_reglement = $val["datereg"];
547  $bookkeeping->doc_ref = $val["ref"];
548  $bookkeeping->date_creation = $now;
549  $bookkeeping->doc_type = 'customer_invoice';
550  $bookkeeping->fk_doc = $key;
551  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
552  $bookkeeping->thirdparty_code = $companystatic->code_client;
553 
554  $bookkeeping->subledger_account = '';
555  $bookkeeping->subledger_label = '';
556 
557  $bookkeeping->numero_compte = $k;
558  $bookkeeping->label_compte = $label_account;
559 
560  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
561  $bookkeeping->montant = $mt;
562  $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
563  $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
564  $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
565  $bookkeeping->code_journal = $journal;
566  $bookkeeping->journal_label = $langs->transnoentities($journal_label);
567  $bookkeeping->fk_user_author = $user->id;
568  $bookkeeping->entity = $conf->entity;
569 
570  $totaldebit += $bookkeeping->debit;
571  $totalcredit += $bookkeeping->credit;
572 
573  $result = $bookkeeping->create($user);
574  if ($result < 0) {
575  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
576  $error++;
577  $errorforline++;
578  $errorforinvoice[$key] = 'alreadyjournalized';
579  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
580  } else {
581  $error++;
582  $errorforline++;
583  $errorforinvoice[$key] = 'other';
584  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
585  }
586  }
587  }
588  }
589  }
590  }
591 
592  // Protection against a bug on lines before
593  if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
594  $error++;
595  $errorforline++;
596  $errorforinvoice[$key] = 'amountsnotbalanced';
597  setEventMessages('Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
598  }
599 
600  if (!$errorforline) {
601  $db->commit();
602  } else {
603  $db->rollback();
604 
605  if ($error >= 10) {
606  setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
607  break; // Break in the foreach
608  }
609  }
610  }
611 
612  $tabpay = $tabfac;
613 
614  if (empty($error) && count($tabpay) > 0) {
615  setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
616  } elseif (count($tabpay) == $error) {
617  setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
618  } else {
619  setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
620  }
621 
622  $action = '';
623 
624  // Must reload data, so we make a redirect
625  if (count($tabpay) != $error) {
626  $param = 'id_journal='.$id_journal;
627  $param .= '&date_startday='.$date_startday;
628  $param .= '&date_startmonth='.$date_startmonth;
629  $param .= '&date_startyear='.$date_startyear;
630  $param .= '&date_endday='.$date_endday;
631  $param .= '&date_endmonth='.$date_endmonth;
632  $param .= '&date_endyear='.$date_endyear;
633  $param .= '&in_bookkeeping='.$in_bookkeeping;
634  header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
635  exit;
636  }
637 }
638 
639 
640 
641 /*
642  * View
643  */
644 
645 $form = new Form($db);
646 
647 // Export
648 if ($action == 'exportcsv') { // ISO and not UTF8 !
649  $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
650 
651  $filename = 'journal';
652  $type_export = 'journal';
653  include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
654 
655  $companystatic = new Client($db);
656  $invoicestatic = new Facture($db);
657 
658  foreach ($tabfac as $key => $val) {
659  $companystatic->id = $tabcompany[$key]['id'];
660  $companystatic->name = $tabcompany[$key]['name'];
661  $companystatic->code_compta = $tabcompany[$key]['code_compta'];
662  $companystatic->code_client = $tabcompany[$key]['code_client'];
663  $companystatic->client = 3;
664 
665  $invoicestatic->id = $key;
666  $invoicestatic->ref = (string) $val["ref"];
667  $invoicestatic->type = $val["type"];
668  $invoicestatic->close_code = $val["close_code"];
669 
670  $date = dol_print_date($val["date"], 'day');
671 
672  // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
673  $replacedinvoice = 0;
674  if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
675  $replacedinvoice = 1;
676  $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
677  if ($alreadydispatched) {
678  $replacedinvoice = 2;
679  }
680  }
681 
682  // If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
683  if ($replacedinvoice == 1) {
684  continue;
685  }
686 
687  // Warranty
688  foreach ($tabwarranty[$key] as $k => $mt) {
689  //if ($mt) {
690  print '"'.$key.'"'.$sep;
691  print '"'.$date.'"'.$sep;
692  print '"'.$val["ref"].'"'.$sep;
693  print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
694  print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
695  print '"'.length_accountg($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY).'"'.$sep;
696  print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
697  print '"'.$langs->trans("Thirdparty").'"'.$sep;
698  print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("Retainedwarranty").'"'.$sep;
699  print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
700  print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
701  print '"'.$journal.'"';
702  print "\n";
703  //}
704  }
705 
706  // Third party
707  foreach ($tabttc[$key] as $k => $mt) {
708  //if ($mt) {
709  print '"'.$key.'"'.$sep;
710  print '"'.$date.'"'.$sep;
711  print '"'.$val["ref"].'"'.$sep;
712  print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
713  print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
714  print '"'.length_accountg($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER).'"'.$sep;
715  print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
716  print '"'.$langs->trans("Thirdparty").'"'.$sep;
717  print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("Thirdparty").'"'.$sep;
718  print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
719  print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
720  print '"'.$journal.'"';
721  print "\n";
722  //}
723  }
724 
725  // Product / Service
726  foreach ($tabht[$key] as $k => $mt) {
727  $accountingaccount = new AccountingAccount($db);
728  $accountingaccount->fetch(null, $k, true);
729  //if ($mt) {
730  print '"'.$key.'"'.$sep;
731  print '"'.$date.'"'.$sep;
732  print '"'.$val["ref"].'"'.$sep;
733  print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
734  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
735  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
736  print '""'.$sep;
737  print '"'.utf8_decode(dol_trunc($accountingaccount->label, 32)).'"'.$sep;
738  print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.dol_trunc($accountingaccount->label, 32).'"'.$sep;
739  print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
740  print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
741  print '"'.$journal.'"';
742  print "\n";
743  //}
744  }
745 
746  // VAT
747  $listoftax = array(0, 1, 2);
748  foreach ($listoftax as $numtax) {
749  $arrayofvat = $tabtva;
750  if ($numtax == 1) {
751  $arrayofvat = $tablocaltax1;
752  }
753  if ($numtax == 2) {
754  $arrayofvat = $tablocaltax2;
755  }
756 
757  foreach ($arrayofvat[$key] as $k => $mt) {
758  if ($mt) {
759  print '"'.$key.'"'.$sep;
760  print '"'.$date.'"'.$sep;
761  print '"'.$val["ref"].'"'.$sep;
762  print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
763  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
764  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
765  print '""'.$sep;
766  print '"'.$langs->trans("VAT").' - '.join(', ', $def_tva[$key][$k]).' %"'.$sep;
767  print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '').'"'.$sep;
768  print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
769  print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
770  print '"'.$journal.'"';
771  print "\n";
772  }
773  }
774  }
775  }
776 }
777 
778 
779 
780 if (empty($action) || $action == 'view') {
781  $title = $langs->trans("GenerationOfAccountingEntries").' - '.$accountingjournalstatic->getNomUrl(0, 2, 1, '', 1);
782 
783  llxHeader('', dol_string_nohtmltag($title));
784 
785  $nom = $title;
786  $nomlink = '';
787  $periodlink = '';
788  $exportlink = '';
789  $builddate = dol_now();
790  $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
791  if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
792  $description .= $langs->trans("DepositsAreNotIncluded");
793  } else {
794  $description .= $langs->trans("DepositsAreIncluded");
795  }
796 
797  $listofchoices = array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
798  $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);
799  $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
800 
801  $varlink = 'id_journal='.$id_journal;
802 
803  journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
804 
805  // Button to write into Ledger
806  if (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') {
807  print '<br><div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
808  $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
809  $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
810  print $desc;
811  print '</div>';
812  }
813  print '<div class="tabsAction tabsActionNoBottom centerimp">';
814  if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL) && $in_bookkeeping == 'notyet') {
815  print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
816  }
817  if (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == "") || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') {
818  print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
819  } else {
820  if ($in_bookkeeping == 'notyet') {
821  print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
822  } else {
823  print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
824  }
825  }
826  print '</div>';
827 
828  // TODO Avoid using js. We can use a direct link with $param
829  print '
830  <script type="text/javascript">
831  function launch_export() {
832  $("div.fiche form input[name=\"action\"]").val("exportcsv");
833  $("div.fiche form input[type=\"submit\"]").click();
834  $("div.fiche form input[name=\"action\"]").val("");
835  }
836  function writebookkeeping() {
837  console.log("click on writebookkeeping");
838  $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
839  $("div.fiche form input[type=\"submit\"]").click();
840  $("div.fiche form input[name=\"action\"]").val("");
841  }
842  </script>';
843 
844  /*
845  * Show result array
846  */
847  print '<br>';
848 
849  $i = 0;
850  print '<div class="div-table-responsive">';
851  print "<table class=\"noborder\" width=\"100%\">";
852  print "<tr class=\"liste_titre\">";
853  print "<td>".$langs->trans("Date")."</td>";
854  print "<td>".$langs->trans("Piece").' ('.$langs->trans("InvoiceRef").")</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 class="center">'.$langs->trans("AccountingDebit")."</td>";
859  print '<td class="center">'.$langs->trans("AccountingCredit")."</td>";
860  print "</tr>\n";
861 
862  $r = '';
863 
864  $companystatic = new Client($db);
865  $invoicestatic = new Facture($db);
866 
867  foreach ($tabfac as $key => $val) {
868  $companystatic->id = $tabcompany[$key]['id'];
869  $companystatic->name = $tabcompany[$key]['name'];
870  $companystatic->code_compta = $tabcompany[$key]['code_compta'];
871  $companystatic->code_client = $tabcompany[$key]['code_client'];
872  $companystatic->client = 3;
873 
874  $invoicestatic->id = $key;
875  $invoicestatic->ref = (string) $val["ref"];
876  $invoicestatic->type = $val["type"];
877  $invoicestatic->close_code = $val["close_code"];
878 
879  $date = dol_print_date($val["date"], 'day');
880 
881  // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
882  $replacedinvoice = 0;
883  if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
884  $replacedinvoice = 1;
885  $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
886  if ($alreadydispatched) {
887  $replacedinvoice = 2;
888  }
889  }
890 
891  // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
892  if ($replacedinvoice == 1) {
893  print '<tr class="oddeven">';
894  print "<!-- Replaced invoice -->";
895  print "<td>".$date."</td>";
896  print "<td><strike>".$invoicestatic->getNomUrl(1)."</strike></td>";
897  // Account
898  print "<td>";
899  print $langs->trans("Replaced");
900  print '</td>';
901  // Subledger account
902  print "<td>";
903  print '</td>';
904  print "<td>";
905  print "</td>";
906  print '<td class="right"></td>';
907  print '<td class="right"></td>';
908  print "</tr>";
909 
910  continue;
911  }
912  if ($errorforinvoice[$key] == 'somelinesarenotbound') {
913  print '<tr class="oddeven">';
914  print "<!-- Some lines are not bound -->";
915  print "<td>".$date."</td>";
916  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
917  // Account
918  print "<td>";
919  print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $val['ref']).'</span>';
920  print '</td>';
921  // Subledger account
922  print "<td>";
923  print '</td>';
924  print "<td>";
925  print "</td>";
926  print '<td class="right"></td>';
927  print '<td class="right"></td>';
928  print "</tr>";
929  }
930 
931  // Warranty
932  foreach ($tabwarranty[$key] as $k => $mt) {
933  print '<tr class="oddeven">';
934  print "<!-- Thirdparty warranty -->";
935  print "<td>".$date."</td>";
936  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
937  // Account
938  print "<td>";
939  $accountoshow = length_accountg($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY);
940  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
941  print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
942  } else {
943  print $accountoshow;
944  }
945  print '</td>';
946  // Subledger account
947  print "<td>";
948  $accountoshow = length_accounta($k);
949  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
950  print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
951  } else {
952  print $accountoshow;
953  }
954  print '</td>';
955  print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$langs->trans("Retainedwarranty")."</td>";
956  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
957  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
958  print "</tr>";
959  }
960 
961  // Third party
962  foreach ($tabttc[$key] as $k => $mt) {
963  print '<tr class="oddeven">';
964  print "<!-- Thirdparty -->";
965  print "<td>".$date."</td>";
966  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
967  // Account
968  print "<td>";
969  $accountoshow = length_accountg($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER);
970  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
971  print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
972  } else {
973  print $accountoshow;
974  }
975  print '</td>';
976  // Subledger account
977  print "<td>";
978  $accountoshow = length_accounta($k);
979  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
980  print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
981  } else {
982  print $accountoshow;
983  }
984  print '</td>';
985  print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$langs->trans("SubledgerAccount")."</td>";
986  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
987  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
988  print "</tr>";
989  }
990 
991  // Product / Service
992  foreach ($tabht[$key] as $k => $mt) {
993  $accountingaccount = new AccountingAccount($db);
994  $accountingaccount->fetch(null, $k, true);
995 
996  print '<tr class="oddeven">';
997  print "<!-- Product -->";
998  print "<td>".$date."</td>";
999  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1000  // Account
1001  print "<td>";
1002  $accountoshow = length_accountg($k);
1003  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1004  print '<span class="error">'.$langs->trans("ProductNotDefined").'</span>';
1005  } else {
1006  print $accountoshow;
1007  }
1008  print "</td>";
1009  // Subledger account
1010  print "<td>";
1011  if (!empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT)) {
1012  if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
1013  print length_accounta($tabcompany[$key]['code_compta']);
1014  }
1015  } elseif (($accountoshow == "") || $accountoshow == 'NotDefined') {
1016  print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
1017  }
1018  print '</td>';
1019  $companystatic->id = $tabcompany[$key]['id'];
1020  $companystatic->name = $tabcompany[$key]['name'];
1021  print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$accountingaccount->label."</td>";
1022  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1023  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1024  print "</tr>";
1025  }
1026 
1027  // VAT
1028  $listoftax = array(0, 1, 2);
1029  foreach ($listoftax as $numtax) {
1030  $arrayofvat = $tabtva;
1031  if ($numtax == 1) {
1032  $arrayofvat = $tablocaltax1;
1033  }
1034  if ($numtax == 2) {
1035  $arrayofvat = $tablocaltax2;
1036  }
1037 
1038  foreach ($arrayofvat[$key] as $k => $mt) {
1039  if ($mt) {
1040  print '<tr class="oddeven">';
1041  print "<!-- VAT -->";
1042  print "<td>".$date."</td>";
1043  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1044  // Account
1045  print "<td>";
1046  $accountoshow = length_accountg($k);
1047  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1048  print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Sale").')</span>';
1049  } else {
1050  print $accountoshow;
1051  }
1052  print "</td>";
1053  // Subledger account
1054  print "<td>";
1055  print '</td>';
1056  print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
1057  print "</td>";
1058  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1059  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1060  print "</tr>";
1061  }
1062  }
1063  }
1064  }
1065 
1066  print "</table>";
1067  print '</div>';
1068 
1069  // End of page
1070  llxFooter();
1071 }
1072 
1073 $db->close();
length_accounta
length_accounta($accounta)
Return Auxiliary accounting account of thirdparties with defined length.
Definition: accounting.lib.php:133
getTaxesFromId
getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
Get tax (VAT) main information from Id.
Definition: functions.lib.php:6202
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:50
dol_trunc
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
Definition: functions.lib.php:3950
llxFooter
llxFooter()
Empty footer.
Definition: wrapper.php:70
$sql
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)) $sql
Social contributions to pay.
Definition: index.php:745
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:530
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4994
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:143
Facture
Class to manage invoices.
Definition: facture.class.php:60
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5834
Facture\TYPE_DEPOSIT
const TYPE_DEPOSIT
Deposit invoice.
Definition: facture.class.php:392
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2566
Facture\TYPE_REPLACEMENT
const TYPE_REPLACEMENT
Replacement invoice.
Definition: facture.class.php:382
llxHeader
if(!defined('NOREQUIRESOC')) if(!defined('NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) llxHeader()
Empty header.
Definition: wrapper.php:56
FactureLigne
Class to manage invoice lines.
Definition: facture.class.php:5835
AccountingJournal
Class to manage accounting accounts.
Definition: accountingjournal.class.php:27
length_accountg
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous)
Definition: accounting.lib.php:94
dol_string_nohtmltag
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
Definition: functions.lib.php:6921
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1639
dol_get_first_day
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:576
getDolGlobalString
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
Definition: functions.lib.php:82
journalHead
journalHead($nom, $variante, $period, $periodlink, $description, $builddate, $exportlink='', $moreparam=array(), $calcmode='', $varlink='')
Show header of a page used to transfer/dispatch data in accounting.
Definition: accounting.lib.php:183
dol_get_last_day
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:595
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:147
BookKeeping
Class to manage Ledger (General Ledger and Subledger)
Definition: bookkeeping.class.php:33
Facture\TYPE_CREDIT_NOTE
const TYPE_CREDIT_NOTE
Credit note invoice.
Definition: facture.class.php:387
AccountingAccount
Class to manage accounting accounts.
Definition: accountingaccount.class.php:36
GETPOSTISSET
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
Definition: functions.lib.php:431
Lettering
Class Lettering.
Definition: lettering.class.php:34
Form
Class to manage generation of HTML components Only common components must be here.
Definition: html.form.class.php:52
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2947
getDefaultDatesForTransfer
getDefaultDatesForTransfer()
Return Default dates for transfer based on periodicity option in accountancy setup.
Definition: accounting.lib.php:273
price
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
Definition: functions.lib.php:5708
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8509
accessforbidden
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
Definition: security.lib.php:1106
dol_mktime
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
Definition: functions.lib.php:2859
getDolGlobalInt
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
Definition: functions.lib.php:96
Facture\TYPE_SITUATION
const TYPE_SITUATION
Situation invoice.
Definition: facture.class.php:402
Client
Class to manage customers or prospects.
Definition: client.class.php:31
vatrate
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formated for view output Used into pdf and HTML pages.
Definition: functions.lib.php:5659
if
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
Definition: journals_list.php:25