dolibarr  7.0.0-beta
card.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2016 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
5  * Copyright (C) 2005 Marc Barilley <marc@ocebo.fr>
6  * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@capnetworks.com>
7  * Copyright (C) 2010-2014 Juanjo Menent <jmenent@2byte.es>
8  * Copyright (C) 2013-2015 Philippe Grand <philippe.grand@atoo-net.com>
9  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
10  * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
11  * Copyright (C) 2016-2017 Alexandre Spangaro <aspangaro@zendsi.com>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 3 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program. If not, see <http://www.gnu.org/licenses/>.
25  */
26 
33 require '../../main.inc.php';
34 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
35 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
36 require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
37 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
38 require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
39 require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
40 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
42 if (!empty($conf->produit->enabled))
43  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
44 if (!empty($conf->projet->enabled)) {
45  require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
46  require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
47 }
48 
49 if (!empty($conf->variants->enabled)) {
50  require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
51 }
52 if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php';
53 
54 
55 $langs->loadLangs(array('bills','compta','suppliers','companies','products','banks'));
56 if (!empty($conf->incoterm->enabled)) $langs->load('incoterm');
57 
58 $id = (GETPOST('facid','int') ? GETPOST('facid','int') : GETPOST('id','int'));
59 $socid = GETPOST('socid', 'int');
60 $action = GETPOST('action','aZ09');
61 $confirm = GETPOST("confirm");
62 $ref = GETPOST('ref','alpha');
63 $cancel = GETPOST('cancel','alpha');
64 $lineid = GETPOST('lineid', 'int');
65 $projectid = GETPOST('projectid','int');
66 $origin = GETPOST('origin', 'alpha');
67 $originid = GETPOST('originid', 'int');
68 
69 // PDF
70 $hidedetails = (GETPOST('hidedetails','int') ? GETPOST('hidedetails','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
71 $hidedesc = (GETPOST('hidedesc','int') ? GETPOST('hidedesc','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
72 $hideref = (GETPOST('hideref','int') ? GETPOST('hideref','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
73 
74 // Security check
75 $socid='';
76 if (! empty($user->societe_id)) $socid=$user->societe_id;
77 $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture');
78 
79 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
80 $hookmanager->initHooks(array('invoicesuppliercard','globalcard'));
81 
82 $object=new FactureFournisseur($db);
83 $extrafields = new ExtraFields($db);
84 
85 // fetch optionals attributes and labels
86 $extralabels=$extrafields->fetch_name_optionals_label($object->table_element);
87 
88 // Load object
89 if ($id > 0 || ! empty($ref))
90 {
91  $ret=$object->fetch($id, $ref);
92  if ($ret < 0) dol_print_error($db,$object->error);
93  $ret=$object->fetch_thirdparty();
94  if ($ret < 0) dol_print_error($db,$object->error);
95 }
96 
97 $permissionnote=$user->rights->fournisseur->facture->creer; // Used by the include of actions_setnotes.inc.php
98 $permissiondellink=$user->rights->fournisseur->facture->creer; // Used by the include of actions_dellink.inc.php
99 $permissionedit=$user->rights->fournisseur->facture->creer; // Used by the include of actions_lineupdown.inc.php
100 
101 
102 /*
103  * Actions
104  */
105 
106 $parameters=array('socid'=>$socid);
107 $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
108 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
109 
110 if (empty($reshook))
111 {
112  if ($cancel)
113  {
114  if (! empty($backtopage))
115  {
116  header("Location: ".$backtopage);
117  exit;
118  }
119  $action='';
120  }
121 
122  include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
123 
124  include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
125 
126  include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
127 
128  // Link invoice to order
129  if (GETPOST('linkedOrder') && empty($cancel) && $id > 0)
130  {
131  $object->fetch($id);
132  $object->fetch_thirdparty();
133  $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder'));
134  }
135 
136  // Action clone object
137  if ($action == 'confirm_clone' && $confirm == 'yes')
138  {
139  // if (1==0 && empty($_REQUEST["clone_content"]) && empty($_REQUEST["clone_receivers"]))
140  // {
141  // $mesg='<div class="error">'.$langs->trans("NoCloneOptionsSpecified").'</div>';
142  // }
143  // else
144  // {
145  $result=$object->createFromClone($id);
146  if ($result > 0)
147  {
148  header("Location: ".$_SERVER['PHP_SELF'].'?action=editref_supplier&id='.$result);
149  exit;
150  }
151  else
152  {
153  $langs->load("errors");
154  setEventMessages($langs->trans($object->error), null, 'errors');
155  $action='';
156  }
157  // }
158  }
159 
160  elseif ($action == 'confirm_valid' && $confirm == 'yes' &&
161  ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->facture->creer))
162  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_invoice_advance->validate)))
163  )
164  {
165  $idwarehouse=GETPOST('idwarehouse');
166 
167  $object->fetch($id);
168  $object->fetch_thirdparty();
169 
170  $qualified_for_stock_change=0;
171  if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
172  {
173  $qualified_for_stock_change=$object->hasProductsOrServices(2);
174  }
175  else
176  {
177  $qualified_for_stock_change=$object->hasProductsOrServices(1);
178  }
179 
180  // Check parameters
181  if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change)
182  {
183  $langs->load("stocks");
184  if (! $idwarehouse || $idwarehouse == -1)
185  {
186  $error++;
187  setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
188  $action='';
189  }
190  }
191 
192  if (! $error)
193  {
194  $result = $object->validate($user,'',$idwarehouse);
195  if ($result < 0)
196  {
197  setEventMessages($object->error,$object->errors,'errors');
198  }else{
199  // Define output language
200  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
201  {
202  $outputlangs = $langs;
203  $newlang = '';
204  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
205  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
206  if (! empty($newlang)) {
207  $outputlangs = new Translate("", $conf);
208  $outputlangs->setDefaultLang($newlang);
209  }
210  $model=$object->modelpdf;
211  $ret = $object->fetch($id); // Reload to get new records
212 
213  $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
214  if ($result < 0) dol_print_error($db,$result);
215  }
216  }
217  }
218  }
219 
220  elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->facture->supprimer)
221  {
222  $object->fetch($id);
223  $object->fetch_thirdparty();
224  $result=$object->delete($user);
225  if ($result > 0)
226  {
227  header('Location: list.php');
228  exit;
229  }
230  else
231  {
232  setEventMessages($object->error, $object->errors, 'errors');
233  }
234  }
235 
236  // Remove a product line
237  else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer)
238  {
239  $result = $object->deleteline($lineid);
240  if ($result > 0)
241  {
242  // Define output language
243  /*$outputlangs = $langs;
244  $newlang = '';
245  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09'))
246  $newlang = GETPOST('lang_id','aZ09');
247  if ($conf->global->MAIN_MULTILANGS && empty($newlang))
248  $newlang = $object->thirdparty->default_lang;
249  if (! empty($newlang)) {
250  $outputlangs = new Translate("", $conf);
251  $outputlangs->setDefaultLang($newlang);
252  }
253  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
254  $ret = $object->fetch($object->id); // Reload to get new records
255  $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
256  }*/
257 
258  header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
259  exit;
260  }
261  else
262  {
263  setEventMessages($object->error, $object->errors, 'errors');
264  /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */
265  $action='';
266  }
267  }
268 
269  elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer)
270  {
271  $object->fetch($id);
272  $result=$object->set_paid($user);
273  if ($result<0)
274  {
275  setEventMessages($object->error, $object->errors, 'errors');
276  }
277  }
278 
279  // Set supplier ref
280  if ($action == 'setref_supplier' && $user->rights->fournisseur->facture->creer)
281  {
282  $object->ref_supplier = GETPOST('ref_supplier', 'alpha');
283 
284  if ($object->update($user) < 0) {
285  setEventMessages($object->error, $object->errors, 'errors');
286  }
287  else
288  {
289  // Define output language
290  $outputlangs = $langs;
291  $newlang = '';
292  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09'))
293  $newlang = GETPOST('lang_id','aZ09');
294  if ($conf->global->MAIN_MULTILANGS && empty($newlang))
295  $newlang = $object->thirdparty->default_lang;
296  if (! empty($newlang)) {
297  $outputlangs = new Translate("", $conf);
298  $outputlangs->setDefaultLang($newlang);
299  }
300  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
301  $ret = $object->fetch($object->id); // Reload to get new records
302  $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
303  }
304  }
305  }
306 
307  // payments conditions
308  if ($action == 'setconditions' && $user->rights->fournisseur->facture->creer)
309  {
310  $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int'));
311  }
312 
313  // payment mode
314  else if ($action == 'setmode' && $user->rights->fournisseur->facture->creer)
315  {
316  $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int'));
317  }
318 
319  // Multicurrency Code
320  else if ($action == 'setmulticurrencycode' && $user->rights->facture->creer) {
321  $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
322  }
323 
324  // Multicurrency rate
325  else if ($action == 'setmulticurrencyrate' && $user->rights->facture->creer) {
326  $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx', 'alpha')));
327  }
328 
329  // bank account
330  else if ($action == 'setbankaccount' && $user->rights->fournisseur->facture->creer) {
331  $result=$object->setBankAccount(GETPOST('fk_account', 'int'));
332  }
333 
334  // Set label
335  elseif ($action == 'setlabel' && $user->rights->fournisseur->facture->creer)
336  {
337  $object->fetch($id);
338  $object->label=GETPOST('label');
339  $result=$object->update($user);
340  if ($result < 0) dol_print_error($db);
341  }
342  elseif ($action == 'setdatef' && $user->rights->fournisseur->facture->creer)
343  {
344  $newdate=dol_mktime(0,0,0,$_POST['datefmonth'],$_POST['datefday'],$_POST['datefyear']);
345  if ($newdate > (dol_now() + (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)?0:$conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)))
346  {
347  if (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)) setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings');
348  else setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings');
349  }
350 
351  $object->fetch($id);
352 
353  $object->date=$newdate;
354  $date_echence_calc=$object->calculate_date_lim_reglement();
355  if (!empty($object->date_echeance) && $object->date_echeance < $date_echence_calc)
356  {
357  $object->date_echeance = $date_echence_calc;
358  }
359  if ($object->date_echeance && $object->date_echeance < $object->date)
360  {
361  $object->date_echeance=$object->date;
362  }
363 
364  $result=$object->update($user);
365  if ($result < 0) dol_print_error($db,$object->error);
366  }
367  elseif ($action == 'setdate_lim_reglement' && $user->rights->fournisseur->facture->creer)
368  {
369  $object->fetch($id);
370  $object->date_echeance=dol_mktime(12,0,0,$_POST['date_lim_reglementmonth'],$_POST['date_lim_reglementday'],$_POST['date_lim_reglementyear']);
371  if (! empty($object->date_echeance) && $object->date_echeance < $object->date)
372  {
373  $object->date_echeance=$object->date;
374  setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
375  }
376  $result=$object->update($user);
377  if ($result < 0) dol_print_error($db,$object->error);
378  }
379 
380  // Delete payment
381  elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer)
382  {
383  $object->fetch($id);
384  if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0)
385  {
386  $paiementfourn = new PaiementFourn($db);
387  $result=$paiementfourn->fetch(GETPOST('paiement_id'));
388  if ($result > 0) {
389  $result=$paiementfourn->delete(); // If fetch ok and found
390  header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
391  }
392  if ($result < 0) {
393  setEventMessages($paiementfourn->error, $paiementfourn->errors, 'errors');
394  }
395  }
396  }
397 
398  // Create
399  elseif ($action == 'add' && $user->rights->fournisseur->facture->creer)
400  {
401  if ($socid > 0) $object->socid = GETPOST('socid', 'int');
402 
403  $db->begin();
404 
405  $error = 0;
406 
407  // Fill array 'array_options' with data from add form
408  $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
409  $ret = $extrafields->setOptionalsFromPost($extralabels, $object);
410  if ($ret < 0) $error++;
411 
412  $datefacture=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']);
413  $datedue=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']);
414 
415  // Replacement invoice
416  if ($_POST['type'] == FactureFournisseur::TYPE_REPLACEMENT)
417  {
418  if ($datefacture == '')
419  {
420  setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('DateInvoice')), null, 'errors');
421  $action='create';
422  $_GET['socid']=$_POST['socid'];
423  $error++;
424  }
425  if (! ($_POST['fac_replacement'] > 0)) {
426  $error ++;
427  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
428  }
429 
430  if (! $error) {
431  // This is a replacement invoice
432  $result = $object->fetch(GETPOST('fac_replacement'),'int');
433  $object->fetch_thirdparty();
434 
435  $object->ref = GETPOST('ref');
436  $object->ref_supplier = GETPOST('ref_supplier','alpha');
437  $object->socid = GETPOST('socid','int');
438  $object->libelle = GETPOST('label');
439  $object->date = $datefacture;
440  $object->date_echeance = $datedue;
441  $object->note_public = GETPOST('note_public','none');
442  $object->note_private = GETPOST('note_private','none');
443  $object->cond_reglement_id = GETPOST('cond_reglement_id');
444  $object->mode_reglement_id = GETPOST('mode_reglement_id');
445  $object->fk_account = GETPOST('fk_account', 'int');
446  $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
447  $object->fk_incoterms = GETPOST('incoterm_id', 'int');
448  $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
449  $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
450  $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
451 
452  // Proprietes particulieres a facture de remplacement
453  $object->fk_facture_source = GETPOST('fac_replacement');
454  $object->type = FactureFournisseur::TYPE_REPLACEMENT;
455 
456  $id = $object->createFromCurrent($user);
457  if ($id <= 0) {
458  $error++;
459  setEventMessages($object->error, $object->errors, 'errors');
460  }
461  }
462  }
463 
464  // Credit note invoice
465  if ($_POST['type'] == FactureFournisseur::TYPE_CREDIT_NOTE)
466  {
467  $sourceinvoice = GETPOST('fac_avoir','int');
468  if (! ($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE))
469  {
470  $error ++;
471  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
472  }
473  if (GETPOST('socid','int')<1)
474  {
475  setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), null, 'errors');
476  $action='create';
477  $error++;
478  }
479  if ($datefacture == '')
480  {
481  setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('DateInvoice')), null, 'errors');
482  $action='create';
483  $_GET['socid']=$_POST['socid'];
484  $error++;
485  }
486  if (! GETPOST('ref_supplier'))
487  {
488  setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('RefSupplier')), null, 'errors');
489  $action='create';
490  $_GET['socid']=$_POST['socid'];
491  $error++;
492  }
493 
494  if (! $error)
495  {
496  $tmpproject = GETPOST('projectid', 'int');
497 
498  // Creation facture
499  $object->ref = $_POST['ref'];
500  $object->ref_supplier = $_POST['ref_supplier'];
501  $object->socid = $_POST['socid'];
502  $object->libelle = $_POST['label'];
503  $object->date = $datefacture;
504  $object->date_echeance = $datedue;
505  $object->note_public = GETPOST('note_public','none');
506  $object->note_private = GETPOST('note_private','none');
507  $object->cond_reglement_id = GETPOST('cond_reglement_id');
508  $object->mode_reglement_id = GETPOST('mode_reglement_id');
509  $object->fk_account = GETPOST('fk_account', 'int');
510  $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
511  $object->fk_incoterms = GETPOST('incoterm_id', 'int');
512  $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
513  $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
514  $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
515 
516  // Proprietes particulieres a facture avoir
517  $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
518  $object->type = FactureFournisseur::TYPE_CREDIT_NOTE;
519 
520  $id = $object->create($user);
521 
522  if (GETPOST('invoiceAvoirWithLines', 'int')==1 && $id>0)
523  {
524  $facture_source = new FactureFournisseur($db); // fetch origin object
525  if ($facture_source->fetch($object->fk_facture_source)>0)
526  {
527  $fk_parent_line = 0;
528 
529  foreach($facture_source->lines as $line)
530  {
531  // Reset fk_parent_line for no child products and special product
532  if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
533  $fk_parent_line = 0;
534  }
535 
536  $line->fk_facture_fourn = $object->id;
537  $line->fk_parent_line = $fk_parent_line;
538 
539  $line->subprice =-$line->subprice; // invert price for object
540  $line->pa_ht = -$line->pa_ht;
541  $line->total_ht=-$line->total_ht;
542  $line->total_tva=-$line->total_tva;
543  $line->total_ttc=-$line->total_ttc;
544  $line->total_localtax1=-$line->total_localtax1;
545  $line->total_localtax2=-$line->total_localtax2;
546 
547  $result = $line->insert();
548 
549  $object->lines[] = $line; // insert new line in current object
550 
551  // Defined the new fk_parent_line
552  if ($result > 0 && $line->product_type == 9) {
553  $fk_parent_line = $result;
554  }
555  }
556 
557  $object->update_price(1);
558  }
559 
560  }
561 
562  if(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int')==1 && $id>0)
563  {
564  $facture_source = new FactureFournisseur($db); // fetch origin object if not previously defined
565  if ($facture_source->fetch($object->fk_facture_source)>0)
566  {
567  $totalpaye = $facture_source->getSommePaiement();
568  $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
569  $totaldeposits = $facture_source->getSumDepositsUsed();
570  $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits);
571 
572  $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'),$remain_to_pay,1,0,0,0,0,0,'','','TTC');
573  }
574  }
575  }
576  }
577 
578  // Standard or deposit
579  if ($_POST['type'] == FactureFournisseur::TYPE_STANDARD || $_POST['type'] == FactureFournisseur::TYPE_DEPOSIT)
580  {
581  if (GETPOST('socid','int')<1)
582  {
583  setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), null, 'errors');
584  $action='create';
585  $error++;
586  }
587 
588  if ($datefacture == '')
589  {
590  setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('DateInvoice')), null, 'errors');
591  $action='create';
592  $_GET['socid']=$_POST['socid'];
593  $error++;
594  }
595  if (! GETPOST('ref_supplier'))
596  {
597  setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('RefSupplier')), null, 'errors');
598  $action='create';
599  $_GET['socid']=$_POST['socid'];
600  $error++;
601  }
602 
603  if (! $error)
604  {
605  $tmpproject = GETPOST('projectid', 'int');
606 
607  // Creation facture
608  $object->ref = $_POST['ref'];
609  $object->ref_supplier = $_POST['ref_supplier'];
610  $object->socid = $_POST['socid'];
611  $object->libelle = $_POST['label'];
612  $object->date = $datefacture;
613  $object->date_echeance = $datedue;
614  $object->note_public = GETPOST('note_public','none');
615  $object->note_private = GETPOST('note_private','none');
616  $object->cond_reglement_id = GETPOST('cond_reglement_id');
617  $object->mode_reglement_id = GETPOST('mode_reglement_id');
618  $object->fk_account = GETPOST('fk_account', 'int');
619  $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
620  $object->fk_incoterms = GETPOST('incoterm_id', 'int');
621  $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
622  $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
623  $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
624 
625  // Auto calculation of date due if not filled by user
626  if(empty($object->date_echeance)) $object->date_echeance = $object->calculate_date_lim_reglement();
627 
628  // If creation from another object of another module
629  if (! $error && $_POST['origin'] && $_POST['originid'])
630  {
631  // Parse element/subelement (ex: project_task)
632  $element = $subelement = GETPOST('origin');
633  /*if (preg_match('/^([^_]+)_([^_]+)/i',$_POST['origin'],$regs))
634  {
635  $element = $regs[1];
636  $subelement = $regs[2];
637  }*/
638 
639  // For compatibility
640  if ($element == 'order') {
641  $element = $subelement = 'commande';
642  }
643  if ($element == 'propal') {
644  $element = 'comm/propal'; $subelement = 'propal';
645  }
646  if ($element == 'contract') {
647  $element = $subelement = 'contrat';
648  }
649  if ($element == 'order_supplier') {
650  $element = 'fourn'; $subelement = 'fournisseur.commande';
651  }
652  if ($element == 'project')
653  {
654  $element = 'projet';
655  }
656  $object->origin = GETPOST('origin');
657  $object->origin_id = GETPOST('originid');
658 
659  $id = $object->create($user);
660 
661  // Add lines
662  if ($id > 0)
663  {
664  require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
665  $classname = ucfirst($subelement);
666  if ($classname == 'Fournisseur.commande') $classname='CommandeFournisseur';
667  $srcobject = new $classname($db);
668 
669  $result=$srcobject->fetch(GETPOST('originid','int'));
670  if ($result > 0)
671  {
672  $lines = $srcobject->lines;
673  if (empty($lines) && method_exists($srcobject,'fetch_lines'))
674  {
675  $srcobject->fetch_lines();
676  $lines = $srcobject->lines;
677  }
678 
679  $num=count($lines);
680  for ($i = 0; $i < $num; $i++)
681  {
682  $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle);
683  $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
684 
685  // Extrafields
686  if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) {
687  $lines[$i]->fetch_optionals($lines[$i]->rowid);
688  }
689 
690  // Dates
691  // TODO mutualiser
692  $date_start=$lines[$i]->date_debut_prevue;
693  if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
694  if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
695  $date_end=$lines[$i]->date_fin_prevue;
696  if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
697  if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
698 
699  // FIXME Missing $lines[$i]->ref_supplier and $lines[$i]->label into addline and updateline methods. They are filled when coming from order for example.
700  $result = $object->addline(
701  $desc,
702  $lines[$i]->subprice,
703  $lines[$i]->tva_tx,
704  $lines[$i]->localtax1_tx,
705  $lines[$i]->localtax2_tx,
706  $lines[$i]->qty,
707  $lines[$i]->fk_product,
708  $lines[$i]->remise_percent,
709  $date_start,
710  $date_end,
711  0,
712  $lines[$i]->info_bits,
713  'HT',
714  $product_type,
715  $lines[$i]->rang,
716  0,
717  $lines[$i]->array_options,
718  $lines[$i]->fk_unit,
719  $lines[$i]->id
720  );
721 
722  if ($result < 0)
723  {
724  $error++;
725  break;
726  }
727  }
728 
729  // Now reload line
730  $object->fetch_lines();
731  }
732  else
733  {
734  $error++;
735  }
736  }
737  else
738  {
739  $error++;
740  }
741  }
742  else if (! $error)
743  {
744  $id = $object->create($user);
745  if ($id < 0)
746  {
747  $error++;
748  }
749  }
750  }
751  }
752 
753  if ($error)
754  {
755  $langs->load("errors");
756  $db->rollback();
757 
758  setEventMessages($object->error, $object->errors, 'errors');
759  $action='create';
760  $_GET['socid']=$_POST['socid'];
761  }
762  else
763  {
764  $db->commit();
765 
766  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
767  $outputlangs = $langs;
768  $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
769  if ($result < 0)
770  {
771  dol_print_error($db,$object->error,$object->errors);
772  exit;
773  }
774  }
775 
776  header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
777  exit;
778  }
779  }
780 
781  // Edit line
782  elseif ($action == 'updateline' && $user->rights->fournisseur->facture->creer)
783  {
784  $db->begin();
785 
786  $object->fetch($id);
787  $object->fetch_thirdparty();
788 
789  $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
790 
791  if (GETPOST('price_ht') != '')
792  {
793  $up = price2num(GETPOST('price_ht'));
794  $price_base_type = 'HT';
795  }
796  else
797  {
798  $up = price2num(GETPOST('price_ttc'));
799  $price_base_type = 'TTC';
800  }
801 
802  if (GETPOST('productid'))
803  {
804  $prod = new Product($db);
805  $prod->fetch(GETPOST('productid'));
806  $label = $prod->description;
807  if (trim($_POST['product_desc']) != trim($label)) $label=$_POST['product_desc'];
808 
809  $type = $prod->type;
810  }
811  else
812  {
813  $label = $_POST['product_desc'];
814  $type = $_POST["type"]?$_POST["type"]:0;
815  }
816 
817  $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
818  $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
819 
820  // Define info_bits
821  $info_bits = 0;
822  if (preg_match('/\*/', $tva_tx))
823  $info_bits |= 0x01;
824 
825  // Define vat_rate
826  $tva_tx = str_replace('*', '', $tva_tx);
827  $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
828  $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
829 
830  $remise_percent=GETPOST('remise_percent');
831  $pu_ht_devise = GETPOST('multicurrency_subprice');
832 
833  // Extrafields Lines
834  $extrafieldsline = new ExtraFields($db);
835  $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
836  $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline);
837  // Unset extrafield POST Data
838  if (is_array($extralabelsline)) {
839  foreach ($extralabelsline as $key => $value) {
840  unset($_POST["options_" . $key]);
841  }
842  }
843 
844  $result=$object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise);
845  if ($result >= 0)
846  {
847  unset($_POST['label']);
848  unset($_POST['fourn_ref']);
849  unset($_POST['date_starthour']);
850  unset($_POST['date_startmin']);
851  unset($_POST['date_startsec']);
852  unset($_POST['date_startday']);
853  unset($_POST['date_startmonth']);
854  unset($_POST['date_startyear']);
855  unset($_POST['date_endhour']);
856  unset($_POST['date_endmin']);
857  unset($_POST['date_endsec']);
858  unset($_POST['date_endday']);
859  unset($_POST['date_endmonth']);
860  unset($_POST['date_endyear']);
861 
862  $db->commit();
863  }
864  else
865  {
866  $db->rollback();
867  setEventMessages($object->error, $object->errors, 'errors');
868  }
869  }
870 
871  elseif ($action == 'addline' && $user->rights->fournisseur->facture->creer)
872  {
873  $db->begin();
874 
875  $ret=$object->fetch($id);
876  if ($ret < 0)
877  {
878  dol_print_error($db,$object->error);
879  exit;
880  }
881  $ret=$object->fetch_thirdparty();
882 
883  $langs->load('errors');
884  $error=0;
885 
886  // Set if we used free entry or predefined product
887  $predef='';
888  $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
889  $prod_entry_mode = GETPOST('prod_entry_mode');
890  if ($prod_entry_mode == 'free')
891  {
892  $idprod=0;
893  $price_ht = GETPOST('price_ht');
894  $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
895  }
896  else
897  {
898  $idprod=GETPOST('idprod', 'int');
899  $price_ht = '';
900  $tva_tx = '';
901  }
902 
903  $qty = GETPOST('qty'.$predef);
904  $remise_percent=GETPOST('remise_percent'.$predef);
905  $price_ht_devise = GETPOST('multicurrency_price_ht');
906 
907  $date_start=dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start' . $predef . 'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year'));
908  $date_end=dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end' . $predef . 'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year'));
909 
910  // Extrafields
911  $extrafieldsline = new ExtraFields($db);
912  $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
913  $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
914  // Unset extrafield
915  if (is_array($extralabelsline)) {
916  // Get extra fields
917  foreach ($extralabelsline as $key => $value) {
918  unset($_POST["options_" . $key]);
919  }
920  }
921 
922  if ($prod_entry_mode =='free' && GETPOST('price_ht') < 0 && $qty < 0)
923  {
924  setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
925  $error++;
926  }
927  if ($prod_entry_mode =='free' && ! GETPOST('idprodfournprice') && GETPOST('type') < 0)
928  {
929  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
930  $error++;
931  }
932  if ($prod_entry_mode =='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='' && $price_ht_devise==='') // Unit price can be 0 but not ''
933  {
934  setEventMessages($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), null, 'errors');
935  $error++;
936  }
937  if ($prod_entry_mode =='free' && ! GETPOST('dp_desc'))
938  {
939  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
940  $error++;
941  }
942  if (! GETPOST('qty'))
943  {
944  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
945  $error++;
946  }
947 
948  if (!$error && !empty($conf->variants->enabled) && $prod_entry_mode != 'free') {
949  if ($combinations = GETPOST('combinations', 'array')) {
950  //Check if there is a product with the given combination
951  $prodcomb = new ProductCombination($db);
952 
953  if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
954  $idprod = $res->fk_product_child;
955  } else {
956  setEventMessage($langs->trans('ErrorProductCombinationNotFound'), 'errors');
957  $error ++;
958  }
959  }
960  }
961 
962  if ($prod_entry_mode != 'free' && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or ''
963  {
964  $productsupplier=new ProductFournisseur($db);
965 
966  $idprod=0;
967  if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...)
968 
969  if (preg_match('/^idprod_([0-9]+)$/',GETPOST('idprodfournprice'), $reg))
970  {
971  $idprod=$reg[1];
972  $res=$productsupplier->fetch($idprod);
973  // Call to init properties of $productsupplier
974  // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price
975  $productsupplier->get_buyprice(0, -1, $idprod, 'none'); // We force qty to -1 to be sure to find if a supplier price exist
976  }
977  elseif (GETPOST('idprodfournprice') > 0)
978  {
979  $qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat.
980  //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist
981  $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qtytosearch);
982  $res=$productsupplier->fetch($idprod);
983  }
984 
985  //Replaces $fk_unit with the product's
986  if ($idprod > 0)
987  {
988  $label = $productsupplier->label;
989 
990  $desc = $productsupplier->description;
991  if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc);
992 
993  $tva_tx=get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']);
994  $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, $_POST['idprodfournprice']);
995  if (empty($tva_tx)) $tva_npr=0;
996  $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr);
997  $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr);
998 
999  $type = $productsupplier->type;
1000  $price_base_type = 'HT';
1001 
1002  $result=$object->addline(
1003  $desc,
1004  $productsupplier->fourn_pu,
1005  $tva_tx,
1006  $localtax1_tx,
1007  $localtax2_tx,
1008  $qty,
1009  $idprod,
1010  $remise_percent,
1011  $date_start,
1012  $date_end,
1013  0,
1014  $tva_npr,
1015  $price_base_type,
1016  $type,
1017  -1,
1018  0,
1019  $array_options,
1020  $productsupplier->fk_unit,
1021  $productsupplier->fourn_ref
1022  );
1023  }
1024  if ($idprod == -99 || $idprod == 0)
1025  {
1026  // Product not selected
1027  $error++;
1028  $langs->load("errors");
1029  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors');
1030  }
1031  if ($idprod == -1)
1032  {
1033  // Quantity too low
1034  $error++;
1035  $langs->load("errors");
1036  setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors');
1037  }
1038  }
1039  else if (empty($error)) // $price_ht is already set
1040  {
1041  $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
1042  $tva_tx = str_replace('*', '', $tva_tx);
1043  $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
1044  $desc = $product_desc;
1045  $type = GETPOST('type');
1046  $ref_supplier = GETPOST('fourn_ref','alpha');
1047 
1048  $fk_unit= GETPOST('units', 'alpha');
1049 
1050  $tva_tx = price2num($tva_tx); // When vat is text input field
1051 
1052  // Local Taxes
1053  $localtax1_tx= get_localtax($tva_tx, 1,$mysoc,$object->thirdparty);
1054  $localtax2_tx= get_localtax($tva_tx, 2,$mysoc,$object->thirdparty);
1055 
1056  if ($price_ht !== '')
1057  {
1058  $pu_ht = price2num($price_ht, 'MU'); // $pu_ht must be rounded according to settings
1059  }
1060  else
1061  {
1062  $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
1063  $pu_ht = price2num($pu_ttc / (1 + ($tva_tx / 100)), 'MU'); // $pu_ht must be rounded according to settings
1064  }
1065  $price_base_type = 'HT';
1066  $pu_ht_devise = price2num($price_ht_devise, 'MU');
1067 
1068  $result=$object->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, 0, $remise_percent, $date_start, $date_end, 0, $tva_npr, $price_base_type, $type, -1, 0, $array_options, $fk_unit, 0, $pu_ht_devise, $ref_supplier);
1069  }
1070 
1071  //print "xx".$tva_tx; exit;
1072  if (! $error && $result > 0)
1073  {
1074  $db->commit();
1075 
1076  // Define output language
1077  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
1078  {
1079  $outputlangs = $langs;
1080  $newlang = '';
1081  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
1082  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
1083  if (! empty($newlang)) {
1084  $outputlangs = new Translate("", $conf);
1085  $outputlangs->setDefaultLang($newlang);
1086  }
1087  $model=$object->modelpdf;
1088  $ret = $object->fetch($id); // Reload to get new records
1089 
1090  $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1091  if ($result < 0) dol_print_error($db,$result);
1092  }
1093 
1094  unset($_POST ['prod_entry_mode']);
1095 
1096  unset($_POST['qty']);
1097  unset($_POST['type']);
1098  unset($_POST['remise_percent']);
1099  unset($_POST['pu']);
1100  unset($_POST['price_ht']);
1101  unset($_POST['multicurrency_price_ht']);
1102  unset($_POST['price_ttc']);
1103  unset($_POST['fourn_ref']);
1104  unset($_POST['tva_tx']);
1105  unset($_POST['label']);
1106  unset($localtax1_tx);
1107  unset($localtax2_tx);
1108  unset($_POST['np_marginRate']);
1109  unset($_POST['np_markRate']);
1110  unset($_POST['dp_desc']);
1111  unset($_POST['idprodfournprice']);
1112  unset($_POST['units']);
1113 
1114  unset($_POST['date_starthour']);
1115  unset($_POST['date_startmin']);
1116  unset($_POST['date_startsec']);
1117  unset($_POST['date_startday']);
1118  unset($_POST['date_startmonth']);
1119  unset($_POST['date_startyear']);
1120  unset($_POST['date_endhour']);
1121  unset($_POST['date_endmin']);
1122  unset($_POST['date_endsec']);
1123  unset($_POST['date_endday']);
1124  unset($_POST['date_endmonth']);
1125  unset($_POST['date_endyear']);
1126  }
1127  else
1128  {
1129  $db->rollback();
1130  setEventMessages($object->error, $object->errors, 'errors');
1131  }
1132 
1133  $action = '';
1134  }
1135 
1136  elseif ($action == 'classin' && $user->rights->fournisseur->facture->creer)
1137  {
1138  $object->fetch($id);
1139  $result=$object->setProject($projectid);
1140  }
1141 
1142 
1143  // Set invoice to draft status
1144  elseif ($action == 'confirm_edit' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer)
1145  {
1146  $object->fetch($id);
1147 
1148  $totalpaye = $object->getSommePaiement();
1149  $resteapayer = $object->total_ttc - $totalpaye;
1150 
1151  // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
1152  //$ventilExportCompta = $object->getVentilExportCompta();
1153 
1154  // On verifie si aucun paiement n'a ete effectue
1155  if ($resteapayer == $object->total_ttc && $object->paye == 0 && $ventilExportCompta == 0)
1156  {
1157  $idwarehouse = GETPOST('idwarehouse');
1158 
1159  $object->fetch_thirdparty();
1160 
1161  $qualified_for_stock_change=0;
1162  if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
1163  {
1164  $qualified_for_stock_change=$object->hasProductsOrServices(2);
1165  }
1166  else
1167  {
1168  $qualified_for_stock_change=$object->hasProductsOrServices(1);
1169  }
1170 
1171  // Check parameters
1172  if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change)
1173  {
1174  $langs->load("stocks");
1175  if (! $idwarehouse || $idwarehouse == -1)
1176  {
1177  $error++;
1178  setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
1179  $action='';
1180  }
1181  }
1182 
1183  $object->set_draft($user, $idwarehouse);
1184 
1185  // Define output language
1186  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
1187  {
1188  $outputlangs = $langs;
1189  $newlang = '';
1190  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
1191  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
1192  if (! empty($newlang)) {
1193  $outputlangs = new Translate("", $conf);
1194  $outputlangs->setDefaultLang($newlang);
1195  }
1196  $model=$object->modelpdf;
1197  $ret = $object->fetch($id); // Reload to get new records
1198 
1199  $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1200  if ($result < 0) dol_print_error($db,$result);
1201  }
1202 
1203  $action='';
1204  }
1205  }
1206 
1207  // Set invoice to validated/unpaid status
1208  elseif ($action == 'reopen' && $user->rights->fournisseur->facture->creer)
1209  {
1210  $result = $object->fetch($id);
1211  if ($object->statut == FactureFournisseur::STATUS_CLOSED
1212  || ($object->statut == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced'))
1213  {
1214  $result = $object->set_unpaid($user);
1215  if ($result > 0)
1216  {
1217  header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id);
1218  exit;
1219  }
1220  else
1221  {
1222  setEventMessages($object->error, $object->errors, 'errors');
1223  }
1224  }
1225  }
1226 
1227  // Actions when printing a doc from card
1228  include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
1229 
1230  // Actions to send emails
1231  $trigger_name='BILL_SUPPLIER_SENTBYMAIL';
1232  $paramname='id';
1233  $autocopy='MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO';
1234  $trackid='sin'.$object->id;
1235  include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
1236 
1237  // Actions to build doc
1238  $upload_dir = $conf->fournisseur->facture->dir_output;
1239  $permissioncreate = $user->rights->fournisseur->facture->creer;
1240  include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
1241 
1242  // Make calculation according to calculationrule
1243  if ($action == 'calculate')
1244  {
1245  $calculationrule=GETPOST('calculationrule');
1246 
1247  $object->fetch($id);
1248  $object->fetch_thirdparty();
1249  $result=$object->update_price(0, (($calculationrule=='totalofround')?'0':'1'), 0, $object->thirdparty);
1250  if ($result <= 0)
1251  {
1252  dol_print_error($db,$result);
1253  exit;
1254  }
1255  }
1256  if ($action == 'update_extras')
1257  {
1258  // Fill array 'array_options' with data from add form
1259  $extralabels=$extrafields->fetch_name_optionals_label($object->table_element);
1260  $ret = $extrafields->setOptionalsFromPost($extralabels,$object,GETPOST('attribute'));
1261  if ($ret < 0) $error++;
1262 
1263  if (!$error)
1264  {
1265  // Actions on extra fields (by external module or standard code)
1266  // TODO le hook fait double emploi avec le trigger !!
1267  $hookmanager->initHooks(array('supplierinvoicedao'));
1268  $parameters=array('id'=>$object->id);
1269 
1270  $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
1271 
1272  if (empty($reshook))
1273  {
1274  if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
1275  {
1276 
1277  $result=$object->insertExtraFields();
1278 
1279  if ($result < 0)
1280  {
1281  $error++;
1282  }
1283 
1284  }
1285  }
1286  else if ($reshook < 0) $error++;
1287  }
1288  else
1289  {
1290  $action = 'edit_extras';
1291  }
1292  }
1293 
1294  if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->facture->creer)
1295  {
1296  if ($action == 'addcontact')
1297  {
1298  $result = $object->fetch($id);
1299 
1300  if ($result > 0 && $id > 0)
1301  {
1302  $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
1303  $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]);
1304  }
1305 
1306  if ($result >= 0)
1307  {
1308  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1309  exit;
1310  }
1311  else
1312  {
1313  if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1314  {
1315  $langs->load("errors");
1316  setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
1317  }
1318  else
1319  {
1320  setEventMessages($object->error, $object->errors, 'errors');
1321  }
1322  }
1323  }
1324 
1325  // bascule du statut d'un contact
1326  else if ($action == 'swapstatut')
1327  {
1328  if ($object->fetch($id))
1329  {
1330  $result=$object->swapContactStatus(GETPOST('ligne'));
1331  }
1332  else
1333  {
1334  dol_print_error($db);
1335  }
1336  }
1337 
1338  // Efface un contact
1339  else if ($action == 'deletecontact')
1340  {
1341  $object->fetch($id);
1342  $result = $object->delete_contact($_GET["lineid"]);
1343 
1344  if ($result >= 0)
1345  {
1346  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1347  exit;
1348  }
1349  else {
1350  dol_print_error($db);
1351  }
1352  }
1353  }
1354 }
1355 
1356 
1357 /*
1358  * View
1359  */
1360 
1361 $form = new Form($db);
1362 $formfile = new FormFile($db);
1363 $bankaccountstatic=new Account($db);
1364 $paymentstatic=new PaiementFourn($db);
1365 if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
1366 
1367 $now = dol_now();
1368 
1369 $title = $langs->trans('SupplierInvoice') . " - " . $langs->trans('Card');
1370 $helpurl = "EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Módulo_Facturas_de_proveedores";
1371 llxHeader('', $title, $helpurl);
1372 
1373 // Mode creation
1374 if ($action == 'create')
1375 {
1376  $facturestatic = new FactureFournisseur($db);
1377  $extralabels = $extrafields->fetch_name_optionals_label($facturestatic->table_element);
1378 
1379  print load_fiche_titre($langs->trans('NewBill'));
1380 
1382 
1383  $currency_code = $conf->currency;
1384 
1385  $societe='';
1386  if (GETPOST('socid') > 0)
1387  {
1388  $societe=new Societe($db);
1389  $societe->fetch(GETPOST('socid','int'));
1390  if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) $currency_code = $societe->multicurrency_code;
1391  }
1392 
1393  if (! empty($origin) && ! empty($originid))
1394  {
1395  // Parse element/subelement (ex: project_task)
1396  $element = $subelement = $origin;
1397 
1398  if ($element == 'project')
1399  {
1400  $projectid = $originid;
1401  $element = 'projet';
1402  }
1403  else if (in_array($element,array('order_supplier')))
1404  {
1405  // For compatibility
1406  if ($element == 'order') {
1407  $element = $subelement = 'commande';
1408  }
1409  if ($element == 'propal') {
1410  $element = 'comm/propal'; $subelement = 'propal';
1411  }
1412  if ($element == 'contract') {
1413  $element = $subelement = 'contrat';
1414  }
1415  if ($element == 'order_supplier') {
1416  $element = 'fourn'; $subelement = 'fournisseur.commande';
1417  }
1418 
1419  require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
1420  $classname = ucfirst($subelement);
1421  if ($classname == 'Fournisseur.commande') $classname='CommandeFournisseur';
1422  $objectsrc = new $classname($db);
1423  $objectsrc->fetch($originid);
1424  $objectsrc->fetch_thirdparty();
1425 
1426  $projectid = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:'');
1427  //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:'');
1428 
1429  $soc = $objectsrc->thirdparty;
1430  $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:1));
1431  $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0));
1432  $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0));
1433  $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0));
1434  $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0));
1435  $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:'';
1436 
1437  if (!empty($conf->multicurrency->enabled))
1438  {
1439  if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code;
1440  if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx;
1441  }
1442 
1443  $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']);
1444  $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp);
1445  $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']);
1446  $datedue=($datetmp==''?-1:$datetmp);
1447 
1448  // Replicate extrafields
1449  $objectsrc->fetch_optionals($originid);
1450  $object->array_options = $objectsrc->array_options;
1451 
1452  }
1453  }
1454  else
1455  {
1456  $cond_reglement_id = $societe->cond_reglement_supplier_id;
1457  $mode_reglement_id = $societe->mode_reglement_supplier_id;
1458  $fk_account = $societe->fk_account;
1459  $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']);
1460  $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp);
1461  $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']);
1462  $datedue=($datetmp==''?-1:$datetmp);
1463 
1464  if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code;
1465  }
1466 
1467  print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">';
1468  print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1469  print '<input type="hidden" name="action" value="add">';
1470  if ($societe->id > 0) print '<input type="hidden" name="socid" value="' . $societe->id . '">' . "\n";
1471  print '<input type="hidden" name="origin" value="'.$origin.'">';
1472  print '<input type="hidden" name="originid" value="'.$originid.'">';
1473  if (!empty($currency_tx)) print '<input type="hidden" name="originmulticurrency_tx" value="' . $currency_tx . '">';
1474 
1475  dol_fiche_head();
1476 
1477  print '<table class="border" width="100%">';
1478 
1479  // Ref
1480  print '<tr><td class="titlefieldcreate">'.$langs->trans('Ref').'</td><td>'.$langs->trans('Draft').'</td></tr>';
1481 
1482  // Third party
1483  print '<tr><td class="fieldrequired">'.$langs->trans('Supplier').'</td>';
1484  print '<td>';
1485 
1486  if ($societe->id > 0)
1487  {
1488  print $societe->getNomUrl(1);
1489  print '<input type="hidden" name="socid" value="'.$societe->id.'">';
1490  }
1491  else
1492  {
1493  print $form->select_company($societe->id, 'socid', 's.fournisseur = 1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300');
1494  // reload page to retrieve supplier informations
1495  if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE))
1496  {
1497  print '<script type="text/javascript">
1498  $(document).ready(function() {
1499  $("#socid").change(function() {
1500  var socid = $(this).val();
1501  // reload page
1502  window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid;
1503  });
1504  });
1505  </script>';
1506  }
1507  print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&client=0&fournisseur=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'">'.$langs->trans("AddThirdParty").'</a>';
1508  }
1509  print '</td></tr>';
1510 
1511  // Ref supplier
1512  print '<tr><td class="fieldrequired">'.$langs->trans('RefSupplier').'</td><td><input name="ref_supplier" value="'.(isset($_POST['ref_supplier'])?$_POST['ref_supplier']:'').'" type="text"></td>';
1513  print '</tr>';
1514 
1515  // Type invoice
1516  $facids = $facturestatic->list_replacable_supplier_invoices($societe->id);
1517  if ($facids < 0) {
1518  dol_print_error($db, $facturestatic);
1519  exit();
1520  }
1521  $options = "";
1522  foreach ($facids as $facparam)
1523  {
1524  $options .= '<option value="' . $facparam ['id'] . '"';
1525  if ($facparam ['id'] == $_POST['fac_replacement'])
1526  $options .= ' selected';
1527  $options .= '>' . $facparam ['ref'];
1528  $options .= ' (' . $facturestatic->LibStatut(0, $facparam ['status']) . ')';
1529  $options .= '</option>';
1530  }
1531 
1532  // Show link for credit note
1533  $facids=$facturestatic->list_qualified_avoir_supplier_invoices($societe->id);
1534  if ($facids < 0)
1535  {
1536  dol_print_error($db,$facturestatic);
1537  exit;
1538  }
1539  $optionsav = "";
1540  $newinvoice_static = new FactureFournisseur($db);
1541  foreach ($facids as $key => $valarray)
1542  {
1543  $newinvoice_static->id = $key;
1544  $newinvoice_static->ref = $valarray ['ref'];
1545  $newinvoice_static->statut = $valarray ['status'];
1546  $newinvoice_static->type = $valarray ['type'];
1547  $newinvoice_static->paye = $valarray ['paye'];
1548 
1549  $optionsav .= '<option value="' . $key . '"';
1550  if ($key == GETPOST('fac_avoir','int'))
1551  $optionsav .= ' selected';
1552  $optionsav .= '>';
1553  $optionsav .= $newinvoice_static->ref;
1554  $optionsav .= ' (' . $newinvoice_static->getLibStatut(1, $valarray ['paymentornot']) . ')';
1555  $optionsav .= '</option>';
1556  }
1557 
1558  print '<tr><td class="tdtop fieldrequired">'.$langs->trans('Type').'</td><td>';
1559 
1560  print '<div class="tagtable">' . "\n";
1561 
1562  // Standard invoice
1563  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
1564  $tmp='<input type="radio" id="radio_standard" name="type" value="0"' . (GETPOST('type') == 0 ? ' checked' : '') . '> ';
1565  $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3);
1566  print $desc;
1567  print '</div></div>';
1568 
1569  /* Not yet supported
1570  if ((empty($origin)) || ((($origin == 'propal') || ($origin == 'commande')) && (! empty($originid))))
1571  {
1572  // Deposit
1573  if (empty($conf->global->INVOICE_DISABLE_DEPOSIT))
1574  {
1575  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
1576  $tmp='<input type="radio" id="radio_deposit" name="type" value="3"' . (GETPOST('type') == 3 ? ' checked' : '') . '> ';
1577  print '<script type="text/javascript" language="javascript">
1578  jQuery(document).ready(function() {
1579  jQuery("#typedeposit, #valuedeposit").click(function() {
1580  jQuery("#radio_deposit").prop("checked", true);
1581  });
1582  });
1583  </script>';
1584 
1585  $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceDeposit"), $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3);
1586  print '<table class="nobordernopadding"><tr><td>';
1587  print $desc;
1588  print '</td>';
1589  if (($origin == 'propal') || ($origin == 'commande'))
1590  {
1591  print '<td class="nowrap" style="padding-left: 5px">';
1592  $arraylist = array('amount' => 'FixAmount','variable' => 'VarAmount');
1593  print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit'), 0, 0, 0, '', 1);
1594  print '</td>';
1595  print '<td class="nowrap" style="padding-left: 5px">' . $langs->trans('Value') . ':<input type="text" id="valuedeposit" name="valuedeposit" size="3" value="' . GETPOST('valuedeposit', 'int') . '"/>';
1596  }
1597  print '</td></tr></table>';
1598 
1599  print '</div></div>';
1600  }
1601  }
1602  */
1603 
1604  /* Not yet supported for supplier
1605  if ($societe->id > 0)
1606  {
1607  // Replacement
1608  if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT))
1609  {
1610  print '<!-- replacement line -->';
1611  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
1612  $tmp='<input type="radio" name="type" id="radio_replacement" value="1"' . (GETPOST('type') == 1 ? ' checked' : '');
1613  if (! $options) $tmp.=' disabled';
1614  $tmp.='> ';
1615  print '<script type="text/javascript" language="javascript">
1616  jQuery(document).ready(function() {
1617  jQuery("#fac_replacement").change(function() {
1618  jQuery("#radio_replacement").prop("checked", true);
1619  });
1620  });
1621  </script>';
1622  $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' ';
1623  $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
1624  if (! $options)
1625  $text .= ' disabled';
1626  $text .= '>';
1627  if ($options) {
1628  $text .= '<option value="-1">&nbsp;</option>';
1629  $text .= $options;
1630  } else {
1631  $text .= '<option value="-1">' . $langs->trans("NoReplacableInvoice") . '</option>';
1632  }
1633  $text .= '</select>';
1634  $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
1635  print $desc;
1636  print '</div></div>';
1637  }
1638  }
1639  else
1640  {
1641  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
1642  $tmp='<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
1643  $text = $tmp.$langs->trans("InvoiceReplacement") . ' ';
1644  $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') ';
1645  $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
1646  print $desc;
1647  print '</div></div>';
1648  }
1649  */
1650 
1651  if (empty($origin))
1652  {
1653  if ($conf->global->MAIN_FEATURES_LEVEL > 0) // Need to fix reports of standard accounting module to manage supplier credit note
1654  {
1655  if ($societe->id > 0)
1656  {
1657  // Credit note
1658  if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE))
1659  {
1660  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
1661  $tmp='<input type="radio" id="radio_creditnote" name="type" value="2"' . (GETPOST('type') == 2 ? ' checked' : '');
1662  if (! $optionsav) $tmp.=' disabled';
1663  $tmp.= '> ';
1664  // Show credit note options only if we checked credit note
1665  print '<script type="text/javascript" language="javascript">
1666  jQuery(document).ready(function() {
1667  if (! jQuery("#radio_creditnote").is(":checked"))
1668  {
1669  jQuery("#credit_note_options").hide();
1670  }
1671  jQuery("#radio_creditnote").click(function() {
1672  jQuery("#credit_note_options").show();
1673  });
1674  jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() {
1675  jQuery("#credit_note_options").hide();
1676  });
1677  });
1678  </script>';
1679  $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk") . ' ';
1680  // $text.='<input type="text" value="">';
1681  $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
1682  if (! $optionsav)
1683  $text .= ' disabled';
1684  $text .= '>';
1685  if ($optionsav) {
1686  $text .= '<option value="-1"></option>';
1687  $text .= $optionsav;
1688  } else {
1689  $text .= '<option value="-1">' . $langs->trans("NoInvoiceToCorrect") . '</option>';
1690  }
1691  $text .= '</select>';
1692  $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
1693  print $desc;
1694 
1695  print '<div id="credit_note_options" class="clearboth">';
1696  print '&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="if($(this).is(\':checked\') ) { $(\'#radio_creditnote\').prop(\'checked\', true); $(\'#invoiceAvoirWithPaymentRestAmount\').removeAttr(\'checked\'); }" '.(GETPOST('invoiceAvoirWithLines','int')>0 ? 'checked':'').' /> <label for="invoiceAvoirWithLines">'.$langs->trans('invoiceAvoirWithLines')."</label>";
1697  print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="if($(this).is(\':checked\') ) { $(\'#radio_creditnote\').prop(\'checked\', true); $(\'#invoiceAvoirWithLines\').removeAttr(\'checked\'); }" '.(GETPOST('invoiceAvoirWithPaymentRestAmount','int')>0 ? 'checked':'').' /> <label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label>";
1698  print '</div>';
1699 
1700  print '</div></div>';
1701  }
1702  }
1703  else
1704  {
1705  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
1706  $tmp='<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
1707  $text = $tmp.$langs->trans("InvoiceAvoir") . ' ';
1708  $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') ';
1709  $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
1710  print $desc;
1711  print '</div></div>' . "\n";
1712  }
1713  }
1714  }
1715 
1716  print '</div>';
1717 
1718  print '</td></tr>';
1719 
1720  if ($socid > 0)
1721  {
1722  // Discounts for third party
1723  print '<tr><td>' . $langs->trans('Discounts') . '</td><td>';
1724  if ($soc->remise_percent)
1725  print $langs->trans("CompanyHasRelativeDiscount", '<a href="' . DOL_URL_ROOT . '/comm/remise.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $soc->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">' . $soc->remise_percent . '</a>');
1726  else
1727  print $langs->trans("CompanyHasNoRelativeDiscount");
1728  print ' <a href="' . DOL_URL_ROOT . '/comm/remise.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $soc->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">(' . $langs->trans("EditRelativeDiscount") . ')</a>';
1729  print '. ';
1730  print '<br>';
1731  if ($absolute_discount)
1732  print $langs->trans("CompanyHasAbsoluteDiscount", '<a href="' . DOL_URL_ROOT . '/comm/remx.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $soc->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">' . price($absolute_discount) . '</a>', $langs->trans("Currency" . $conf->currency));
1733  else
1734  print $langs->trans("CompanyHasNoAbsoluteDiscount");
1735  print ' <a href="' . DOL_URL_ROOT . '/comm/remx.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?socid=' . $soc->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid')) . '">(' . $langs->trans("EditGlobalDiscounts") . ')</a>';
1736  print '.';
1737  print '</td></tr>';
1738  }
1739 
1740  // Label
1741  print '<tr><td>'.$langs->trans('Label').'</td><td><input class="minwidth200" name="label" value="'.dol_escape_htmltag(GETPOST('label')).'" type="text"></td></tr>';
1742 
1743  // Date invoice
1744  print '<tr><td class="fieldrequired">'.$langs->trans('DateInvoice').'</td><td>';
1745  $form->select_date($dateinvoice,'','','','',"add",1,1);
1746  print '</td></tr>';
1747 
1748  // Due date
1749  print '<tr><td>'.$langs->trans('DateMaxPayment').'</td><td>';
1750  $form->select_date($datedue,'ech','','','',"add",1,1);
1751  print '</td></tr>';
1752 
1753  // Payment term
1754  print '<tr><td class="nowrap">'.$langs->trans('PaymentConditionsShort').'</td><td>';
1755  $form->select_conditions_paiements(isset($_POST['cond_reglement_id'])?$_POST['cond_reglement_id']:$cond_reglement_id, 'cond_reglement_id');
1756  print '</td></tr>';
1757 
1758  // Payment mode
1759  print '<tr><td>'.$langs->trans('PaymentMode').'</td><td>';
1760  $form->select_types_paiements(isset($_POST['mode_reglement_id'])?$_POST['mode_reglement_id']:$mode_reglement_id, 'mode_reglement_id', 'DBIT');
1761  print '</td></tr>';
1762 
1763  // Bank Account
1764  print '<tr><td>'.$langs->trans('BankAccount').'</td><td>';
1765  $form->select_comptes($fk_account, 'fk_account', 0, '', 1);
1766  print '</td></tr>';
1767 
1768  // Multicurrency
1769  if (! empty($conf->multicurrency->enabled))
1770  {
1771  print '<tr>';
1772  print '<td>'.fieldLabel('Currency','multicurrency_code').'</td>';
1773  print '<td class="maxwidthonsmartphone">';
1774  print $form->selectMultiCurrency($currency_code, 'multicurrency_code');
1775  print '</td></tr>';
1776  }
1777 
1778  // Project
1779  if (! empty($conf->projet->enabled))
1780  {
1781  $formproject = new FormProjets($db);
1782 
1783  $langs->load('projects');
1784  print '<tr><td>' . $langs->trans('Project') . '</td><td>';
1785  $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$societe->id:-1), $projectid, 'projectid', 0, 0, 1, 1);
1786  print '</td></tr>';
1787  }
1788 
1789  // Incoterms
1790  if (!empty($conf->incoterm->enabled))
1791  {
1792  print '<tr>';
1793  print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), $objectsrc->libelle_incoterms, 1).'</label></td>';
1794  print '<td colspan="3" class="maxwidthonsmartphone">';
1795  print $form->select_incoterms((!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), (!empty($objectsrc->location_incoterms)?$objectsrc->location_incoterms:''));
1796  print '</td></tr>';
1797  }
1798 
1799  // Public note
1800  print '<tr><td>'.$langs->trans('NotePublic').'</td>';
1801  print '<td>';
1802  $note_public = $object->getDefaultCreateValueFor('note_public');
1803  $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
1804  print $doleditor->Create(1);
1805  print '</td>';
1806  // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
1807  print '</tr>';
1808 
1809  // Private note
1810  print '<tr><td>'.$langs->trans('NotePrivate').'</td>';
1811  print '<td>';
1812  $note_private = $object->getDefaultCreateValueFor('note_private');
1813  $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
1814  print $doleditor->Create(1);
1815  print '</td>';
1816  // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
1817  print '</tr>';
1818 
1819  if (empty($reshook) && ! empty($extrafields->attribute_label))
1820  {
1821  print $object->showOptionals($extrafields, 'edit');
1822  }
1823 
1824  if (is_object($objectsrc))
1825  {
1826  print "\n<!-- ".$classname." info -->";
1827  print "\n";
1828  print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n";
1829  print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n";
1830  print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n";
1831  print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
1832  print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
1833 
1834  $txt=$langs->trans($classname);
1835  if ($classname=='CommandeFournisseur') {
1836  $langs->load('orders');
1837  $txt=$langs->trans("SupplierOrder");
1838  }
1839  print '<tr><td>'.$txt.'</td><td>'.$objectsrc->getNomUrl(1);
1840  // We check if Origin document (id and type is known) has already at least one invoice attached to it
1841  $objectsrc->fetchObjectLinked($originid,$origin,'','invoice_supplier');
1842  $cntinvoice=count($objectsrc->linkedObjects['invoice_supplier']);
1843  if ($cntinvoice>=1)
1844  {
1845  setEventMessages('WarningBillExist', null, 'warnings');
1846  echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['invoice_supplier'])->getNomUrl(1).')';
1847  }
1848  echo '</td></tr>';
1849  print '<tr><td>'.$langs->trans('TotalHT').'</td><td>'.price($objectsrc->total_ht).'</td></tr>';
1850  print '<tr><td>'.$langs->trans('TotalVAT').'</td><td>'.price($objectsrc->total_tva)."</td></tr>";
1851  if ($mysoc->localtax1_assuj=="1" || $object->total_localtax1 != 0) //Localtax1
1852  {
1853  print '<tr><td>'.$langs->transcountry("AmountLT1",$mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1)."</td></tr>";
1854  }
1855 
1856  if ($mysoc->localtax2_assuj=="1" || $object->total_localtax2 != 0) //Localtax2
1857  {
1858  print '<tr><td>'.$langs->transcountry("AmountLT2",$mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2)."</td></tr>";
1859  }
1860  print '<tr><td>'.$langs->trans('TotalTTC').'</td><td>'.price($objectsrc->total_ttc)."</td></tr>";
1861 
1862  if (!empty($conf->multicurrency->enabled))
1863  {
1864  print '<tr><td>' . $langs->trans('MulticurrencyTotalHT') . '</td><td>' . price($objectsrc->multicurrency_total_ht) . '</td></tr>';
1865  print '<tr><td>' . $langs->trans('MulticurrencyTotalVAT') . '</td><td>' . price($objectsrc->multicurrency_total_tva) . "</td></tr>";
1866  print '<tr><td>' . $langs->trans('MulticurrencyTotalTTC') . '</td><td>' . price($objectsrc->multicurrency_total_ttc) . "</td></tr>";
1867  }
1868  }
1869 
1870  // Other options
1871  $parameters=array();
1872  $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
1873  print $hookmanager->resPrint;
1874 
1875  // Bouton "Create Draft"
1876  print "</table>\n";
1877 
1878  dol_fiche_end();
1879 
1880  print '<div class="center">';
1881  print '<input type="submit" class="button" name="bouton" value="'.$langs->trans('CreateDraft').'">';
1882  print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1883  print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
1884  print '</div>';
1885 
1886  print "</form>\n";
1887 
1888 
1889  // Show origin lines
1890  if (is_object($objectsrc))
1891  {
1892  print '<br>';
1893 
1894  $title=$langs->trans('ProductsAndServices');
1896 
1897  print '<table class="noborder" width="100%">';
1898 
1899  $objectsrc->printOriginLinesList();
1900 
1901  print '</table>';
1902  }
1903 }
1904 else
1905 {
1906  if ($id > 0 || ! empty($ref))
1907  {
1908  /* *************************************************************************** */
1909  /* */
1910  /* Fiche en mode visu ou edition */
1911  /* */
1912  /* *************************************************************************** */
1913 
1914  $now=dol_now();
1915 
1916  $productstatic = new Product($db);
1917 
1918  $object->fetch($id,$ref);
1919  $result=$object->fetch_thirdparty();
1920  if ($result < 0) dol_print_error($db);
1921 
1922  $societe = new Fournisseur($db);
1923  $result=$societe->fetch($object->socid);
1924  if ($result < 0) dol_print_error($db);
1925 
1926  // fetch optionals attributes and labels
1927  $extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
1928 
1929  $totalpaye = $object->getSommePaiement();
1930  $totalcreditnotes = $object->getSumCreditNotesUsed();
1931  $totaldeposits = $object->getSumDepositsUsed();
1932  // print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
1933  // selleruserrevenuestamp=".$selleruserevenustamp;
1934 
1935  // We can also use bcadd to avoid pb with floating points
1936  // For example print 239.2 - 229.3 - 9.9; does not return 0.
1937  // $resteapayer=bcadd($object->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
1938  // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
1939  $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
1940 
1941  if ($object->paye)
1942  {
1943  $resteapayer = 0;
1944  }
1945  $resteapayeraffiche = $resteapayer;
1946 
1947 
1948  /*
1949  * View card
1950  */
1951  $head = facturefourn_prepare_head($object);
1952  $titre=$langs->trans('SupplierInvoice');
1953 
1954  dol_fiche_head($head, 'card', $titre, -1, 'bill');
1955 
1956  // Clone confirmation
1957  if ($action == 'clone')
1958  {
1959  // Create an array for form
1960  $formquestion=array(
1961  //'text' => $langs->trans("ConfirmClone"),
1962  //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1)
1963  );
1964  // Paiement incomplet. On demande si motif = escompte ou autre
1965  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneInvoice'),$langs->trans('ConfirmCloneInvoice',$object->ref),'confirm_clone',$formquestion,'yes', 1);
1966  }
1967 
1968  // Confirmation de la validation
1969  if ($action == 'valid')
1970  {
1971  // on verifie si l'objet est en numerotation provisoire
1972  $objectref = substr($object->ref, 1, 4);
1973  if ($objectref == 'PROV')
1974  {
1975  $savdate=$object->date;
1976  $numref = $object->getNextNumRef($societe);
1977  }
1978  else
1979  {
1980  $numref = $object->ref;
1981  }
1982 
1983  $text=$langs->trans('ConfirmValidateBill',$numref);
1984  /*if (! empty($conf->notification->enabled))
1985  {
1986  require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php';
1987  $notify=new Notify($db);
1988  $text.='<br>';
1989  $text.=$notify->confirmMessage('BILL_SUPPLIER_VALIDATE',$object->socid, $object);
1990  }*/
1991  $formquestion=array();
1992 
1993  $qualified_for_stock_change=0;
1994  if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
1995  {
1996  $qualified_for_stock_change=$object->hasProductsOrServices(2);
1997  }
1998  else
1999  {
2000  $qualified_for_stock_change=$object->hasProductsOrServices(1);
2001  }
2002 
2003  if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change)
2004  {
2005  $langs->load("stocks");
2006  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
2007  $formproduct=new FormProduct($db);
2008  $warehouse = new Entrepot($db);
2009  $warehouse_array = $warehouse->list_array();
2010  if (count($warehouse_array) == 1) {
2011  $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
2012  $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="' . key($warehouse_array) . '">';
2013  } else {
2014  $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
2015  $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1);
2016  }
2017  $formquestion = array(
2018  array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value)
2019  );
2020  }
2021 
2022  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1);
2023 
2024  }
2025 
2026  // Confirmation edit (back to draft)
2027  if ($action == 'edit')
2028  {
2029  $formquestion = array();
2030 
2031  $qualified_for_stock_change = 0;
2032  if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
2033  {
2034  $qualified_for_stock_change = $object->hasProductsOrServices(2);
2035  }
2036  else
2037  {
2038  $qualified_for_stock_change = $object->hasProductsOrServices(1);
2039  }
2040  if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change)
2041  {
2042  $langs->load("stocks");
2043  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
2044  $formproduct = new FormProduct($db);
2045  $warehouse = new Entrepot($db);
2046  $warehouse_array = $warehouse->list_array();
2047  if (count($warehouse_array) == 1) {
2048  $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
2049  $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="' . key($warehouse_array) . '">';
2050  } else {
2051  $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
2052  $value = $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1);
2053  }
2054  $formquestion = array(
2055  array('type' => 'other','name' => 'idwarehouse','label' => $label,'value' => $value)
2056  );
2057  }
2058  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1);
2059 
2060  }
2061 
2062  // Confirmation set paid
2063  if ($action == 'paid')
2064  {
2065  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', 0, 1);
2066 
2067  }
2068 
2069  // Confirmation de la suppression de la facture fournisseur
2070  if ($action == 'delete')
2071  {
2072  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', '', 0, 1);
2073 
2074  }
2075  if ($action == 'deletepaiement')
2076  {
2077  $payment_id = GETPOST('paiement_id');
2078  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 0, 1);
2079 
2080  }
2081 
2082  // Confirmation to delete line
2083  if ($action == 'ask_deleteline')
2084  {
2085  $formconfirm=$form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1);
2086  }
2087 
2088  if (!$formconfirm)
2089  {
2090  $parameters=array('lineid'=>$lineid);
2091  $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2092  if (empty($reshook)) $formconfirm.=$hookmanager->resPrint;
2093  elseif ($reshook > 0) $formconfirm=$hookmanager->resPrint;
2094  }
2095 
2096  // Print form confirm
2097  print $formconfirm;
2098 
2099 
2100  // Supplier invoice card
2101  $linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?restore_lastsearch_values=1'.(! empty($socid)?'&socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
2102 
2103  $morehtmlref='<div class="refidno">';
2104  // Ref supplier
2105  $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->facture->creer, 'string', '', 0, 1);
2106  $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->facture->creer, 'string', '', null, null, '', 1);
2107  // Thirdparty
2108  $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
2109  if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'">'.$langs->trans("OtherBills").'</a>)';
2110  // Project
2111  if (! empty($conf->projet->enabled))
2112  {
2113  $langs->load("projects");
2114  $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
2115  if ($user->rights->fournisseur->facture->creer)
2116  {
2117  if ($action != 'classify')
2118  $morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
2119  if ($action == 'classify') {
2120  //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
2121  $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
2122  $morehtmlref.='<input type="hidden" name="action" value="classin">';
2123  $morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2124  $morehtmlref.=$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$object->socid:-1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
2125  $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
2126  $morehtmlref.='</form>';
2127  } else {
2128  $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
2129  }
2130  } else {
2131  if (! empty($object->fk_project)) {
2132  $proj = new Project($db);
2133  $proj->fetch($object->fk_project);
2134  $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
2135  $morehtmlref.=$proj->ref;
2136  $morehtmlref.='</a>';
2137  } else {
2138  $morehtmlref.='';
2139  }
2140  }
2141  }
2142  $morehtmlref.='</div>';
2143 
2144  $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
2145 
2146  dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
2147 
2148  print '<div class="fichecenter">';
2149  print '<div class="fichehalfleft">';
2150  print '<div class="underbanner clearboth"></div>';
2151 
2152  print '<table class="border" width="100%">';
2153 
2154  // Type
2155  print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td>';
2156  print $object->getLibType();
2157  if ($object->type == FactureFournisseur::TYPE_REPLACEMENT)
2158  {
2159  $facreplaced=new FactureFournisseur($db);
2160  $facreplaced->fetch($object->fk_facture_source);
2161  print ' ('.$langs->transnoentities("ReplaceInvoice",$facreplaced->getNomUrl(1)).')';
2162  }
2163  if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE)
2164  {
2165  $facusing=new FactureFournisseur($db);
2166  $facusing->fetch($object->fk_facture_source);
2167  print ' ('.$langs->transnoentities("CorrectInvoice",$facusing->getNomUrl(1)).')';
2168  }
2169 
2170  $facidavoir=$object->getListIdAvoirFromInvoice();
2171  if (count($facidavoir) > 0)
2172  {
2173  print ' ('.$langs->transnoentities("InvoiceHasAvoir");
2174  $i=0;
2175  foreach($facidavoir as $id)
2176  {
2177  if ($i==0) print ' ';
2178  else print ',';
2179  $facavoir=new FactureFournisseur($db);
2180  $facavoir->fetch($id);
2181  print $facavoir->getNomUrl(1);
2182  }
2183  print ')';
2184  }
2185  if (isset($facidnext) && $facidnext > 0)
2186  {
2187  $facthatreplace=new FactureFournisseur($db);
2188  $facthatreplace->fetch($facidnext);
2189  print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')';
2190  }
2191  print '</td></tr>';
2192 
2193  // Label
2194  print '<tr>';
2195  print '<td>'.$form->editfieldkey("Label",'label',$object->label,$object,($user->rights->fournisseur->facture->creer)).'</td>';
2196  print '<td>'.$form->editfieldval("Label",'label',$object->label,$object,($user->rights->fournisseur->facture->creer)).'</td>';
2197  print '</tr>';
2198 
2199  $form_permission = $object->statut<FactureFournisseur::STATUS_CLOSED && $user->rights->fournisseur->facture->creer && $object->getSommePaiement() <= 0;
2200 
2201  // Date
2202  print '<tr><td>'.$form->editfieldkey("DateInvoice",'datef',$object->datep,$object,$form_permission,'datepicker').'</td><td colspan="3">';
2203  print $form->editfieldval("Date",'datef',$object->datep,$object,$form_permission,'datepicker');
2204  print '</td>';
2205 
2206  // Due date
2207  print '<tr><td>'.$form->editfieldkey("DateMaxPayment",'date_lim_reglement',$object->date_echeance,$object,$form_permission,'datepicker').'</td><td colspan="3">';
2208  print $form->editfieldval("DateMaxPayment",'date_lim_reglement',$object->date_echeance,$object,$form_permission,'datepicker');
2209  if ($action != 'editdate_lim_reglement' && $object->hasDelay()) {
2210  print img_warning($langs->trans('Late'));
2211  }
2212  print '</td>';
2213 
2214  // Conditions de reglement par defaut
2215  $langs->load('bills');
2216  print '<tr><td class="nowrap">';
2217  print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
2218  print $langs->trans('PaymentConditions');
2219  print '<td>';
2220  if ($action != 'editconditions' && $user->rights->fournisseur->facture->creer) {
2221  print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;id='.$object->id.'">'.img_edit($langs->trans('SetConditions'),1).'</a></td>';
2222  }
2223  print '</tr></table>';
2224  print '</td><td colspan="2">';
2225  if ($action == 'editconditions')
2226  {
2227  $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id,'cond_reglement_id');
2228  }
2229  else
2230  {
2231  $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id,'none');
2232  }
2233  print "</td>";
2234  print '</tr>';
2235 
2236  // Mode of payment
2237  $langs->load('bills');
2238  print '<tr><td class="nowrap">';
2239  print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
2240  print $langs->trans('PaymentMode');
2241  print '</td>';
2242  if ($action != 'editmode' && $user->rights->fournisseur->facture->creer) {
2243  print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->trans('SetMode'),1).'</a></td>';
2244  }
2245  print '</tr></table>';
2246  print '</td><td colspan="2">';
2247  if ($action == 'editmode')
2248  {
2249  $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'DBIT');
2250  }
2251  else
2252  {
2253  $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none', 'DBIT');
2254  }
2255  print '</td></tr>';
2256 
2257  // Multicurrency
2258  if (! empty($conf->multicurrency->enabled))
2259  {
2260  // Multicurrency code
2261  print '<tr>';
2262  print '<td>';
2263  print '<table class="nobordernopadding" width="100%"><tr><td>';
2264  print fieldLabel('Currency','multicurrency_code');
2265  print '</td>';
2266  if ($action != 'editmulticurrencycode' && ! empty($object->brouillon))
2267  print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencycode&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
2268  print '</tr></table>';
2269  print '</td><td colspan="3">';
2270  if ($action == 'editmulticurrencycode') {
2271  $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code');
2272  } else {
2273  $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'none');
2274  }
2275  print '</td></tr>';
2276 
2277  // Multicurrency rate
2278  print '<tr>';
2279  print '<td>';
2280  print '<table class="nobordernopadding" width="100%"><tr><td>';
2281  print fieldLabel('CurrencyRate','multicurrency_tx');
2282  print '</td>';
2283  if ($action != 'editmulticurrencyrate' && ! empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency)
2284  print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencyrate&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
2285  print '</tr></table>';
2286  print '</td><td colspan="3">';
2287  if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
2288  if($action == 'actualizemulticurrencyrate') {
2289  list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
2290  }
2291  $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
2292  } else {
2293  $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
2294  if($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
2295  print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
2296  print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
2297  print '</div>';
2298  }
2299  }
2300  print '</td></tr>';
2301  }
2302 
2303  // Bank Account
2304  print '<tr><td class="nowrap">';
2305  print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
2306  print $langs->trans('BankAccount');
2307  print '<td>';
2308  if ($action != 'editbankaccount' && $user->rights->fournisseur->facture->creer)
2309  print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'),1).'</a></td>';
2310  print '</tr></table>';
2311  print '</td><td colspan="3">';
2312  if ($action == 'editbankaccount') {
2313  $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
2314  } else {
2315  $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
2316  }
2317  print "</td>";
2318  print '</tr>';
2319 
2320  // Incoterms
2321  if (!empty($conf->incoterm->enabled))
2322  {
2323  print '<tr><td>';
2324  print '<table width="100%" class="nobordernopadding"><tr><td>';
2325  print $langs->trans('IncotermLabel');
2326  print '<td><td align="right">';
2327  if ($user->rights->fournisseur->facture->creer) print '<a href="'.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id.'&action=editincoterm">'.img_edit().'</a>';
2328  else print '&nbsp;';
2329  print '</td></tr></table>';
2330  print '</td>';
2331  print '<td colspan="3">';
2332  if ($action != 'editincoterm')
2333  {
2334  print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1);
2335  }
2336  else
2337  {
2338  print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id);
2339  }
2340  print '</td></tr>';
2341  }
2342 
2343  // Other attributes
2344  $cols = 2;
2345  include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
2346 
2347  print '</table>';
2348 
2349  print '</div>';
2350  print '<div class="fichehalfright">';
2351  print '<div class="ficheaddleft">';
2352  print '<div class="underbanner clearboth"></div>';
2353 
2354  print '<table class="border centpercent">';
2355 
2356  if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency))
2357  {
2358  // Multicurrency Amount HT
2359  print '<tr><td class="titlefieldmiddle">' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . '</td>';
2360  print '<td class="nowrap">' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
2361  print '</tr>';
2362 
2363  // Multicurrency Amount VAT
2364  print '<tr><td>' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '</td>';
2365  print '<td>' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
2366  print '</tr>';
2367 
2368  // Multicurrency Amount TTC
2369  print '<tr><td height="10">' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . '</td>';
2370  print '<td>' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
2371  print '</tr>';
2372  }
2373 
2374  // Amount
2375  print '<tr><td class="titlefield">'.$langs->trans('AmountHT').'</td><td>'.price($object->total_ht,1,$langs,0,-1,-1,$conf->currency).'</td></tr>';
2376  print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($object->total_tva,1,$langs,0,-1,-1,$conf->currency).'<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
2377  if (GETPOST('calculationrule')) $calculationrule=GETPOST('calculationrule','alpha');
2378  else $calculationrule=(empty($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)?'totalofround':'roundoftotal');
2379  if ($calculationrule == 'totalofround') $calculationrulenum=1;
2380  else $calculationrulenum=2;
2381  $s=$langs->trans("ReCalculate").' ';
2382  $s.='<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=calculate&calculationrule=totalofround">'.$langs->trans("Mode1").'</a>';
2383  $s.=' / ';
2384  $s.='<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=calculate&calculationrule=roundoftotal">'.$langs->trans("Mode2").'</a>';
2385  print $form->textwithtooltip($s, $langs->trans("CalculationRuleDesc",$calculationrulenum).'<br>'.$langs->trans("CalculationRuleDescSupplier"), 2, 1, img_picto('','help'));
2386  print '</div></td></tr>';
2387 
2388  // Amount Local Taxes
2389  //TODO: Place into a function to control showing by country or study better option
2390  if ($societe->localtax1_assuj=="1") //Localtax1
2391  {
2392  print '<tr><td>'.$langs->transcountry("AmountLT1",$societe->country_code).'</td>';
2393  print '<td>'.price($object->total_localtax1,1,$langs,0,-1,-1,$conf->currency).'</td>';
2394  print '</tr>';
2395  }
2396  if ($societe->localtax2_assuj=="1") //Localtax2
2397  {
2398  print '<tr><td>'.$langs->transcountry("AmountLT2",$societe->country_code).'</td>';
2399  print '<td>'.price($object->total_localtax2,1,$langs,0,-1,-1,$conf->currency).'</td>';
2400  print '</tr>';
2401  }
2402  print '<tr><td>'.$langs->trans('AmountTTC').'</td><td colspan="3">'.price($object->total_ttc,1,$langs,0,-1,-1,$conf->currency).'</td></tr>';
2403 
2404  print '</table>';
2405 
2406  /*
2407  * List of payments
2408  */
2409 
2410  $totalpaye = 0;
2411 
2412  $sign = 1;
2413  if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $sign = - 1;
2414 
2415  $nbrows=9; $nbcols=3;
2416  if (! empty($conf->projet->enabled)) $nbrows++;
2417  if (! empty($conf->banque->enabled)) { $nbrows++; $nbcols++; }
2418  if (! empty($conf->incoterm->enabled)) $nbrows++;
2419  if (! empty($conf->multicurrency->enabled)) $nbrows += 5;
2420 
2421  // Local taxes
2422  if ($societe->localtax1_assuj=="1") $nbrows++;
2423  if ($societe->localtax2_assuj=="1") $nbrows++;
2424 
2425  $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement, p.rowid, p.fk_bank,';
2426  $sql.= ' c.id as paiement_type,';
2427  $sql.= ' pf.amount,';
2428  $sql.= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal';
2429  $sql.= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p';
2430  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
2431  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
2432  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN ('.getEntity('c_paiement').')';
2433  $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid';
2434  $sql.= ' WHERE pf.fk_facturefourn = '.$object->id;
2435  $sql.= ' ORDER BY p.datep, p.tms';
2436 
2437  $result = $db->query($sql);
2438  if ($result)
2439  {
2440  $num = $db->num_rows($result);
2441  $i = 0;
2442 
2443  print '<div class="div-table-responsive-no-min">';
2444  print '<table class="noborder paymenttable" width="100%">';
2445  print '<tr class="liste_titre">';
2446  print '<td class="liste_titre">' . ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')) . '</td>';
2447  print '<td>'.$langs->trans('Date').'</td>';
2448  print '<td>'.$langs->trans('Type').'</td>';
2449  if (! empty($conf->banque->enabled)) print '<td align="right">'.$langs->trans('BankAccount').'</td>';
2450  print '<td align="right">'.$langs->trans('Amount').'</td>';
2451  print '<td width="18">&nbsp;</td>';
2452  print '</tr>';
2453 
2454  if ($num > 0)
2455  {
2456  while ($i < $num)
2457  {
2458  $objp = $db->fetch_object($result);
2459 
2460  $paymentstatic->id=$objp->rowid;
2461  $paymentstatic->datepaye=$db->jdate($objp->dp);
2462  $paymentstatic->ref=($objp->ref ? $objp->ref : $objp->rowid);;
2463  $paymentstatic->num_paiement=$objp->num_paiement;
2464  $paymentstatic->payment_code=$objp->payment_code;
2465 
2466  print '<tr class="oddeven">';
2467  print '<td>';
2468  print $paymentstatic->getNomUrl(1);
2469  print '</td>';
2470  print '<td>'.dol_print_date($db->jdate($objp->dp), 'day') . '</td>';
2471  print '<td>';
2472  print $form->form_modes_reglement(null, $objp->paiement_type,'none').' '.$objp->num_paiement;
2473  print '</td>';
2474  if (! empty($conf->banque->enabled))
2475  {
2476  $bankaccountstatic->id=$objp->baid;
2477  $bankaccountstatic->ref=$objp->baref;
2478  $bankaccountstatic->label=$objp->baref;
2479  $bankaccountstatic->number = $objp->banumber;
2480 
2481  if (! empty($conf->accounting->enabled)) {
2482  $bankaccountstatic->account_number = $objp->account_number;
2483 
2484  $accountingjournal = new AccountingJournal($db);
2485  $accountingjournal->fetch($objp->fk_accountancy_journal);
2486  $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0,1,1,'',1);
2487  }
2488 
2489  print '<td align="right">';
2490  if ($objp->baid > 0) print $bankaccountstatic->getNomUrl(1,'transactions');
2491  print '</td>';
2492  }
2493  print '<td align="right">' . price($sign * $objp->amount) . '</td>';
2494  print '<td align="center">';
2495  if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0)
2496  {
2497  print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deletepaiement&paiement_id='.$objp->rowid.'">';
2498  print img_delete();
2499  print '</a>';
2500  }
2501  print '</td>';
2502  print '</tr>';
2503  $totalpaye += $objp->amount;
2504  $i++;
2505  }
2506  }
2507  else
2508  {
2509  print '<tr class="oddeven"><td colspan="'.$nbcols.'" class="opacitymedium">'.$langs->trans("None").'</td><td></td><td></td></tr>';
2510  }
2511 
2512  /*
2513  if ($object->paye == 0)
2514  {
2515  print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans('AlreadyPaid').' :</td><td align="right">'.price($totalpaye).'</td><td></td></tr>';
2516  print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans("Billed").' :</td><td align="right">'.price($object->total_ttc).'</td><td></td></tr>';
2517 
2518  $resteapayer = $object->total_ttc - $totalpaye;
2519 
2520  print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans('RemainderToPay').' :</td>';
2521  print '<td align="right"'.($resteapayer?' class="amountremaintopay"':'').'>'.price($resteapayer).'</td><td></td></tr>';
2522  }
2523  */
2524 
2525  $db->free($result);
2526  }
2527  else
2528  {
2529  dol_print_error($db);
2530  }
2531 
2532  if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE)
2533  {
2534  // Total already paid
2535  print '<tr><td colspan="' . $nbcols . '" align="right">';
2536  if ($object->type != FactureFournisseur::TYPE_DEPOSIT)
2537  print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
2538  else
2539  print $langs->trans('AlreadyPaid');
2540  print ' :</td><td align="right"'.(($totalpaye > 0)?' class="amountalreadypaid"':'').'>' . price($totalpaye) . '</td><td>&nbsp;</td></tr>';
2541 
2542  $resteapayer = $object->total_ttc - $totalpaye;
2543  $resteapayeraffiche = $resteapayer;
2544  $cssforamountpaymentcomplete = 'amountpaymentcomplete';
2545 
2546  // Loop on each credit note or deposit amount applied
2547  $creditnoteamount = 0;
2548  $depositamount = 0;
2549  /*
2550  $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
2551  $sql .= " re.description, re.fk_facture_source";
2552  $sql .= " FROM " . MAIN_DB_PREFIX . "societe_remise_except_supplier as re";
2553  $sql .= " WHERE fk_facture = " . $object->id;
2554  $resql = $db->query($sql);
2555  if ($resql) {
2556  $num = $db->num_rows($resql);
2557  $i = 0;
2558  $invoice = new FactureFournisseur($db);
2559  while ($i < $num) {
2560  $obj = $db->fetch_object($resql);
2561  $invoice->fetch($obj->fk_facture_source);
2562  print '<tr><td colspan="' . $nbcols . '" align="right">';
2563  if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE)
2564  print $langs->trans("CreditNote") . ' ';
2565  if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT)
2566  print $langs->trans("Deposit") . ' ';
2567  print $invoice->getNomUrl(0);
2568  print ' :</td>';
2569  print '<td align="right">' . price($obj->amount_ttc) . '</td>';
2570  print '<td align="right">';
2571  print '<a href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&action=unlinkdiscount&discountid=' . $obj->rowid . '">' . img_delete() . '</a>';
2572  print '</td></tr>';
2573  $i ++;
2574  if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE)
2575  $creditnoteamount += $obj->amount_ttc;
2576  if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT)
2577  $depositamount += $obj->amount_ttc;
2578  }
2579  } else {
2580  dol_print_error($db);
2581  }
2582  */
2583 
2584  // Paye partiellement 'escompte'
2585  if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'discount_vat') {
2586  print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
2587  print $form->textwithpicto($langs->trans("Discount") . ':', $langs->trans("HelpEscompte"), - 1);
2588  print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td>&nbsp;</td></tr>';
2589  $resteapayeraffiche = 0;
2590  $cssforamountpaymentcomplete = '';
2591  }
2592  // Paye partiellement ou Abandon 'badsupplier'
2593  if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'badsupplier') {
2594  print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
2595  print $form->textwithpicto($langs->trans("Abandoned") . ':', $langs->trans("HelpAbandonBadCustomer"), - 1);
2596  print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td>&nbsp;</td></tr>';
2597  // $resteapayeraffiche=0;
2598  $cssforamountpaymentcomplete = '';
2599  }
2600  // Paye partiellement ou Abandon 'product_returned'
2601  if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'product_returned') {
2602  print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
2603  print $form->textwithpicto($langs->trans("ProductReturned") . ':', $langs->trans("HelpAbandonProductReturned"), - 1);
2604  print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td>&nbsp;</td></tr>';
2605  $resteapayeraffiche = 0;
2606  $cssforamountpaymentcomplete = '';
2607  }
2608  // Paye partiellement ou Abandon 'abandon'
2609  if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'abandon') {
2610  print '<tr><td colspan="' . $nbcols . '" align="right" class="nowrap">';
2611  $text = $langs->trans("HelpAbandonOther");
2612  if ($object->close_note)
2613  $text .= '<br><br><b>' . $langs->trans("Reason") . '</b>:' . $object->close_note;
2614  print $form->textwithpicto($langs->trans("Abandoned") . ':', $text, - 1);
2615  print '</td><td align="right">' . price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye) . '</td><td>&nbsp;</td></tr>';
2616  $resteapayeraffiche = 0;
2617  $cssforamountpaymentcomplete = '';
2618  }
2619 
2620  // Billed
2621  print '<tr><td colspan="' . $nbcols . '" align="right">' . $langs->trans("Billed") . ' :</td><td align="right">' . price($object->total_ttc) . '</td><td>&nbsp;</td></tr>';
2622 
2623  // Remainder to pay
2624  print '<tr><td colspan="' . $nbcols . '" align="right">';
2625  if ($resteapayeraffiche >= 0)
2626  print $langs->trans('RemainderToPay');
2627  else
2628  print $langs->trans('ExcessReceived');
2629  print ' :</td>';
2630  print '<td align="right"'.($resteapayeraffiche?' class="amountremaintopay"':$cssforamountpaymentcomplete).'>' . price($resteapayeraffiche) . '</td>';
2631  print '<td class="nowrap">&nbsp;</td></tr>';
2632  }
2633  else // Credit note
2634  {
2635  $cssforamountpaymentcomplete='';
2636 
2637  // Total already paid back
2638  print '<tr><td colspan="' . $nbcols . '" align="right">';
2639  print $langs->trans('AlreadyPaidBack');
2640  print ' :</td><td align="right">' . price($sign * $totalpaye) . '</td><td>&nbsp;</td></tr>';
2641 
2642  // Billed
2643  print '<tr><td colspan="' . $nbcols . '" align="right">' . $langs->trans("Billed") . ' :</td><td align="right">' . price($sign * $object->total_ttc) . '</td><td>&nbsp;</td></tr>';
2644 
2645  // Remainder to pay back
2646  print '<tr><td colspan="' . $nbcols . '" align="right">';
2647  if ($resteapayeraffiche <= 0)
2648  print $langs->trans('RemainderToPayBack');
2649  else
2650  print $langs->trans('ExcessPaydBack');
2651  print ' :</td>';
2652  print '<td align="right"'.($resteapayeraffiche?' class="amountremaintopay"':(' class="'.$cssforamountpaymentcomplete.'"')).'>' . price($sign * $resteapayeraffiche) . '</td>';
2653  print '<td class="nowrap">&nbsp;</td></tr>';
2654 
2655  // Sold credit note
2656  // print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans('TotalTTC').' :</td>';
2657  // print '<td align="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
2658  // $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
2659  }
2660 
2661  print '</table>';
2662  print '</div>';
2663 
2664  print '</div>';
2665  print '</div>';
2666  print '</div>';
2667 
2668  print '<div class="clearboth"></div><br>';
2669 
2670  if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
2671  {
2672  $blocname = 'contacts';
2673  $title = $langs->trans('ContactsAddresses');
2674  include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
2675  }
2676 
2677  if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
2678  {
2679  $colwidth=20;
2680  $blocname = 'notes';
2681  $title = $langs->trans('Notes');
2682  include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
2683  }
2684 
2685 
2686  /*
2687  * Lines
2688  */
2689  print '<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline')?'#addline':'#line_'.GETPOST('lineid')).'" method="POST">';
2690  print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2691  print '<input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline') . '">';
2692  print '<input type="hidden" name="mode" value="">';
2693  print '<input type="hidden" name="id" value="'.$object->id.'">';
2694  print '<input type="hidden" name="socid" value="'.$societe->id.'">';
2695 
2696  if (! empty($conf->use_javascript_ajax) && $object->statut == FactureFournisseur::STATUS_DRAFT) {
2697  include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
2698  }
2699 
2700  print '<div class="div-table-responsive-no-min">';
2701  print '<table id="tablelines" class="noborder noshadow" width="100%">';
2702 
2703  global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax;
2704  $forceall=1; $senderissupplier=1; $dateSelector=0; $inputalsopricewithtax=1;
2705 
2706  // Show object lines
2707  if (! empty($object->lines))
2708  $ret = $object->printObjectLines($action, $societe, $mysoc, $lineid, 1);
2709 
2710  $num=count($object->lines);
2711 
2712  // Form to add new line
2713  if ($object->statut == FactureFournisseur::STATUS_DRAFT && $user->rights->fournisseur->facture->creer)
2714  {
2715  if ($action != 'editline')
2716  {
2717  // Add free products/services
2718  $object->formAddObjectLine(1, $societe, $mysoc);
2719 
2720  $parameters = array();
2721  $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2722  }
2723  }
2724 
2725  print '</table>';
2726  print '</div>';
2727  print '</form>';
2728 
2729  dol_fiche_end();
2730 
2731 
2732  if ($action != 'presend')
2733  {
2734  /*
2735  * Boutons actions
2736  */
2737 
2738  print '<div class="tabsAction">';
2739 
2740  $parameters = array();
2741  $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
2742  // modified by hook
2743  if (empty($reshook))
2744  {
2745 
2746  // Modify a validated invoice with no payments
2747  if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $user->rights->fournisseur->facture->creer)
2748  {
2749  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=edit">'.$langs->trans('Modify').'</a></div>';
2750  }
2751 
2752  // Reopen a standard paid invoice
2753  if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT) && ($object->statut == 2 || $object->statut == 3)) // A paid invoice (partially or completely)
2754  {
2755  if (! $facidnext && $object->close_code != 'replaced' && $user->rights->fournisseur->facture->creer) // Not replaced by another invoice
2756  {
2757  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans('ReOpen').'</a></div>';
2758  }
2759  else
2760  {
2761  if ($user->rights->fournisseur->facture->creer) {
2762  print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ReOpen').'</span></div>';
2763  } elseif (empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) {
2764  print '<div class="inline-block divButAction"><span class="butActionRefused">'.$langs->trans('ReOpen').'</span></div>';
2765  }
2766  }
2767  }
2768 
2769  // Send by mail
2770  if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED))
2771  {
2772  if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->fournisseur->supplier_invoice_advance->send)
2773  {
2774  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendByMail').'</a></div>';
2775  }
2776  else print '<div class="inline-block divButAction"><span class="butActionRefused">'.$langs->trans('SendByMail').'</a></div>';
2777  }
2778 
2779  // Make payments
2780  if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0)
2781  {
2782  print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create'.($object->fk_account>0?'&amp;accountid='.$object->fk_account:'').'">'.$langs->trans('DoPayment').'</a></div>'; // must use facid because id is for payment id not invoice
2783  }
2784 
2785  // Classify paid
2786  if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->societe_id == 0)
2787  {
2788  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=paid"';
2789  print '>'.$langs->trans('ClassifyPaid').'</a></div>';
2790 
2791  //print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a>';
2792  }
2793 
2794  // Reverse back money or convert to reduction
2795  if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) {
2796  // For credit note only
2797  if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0)
2798  {
2799  if ($resteapayer == 0)
2800  {
2801  print '<div class="inline-block divButAction"><span class="butActionRefused" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span></div>';
2802  }
2803  else
2804  {
2805  print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create&amp;accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a></div>';
2806  }
2807  }
2808 
2809  // For credit note
2810  if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $user->rights->fournisseur->facture->creer && $object->getSommePaiement() == 0) {
2811  print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?facid=' . $object->id . '&amp;action=converttoreduc">' . $langs->trans('ConvertToReduc') . '</a></div>';
2812  }
2813  // For deposit invoice
2814  if ($object->type == FactureFournisseur::TYPE_DEPOSIT && $object->paye == 1 && $resteapayer == 0 && $user->rights->fournisseur->facture->creer && empty($discount->id))
2815  {
2816  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a></div>';
2817  }
2818  }
2819 
2820  // Validate
2821  if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT)
2822  {
2823  if (count($object->lines))
2824  {
2825  if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->facture->creer))
2826  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_invoice_advance->validate)))
2827  {
2828  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid"';
2829  print '>'.$langs->trans('Validate').'</a></div>';
2830  }
2831  else
2832  {
2833  print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'"';
2834  print '>'.$langs->trans('Validate').'</a></div>';
2835  }
2836  }
2837  }
2838 
2839  // Create event
2840  /*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page.
2841  {
2842  print '<div class="inline-block divButAction"><a class="butAction" href="' . DOL_URL_ROOT . '/comm/action/card.php?action=create&amp;origin=' . $object->element . '&amp;originid=' . $object->id . '&amp;socid=' . $object->socid . '">' . $langs->trans("AddAction") . '</a></div>';
2843  }*/
2844 
2845  // Clone
2846  if ($action != 'edit' && $user->rights->fournisseur->facture->creer)
2847  {
2848  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=clone&amp;socid='.$object->socid.'">'.$langs->trans('ToClone').'</a></div>';
2849  }
2850 
2851  // Create a credit note
2852  if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut > 0 && $user->rights->fournisseur->facture->creer)
2853  {
2854  if (! $objectidnext)
2855  {
2856  print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER['PHP_SELF'] . '?socid=' . $object->socid .'&amp;fac_avoir=' . $object->id . '&amp;action=create&amp;type=2'.($object->fk_project > 0 ? '&amp;projectid='.$object->fk_project : '').'">' . $langs->trans("CreateCreditNote") . '</a></div>';
2857  }
2858  }
2859 
2860  // Delete
2861  if ($action != 'confirm_edit' && $user->rights->fournisseur->facture->supprimer)
2862  {
2863  $isErasable=$object->is_erasable();
2864  //var_dump($isErasable);
2865  if ($isErasable == -4) {
2866  print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecausePayments") . '">' . $langs->trans('Delete') . '</a></div>';
2867  }
2868  elseif ($isErasable == -3) { // Should never happen with supplier invoice
2869  print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseNotLastSituationInvoice") . '">' . $langs->trans('Delete') . '</a></div>';
2870  }
2871  elseif ($isErasable == -2) { // Should never happen with supplier invoice
2872  print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseNotLastInvoice") . '">' . $langs->trans('Delete') . '</a></div>';
2873  }
2874  elseif ($isErasable == -1) {
2875  print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseDispatchedInBookkeeping") . '">' . $langs->trans('Delete') . '</a></div>';
2876  }
2877  elseif ($isErasable <= 0) // Any other cases
2878  {
2879  print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . $langs->trans("DisabledBecauseNotErasable") . '">' . $langs->trans('Delete') . '</a></div>';
2880  }
2881  else
2882  {
2883  print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete">'.$langs->trans('Delete').'</a></div>';
2884  }
2885  }
2886  print '</div>';
2887 
2888  if ($action != 'confirm_edit')
2889  {
2890  print '<div class="fichecenter"><div class="fichehalfleft">';
2891 
2892  /*
2893  * Documents generes
2894  */
2895  $ref=dol_sanitizeFileName($object->ref);
2896  $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref;
2897  $filedir = $conf->fournisseur->facture->dir_output.'/'.$subdir;
2898  $urlsource=$_SERVER['PHP_SELF'].'?id='.$object->id;
2899  $genallowed=$user->rights->fournisseur->facture->lire;
2900  $delallowed=$user->rights->fournisseur->facture->creer;
2901  $modelpdf=(! empty($object->modelpdf)?$object->modelpdf:(empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)?'':$conf->global->INVOICE_SUPPLIER_ADDON_PDF));
2902 
2903  print $formfile->showdocuments('facture_fournisseur',$subdir,$filedir,$urlsource,$genallowed,$delallowed,$modelpdf,1,0,0,40,0,'','','',$societe->default_lang);
2904  $somethingshown=$formfile->numoffiles;
2905 
2906  // Show links to link elements
2907  $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice_supplier'));
2908  $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
2909 
2910  print '</div><div class="fichehalfright"><div class="ficheaddleft">';
2911  //print '</td><td valign="top" width="50%">';
2912  //print '<br>';
2913 
2914  // List of actions on element
2915  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
2916  $formactions=new FormActions($db);
2917  $somethingshown = $formactions->showactions($object,'invoice_supplier',$socid,1,'listaction'.($genallowed?'largetitle':''));
2918 
2919  print '</div></div></div>';
2920  //print '</td></tr></table>';
2921  }
2922  }
2923  }
2924 
2925  // Select mail models is same action as presend
2926  if (GETPOST('modelselected')) {
2927  $action = 'presend';
2928  }
2929 
2930  // Presend form
2931  $modelmail='supplier_order_send';
2932  $defaulttopic='SendBillRef';
2933  $diroutput = $conf->fournisseur->facture->dir_output;
2934  $trackid = 'sin'.$object->id;
2935 
2936  include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
2937  }
2938 }
2939 
2940 
2941 // End of page
2942 llxFooter();
2943 $db->close();
const TYPE_STANDARD
Standard invoice.
llxFooter()
Empty footer.
Definition: wrapper.php:58
dol_htmloutput_events($disabledoutputofmessages=0)
Print formated messages to output (Used to show messages on html output).
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='')
Show picto whatever it's its name (generic function)
setEventMessages($mesg, $mesgs, $style='mesgs')
Set event messages in dol_events session object.
Class to manage building of HTML components.
const TYPE_DEPOSIT
Deposit invoice.
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...
dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='')
Show tab header of a card.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart)
Return a path to have a the directory according to object where files are stored. ...
Class to manage products or services.
dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='rowid', $fieldref='ref', $morehtmlref='', $moreparam='', $nodbprefix=0, $morehtmlleft='', $morehtmlstatus='', $onlybanner=0, $morehtmlright='')
Show tab footer of a card.
const TYPE_REPLACEMENT
Replacement invoice.
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
const STATUS_VALIDATED
Validated (need to be paid)
dol_concatdesc($text1, $text2, $forxml=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
Class to manage suppliers invoices.
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Fonction qui renvoie si tva doit etre tva percue recuperable.
if(empty($reshook)) $form
View.
Definition: perms.php:103
get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller="", $vatnpr=0)
Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller Note: This function applies same rules than get_default_tva.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...
Class to manage bank accounts.
Class to manage suppliers.
GETPOST($paramname, $check='none', $method=0, $filter=NULL, $options=NULL, $noreplace=0)
Return value of a param into GET or POST supervariable.
Class with static methods for building HTML components related to products Only components common to ...
Class to manage standard extra fields.
Class to manage generation of HTML components Only common components must be here.
Class to manage third parties objects (customers, suppliers, prospects...)
img_warning($titlealt= 'default', $moreatt= '')
Show warning logo.
Class to manage projects.
Class to manage building of HTML components.
if($_POST["cancel"]==$langs->trans("Cancel")&&!$id) if($action== 'setdatev'&&$user->rights->tax->charges->creer) if($action== 'add'&&$_POST["cancel"]<> $langs->trans("Cancel")) if($action== 'delete') $title
Actions.
Definition: card.php:183
dol_fiche_end($notab=0)
Show tab footer of a card.
load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', $pictoisfullpath=0, $id=0, $morecssontable='', $morehtmlcenter='')
Load a title with picto.
llxHeader()
Empty header.
Definition: wrapper.php:46
getEntity($element, $shared=1, $forceentity=null)
Get list of entity id to use.
Class to manage translations.
dol_now($mode='gmt')
Return date for now.
img_delete($titlealt= 'default', $other= 'class="pictodelete"')
Show delete logo.
Class ProductCombination Used to represent a product combination.
Class to offer components to list and upload files.
facturefourn_prepare_head($object)
Prepare array with list of tabs.
Definition: fourn.lib.php:34
const STATUS_CLOSED
Classified paid.
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...
const TYPE_CREDIT_NOTE
Credit note invoice.
print
Draft customers invoices.
Definition: index.php:91
setEventMessage($mesgs, $style='mesgs')
Set event message in dol_events session object.
if(preg_match('/set_(.*)/', $action, $reg)) if(preg_match('/del_(.*)/', $action, $reg)) if($action== 'set') else if($action== 'specimen') else if($action== 'setmodel') else if($action== 'del') else if($action== 'setdoc' $formactions)
View.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) Si ...
const STATUS_ABANDONED
Classified abandoned and no payment done.
Class to manage a WYSIWYG editor.
Class to manage accounting accounts.
fieldLabel($langkey, $fieldkey, $fieldrequired=0)
Show a string with the label tag dedicated to the HTML edit field.
Class to manage payments for supplier invoices.
img_edit($titlealt= 'default', $float=0, $other= 'class="pictoedit"')
Show logo editer/modifier fiche.
price2num($amount, $rounding='', $alreadysqlnb=0)
Function that return a number with universal decimal format (decimal separator is '...
restrictedArea($user, $features, $objectid=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $objcanvas=null)
Check permissions of a user to show a page and an object.
Class to manage predefined suppliers products.
$parameters
Actions.
Definition: card.php:112
Class to manage warehouses.
static getIdAndTxFromCode(&$db, $code, $date_document='')
Get id and rate of currency from code.