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