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