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