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