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