dolibarr  18.0.0
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-2023 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 (!$user->hasRight('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.situation_cycle_ref, 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, fd.info_bits,";
111 $sql .= " s.rowid as socid, s.nom as name, s.code_client, s.code_fournisseur,";
112 if (getDolGlobalString('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 (getDolGlobalString('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 (getDolGlobalString('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 (getDolGlobalString('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 (getDolGlobalString('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 (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) {
150  $sql .= " AND f.datef >= '".$db->idate(getDolGlobalString('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, f.ref";
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 = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER', 'NotDefined');
181  $cpttva = getDolGlobalString('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 = getDolGlobalString('ACCOUNTING_PRODUCT_SOLD_ACCOUNT', 'NotDefined');
194  } else {
195  $compta_prod = getDolGlobalString('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  // Create a compensation rate.
210  $situation_ratio = 1;
211  if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
212  if ($obj->situation_cycle_ref) {
213  // Avoid divide by 0
214  if ($obj->situation_percent == 0) {
215  $situation_ratio = 0;
216  } else {
217  $line = new FactureLigne($db);
218  $line->fetch($obj->fdid);
219 
220  // Situation invoices handling
221  $prev_progress = $line->get_prev_progress($obj->rowid);
222 
223  $situation_ratio = ($obj->situation_percent - $prev_progress) / $obj->situation_percent;
224  }
225  }
226  }
227 
228  // Invoice lines
229  $tabfac[$obj->rowid]["date"] = $db->jdate($obj->df);
230  $tabfac[$obj->rowid]["datereg"] = $db->jdate($obj->dlr);
231  $tabfac[$obj->rowid]["ref"] = $obj->ref;
232  $tabfac[$obj->rowid]["type"] = $obj->type;
233  $tabfac[$obj->rowid]["description"] = $obj->label_compte;
234  $tabfac[$obj->rowid]["close_code"] = $obj->close_code; // close_code = 'replaced' for replacement invoices (not used in most european countries)
235  //$tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid;
236 
237  // Avoid warnings
238  if (!isset($tabttc[$obj->rowid][$compta_soc])) {
239  $tabttc[$obj->rowid][$compta_soc] = 0;
240  }
241  if (!isset($tabht[$obj->rowid][$compta_prod])) {
242  $tabht[$obj->rowid][$compta_prod] = 0;
243  }
244  if (!isset($tabtva[$obj->rowid][$compta_tva])) {
245  $tabtva[$obj->rowid][$compta_tva] = 0;
246  }
247  if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
248  $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
249  }
250  if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
251  $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
252  }
253 
254  // Compensation of data for invoice situation by using $situation_ratio. This works (nearly) for invoice that was not correctly recorded
255  // but it may introduces an error for situation invoices that were correctly saved. There is still rounding problem that differs between
256  // real data we should have stored and result obtained with a compensation.
257  // It also seems that credit notes on situation invoices are correctly saved (but it depends on the version used in fact).
258  // For credit notes, we hope to have situation_ratio = 1 so the compensation has no effect to avoid introducing troubles with credit notes.
259  $total_ttc = $obj->total_ttc * $situation_ratio;
260  if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY') && $obj->retained_warranty > 0) {
261  $retained_warranty = (double) price2num($total_ttc * $obj->retained_warranty / 100, 'MT');
262  $tabwarranty[$obj->rowid][$compta_soc] += $retained_warranty;
263  $total_ttc -= $retained_warranty;
264  }
265  $tabttc[$obj->rowid][$compta_soc] += $total_ttc;
266  $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
267  $tva_npr = (($obj->info_bits & 1 == 1) ? 1 : 0);
268  if (!$tva_npr) { // We ignore line if VAT is a NPR
269  $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio;
270  }
271  $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1 * $situation_ratio;
272  $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2 * $situation_ratio;
273 
274 
275  $tabcompany[$obj->rowid] = array(
276  'id' => $obj->socid,
277  'name' => $obj->name,
278  'code_client' => $obj->code_client,
279  'code_compta' => $compta_soc
280  );
281 
282  $i++;
283  }
284 } else {
285  dol_print_error($db);
286 }
287 
288 $errorforinvoice = array();
289 
290 // Loop in invoices to detect lines with not binding lines
291 foreach ($tabfac as $key => $val) { // Loop on each invoice
292  $sql = "SELECT COUNT(fd.rowid) as nb";
293  $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
294  $sql .= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
295  $sql .= " AND fd.total_ttc <> 0 AND fk_facture = ".((int) $key);
296  $resql = $db->query($sql);
297  if ($resql) {
298  $obj = $db->fetch_object($resql);
299  if ($obj->nb > 0) {
300  $errorforinvoice[$key] = 'somelinesarenotbound';
301  }
302  } else {
303  dol_print_error($db);
304  }
305 }
306 //var_dump($errorforinvoice);exit;
307 
308 
309 // Bookkeeping Write
310 if ($action == 'writebookkeeping') {
311  $now = dol_now();
312  $error = 0;
313 
314  $companystatic = new Societe($db);
315  $invoicestatic = new Facture($db);
316  $accountingaccountcustomer = new AccountingAccount($db);
317 
318  $accountingaccountcustomer->fetch(null, getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'), true);
319 
320  $accountingaccountcustomerwarranty = new AccountingAccount($db);
321 
322  $accountingaccountcustomerwarranty->fetch(null, getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY'), true);
323 
324  foreach ($tabfac as $key => $val) { // Loop on each invoice
325  $errorforline = 0;
326 
327  $totalcredit = 0;
328  $totaldebit = 0;
329 
330  $db->begin();
331 
332  $companystatic->id = $tabcompany[$key]['id'];
333  $companystatic->name = $tabcompany[$key]['name'];
334  $companystatic->code_compta = $tabcompany[$key]['code_compta'];
335  $companystatic->code_client = $tabcompany[$key]['code_client'];
336  $companystatic->client = 3;
337 
338  $invoicestatic->id = $key;
339  $invoicestatic->ref = (string) $val["ref"];
340  $invoicestatic->type = $val["type"];
341  $invoicestatic->close_code = $val["close_code"];
342 
343  $date = dol_print_date($val["date"], 'day');
344 
345  // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
346  $replacedinvoice = 0;
347  if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
348  $replacedinvoice = 1;
349  $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
350  if ($alreadydispatched) {
351  $replacedinvoice = 2;
352  }
353  }
354 
355  // 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)
356  if ($replacedinvoice == 1) {
357  $db->rollback();
358  continue;
359  }
360 
361  // Error if some lines are not binded/ready to be journalized
362  if ($errorforinvoice[$key] == 'somelinesarenotbound') {
363  $error++;
364  $errorforline++;
365  setEventMessages($langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $val['ref']), null, 'errors');
366  }
367 
368  // Warranty
369  if (!$errorforline) {
370  foreach ($tabwarranty[$key] as $k => $mt) {
371  $bookkeeping = new BookKeeping($db);
372  $bookkeeping->doc_date = $val["date"];
373  $bookkeeping->date_lim_reglement = $val["datereg"];
374  $bookkeeping->doc_ref = $val["ref"];
375  $bookkeeping->date_creation = $now;
376  $bookkeeping->doc_type = 'customer_invoice';
377  $bookkeeping->fk_doc = $key;
378  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
379  $bookkeeping->thirdparty_code = $companystatic->code_client;
380 
381  $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
382  $bookkeeping->subledger_label = $tabcompany[$key]['name'];
383 
384  $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY');
385  $bookkeeping->label_compte = $accountingaccountcustomerwarranty->label;
386 
387  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$langs->trans("Retainedwarranty");
388  $bookkeeping->montant = $mt;
389  $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
390  $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
391  $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
392  $bookkeeping->code_journal = $journal;
393  $bookkeeping->journal_label = $langs->transnoentities($journal_label);
394  $bookkeeping->fk_user_author = $user->id;
395  $bookkeeping->entity = $conf->entity;
396 
397  $totaldebit += $bookkeeping->debit;
398  $totalcredit += $bookkeeping->credit;
399 
400  $result = $bookkeeping->create($user);
401  if ($result < 0) {
402  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
403  $error++;
404  $errorforline++;
405  $errorforinvoice[$key] = 'alreadyjournalized';
406  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
407  } else {
408  $error++;
409  $errorforline++;
410  $errorforinvoice[$key] = 'other';
411  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
412  }
413  }
414  }
415  }
416 
417  // Thirdparty
418  if (!$errorforline) {
419  foreach ($tabttc[$key] as $k => $mt) {
420  $bookkeeping = new BookKeeping($db);
421  $bookkeeping->doc_date = $val["date"];
422  $bookkeeping->date_lim_reglement = $val["datereg"];
423  $bookkeeping->doc_ref = $val["ref"];
424  $bookkeeping->date_creation = $now;
425  $bookkeeping->doc_type = 'customer_invoice';
426  $bookkeeping->fk_doc = $key;
427  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
428  $bookkeeping->thirdparty_code = $companystatic->code_client;
429 
430  $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
431  $bookkeeping->subledger_label = $tabcompany[$key]['name'];
432 
433  $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER');
434  $bookkeeping->label_compte = $accountingaccountcustomer->label;
435 
436  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$langs->trans("SubledgerAccount");
437  $bookkeeping->montant = $mt;
438  $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
439  $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
440  $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
441  $bookkeeping->code_journal = $journal;
442  $bookkeeping->journal_label = $langs->transnoentities($journal_label);
443  $bookkeeping->fk_user_author = $user->id;
444  $bookkeeping->entity = $conf->entity;
445 
446  $totaldebit += $bookkeeping->debit;
447  $totalcredit += $bookkeeping->credit;
448 
449  $result = $bookkeeping->create($user);
450  if ($result < 0) {
451  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
452  $error++;
453  $errorforline++;
454  $errorforinvoice[$key] = 'alreadyjournalized';
455  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
456  } else {
457  $error++;
458  $errorforline++;
459  $errorforinvoice[$key] = 'other';
460  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
461  }
462  } else {
463  if (getDolGlobalInt('ACCOUNTING_ENABLE_LETTERING') && getDolGlobalInt('ACCOUNTING_ENABLE_AUTOLETTERING')) {
464  require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php';
465  $lettering_static = new Lettering($db);
466 
467  $nb_lettering = $lettering_static->bookkeepingLettering(array($bookkeeping->id));
468  }
469  }
470  }
471  }
472 
473  // Product / Service
474  if (!$errorforline) {
475  foreach ($tabht[$key] as $k => $mt) {
476  $resultfetch = $accountingaccount->fetch(null, $k, true); // TODO Use a cache
477  $label_account = $accountingaccount->label;
478 
479  // get compte id and label
480  if ($resultfetch > 0) {
481  $bookkeeping = new BookKeeping($db);
482  $bookkeeping->doc_date = $val["date"];
483  $bookkeeping->date_lim_reglement = $val["datereg"];
484  $bookkeeping->doc_ref = $val["ref"];
485  $bookkeeping->date_creation = $now;
486  $bookkeeping->doc_type = 'customer_invoice';
487  $bookkeeping->fk_doc = $key;
488  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
489  $bookkeeping->thirdparty_code = $companystatic->code_client;
490 
491  if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
492  if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
493  $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
494  $bookkeeping->subledger_label = $tabcompany[$key]['name'];
495  } else {
496  $bookkeeping->subledger_account = '';
497  $bookkeeping->subledger_label = '';
498  }
499  } else {
500  $bookkeeping->subledger_account = '';
501  $bookkeeping->subledger_label = '';
502  }
503 
504  $bookkeeping->numero_compte = $k;
505  $bookkeeping->label_compte = $label_account;
506 
507  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$label_account;
508  $bookkeeping->montant = $mt;
509  $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
510  $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
511  $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
512  $bookkeeping->code_journal = $journal;
513  $bookkeeping->journal_label = $langs->transnoentities($journal_label);
514  $bookkeeping->fk_user_author = $user->id;
515  $bookkeeping->entity = $conf->entity;
516 
517  $totaldebit += $bookkeeping->debit;
518  $totalcredit += $bookkeeping->credit;
519 
520  $result = $bookkeeping->create($user);
521  if ($result < 0) {
522  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
523  $error++;
524  $errorforline++;
525  $errorforinvoice[$key] = 'alreadyjournalized';
526  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
527  } else {
528  $error++;
529  $errorforline++;
530  $errorforinvoice[$key] = 'other';
531  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
532  }
533  }
534  }
535  }
536  }
537 
538  // VAT
539  if (!$errorforline) {
540  $listoftax = array(0, 1, 2);
541  foreach ($listoftax as $numtax) {
542  $arrayofvat = $tabtva;
543  if ($numtax == 1) {
544  $arrayofvat = $tablocaltax1;
545  }
546  if ($numtax == 2) {
547  $arrayofvat = $tablocaltax2;
548  }
549 
550  foreach ($arrayofvat[$key] as $k => $mt) {
551  if ($mt) {
552  $accountingaccount->fetch(null, $k, true); // TODO Use a cache for label
553  $label_account = $accountingaccount->label;
554 
555  $bookkeeping = new BookKeeping($db);
556  $bookkeeping->doc_date = $val["date"];
557  $bookkeeping->date_lim_reglement = $val["datereg"];
558  $bookkeeping->doc_ref = $val["ref"];
559  $bookkeeping->date_creation = $now;
560  $bookkeeping->doc_type = 'customer_invoice';
561  $bookkeeping->fk_doc = $key;
562  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
563  $bookkeeping->thirdparty_code = $companystatic->code_client;
564 
565  $bookkeeping->subledger_account = '';
566  $bookkeeping->subledger_label = '';
567 
568  $bookkeeping->numero_compte = $k;
569  $bookkeeping->label_compte = $label_account;
570 
571  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
572  $bookkeeping->montant = $mt;
573  $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
574  $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
575  $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
576  $bookkeeping->code_journal = $journal;
577  $bookkeeping->journal_label = $langs->transnoentities($journal_label);
578  $bookkeeping->fk_user_author = $user->id;
579  $bookkeeping->entity = $conf->entity;
580 
581  $totaldebit += $bookkeeping->debit;
582  $totalcredit += $bookkeeping->credit;
583 
584  $result = $bookkeeping->create($user);
585  if ($result < 0) {
586  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
587  $error++;
588  $errorforline++;
589  $errorforinvoice[$key] = 'alreadyjournalized';
590  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
591  } else {
592  $error++;
593  $errorforline++;
594  $errorforinvoice[$key] = 'other';
595  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
596  }
597  }
598  }
599  }
600  }
601  }
602 
603  // Protection against a bug on lines before
604  if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
605  $error++;
606  $errorforline++;
607  $errorforinvoice[$key] = 'amountsnotbalanced';
608  setEventMessages('Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
609  }
610 
611  if (!$errorforline) {
612  $db->commit();
613  } else {
614  $db->rollback();
615 
616  if ($error >= 10) {
617  setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
618  break; // Break in the foreach
619  }
620  }
621  }
622 
623  $tabpay = $tabfac;
624 
625  if (empty($error) && count($tabpay) > 0) {
626  setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
627  } elseif (count($tabpay) == $error) {
628  setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
629  } else {
630  setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
631  }
632 
633  $action = '';
634 
635  // Must reload data, so we make a redirect
636  if (count($tabpay) != $error) {
637  $param = 'id_journal='.$id_journal;
638  $param .= '&date_startday='.$date_startday;
639  $param .= '&date_startmonth='.$date_startmonth;
640  $param .= '&date_startyear='.$date_startyear;
641  $param .= '&date_endday='.$date_endday;
642  $param .= '&date_endmonth='.$date_endmonth;
643  $param .= '&date_endyear='.$date_endyear;
644  $param .= '&in_bookkeeping='.$in_bookkeeping;
645  header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
646  exit;
647  }
648 }
649 
650 
651 
652 /*
653  * View
654  */
655 
656 $form = new Form($db);
657 
658 // Export
659 if ($action == 'exportcsv') { // ISO and not UTF8 !
660  $sep = getDolGlobalString('ACCOUNTING_EXPORT_SEPARATORCSV');
661 
662  $filename = 'journal';
663  $type_export = 'journal';
664  include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
665 
666  $companystatic = new Client($db);
667  $invoicestatic = new Facture($db);
668 
669  foreach ($tabfac as $key => $val) {
670  $companystatic->id = $tabcompany[$key]['id'];
671  $companystatic->name = $tabcompany[$key]['name'];
672  $companystatic->code_compta = $tabcompany[$key]['code_compta']; // deprecated
673  $companystatic->code_compta_client = $tabcompany[$key]['code_compta'];
674  $companystatic->code_client = $tabcompany[$key]['code_client'];
675  $companystatic->client = 3;
676 
677  $invoicestatic->id = $key;
678  $invoicestatic->ref = (string) $val["ref"];
679  $invoicestatic->type = $val["type"];
680  $invoicestatic->close_code = $val["close_code"];
681 
682  $date = dol_print_date($val["date"], 'day');
683 
684  // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
685  $replacedinvoice = 0;
686  if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
687  $replacedinvoice = 1;
688  $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
689  if ($alreadydispatched) {
690  $replacedinvoice = 2;
691  }
692  }
693 
694  // 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)
695  if ($replacedinvoice == 1) {
696  continue;
697  }
698 
699  // Warranty
700  foreach ($tabwarranty[$key] as $k => $mt) {
701  //if ($mt) {
702  print '"'.$key.'"'.$sep;
703  print '"'.$date.'"'.$sep;
704  print '"'.$val["ref"].'"'.$sep;
705  print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
706  print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
707  print '"'.length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY')).'"'.$sep;
708  print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
709  print '"'.$langs->trans("Thirdparty").'"'.$sep;
710  print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("Retainedwarranty").'"'.$sep;
711  print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
712  print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
713  print '"'.$journal.'"';
714  print "\n";
715  //}
716  }
717 
718  // Third party
719  foreach ($tabttc[$key] as $k => $mt) {
720  //if ($mt) {
721  print '"'.$key.'"'.$sep;
722  print '"'.$date.'"'.$sep;
723  print '"'.$val["ref"].'"'.$sep;
724  print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
725  print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
726  print '"'.length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER')).'"'.$sep;
727  print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
728  print '"'.$langs->trans("Thirdparty").'"'.$sep;
729  print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("Thirdparty").'"'.$sep;
730  print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
731  print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
732  print '"'.$journal.'"';
733  print "\n";
734  //}
735  }
736 
737  // Product / Service
738  foreach ($tabht[$key] as $k => $mt) {
739  $accountingaccount = new AccountingAccount($db);
740  $accountingaccount->fetch(null, $k, true);
741  //if ($mt) {
742  print '"'.$key.'"'.$sep;
743  print '"'.$date.'"'.$sep;
744  print '"'.$val["ref"].'"'.$sep;
745  print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
746  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
747  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
748  print '""'.$sep;
749  print '"'.utf8_decode(dol_trunc($accountingaccount->label, 32)).'"'.$sep;
750  print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.dol_trunc($accountingaccount->label, 32).'"'.$sep;
751  print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
752  print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
753  print '"'.$journal.'"';
754  print "\n";
755  //}
756  }
757 
758  // VAT
759  $listoftax = array(0, 1, 2);
760  foreach ($listoftax as $numtax) {
761  $arrayofvat = $tabtva;
762  if ($numtax == 1) {
763  $arrayofvat = $tablocaltax1;
764  }
765  if ($numtax == 2) {
766  $arrayofvat = $tablocaltax2;
767  }
768 
769  foreach ($arrayofvat[$key] as $k => $mt) {
770  if ($mt) {
771  print '"'.$key.'"'.$sep;
772  print '"'.$date.'"'.$sep;
773  print '"'.$val["ref"].'"'.$sep;
774  print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
775  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
776  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
777  print '""'.$sep;
778  print '"'.$langs->trans("VAT").' - '.join(', ', $def_tva[$key][$k]).' %"'.$sep;
779  print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '').'"'.$sep;
780  print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
781  print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
782  print '"'.$journal.'"';
783  print "\n";
784  }
785  }
786  }
787  }
788 }
789 
790 
791 
792 if (empty($action) || $action == 'view') {
793  $title = $langs->trans("GenerationOfAccountingEntries").' - '.$accountingjournalstatic->getNomUrl(0, 2, 1, '', 1);
794 
795  llxHeader('', dol_string_nohtmltag($title));
796 
797  $nom = $title;
798  $nomlink = '';
799  $periodlink = '';
800  $exportlink = '';
801  $builddate = dol_now();
802  $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
803  if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
804  $description .= $langs->trans("DepositsAreNotIncluded");
805  } else {
806  $description .= $langs->trans("DepositsAreIncluded");
807  }
808 
809  $listofchoices = array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
810  $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);
811  $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
812 
813  $varlink = 'id_journal='.$id_journal;
814 
815  journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
816 
817  // Button to write into Ledger
818  $acctCustomerNotConfigured = in_array(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'), ['','-1']);
819  if ($acctCustomerNotConfigured) {
820  print '<br><div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
821  $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
822  $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
823  print $desc;
824  print '</div>';
825  }
826  print '<div class="tabsAction tabsActionNoBottom centerimp">';
827  if (getDolGlobalString('ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL') && $in_bookkeeping == 'notyet') {
828  print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
829  }
830  if ($acctCustomerNotConfigured) {
831  print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
832  } else {
833  if ($in_bookkeeping == 'notyet') {
834  print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
835  } else {
836  print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
837  }
838  }
839  print '</div>';
840 
841  // TODO Avoid using js. We can use a direct link with $param
842  print '
843  <script type="text/javascript">
844  function launch_export() {
845  $("div.fiche form input[name=\"action\"]").val("exportcsv");
846  $("div.fiche form input[type=\"submit\"]").click();
847  $("div.fiche form input[name=\"action\"]").val("");
848  }
849  function writebookkeeping() {
850  console.log("click on writebookkeeping");
851  $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
852  $("div.fiche form input[type=\"submit\"]").click();
853  $("div.fiche form input[name=\"action\"]").val("");
854  }
855  </script>';
856 
857  /*
858  * Show result array
859  */
860  print '<br>';
861 
862  print '<div class="div-table-responsive">';
863  print "<table class=\"noborder\" width=\"100%\">";
864  print "<tr class=\"liste_titre\">";
865  print "<td>".$langs->trans("Date")."</td>";
866  print "<td>".$langs->trans("Piece").' ('.$langs->trans("InvoiceRef").")</td>";
867  print "<td>".$langs->trans("AccountAccounting")."</td>";
868  print "<td>".$langs->trans("SubledgerAccount")."</td>";
869  print "<td>".$langs->trans("LabelOperation")."</td>";
870  print '<td class="center">'.$langs->trans("AccountingDebit")."</td>";
871  print '<td class="center">'.$langs->trans("AccountingCredit")."</td>";
872  print "</tr>\n";
873 
874  $i = 0;
875 
876  $companystatic = new Client($db);
877  $invoicestatic = new Facture($db);
878 
879  foreach ($tabfac as $key => $val) {
880  $companystatic->id = $tabcompany[$key]['id'];
881  $companystatic->name = $tabcompany[$key]['name'];
882  $companystatic->code_compta = $tabcompany[$key]['code_compta'];
883  $companystatic->code_client = $tabcompany[$key]['code_client'];
884  $companystatic->client = 3;
885 
886  $invoicestatic->id = $key;
887  $invoicestatic->ref = (string) $val["ref"];
888  $invoicestatic->type = $val["type"];
889  $invoicestatic->close_code = $val["close_code"];
890 
891  $date = dol_print_date($val["date"], 'day');
892 
893  // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
894  $replacedinvoice = 0;
895  if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
896  $replacedinvoice = 1;
897  $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
898  if ($alreadydispatched) {
899  $replacedinvoice = 2;
900  }
901  }
902 
903  // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
904  if ($replacedinvoice == 1) {
905  print '<tr class="oddeven">';
906  print "<!-- Replaced invoice -->";
907  print "<td>".$date."</td>";
908  print "<td><strike>".$invoicestatic->getNomUrl(1)."</strike></td>";
909  // Account
910  print "<td>";
911  print $langs->trans("Replaced");
912  print '</td>';
913  // Subledger account
914  print "<td>";
915  print '</td>';
916  print "<td>";
917  print "</td>";
918  print '<td class="right"></td>';
919  print '<td class="right"></td>';
920  print "</tr>";
921 
922  $i++;
923  continue;
924  }
925  if ($errorforinvoice[$key] == 'somelinesarenotbound') {
926  print '<tr class="oddeven">';
927  print "<!-- Some lines are not bound -->";
928  print "<td>".$date."</td>";
929  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
930  // Account
931  print "<td>";
932  print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $val['ref']).'</span>';
933  print '</td>';
934  // Subledger account
935  print "<td>";
936  print '</td>';
937  print "<td>";
938  print "</td>";
939  print '<td class="right"></td>';
940  print '<td class="right"></td>';
941  print "</tr>";
942 
943  $i++;
944  }
945 
946  // Warranty
947  foreach ($tabwarranty[$key] as $k => $mt) {
948  print '<tr class="oddeven">';
949  print "<!-- Thirdparty warranty -->";
950  print "<td>".$date."</td>";
951  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
952  // Account
953  print "<td>";
954  $accountoshow = length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY'));
955  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
956  print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
957  } else {
958  print $accountoshow;
959  }
960  print '</td>';
961  // Subledger account
962  print "<td>";
963  $accountoshow = length_accounta($k);
964  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
965  print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
966  } else {
967  print $accountoshow;
968  }
969  print '</td>';
970  print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$langs->trans("Retainedwarranty")."</td>";
971  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
972  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
973  print "</tr>";
974  }
975 
976  // Third party
977  foreach ($tabttc[$key] as $k => $mt) {
978  print '<tr class="oddeven">';
979  print "<!-- Thirdparty -->";
980  print "<td>".$date."</td>";
981  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
982  // Account
983  print "<td>";
984  $accountoshow = length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'));
985  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
986  print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
987  } else {
988  print $accountoshow;
989  }
990  print '</td>';
991  // Subledger account
992  print "<td>";
993  $accountoshow = length_accounta($k);
994  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
995  print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
996  } else {
997  print $accountoshow;
998  }
999  print '</td>';
1000  print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$langs->trans("SubledgerAccount")."</td>";
1001  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1002  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1003  print "</tr>";
1004 
1005  $i++;
1006  }
1007 
1008  // Product / Service
1009  foreach ($tabht[$key] as $k => $mt) {
1010  $accountingaccount = new AccountingAccount($db);
1011  $accountingaccount->fetch(null, $k, true);
1012 
1013  print '<tr class="oddeven">';
1014  print "<!-- Product -->";
1015  print "<td>".$date."</td>";
1016  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1017  // Account
1018  print "<td>";
1019  $accountoshow = length_accountg($k);
1020  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1021  print '<span class="error">'.$langs->trans("ProductNotDefined").'</span>';
1022  } else {
1023  print $accountoshow;
1024  }
1025  print "</td>";
1026  // Subledger account
1027  print "<td>";
1028  if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
1029  if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
1030  print length_accounta($tabcompany[$key]['code_compta']);
1031  }
1032  } elseif (($accountoshow == "") || $accountoshow == 'NotDefined') {
1033  print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
1034  }
1035  print '</td>';
1036  $companystatic->id = $tabcompany[$key]['id'];
1037  $companystatic->name = $tabcompany[$key]['name'];
1038  print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$accountingaccount->label."</td>";
1039  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1040  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1041  print "</tr>";
1042 
1043  $i++;
1044  }
1045 
1046  // VAT
1047  $listoftax = array(0, 1, 2);
1048  foreach ($listoftax as $numtax) {
1049  $arrayofvat = $tabtva;
1050  if ($numtax == 1) {
1051  $arrayofvat = $tablocaltax1;
1052  }
1053  if ($numtax == 2) {
1054  $arrayofvat = $tablocaltax2;
1055  }
1056 
1057  foreach ($arrayofvat[$key] as $k => $mt) {
1058  if ($mt) {
1059  print '<tr class="oddeven">';
1060  print "<!-- VAT -->";
1061  print "<td>".$date."</td>";
1062  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1063  // Account
1064  print "<td>";
1065  $accountoshow = length_accountg($k);
1066  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1067  print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Sale").')</span>';
1068  } else {
1069  print $accountoshow;
1070  }
1071  print "</td>";
1072  // Subledger account
1073  print "<td>";
1074  print '</td>';
1075  print "<td>".$companystatic->getNomUrl(0, 'customer', 16).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
1076  print "</td>";
1077  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1078  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1079  print "</tr>";
1080 
1081  $i++;
1082  }
1083  }
1084  }
1085  }
1086 
1087  if (!$i) {
1088  print '<tr class="oddeven"><td colspan="6"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
1089  }
1090 
1091  print "</table>";
1092  print '</div>';
1093 
1094  // End of page
1095  llxFooter();
1096 }
1097 
1098 $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:6325
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:51
dol_trunc
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
Definition: functions.lib.php:4059
llxFooter
llxFooter()
Empty footer.
Definition: wrapper.php:70
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:609
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:5107
$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:5955
Facture\TYPE_DEPOSIT
const TYPE_DEPOSIT
Deposit invoice.
Definition: facture.class.php:422
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2675
Facture\TYPE_REPLACEMENT
const TYPE_REPLACEMENT
Replacement invoice.
Definition: facture.class.php:412
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:6013
AccountingJournal
Class to manage accounting accounts.
Definition: accountingjournal.class.php:27
length_accountg
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous)
Definition: accounting.lib.php:94
dol_string_nohtmltag
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
Definition: functions.lib.php:7046
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1741
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
Definition: functions.lib.php:8673
dol_get_first_day
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:576
$sql
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
journalHead
journalHead($nom, $variante, $period, $periodlink, $description, $builddate, $exportlink='', $moreparam=array(), $calcmode='', $varlink='')
Show header of a page used to transfer/dispatch data in accounting.
Definition: accounting.lib.php:183
dol_get_last_day
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:595
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:207
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:417
getDolGlobalString
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
Definition: functions.lib.php:142
AccountingAccount
Class to manage accounting accounts.
Definition: accountingaccount.class.php:36
GETPOSTISSET
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
Definition: functions.lib.php:509
Lettering
Class Lettering.
Definition: lettering.class.php:34
Form
Class to manage generation of HTML components Only common components must be here.
Definition: html.form.class.php:53
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:3056
getDefaultDatesForTransfer
getDefaultDatesForTransfer()
Return Default dates for transfer based on periodicity option in accountancy setup.
Definition: accounting.lib.php:273
price
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
Definition: functions.lib.php:5829
accessforbidden
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
Definition: security.lib.php:1164
dol_mktime
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
Definition: functions.lib.php:2968
getDolGlobalInt
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
Definition: functions.lib.php:156
Facture\TYPE_SITUATION
const TYPE_SITUATION
Situation invoice.
Definition: facture.class.php:432
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:5780
if
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
Definition: journals_list.php:25