dolibarr  7.0.0-beta
sellsjournal.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2007-2010 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2007-2010 Jean Heimburger <jean@tiaris.info>
4  * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
5  * Copyright (C) 2012 Regis Houssin <regis.houssin@capnetworks.com>
6  * Copyright (C) 2013 Christophe Battarel <christophe.battarel@altairis.fr>
7  * Copyright (C) 2013-2017 Alexandre Spangaro <aspangaro@zendsi.com>
8  * Copyright (C) 2013-2016 Florian Henry <florian.henry@open-concept.pro>
9  * Copyright (C) 2013-2016 Olivier Geffroy <jeff@jeffinfo.com>
10  * Copyright (C) 2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
11  *
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 <http://www.gnu.org/licenses/>.
24  */
25 
32 require '../../main.inc.php';
33 require_once DOL_DOCUMENT_ROOT . '/core/lib/report.lib.php';
34 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
35 require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
36 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
37 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php';
38 require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
39 require_once DOL_DOCUMENT_ROOT . '/societe/class/client.class.php';
40 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeeping.class.php';
41 
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 == '') $in_bookkeeping = 'notyet';
55 
56 $now = dol_now();
57 
58 // Security check
59 if ($user->societe_id > 0)
61 
62 
63 /*
64  * Actions
65  */
66 
67 // Get informations of journal
68 $accountingjournalstatic = new AccountingJournal($db);
69 $accountingjournalstatic->fetch($id_journal);
70 $journal = $accountingjournalstatic->code;
71 $journal_label = $accountingjournalstatic->label;
72 
73 $year_current = strftime("%Y", dol_now());
74 $pastmonth = strftime("%m", dol_now()) - 1;
75 $pastmonthyear = $year_current;
76 if ($pastmonth == 0) {
77  $pastmonth = 12;
78  $pastmonthyear --;
79 }
80 
81 $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
82 $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
83 
84 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
85 {
86  $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
87  $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
88 }
89 
90 $idpays = $mysoc->country_id;
91 
92 $sql = "SELECT f.rowid, f.facnumber, f.type, f.datef as df, f.ref_client, f.date_lim_reglement as dlr, f.close_code,";
93 $sql .= " fd.rowid as fdid, fd.description, fd.product_type, fd.total_ht, fd.total_tva, fd.total_localtax1, fd.total_localtax2, fd.tva_tx, fd.total_ttc, fd.situation_percent, fd.vat_src_code,";
94 $sql .= " s.rowid as socid, s.nom as name, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,";
95 $sql .= " p.rowid as pid, p.ref as pref, p.accountancy_code_sell, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte";
96 //$sql .= " ct.accountancy_code_sell as account_tva";
97 $sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd";
98 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = fd.fk_product";
99 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
100 $sql .= " JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture";
101 $sql .= " JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc";
102 //$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_tva as ct ON ((fd.vat_src_code <> '' AND fd.vat_src_code = ct.code) OR (fd.vat_src_code = '' AND fd.tva_tx = ct.taux)) AND ct.fk_pays = '" . $idpays . "'";
103 $sql .= " WHERE fd.fk_code_ventilation > 0";
104 $sql .= " AND f.entity IN (".getEntity('facture', 0).')'; // We don't share object for accountancy
105 $sql .= " AND f.fk_statut > 0"; // TODO Facture annulée ?
106 if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
107  $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_SITUATION . ")";
108 } else {
109  $sql .= " AND f.type IN (" . Facture::TYPE_STANDARD . "," . Facture::TYPE_REPLACEMENT . "," . Facture::TYPE_CREDIT_NOTE . "," . Facture::TYPE_DEPOSIT . "," . Facture::TYPE_SITUATION . ")";
110 }
111 $sql .= " AND fd.product_type IN (0,1)";
112 if ($date_start && $date_end)
113  $sql .= " AND f.datef >= '" . $db->idate($date_start) . "' AND f.datef <= '" . $db->idate($date_end) . "'";
114 // Already in bookkeeping or not
115 if ($in_bookkeeping == 'already')
116 {
117  $sql .= " AND f.rowid IN (SELECT fk_doc FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
118  // $sql .= " AND fd.rowid IN (SELECT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')"; // Useless, we save one line for all products with same account
119 }
120 if ($in_bookkeeping == 'notyet')
121 {
122  $sql .= " AND f.rowid NOT IN (SELECT fk_doc FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
123 // $sql .= " AND fd.rowid NOT IN (SELECT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')"; // Useless, we save one line for all products with same account
124 }
125 $sql .= " ORDER BY f.datef";
126 
127 dol_syslog('accountancy/journal/sellsjournal.php', LOG_DEBUG);
128 $result = $db->query($sql);
129 if ($result) {
130  $tabfac = array ();
131  $tabht = array ();
132  $tabtva = array ();
133  $def_tva = array ();
134  $tabttc = array ();
135  $tablocaltax1 = array ();
136  $tablocaltax2 = array ();
137  $tabcompany = array ();
138 
139  $num = $db->num_rows($result);
140 
141  // Variables
142  $cptcli = (! empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER)) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : 'NotDefined';
143  $cpttva = (! empty($conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT : 'NotDefined';
144 
145  $i = 0;
146  while ( $i < $num ) {
147  $obj = $db->fetch_object($result);
148 
149  // Controls
150  $compta_soc = (! empty($obj->code_compta)) ? $obj->code_compta : $cptcli;
151 
152  $compta_prod = $obj->compte;
153  if (empty($compta_prod)) {
154  if ($obj->product_type == 0)
155  $compta_prod = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : 'NotDefined';
156  else
157  $compta_prod = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : 'NotDefined';
158  }
159 
160  $vatdata = getTaxesFromId($obj->tva_tx.($obj->vat_src_code?' ('.$obj->vat_src_code.')':''), $mysoc, $mysoc, 0);
161  $compta_tva = (! empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
162  $compta_localtax1 = (! empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
163  $compta_localtax2 = (! empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
164 
165  // Define array to display all VAT rates that use this accounting account $compta_tva
166  if (price2num($obj->tva_tx) || ! empty($obj->vat_src_code))
167  {
168  $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.')':''));
169  }
170 
171  $line = new FactureLigne($db);
172  $line->fetch($obj->fdid);
173 
174  // Situation invoices handling
175  $prev_progress = $line->get_prev_progress($obj->fdid);
176  if ($obj->type == Facture::TYPE_SITUATION) {
177  // Avoid divide by 0
178  if ($obj->situation_percent == 0) {
179  $situation_ratio = 0;
180  } else {
181  $situation_ratio = ($obj->situation_percent - $prev_progress) / $obj->situation_percent;
182  }
183  } else {
184  $situation_ratio = 1;
185  }
186 
187  // Invoice lines
188  $tabfac[$obj->rowid]["date"] = $db->jdate($obj->df);
189  $tabfac[$obj->rowid]["datereg"] = $db->jdate($obj->dlr);
190  $tabfac[$obj->rowid]["ref"] = $obj->facnumber;
191  $tabfac[$obj->rowid]["type"] = $obj->type;
192  $tabfac[$obj->rowid]["description"] = $obj->label_compte;
193  $tabfac[$obj->rowid]["close_code"] = $obj->close_code; // close_code = 'replaced' for replacement invoices (not used in most european countries)
194  //$tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid;
195 
196  // Avoid warnings
197  if (! isset($tabttc[$obj->rowid][$compta_soc])) $tabttc[$obj->rowid][$compta_soc] = 0;
198  if (! isset($tabht[$obj->rowid][$compta_prod])) $tabht[$obj->rowid][$compta_prod] = 0;
199  if (! isset($tabtva[$obj->rowid][$compta_tva])) $tabtva[$obj->rowid][$compta_tva] = 0;
200  if (! isset($tablocaltax1[$obj->rowid][$compta_localtax1])) $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
201  if (! isset($tablocaltax2[$obj->rowid][$compta_localtax2])) $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
202 
203  $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio;
204  $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
205  if (empty($line->tva_npr)) $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio; // We ignore line if VAT is a NPR
206  $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1 * $situation_ratio;
207  $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2 * $situation_ratio;
208  $tabcompany[$obj->rowid] = array (
209  'id' => $obj->socid,
210  'name' => $obj->name,
211  'code_client' => $obj->code_client,
212  'code_compta' => $compta_soc
213  );
214 
215  $i ++;
216  }
217 } else {
218  dol_print_error($db);
219 }
220 
221 // Bookkeeping Write
222 if ($action == 'writebookkeeping') {
223  $now = dol_now();
224  $error = 0;
225 
226  $companystatic = new Societe($db);
227  $invoicestatic = new Facture($db);
228 
229  foreach ($tabfac as $key => $val) { // Loop on each invoice
230 
231  $errorforline = 0;
232 
233  $totalcredit = 0;
234  $totaldebit = 0;
235 
236  $db->begin();
237 
238  $companystatic->id = $tabcompany[$key]['id'];
239  $companystatic->name = $tabcompany[$key]['name'];
240  $companystatic->code_compta = $tabcompany[$key]['code_compta'];
241  $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
242  $companystatic->code_client = $tabcompany[$key]['code_client'];
243  $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
244  $companystatic->client = 3;
245 
246  $invoicestatic->id = $key;
247  $invoicestatic->ref = (string) $val["ref"];
248  $invoicestatic->type = $val["type"];
249  $invoicestatic->close_code = $val["close_code"];
250 
251  $date = dol_print_date($val["date"], 'day');
252 
253  // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
254  $replacedinvoice = 0;
255  if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
256  {
257  $replacedinvoice = 1;
258  $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
259  if ($alreadydispatched) $replacedinvoice = 2;
260  }
261 
262  // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
263  if ($replacedinvoice == 1)
264  {
265  continue;
266  }
267 
268  // Thirdparty
269  if (! $errorforline)
270  {
271  foreach ( $tabttc[$key] as $k => $mt ) {
272  if ($mt) {
273  $bookkeeping = new BookKeeping($db);
274  $bookkeeping->doc_date = $val["date"];
275  $bookkeeping->date_lim_reglement = $val["datereg"];
276  $bookkeeping->doc_ref = $val["ref"];
277  $bookkeeping->date_create = $now;
278  $bookkeeping->doc_type = 'customer_invoice';
279  $bookkeeping->fk_doc = $key;
280  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
281  $bookkeeping->thirdparty_code = $companystatic->code_client;
282  $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
283  $bookkeeping->subledger_label = ''; // TODO To complete
284  $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER;
285  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("SubledgerAccount");
286  $bookkeeping->montant = $mt;
287  $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
288  $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
289  $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
290  $bookkeeping->code_journal = $journal;
291  $bookkeeping->journal_label = $journal_label;
292  $bookkeeping->fk_user_author = $user->id;
293 
294  $totaldebit += $bookkeeping->debit;
295  $totalcredit += $bookkeeping->credit;
296 
297  $result = $bookkeeping->create($user);
298  if ($result < 0) {
299  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
300  {
301  $error++;
302  $errorforline++;
303  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
304  }
305  else
306  {
307  $error++;
308  $errorforline++;
309  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
310  }
311  }
312  }
313  }
314  }
315 
316  // Product / Service
317  if (! $errorforline)
318  {
319  foreach ( $tabht[$key] as $k => $mt ) {
320  if ($mt) {
321  // get compte id and label
322  $accountingaccount = new AccountingAccount($db);
323  if ($accountingaccount->fetch(null, $k, true)) {
324  $bookkeeping = new BookKeeping($db);
325  $bookkeeping->doc_date = $val["date"];
326  $bookkeeping->date_lim_reglement = $val["datereg"];
327  $bookkeeping->doc_ref = $val["ref"];
328  $bookkeeping->date_create = $now;
329  $bookkeeping->doc_type = 'customer_invoice';
330  $bookkeeping->fk_doc = $key;
331  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
332  $bookkeeping->thirdparty_code = $companystatic->code_client;
333  $bookkeeping->subledger_account = '';
334  $bookkeeping->subledger_label = '';
335  $bookkeeping->numero_compte = $k;
336  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label;
337  $bookkeeping->montant = $mt;
338  $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
339  $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
340  $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
341  $bookkeeping->code_journal = $journal;
342  $bookkeeping->journal_label = $journal_label;
343  $bookkeeping->fk_user_author = $user->id;
344 
345  $totaldebit += $bookkeeping->debit;
346  $totalcredit += $bookkeeping->credit;
347 
348  $result = $bookkeeping->create($user);
349  if ($result < 0) {
350  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
351  {
352  $error++;
353  $errorforline++;
354  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
355  }
356  else
357  {
358  $error++;
359  $errorforline++;
360  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
361  }
362  }
363  }
364  }
365  }
366  }
367 
368  // VAT
369  // var_dump($tabtva);
370  if (! $errorforline)
371  {
372  $listoftax=array(0, 1, 2);
373  foreach($listoftax as $numtax)
374  {
375  $arrayofvat = $tabtva;
376  if ($numtax == 1) $arrayofvat = $tablocaltax1;
377  if ($numtax == 2) $arrayofvat = $tablocaltax2;
378 
379  foreach ( $arrayofvat[$key] as $k => $mt ) {
380  if ($mt) {
381  $bookkeeping = new BookKeeping($db);
382  $bookkeeping->doc_date = $val["date"];
383  $bookkeeping->date_lim_reglement = $val["datereg"];
384  $bookkeeping->doc_ref = $val["ref"];
385  $bookkeeping->date_create = $now;
386  $bookkeeping->doc_type = 'customer_invoice';
387  $bookkeeping->fk_doc = $key;
388  $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
389  $bookkeeping->thirdparty_code = $companystatic->code_client;
390  $bookkeeping->subledger_account = '';
391  $bookkeeping->subledger_label = '';
392  $bookkeeping->numero_compte = $k;
393  $bookkeeping->label_operation = dol_trunc($companystatic->name, 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT").' '.join(', ',$def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:'');
394  $bookkeeping->montant = $mt;
395  $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
396  $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
397  $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
398  $bookkeeping->code_journal = $journal;
399  $bookkeeping->journal_label = $journal_label;
400  $bookkeeping->fk_user_author = $user->id;
401 
402  $totaldebit += $bookkeeping->debit;
403  $totalcredit += $bookkeeping->credit;
404 
405  $result = $bookkeeping->create($user);
406  if ($result < 0) {
407  if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') // Already exists
408  {
409  $error++;
410  $errorforline++;
411  //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
412  }
413  else
414  {
415  $error++;
416  $errorforline++;
417  setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
418  }
419  }
420  }
421  }
422  }
423  }
424 
425  if ($totaldebit != $totalcredit)
426  {
427  $error++;
428  $errorforline++;
429  setEventMessages('Try to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
430  }
431 
432  if (! $errorforline)
433  {
434  $db->commit();
435  }
436  else
437  {
438  $db->rollback();
439 
440  if ($error >= 10)
441  {
442  setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
443  break; // Break in the foreach
444  }
445  }
446 
447  }
448 
449  $tabpay = $tabfac;
450 
451  if (empty($error) && count($tabpay) > 0) {
452  setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
453  }
454  elseif (count($tabpay) == $error)
455  {
456  setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
457  }
458  else
459  {
460  setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
461  }
462 
463  $action='';
464 
465  // Must reload data, so we make a redirect
466  if (count($tabpay) != $error)
467  {
468  $param='id_journal='.$id_journal;
469  $param.='&date_startday='.$date_startday;
470  $param.='&date_startmonth='.$date_startmonth;
471  $param.='&date_startyear='.$date_startyear;
472  $param.='&date_endday='.$date_endday;
473  $param.='&date_endmonth='.$date_endmonth;
474  $param.='&date_endyear='.$date_endyear;
475  $param.='&in_bookkeeping='.$in_bookkeeping;
476  header("Location: ".$_SERVER['PHP_SELF'].($param?'?'.$param:''));
477  exit;
478  }
479 }
480 
481 
482 
483 /*
484  * View
485  */
486 
487 $form = new Form($db);
488 
489 // Export
490 if ($action == 'exportcsv') {
491 
492  $sep = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV;
493 
494  include DOL_DOCUMENT_ROOT . '/accountancy/tpl/export_journal.tpl.php';
495 
496  $companystatic = new Client($db);
497  $invoicestatic = new Facture($db);
498 
499  foreach ( $tabfac as $key => $val )
500  {
501  $companystatic->id = $tabcompany[$key]['id'];
502  $companystatic->name = $tabcompany[$key]['name'];
503  $companystatic->code_compta = $tabcompany[$key]['code_compta'];
504  $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
505  $companystatic->code_client = $tabcompany[$key]['code_client'];
506  $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
507  $companystatic->client = 3;
508 
509  $invoicestatic->id = $key;
510  $invoicestatic->ref = (string) $val["ref"];
511  $invoicestatic->type = $val["type"];
512  $invoicestatic->close_code = $val["close_code"];
513 
514  $date = dol_print_date($val["date"], 'day');
515 
516  // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
517  $replacedinvoice = 0;
518  if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
519  {
520  $replacedinvoice = 1;
521  $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
522  if ($alreadydispatched) $replacedinvoice = 2;
523  }
524 
525  // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
526  if ($replacedinvoice == 1)
527  {
528  continue;
529  }
530 
531  // Third party
532  foreach ($tabttc[$key] as $k => $mt) {
533  print '"' . $key . '"' . $sep;
534  print '"' . $date . '"' . $sep;
535  print '"' . $val["ref"] . '"' . $sep;
536  print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep;
537  print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
538  print '"' . $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER . '"' . $sep;
539  print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
540  print '"' . $langs->trans("Code_tiers") . '"' . $sep;
541  print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("Code_tiers") . '"' . $sep;
542  print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
543  print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
544  print '"' . $journal . '"';
545  print "\n";
546  }
547 
548  // Product / Service
549  foreach ($tabht[$key] as $k => $mt) {
550  $accountingaccount = new AccountingAccount($db);
551  $accountingaccount->fetch(null, $k, true);
552  if ($mt) {
553  print '"' . $key . '"' . $sep;
554  print '"' . $date . '"' . $sep;
555  print '"' . $val["ref"] . '"' . $sep;
556  print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep;
557  print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
558  print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
559  print '""' . $sep;
560  print '"' . utf8_decode(dol_trunc($accountingaccount->label, 32)) . '"' . $sep;
561  print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . dol_trunc($accountingaccount->label, 32) . '"' . $sep;
562  print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
563  print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
564  print '"' . $journal . '"';
565  print "\n";
566  }
567  }
568 
569  // VAT
570  $listoftax = array(0, 1, 2);
571  foreach ($listoftax as $numtax) {
572  $arrayofvat = $tabtva;
573  if ($numtax == 1) $arrayofvat = $tablocaltax1;
574  if ($numtax == 2) $arrayofvat = $tablocaltax2;
575 
576  foreach ($arrayofvat[$key] as $k => $mt) {
577  if ($mt) {
578  print '"' . $key . '"' . $sep;
579  print '"' . $date . '"' . $sep;
580  print '"' . $val["ref"] . '"' . $sep;
581  print '"' . utf8_decode(dol_trunc($companystatic->name, 32)) . '"' . $sep;
582  print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
583  print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
584  print '""' . $sep;
585  print '"' . $langs->trans("VAT") . ' - ' . $def_tva[$key] . ' %"' . $sep;
586  print '"' . utf8_decode(dol_trunc($companystatic->name, 16)) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT") . join(', ',$def_tva[$key][$k]) .' %' . ($numtax?' - Localtax '.$numtax:'') . '"' . $sep;
587  print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep;
588  print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
589  print '"' . $journal . '"';
590  print "\n";
591  }
592  }
593  }
594  }
595 }
596 
597 
598 
599 if (empty($action) || $action == 'view') {
600 
601  llxHeader('', $langs->trans("SellsJournal"));
602 
603  $nom = $langs->trans("SellsJournal") . ' - ' . $accountingjournalstatic->getNomUrl(1);
604  $nomlink = '';
605  $periodlink = '';
606  $exportlink = '';
607  $builddate=dol_now();
608  $description.= $langs->trans("DescJournalOnlyBindedVisible").'<br>';
609  if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
610  $description .= $langs->trans("DepositsAreNotIncluded");
611  else
612  $description .= $langs->trans("DepositsAreIncluded");
613 
614  $listofchoices=array('already'=>$langs->trans("AlreadyInGeneralLedger"), 'notyet'=>$langs->trans("NotYetInGeneralLedger"));
615  $period = $form->select_date($date_start?$date_start:-1, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end?$date_end:-1, 'date_end', 0, 0, 0, '', 1, 0, 1). ' - ' .$langs->trans("JournalizationInLedgerStatus").' '. $form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
616 
617  $varlink = 'id_journal=' . $id_journal;
618 
619  journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
620 
621  // Button to write into Ledger
622  if (empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') {
623  print img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
624  print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>');
625  }
626  print '<div class="tabsAction tabsActionNoBottom">';
627  print '<input type="button" class="butAction" name="exportcsv" value="' . $langs->trans("ExportDraftJournal") . '" onclick="launch_export();" />';
628  if (empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) || $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER == '-1') {
629  print '<input type="button" class="butActionRefused" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="' . $langs->trans("WriteBookKeeping") . '" />';
630  }
631  else {
632  if ($in_bookkeeping == 'notyet') print '<input type="button" class="butAction" name="writebookkeeping" value="' . $langs->trans("WriteBookKeeping") . '" onclick="writebookkeeping();" />';
633  else print '<a href="#" class="butActionRefused" name="writebookkeeping">' . $langs->trans("WriteBookKeeping") . '</a>';
634  }
635  print '</div>';
636 
637  // TODO Avoid using js. We can use a direct link with $param
638  print '
639  <script type="text/javascript">
640  function launch_export() {
641  $("div.fiche form input[name=\"action\"]").val("exportcsv");
642  $("div.fiche form input[type=\"submit\"]").click();
643  $("div.fiche form input[name=\"action\"]").val("");
644  }
645  function writebookkeeping() {
646  $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
647  $("div.fiche form input[type=\"submit\"]").click();
648  $("div.fiche form input[name=\"action\"]").val("");
649  }
650  </script>';
651 
652  /*
653  * Show result array
654  */
655  print '<br>';
656 
657  $i = 0;
658  print '<div class="div-table-responsive">';
659  print "<table class=\"noborder\" width=\"100%\">";
660  print "<tr class=\"liste_titre\">";
661  print "<td></td>";
662  print "<td>" . $langs->trans("Date") . "</td>";
663  print "<td>" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")</td>";
664  print "<td>" . $langs->trans("AccountAccounting") . "</td>";
665  print "<td>" . $langs->trans("SubledgerAccount") . "</td>";
666  print "<td>" . $langs->trans("LabelOperation") . "</td>";
667  print "<td align='right'>" . $langs->trans("Debit") . "</td>";
668  print "<td align='right'>" . $langs->trans("Credit") . "</td>";
669  print "</tr>\n";
670 
671  $r = '';
672 
673  $companystatic = new Client($db);
674  $invoicestatic = new Facture($db);
675 
676  foreach ( $tabfac as $key => $val )
677  {
678  $companystatic->id = $tabcompany[$key]['id'];
679  $companystatic->name = $tabcompany[$key]['name'];
680  $companystatic->code_compta = $tabcompany[$key]['code_compta'];
681  $companystatic->code_compta_fournisseur = $tabcompany[$key]['code_compta_fournisseur'];
682  $companystatic->code_client = $tabcompany[$key]['code_client'];
683  $companystatic->code_fournisseur = $tabcompany[$key]['code_fournisseur'];
684  $companystatic->client = 3;
685 
686  $invoicestatic->id = $key;
687  $invoicestatic->ref = (string) $val["ref"];
688  $invoicestatic->type = $val["type"];
689  $invoicestatic->close_code = $val["close_code"];
690 
691  $date = dol_print_date($val["date"], 'day');
692 
693  // Is it a replaced invoice ? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
694  $replacedinvoice = 0;
695  if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED)
696  {
697  $replacedinvoice = 1;
698  $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
699  if ($alreadydispatched) $replacedinvoice = 2;
700  }
701 
702  // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
703  if ($replacedinvoice == 1)
704  {
705  print '<tr class="oddeven">';
706  print "<td><!-- Replaced invoice --></td>";
707  print "<td>" . $date . "</td>";
708  print "<td><strike>" . $invoicestatic->getNomUrl(1) . "</strike></td>";
709  // Account
710  print "<td>";
711  print $langs->trans("Replaced");
712  print '</td>';
713  // Subledger account
714  print "<td>";
715  print '</td>';
716  print "<td>";
717  print "</td>";
718  print '<td align="right"></td>';
719  print '<td align="right"></td>';
720  print "</tr>";
721  continue;
722  }
723 
724  // Third party
725  foreach ($tabttc[$key] as $k => $mt)
726  {
727  print '<tr class="oddeven">';
728  print "<td><!-- Thirdparty --></td>";
729  print "<td>" . $date . "</td>";
730  print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
731  // Account
732  print "<td>";
733  $accountoshow = length_accounta($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER);
734  if (empty($accountoshow) || $accountoshow == 'NotDefined')
735  {
736  print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
737  }
738  else print $accountoshow;
739  print '</td>';
740  // Subledger account
741  print "<td>";
742  $accountoshow = length_accounta($k);
743  if (empty($accountoshow) || $accountoshow == 'NotDefined')
744  {
745  print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
746  }
747  else print $accountoshow;
748  print '</td>';
749  print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("SubledgerAccount") . "</td>";
750  print '<td align="right">' . ($mt >= 0 ? price($mt) : '') . "</td>";
751  print '<td align="right">' . ($mt < 0 ? price(- $mt) : '') . "</td>";
752  print "</tr>";
753  }
754 
755  // Product / Service
756  foreach ($tabht[$key] as $k => $mt)
757  {
758  $accountingaccount = new AccountingAccount($db);
759  $accountingaccount->fetch(null, $k, true);
760 
761  if ($mt) {
762  print '<tr class="oddeven">';
763  print "<td><!-- Product --></td>";
764  print "<td>" . $date . "</td>";
765  print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
766  // Account
767  print "<td>";
768  $accountoshow = length_accountg($k);
769  if (empty($accountoshow) || $accountoshow == 'NotDefined')
770  {
771  print '<span class="error">'.$langs->trans("ProductNotDefined").'</span>';
772  }
773  else print $accountoshow;
774  print "</td>";
775  // Subledger account
776  print "<td>";
777  print '</td>';
778  $companystatic->id = $tabcompany[$key]['id'];
779  $companystatic->name = $tabcompany[$key]['name'];
780  print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $accountingaccount->label . "</td>";
781  print "<td align='right'>" . ($mt < 0 ? price(- $mt) : '') . "</td>";
782  print "<td align='right'>" . ($mt >= 0 ? price($mt) : '') . "</td>";
783  print "</tr>";
784  }
785  }
786 
787  // VAT
788  $listoftax = array(0, 1, 2);
789  foreach ($listoftax as $numtax)
790  {
791  $arrayofvat = $tabtva;
792  if ($numtax == 1) $arrayofvat = $tablocaltax1;
793  if ($numtax == 2) $arrayofvat = $tablocaltax2;
794 
795  foreach ( $arrayofvat[$key] as $k => $mt ) {
796  if ($mt) {
797  print '<tr class="oddeven">';
798  print "<td><!-- VAT --></td>";
799  print "<td>" . $date . "</td>";
800  print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
801  // Account
802  print "<td>";
803  $accountoshow = length_accountg($k);
804  if (empty($accountoshow) || $accountoshow == 'NotDefined')
805  {
806  print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("Sale").')'.'</span>';
807  }
808  else print $accountoshow;
809  print "</td>";
810  // Subledger account
811  print "<td>";
812  print '</td>';
813  print "<td>" . $companystatic->getNomUrl(0, 'customer', 16) . ' - ' . $invoicestatic->ref . ' - ' . $langs->trans("VAT"). ' '.join(', ',$def_tva[$key][$k]).' %'.($numtax?' - Localtax '.$numtax:'');
814  print "</td>";
815  print '<td align="right">' . ($mt < 0 ? price(- $mt) : '') . "</td>";
816  print '<td align="right">' . ($mt >= 0 ? price($mt) : '') . "</td>";
817  print "</tr>";
818  }
819  }
820  }
821  }
822 
823  print "</table>";
824  print '</div>';
825 
826  // End of page
827  llxFooter();
828 }
829 
830 $db->close();
llxFooter()
Empty footer.
Definition: wrapper.php:58
const TYPE_STANDARD
Standard invoice.
setEventMessages($mesg, $mesgs, $style='mesgs')
Set event messages in dol_events session object.
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.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm=false, $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
if(GETPOST('cancel','alpha')) if(!GETPOST('confirmmassaction','alpha')&&$massaction!= 'presend'&&$massaction!= 'confirm_presend')
Draft customers invoices.
Definition: list.php:147
Class to manage customers or prospects.
const TYPE_REPLACEMENT
Replacement invoice.
getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
Get vat main information from Id.
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition: date.lib.php:445
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
if(empty($reshook)) $form
View.
Definition: perms.php:103
const TYPE_SITUATION
Situation invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
GETPOST($paramname, $check='none', $method=0, $filter=NULL, $options=NULL, $noreplace=0)
Return value of a param into GET or POST supervariable.
Class to manage Ledger (General Ledger and Subledger)
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
Class to manage generation of HTML components Only common components must be here.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting a parameter.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
Class to manage third parties objects (customers, suppliers, prospects...)
img_warning($titlealt= 'default', $moreatt= '')
Show warning logo.
llxHeader()
Empty header.
Definition: wrapper.php:46
length_accounta($accounta)
Return Auxiliary accounting account of thirdparties with defined length.
dol_now($mode='gmt')
Return date for now.
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0)
Return a string with VAT rate label formated for view output Used into pdf and HTML pages...
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='tzserver', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
const TYPE_DEPOSIT
Deposit invoice.
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition: date.lib.php:459
print
Draft customers invoices.
Definition: index.php:91
Class to manage accounting accounts.
Class to manage accounting accounts.
Class to manage invoices.
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous) ...
journalHead($nom, $variante, $period, $periodlink, $description, $builddate, $exportlink='', $moreparam=array(), $calcmode='', $varlink='')
Show header of a VAT report.
price2num($amount, $rounding='', $alreadysqlnb=0)
Function that return a number with universal decimal format (decimal separator is '...
Class to manage invoice lines.