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