dolibarr  18.0.0-alpha
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-2021 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 {
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') && getDolGlobalInt('ACCOUNTING_ENABLE_AUTOLETTERING')) {
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));
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  if (!empty($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER_USE_AUXILIARY_ON_DEPOSIT)) {
407  if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER_DEPOSIT')) {
408  $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
409  $bookkeeping->subledger_label = $tabcompany[$key]['name'];
410  } else {
411  $bookkeeping->subledger_account = '';
412  $bookkeeping->subledger_label = '';
413  }
414  } else {
415  $bookkeeping->subledger_account = '';
416  $bookkeeping->subledger_label = '';
417  }
418 
419  $bookkeeping->numero_compte = $k;
420  $bookkeeping->label_compte = $label_account;
421 
422  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$label_account;
423  $bookkeeping->montant = $mt;
424  $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
425  $bookkeeping->debit = ($mt > 0) ? $mt : 0;
426  $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
427  $bookkeeping->code_journal = $journal;
428  $bookkeeping->journal_label = $langs->transnoentities($journal_label);
429  $bookkeeping->fk_user_author = $user->id;
430  $bookkeeping->entity = $conf->entity;
431 
432  $totaldebit += $bookkeeping->debit;
433  $totalcredit += $bookkeeping->credit;
434 
435  $result = $bookkeeping->create($user);
436  if ($result < 0) {
437  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
438  $error++;
439  $errorforline++;
440  $errorforinvoice[$key] = 'alreadyjournalized';
441  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
442  } else {
443  $error++;
444  $errorforline++;
445  $errorforinvoice[$key] = 'other';
446  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
447  }
448  }
449  }
450  }
451  }
452 
453  // VAT
454  // var_dump($tabtva);
455  if (!$errorforline) {
456  $listoftax = array(0, 1, 2);
457  foreach ($listoftax as $numtax) {
458  $arrayofvat = $tabtva;
459  if ($numtax == 1) {
460  $arrayofvat = $tablocaltax1;
461  }
462  if ($numtax == 2) {
463  $arrayofvat = $tablocaltax2;
464  }
465 
466  foreach ($arrayofvat[$key] as $k => $mt) {
467  if ($mt) {
468  $accountingaccount->fetch(null, $k, true); // TODO Use a cache for label
469  $label_account = $accountingaccount->label;
470 
471  $bookkeeping = new BookKeeping($db);
472  $bookkeeping->doc_date = $val["date"];
473  $bookkeeping->date_lim_reglement = $val["datereg"];
474  $bookkeeping->doc_ref = $val["refsologest"];
475  $bookkeeping->date_creation = $now;
476  $bookkeeping->doc_type = 'supplier_invoice';
477  $bookkeeping->fk_doc = $key;
478  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
479  $bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
480 
481  $bookkeeping->subledger_account = '';
482  $bookkeeping->subledger_label = '';
483 
484  $bookkeeping->numero_compte = $k;
485  $bookkeeping->label_compte = $label_account;
486 
487  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
488  $bookkeeping->montant = $mt;
489  $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
490  $bookkeeping->debit = ($mt > 0) ? $mt : 0;
491  $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
492  $bookkeeping->code_journal = $journal;
493  $bookkeeping->journal_label = $langs->transnoentities($journal_label);
494  $bookkeeping->fk_user_author = $user->id;
495  $bookkeeping->entity = $conf->entity;
496 
497  $totaldebit += $bookkeeping->debit;
498  $totalcredit += $bookkeeping->credit;
499 
500  $result = $bookkeeping->create($user);
501  if ($result < 0) {
502  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
503  $error++;
504  $errorforline++;
505  $errorforinvoice[$key] = 'alreadyjournalized';
506  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
507  } else {
508  $error++;
509  $errorforline++;
510  $errorforinvoice[$key] = 'other';
511  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
512  }
513  }
514  }
515  }
516  }
517  }
518 
519  // Counterpart of VAT for VAT NPR
520  // var_dump($tabother);
521  if (!$errorforline && is_array($tabother[$key])) {
522  foreach ($tabother[$key] as $k => $mt) {
523  if ($mt) {
524  $bookkeeping = new BookKeeping($db);
525  $bookkeeping->doc_date = $val["date"];
526  $bookkeeping->date_lim_reglement = $val["datereg"];
527  $bookkeeping->doc_ref = $val["refsologest"];
528  $bookkeeping->date_creation = $now;
529  $bookkeeping->doc_type = 'supplier_invoice';
530  $bookkeeping->fk_doc = $key;
531  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
532  $bookkeeping->thirdparty_code = $companystatic->code_fournisseur;
533 
534  $bookkeeping->subledger_account = '';
535  $bookkeeping->subledger_label = '';
536 
537  $bookkeeping->numero_compte = $k;
538 
539  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT").' NPR';
540  $bookkeeping->montant = $mt;
541  $bookkeeping->sens = ($mt < 0) ? 'C' : 'D';
542  $bookkeeping->debit = ($mt > 0) ? $mt : 0;
543  $bookkeeping->credit = ($mt <= 0) ? -$mt : 0;
544  $bookkeeping->code_journal = $journal;
545  $bookkeeping->journal_label = $langs->transnoentities($journal_label);
546  $bookkeeping->fk_user_author = $user->id;
547  $bookkeeping->entity = $conf->entity;
548 
549  $totaldebit += $bookkeeping->debit;
550  $totalcredit += $bookkeeping->credit;
551 
552  $result = $bookkeeping->create($user);
553  if ($result < 0) {
554  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
555  $error++;
556  $errorforline++;
557  $errorforinvoice[$key] = 'alreadyjournalized';
558  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
559  } else {
560  $error++;
561  $errorforline++;
562  $errorforinvoice[$key] = 'other';
563  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
564  }
565  }
566  }
567  }
568  }
569 
570  // Protection against a bug on lines before
571  if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
572  $error++;
573  $errorforline++;
574  $errorforinvoice[$key] = 'amountsnotbalanced';
575  setEventMessages('Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
576  }
577 
578  if (!$errorforline) {
579  $db->commit();
580  } else {
581  $db->rollback();
582 
583  if ($error >= 10) {
584  setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
585  break; // Break in the foreach
586  }
587  }
588  }
589 
590  $tabpay = $tabfac;
591 
592  if (empty($error) && count($tabpay) > 0) {
593  setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
594  } elseif (count($tabpay) == $error) {
595  setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
596  } else {
597  setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
598  }
599 
600  $action = '';
601 
602  // Must reload data, so we make a redirect
603  if (count($tabpay) != $error) {
604  $param = 'id_journal='.$id_journal;
605  $param .= '&date_startday='.$date_startday;
606  $param .= '&date_startmonth='.$date_startmonth;
607  $param .= '&date_startyear='.$date_startyear;
608  $param .= '&date_endday='.$date_endday;
609  $param .= '&date_endmonth='.$date_endmonth;
610  $param .= '&date_endyear='.$date_endyear;
611  $param .= '&in_bookkeeping='.$in_bookkeeping;
612  header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
613  exit;
614  }
615 }
616 
617 /*
618  * View
619  */
620 
621 $form = new Form($db);
622 
623 // Export
624 if ($action == 'exportcsv') { // ISO and not UTF8 !
625  $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
626 
627  $filename = 'journal';
628  $type_export = 'journal';
629  include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
630 
631  $companystatic = new Fournisseur($db);
632  $invoicestatic = new FactureFournisseur($db);
633 
634  foreach ($tabfac as $key => $val) {
635  $companystatic->id = $tabcompany[$key]['id'];
636  $companystatic->name = $tabcompany[$key]['name'];
637  $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
638  $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
639  $companystatic->fournisseur = 1;
640 
641  $invoicestatic->id = $key;
642  $invoicestatic->ref = $val["refsologest"];
643  $invoicestatic->ref_supplier = $val["refsuppliersologest"];
644  $invoicestatic->type = $val["type"];
645  $invoicestatic->description = dol_trunc(html_entity_decode($val["description"]), 32);
646  $invoicestatic->close_code = $val["close_code"];
647 
648  $date = dol_print_date($val["date"], 'day');
649 
650  // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
651  $replacedinvoice = 0;
652  if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED) {
653  $replacedinvoice = 1;
654  $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
655  if ($alreadydispatched) {
656  $replacedinvoice = 2;
657  }
658  }
659 
660  // 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)
661  if ($replacedinvoice == 1) {
662  continue;
663  }
664 
665  // Third party
666  foreach ($tabttc[$key] as $k => $mt) {
667  //if ($mt) {
668  print '"'.$key.'"'.$sep;
669  print '"'.$date.'"'.$sep;
670  print '"'.$val["refsologest"].'"'.$sep;
671  print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
672  print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
673  print '"'.length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER).'"'.$sep;
674  print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
675  print '"'.$langs->trans("Thirdparty").'"'.$sep;
676  print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.$langs->trans("Thirdparty").'"'.$sep;
677  print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
678  print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
679  print '"'.$journal.'"';
680  print "\n";
681  //}
682  }
683 
684  // Product / Service
685  foreach ($tabht[$key] as $k => $mt) {
686  $accountingaccount = new AccountingAccount($db);
687  $accountingaccount->fetch(null, $k, true);
688  //if ($mt) {
689  print '"'.$key.'"'.$sep;
690  print '"'.$date.'"'.$sep;
691  print '"'.$val["refsologest"].'"'.$sep;
692  print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
693  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
694  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
695  print '""'.$sep;
696  print '"'.utf8_decode(dol_trunc($accountingaccount->label, 32)).'"'.$sep;
697  print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.dol_trunc($accountingaccount->label, 32).'"'.$sep;
698  print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
699  print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
700  print '"'.$journal.'"';
701  print "\n";
702  //}
703  }
704 
705  // VAT
706  $listoftax = array(0, 1, 2);
707  foreach ($listoftax as $numtax) {
708  $arrayofvat = $tabtva;
709  if ($numtax == 1) {
710  $arrayofvat = $tablocaltax1;
711  }
712  if ($numtax == 2) {
713  $arrayofvat = $tablocaltax2;
714  }
715 
716  foreach ($arrayofvat[$key] as $k => $mt) {
717  if ($mt) {
718  print '"'.$key.'"'.$sep;
719  print '"'.$date.'"'.$sep;
720  print '"'.$val["refsologest"].'"'.$sep;
721  print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
722  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
723  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
724  print '""'.$sep;
725  print '"'.$langs->trans("VAT").' - '.join(', ', $def_tva[$key][$k]).' %"'.$sep;
726  print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.$langs->trans("VAT").join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '').'"'.$sep;
727  print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
728  print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
729  print '"'.$journal.'"';
730  print "\n";
731  }
732  }
733 
734  // VAT counterpart for NPR
735  if (is_array($tabother[$key])) {
736  foreach ($tabother[$key] as $k => $mt) {
737  if ($mt) {
738  print '"'.$key.'"'.$sep;
739  print '"'.$date.'"'.$sep;
740  print '"'.$val["refsologest"].'"'.$sep;
741  print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep;
742  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
743  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
744  print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
745  print '"'.$langs->trans("Thirdparty").'"'.$sep;
746  print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.$langs->trans("VAT").' NPR"'.$sep;
747  print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
748  print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
749  print '"'.$journal.'"';
750  print "\n";
751  }
752  }
753  }
754  }
755  }
756 }
757 
758 if (empty($action) || $action == 'view') {
759  $title = $langs->trans("GenerationOfAccountingEntries").' - '.$accountingjournalstatic->getNomUrl(0, 2, 1, '', 1);
760 
761  llxHeader('', dol_string_nohtmltag($title));
762 
763  $nom = $title;
764  $nomlink = '';
765  $periodlink = '';
766  $exportlink = '';
767  $builddate = dol_now();
768  $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
769  if (!empty($conf->global->FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS)) {
770  $description .= $langs->trans("DepositsAreNotIncluded");
771  } else {
772  $description .= $langs->trans("DepositsAreIncluded");
773  }
774 
775  $listofchoices = array('notyet'=>$langs->trans("NotYetInGeneralLedger"), 'already'=>$langs->trans("AlreadyInGeneralLedger"));
776  $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);
777  $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
778 
779  $varlink = 'id_journal='.$id_journal;
780 
781  journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
782 
783  // Button to write into Ledger
784  if (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1') {
785  print '<br><div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
786  $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
787  $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
788  print $desc;
789  print '</div>';
790  }
791  print '<div class="tabsAction tabsActionNoBottom centerimp">';
792  if (!empty($conf->global->ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL) && $in_bookkeeping == 'notyet') {
793  print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
794  }
795  if (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == "") || $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER == '-1') {
796  print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
797  } else {
798  if ($in_bookkeeping == 'notyet') {
799  print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
800  } else {
801  print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
802  }
803  }
804  print '</div>';
805 
806  // TODO Avoid using js. We can use a direct link with $param
807  print '
808  <script type="text/javascript">
809  function launch_export() {
810  $("div.fiche form input[name=\"action\"]").val("exportcsv");
811  $("div.fiche form input[type=\"submit\"]").click();
812  $("div.fiche form input[name=\"action\"]").val("");
813  }
814  function writebookkeeping() {
815  console.log("click on writebookkeeping");
816  $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
817  $("div.fiche form input[type=\"submit\"]").click();
818  $("div.fiche form input[name=\"action\"]").val("");
819  }
820  </script>';
821 
822  /*
823  * Show result array
824  */
825  print '<br>';
826 
827  $i = 0;
828  print '<div class="div-table-responsive">';
829  print "<table class=\"noborder\" width=\"100%\">";
830  print "<tr class=\"liste_titre\">";
831  print "<td>".$langs->trans("Date")."</td>";
832  print "<td>".$langs->trans("Piece").' ('.$langs->trans("InvoiceRef").")</td>";
833  print "<td>".$langs->trans("AccountAccounting")."</td>";
834  print "<td>".$langs->trans("SubledgerAccount")."</td>";
835  print "<td>".$langs->trans("LabelOperation")."</td>";
836  print '<td class="center">'.$langs->trans("AccountingDebit")."</td>";
837  print '<td class="center">'.$langs->trans("AccountingCredit")."</td>";
838  print "</tr>\n";
839 
840  $r = '';
841 
842  $invoicestatic = new FactureFournisseur($db);
843  $companystatic = new Fournisseur($db);
844 
845  foreach ($tabfac as $key => $val) {
846  $companystatic->id = $tabcompany[$key]['id'];
847  $companystatic->name = $tabcompany[$key]['name'];
848  $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
849  $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
850  $companystatic->fournisseur = 1;
851 
852  $invoicestatic->id = $key;
853  $invoicestatic->ref = $val["refsologest"];
854  $invoicestatic->ref_supplier = $val["refsuppliersologest"];
855  $invoicestatic->type = $val["type"];
856  $invoicestatic->description = dol_trunc(html_entity_decode($val["description"]), 32);
857  $invoicestatic->close_code = $val["close_code"];
858 
859  $date = dol_print_date($val["date"], 'day');
860 
861  // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
862  $replacedinvoice = 0;
863  if ($invoicestatic->close_code == FactureFournisseur::CLOSECODE_REPLACED) {
864  $replacedinvoice = 1;
865  $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
866  if ($alreadydispatched) {
867  $replacedinvoice = 2;
868  }
869  }
870 
871  // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
872  if ($replacedinvoice == 1) {
873  print '<tr class="oddeven">';
874  print "<!-- Replaced invoice -->";
875  print "<td>".$date."</td>";
876  print "<td><strike>".$invoicestatic->getNomUrl(1)."</strike></td>";
877  // Account
878  print "<td>";
879  print $langs->trans("Replaced");
880  print '</td>';
881  // Subledger account
882  print "<td>";
883  print '</td>';
884  print "<td>";
885  print "</td>";
886  print '<td class="right"></td>';
887  print '<td class="right"></td>';
888  print "</tr>";
889 
890  continue;
891  }
892  if ($errorforinvoice[$key] == 'somelinesarenotbound') {
893  print '<tr class="oddeven">';
894  print "<!-- Some lines are not bound -->";
895  print "<td>".$date."</td>";
896  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
897  // Account
898  print "<td>";
899  print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $val['ref']).'</span>';
900  print '</td>';
901  // Subledger account
902  print "<td>";
903  print '</td>';
904  print "<td>";
905  print "</td>";
906  print '<td class="right"></td>';
907  print '<td class="right"></td>';
908  print "</tr>";
909  }
910 
911  // Third party
912  foreach ($tabttc[$key] as $k => $mt) {
913  print '<tr class="oddeven">';
914  print "<!-- Thirdparty -->";
915  print "<td>".$date."</td>";
916  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
917  // Account
918  print "<td>";
919  $accountoshow = length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER);
920  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
921  print '<span class="error">'.$langs->trans("MainAccountForSuppliersNotDefined").'</span>';
922  } else {
923  print $accountoshow;
924  }
925  print '</td>';
926  // Subledger account
927  print "<td>";
928  $accountoshow = length_accounta($k);
929  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
930  print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
931  } else {
932  print $accountoshow;
933  }
934  print '</td>';
935  print "<td>".$companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("SubledgerAccount")."</td>";
936  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
937  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
938  print "</tr>";
939  }
940 
941  // Product / Service
942  foreach ($tabht[$key] as $k => $mt) {
943  $accountingaccount = new AccountingAccount($db);
944  $accountingaccount->fetch(null, $k, true);
945 
946  print '<tr class="oddeven">';
947  print "<!-- Product -->";
948  print "<td>".$date."</td>";
949  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
950  // Account
951  print "<td>";
952  $accountoshow = length_accountg($k);
953  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
954  print '<span class="error">'.$langs->trans("ProductAccountNotDefined").'</span>';
955  } else {
956  print $accountoshow;
957  }
958  print "</td>";
959  // Subledger account
960  print "<td>";
961  if (!empty($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER_USE_AUXILIARY_ON_DEPOSIT)) {
962  if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER_DEPOSIT')) {
963  print length_accounta($tabcompany[$key]['code_compta']);
964  }
965  } elseif (($accountoshow == "") || $accountoshow == 'NotDefined') {
966  print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
967  }
968  print '</td>';
969  $companystatic->id = $tabcompany[$key]['id'];
970  $companystatic->name = $tabcompany[$key]['name'];
971  print "<td>".$companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$accountingaccount->label."</td>";
972  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
973  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
974  print "</tr>";
975  }
976 
977  // VAT
978  $listoftax = array(0, 1, 2);
979  foreach ($listoftax as $numtax) {
980  $arrayofvat = $tabtva;
981  if ($numtax == 1) {
982  $arrayofvat = $tablocaltax1;
983  }
984  if ($numtax == 2) {
985  $arrayofvat = $tablocaltax2;
986  }
987 
988  foreach ($arrayofvat[$key] as $k => $mt) {
989  if ($mt) {
990  print '<tr class="oddeven">';
991  print "<!-- VAT -->";
992  print "<td>".$date."</td>";
993  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
994  // Account
995  print "<td>";
996  $accountoshow = length_accountg($k);
997  if (($accountoshow == "") || $accountoshow == 'NotDefined') {
998  print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Purchase").')</span>';
999  } else {
1000  print $accountoshow;
1001  }
1002  print "</td>";
1003  // Subledger account
1004  print "<td>";
1005  print '</td>';
1006  print "<td>";
1007  print $companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT").' '.join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '');
1008  print "</td>";
1009  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1010  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1011  print "</tr>";
1012  }
1013  }
1014  }
1015 
1016  // VAT counterpart for NPR
1017  if (is_array($tabother[$key])) {
1018  foreach ($tabother[$key] as $k => $mt) {
1019  if ($mt) {
1020  print '<tr class="oddeven">';
1021  print '<!-- VAT counterpart NPR -->';
1022  print "<td>".$date."</td>";
1023  print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1024  // Account
1025  print '<td>';
1026  $accountoshow = length_accountg($k);
1027  if ($accountoshow == '' || $accountoshow == 'NotDefined') {
1028  print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("NPR counterpart").'). Set ACCOUNTING_COUNTERPART_VAT_NPR to the subvention account</span>';
1029  } else {
1030  print $accountoshow;
1031  }
1032  print '</td>';
1033  // Subledger account
1034  print "<td>";
1035  print '</td>';
1036  print "<td>".$companystatic->getNomUrl(0, 'supplier', 16).' - '.$invoicestatic->ref_supplier.' - '.$langs->trans("VAT")." NPR (counterpart)</td>";
1037  print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1038  print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1039  print "</tr>";
1040  }
1041  }
1042  }
1043  }
1044 
1045  print "</table>";
1046  print '</div>';
1047 
1048  // End of page
1049  llxFooter();
1050 }
1051 $db->close();
length_accounta
length_accounta($accounta)
Return Auxiliary accounting account of thirdparties with defined length.
Definition: accounting.lib.php:133
getTaxesFromId
getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
Get tax (VAT) main information from Id.
Definition: functions.lib.php:6202
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:50
dol_trunc
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
Definition: functions.lib.php:3950
llxFooter
llxFooter()
Empty footer.
Definition: wrapper.php:70
FactureFournisseur\TYPE_CREDIT_NOTE
const TYPE_CREDIT_NOTE
Credit note invoice.
Definition: fournisseur.facture.class.php:336
$sql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:745
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:530
FactureFournisseur
Class to manage suppliers invoices.
Definition: fournisseur.facture.class.php:51
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4994
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:143
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:5834
SupplierInvoiceLine
Class to manage line invoices.
Definition: fournisseur.facture.class.php:3324
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2566
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
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_string_nohtmltag
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
Definition: functions.lib.php:6921
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1639
dol_get_first_day
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:576
getDolGlobalString
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
Definition: functions.lib.php:82
journalHead
journalHead($nom, $variante, $period, $periodlink, $description, $builddate, $exportlink='', $moreparam=array(), $calcmode='', $varlink='')
Show header of a page used to transfer/dispatch data in accounting.
Definition: accounting.lib.php:183
dol_get_last_day
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:595
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:147
BookKeeping
Class to manage Ledger (General Ledger and Subledger)
Definition: bookkeeping.class.php:33
AccountingAccount
Class to manage accounting accounts.
Definition: accountingaccount.class.php:36
GETPOSTISSET
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
Definition: functions.lib.php:431
FactureFournisseur\TYPE_DEPOSIT
const TYPE_DEPOSIT
Deposit invoice.
Definition: fournisseur.facture.class.php:341
Lettering
Class Lettering.
Definition: lettering.class.php:34
Form
Class to manage generation of HTML components Only common components must be here.
Definition: html.form.class.php:52
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2947
getDefaultDatesForTransfer
getDefaultDatesForTransfer()
Return Default dates for transfer based on periodicity option in accountancy setup.
Definition: accounting.lib.php:273
price
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
Definition: functions.lib.php:5708
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8509
accessforbidden
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
Definition: security.lib.php:1106
dol_mktime
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
Definition: functions.lib.php:2859
getDolGlobalInt
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
Definition: functions.lib.php:96
vatrate
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formated for view output Used into pdf and HTML pages.
Definition: functions.lib.php:5659
if
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
Definition: journals_list.php:25
FactureFournisseur\TYPE_REPLACEMENT
const TYPE_REPLACEMENT
Replacement invoice.
Definition: fournisseur.facture.class.php:331