dolibarr  17.0.3
card.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
4  * Copyright (C) 2004-2020 Laurent Destailleur <eldy@users.sourceforge.net>
5  * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
6  * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@inodbox.com>
7  * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
8  * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
9  * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
10  * Copyright (C) 2012-2013 Cédric Salvador <csalvador@gpcsolutions.fr>
11  * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
12  * Copyright (C) 2013 Jean-Francois FERRY <jfefe@aternatik.fr>
13  * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
14  * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
15  * Copyright (C) 2014-2019 Ferran Marcet <fmarcet@2byte.es>
16  * Copyright (C) 2015-2016 Marcos García <marcosgdf@gmail.com>
17  * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
18  * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
19  *
20  * This program is free software; you can redistribute it and/or modify
21  * it under the terms of the GNU General Public License as published by
22  * the Free Software Foundation; either version 3 of the License, or
23  * (at your option) any later version.
24  *
25  * This program is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28  * GNU General Public License for more details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with this program. If not, see <https://www.gnu.org/licenses/>.
32  */
33 
40 // Libraries
41 require '../../main.inc.php';
42 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
43 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
44 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
45 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
46 
47 require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
48 require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
49 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
50 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
51 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
52 require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
53 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
54 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
55 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
56 
57 if (isModEnabled('commande')) {
58  require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
59 }
60 if (isModEnabled('project')) {
61  require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
62  require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
63 }
64 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
65 
66 if (isModEnabled('variants')) {
67  require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
68 }
69 if (isModEnabled('accounting')) {
70  require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
71 }
72 
73 // Load translation files required by the page
74 $langs->loadLangs(array('bills', 'companies', 'compta', 'products', 'banks', 'main', 'withdrawals'));
75 if (isModEnabled('incoterm')) {
76  $langs->load('incoterm');
77 }
78 if (isModEnabled('margin')) {
79  $langs->load('margins');
80 }
81 
82 // General $Variables
83 $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility
84 $ref = GETPOST('ref', 'alpha');
85 $socid = GETPOST('socid', 'int');
86 $action = GETPOST('action', 'aZ09');
87 $confirm = GETPOST('confirm', 'alpha');
88 $cancel = GETPOST('cancel', 'alpha');
89 $lineid = GETPOST('lineid', 'int');
90 $userid = GETPOST('userid', 'int');
91 $search_ref = GETPOST('sf_ref', 'alpha') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha');
92 $search_societe = GETPOST('search_societe', 'alpha');
93 $search_montant_ht = GETPOST('search_montant_ht', 'alpha');
94 $search_montant_ttc = GETPOST('search_montant_ttc', 'alpha');
95 $origin = GETPOST('origin', 'alpha');
96 $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility
97 $fac_rec = GETPOST('fac_rec', 'int');
98 $facid = GETPOST('facid', 'int');
99 $ref_client = GETPOST('ref_client', 'int');
100 $rank = (GETPOST('rank', 'int') > 0) ? GETPOST('rank', 'int') : -1;
101 $projectid = (GETPOST('projectid', 'int') ? GETPOST('projectid', 'int') : 0);
102 
103 // PDF
104 $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
105 $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
106 $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
107 
108 // Number of lines for predefined product/service choices
109 $NBLINES = 4;
110 
111 $usehm = (!empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0);
112 
113 $object = new Facture($db);
114 $extrafields = new ExtraFields($db);
115 
116 // Fetch optionals attributes and labels
117 $extrafields->fetch_name_optionals_label($object->table_element);
118 
119 // Load object
120 if ($id > 0 || !empty($ref)) {
121  if ($action != 'add') {
122  if (empty($conf->global->INVOICE_USE_SITUATION)) {
123  $fetch_situation = false;
124  } else {
125  $fetch_situation = true;
126  }
127  $ret = $object->fetch($id, $ref, '', '', $fetch_situation);
128  }
129 }
130 
131 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
132 $hookmanager->initHooks(array('invoicecard', 'globalcard'));
133 
134 // Permissions
135 $usercanread = $user->hasRight("facture", "lire");
136 $usercancreate = $user->hasRight("facture", "creer");
137 $usercanissuepayment = $user->hasRight("facture", "paiement");
138 $usercandelete = $user->hasRight("facture", "supprimer");
139 $usercancreatecontract = $user->hasRight("contrat", "creer");
140 
141 // Advanced Permissions
142 $usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->validate)));
143 $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->send)));
144 $usercanreopen = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->reopen)));
145 if (!empty($conf->global->INVOICE_DISALLOW_REOPEN)) {
146  $usercanreopen = false;
147 }
148 $usercanunvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->unvalidate)));
149 
150 $usermustrespectpricemin = ((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS));
151 $usercancreatemargin = (!empty($user->rights->margins->creer) ? $user->rights->margins->creer : 0);
152 $usercanreadallmargin = (!empty($user->rights->margins->liretous) ? $user->rights->margins->liretous : 0);
153 $usercancreatewithdrarequest = (!empty($user->rights->prelevement->bons->creer) ? $user->rights->prelevement->bons->creer : 0);
154 
155 $permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
156 $permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
157 $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdonw.inc.php
158 $permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php
159 
160 // retained warranty invoice available type
161 $retainedWarrantyInvoiceAvailableType = array();
162 if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
163  $retainedWarrantyInvoiceAvailableType = explode('+', $conf->global->INVOICE_USE_RETAINED_WARRANTY);
164 }
165 
166 // Security check
167 if ($user->socid) {
168  $socid = $user->socid;
169 }
170 $isdraft = (($object->statut == Facture::STATUS_DRAFT) ? 1 : 0);
171 
172 $result = restrictedArea($user, 'facture', $object->id, '', '', 'fk_soc', 'rowid', $isdraft);
173 
174 
175 /*
176  * Actions
177  */
178 
179 $parameters = array('socid' => $socid);
180 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
181 if ($reshook < 0) {
182  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
183 }
184 
185 if (empty($reshook)) {
186  $backurlforlist = DOL_URL_ROOT.'/compta/facture/list.php';
187 
188  if (empty($backtopage) || ($cancel && empty($id))) {
189  if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
190  if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
191  $backtopage = $backurlforlist;
192  } else {
193  $backtopage = DOL_URL_ROOT.'/compta/facture/card.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
194  }
195  }
196  }
197 
198  if ($cancel) {
199  if (!empty($backtopageforcancel)) {
200  header("Location: ".$backtopageforcancel);
201  exit;
202  } elseif (!empty($backtopage)) {
203  header("Location: ".$backtopage);
204  exit;
205  }
206  $action = '';
207  }
208 
209  include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
210 
211  include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
212 
213  include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
214 
215  // Action clone object
216  if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) {
217  $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.
218 
219  $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int'));
220  $objectutil->socid = $socid;
221  $result = $objectutil->createFromClone($user, $id);
222  if ($result > 0) {
223  header("Location: ".$_SERVER['PHP_SELF'].'?facid='.$result);
224  exit();
225  } else {
226  $langs->load("errors");
227  setEventMessages($objectutil->error, $objectutil->errors, 'errors');
228  $action = '';
229  }
230  } elseif ($action == 'reopen' && $usercanreopen) {
231  $result = $object->fetch($id);
232 
233  if ($object->statut == Facture::STATUS_CLOSED || ($object->statut == Facture::STATUS_ABANDONED && ($object->close_code != 'replaced' || $object->getIdReplacingInvoice() == 0)) || ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 1)) { // ($object->statut == 1 && $object->paye == 1) should not happened but can be found when data are corrupted
234  $result = $object->setUnpaid($user);
235  if ($result > 0) {
236  header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id);
237  exit();
238  } else {
239  setEventMessages($object->error, $object->errors, 'errors');
240  }
241  }
242  } elseif ($action == 'confirm_delete' && $confirm == 'yes') {
243  // Delete invoice
244  $result = $object->fetch($id);
245  $object->fetch_thirdparty();
246 
247  $idwarehouse = GETPOST('idwarehouse');
248 
249  $qualified_for_stock_change = 0;
250  if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
251  $qualified_for_stock_change = $object->hasProductsOrServices(2);
252  } else {
253  $qualified_for_stock_change = $object->hasProductsOrServices(1);
254  }
255 
256  $isErasable = $object->is_erasable();
257 
258  if (($usercandelete && $isErasable > 0)
259  || ($usercancreate && $isErasable == 1)) {
260  $result = $object->delete($user, 0, $idwarehouse);
261  if ($result > 0) {
262  header('Location: '.DOL_URL_ROOT.'/compta/facture/list.php?restore_lastsearch_values=1');
263  exit();
264  } else {
265  setEventMessages($object->error, $object->errors, 'errors');
266  $action = '';
267  }
268  }
269  } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
270  // Delete line
271  $object->fetch($id);
272  $object->fetch_thirdparty();
273 
274  $result = $object->deleteline(GETPOST('lineid', 'int'));
275  if ($result > 0) {
276  // reorder lines
277  $object->line_order(true);
278  // Define output language
279  $outputlangs = $langs;
280  $newlang = '';
281  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id')) {
282  $newlang = GETPOST('lang_id');
283  }
284  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
285  $newlang = $object->thirdparty->default_lang;
286  }
287  if (!empty($newlang)) {
288  $outputlangs = new Translate("", $conf);
289  $outputlangs->setDefaultLang($newlang);
290  $outputlangs->load('products');
291  }
292  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
293  $ret = $object->fetch($id); // Reload to get new records
294  $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
295  }
296  if ($result >= 0) {
297  header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id);
298  exit();
299  }
300  } else {
301  setEventMessages($object->error, $object->errors, 'errors');
302  $action = '';
303  }
304  } elseif ($action == 'unlinkdiscount' && $usercancreate) {
305  // Delete link of credit note to invoice
306  $discount = new DiscountAbsolute($db);
307  $result = $discount->fetch(GETPOST("discountid"));
308  $discount->unlink_invoice();
309  } elseif ($action == 'valid' && $usercancreate) {
310  // Validation
311  $object->fetch($id);
312 
313  if (!empty($conf->global-> INVOICE_CHECK_POSTERIOR_DATE)) {
314  $last_of_type = $object->willBeLastOfSameType(true);
315  if (empty($object->date_validation) && !$last_of_type[0]) {
316  setEventMessages($langs->transnoentities("ErrorInvoiceIsNotLastOfSameType", $object->ref, dol_print_date($object->date, 'day'), dol_print_date($last_of_type[1], 'day')), null, 'errors');
317  $action = '';
318  }
319  }
320 
321  // On verifie signe facture
322  if ($object->type == Facture::TYPE_CREDIT_NOTE) {
323  // Si avoir, le signe doit etre negatif
324  if ($object->total_ht >= 0) {
325  setEventMessages($langs->trans("ErrorInvoiceAvoirMustBeNegative"), null, 'errors');
326  $action = '';
327  }
328  } else {
329  // If not a credit note, amount with tax must be positive or nul.
330  // Note that amount excluding tax can be negative because you can have a invoice of 100 with vat of 20 that
331  // consumes a credit note of 100 with vat 0 (total with tax is 0 but without tax is -20).
332  // For some cases, credit notes can have a vat of 0 (for example when selling goods in France).
333  if (empty($conf->global->FACTURE_ENABLE_NEGATIVE) && $object->total_ttc < 0) {
334  setEventMessages($langs->trans("ErrorInvoiceOfThisTypeMustBePositive"), null, 'errors');
335  $action = '';
336  }
337 
338  // Also negative lines should not be allowed on 'non Credit notes' invoices. A test is done when adding or updating lines but we must
339  // do it again in validation to avoid cases where invoice is created from another object that allow negative lines.
340  // Note that we can accept the negative line if sum with other lines with same vat makes total positive: Because all the lines will be merged together
341  // when converted into 'available credit' and we will get a positive available credit line.
342  // Note: Other solution if you want to add a negative line on invoice, is to create a discount for customer and consumme it (but this is possible on standard invoice only).
343  $array_of_total_ht_per_vat_rate = array();
344  $array_of_total_ht_devise_per_vat_rate = array();
345  foreach ($object->lines as $line) {
346  //$vat_src_code_for_line = $line->vat_src_code; // TODO We chek sign of total per vat without taking into account the vat code because for the moment the vat code is lost/unknown when we add a down payment.
347  $vat_src_code_for_line = '';
348  if (empty($array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line])) {
349  $array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] = 0;
350  }
351  if (empty($array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line])) {
352  $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] = 0;
353  }
354  $array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] += $line->total_ht;
355  $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] += $line->multicurrency_total_ht;
356  }
357 
358  //var_dump($array_of_total_ht_per_vat_rate);exit;
359  foreach ($array_of_total_ht_per_vat_rate as $vatrate => $tmpvalue) {
360  $tmp_total_ht = price2num($array_of_total_ht_per_vat_rate[$vatrate]);
361  $tmp_total_ht_devise = price2num($array_of_total_ht_devise_per_vat_rate[$vatrate]);
362 
363  if (($tmp_total_ht < 0 || $tmp_total_ht_devise < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) {
364  if ($object->type == $object::TYPE_DEPOSIT) {
365  $langs->load("errors");
366  // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
367  setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
368  $error++;
369  $action = '';
370  } else {
371  $tmpvatratetoshow = explode('_', $vatrate);
372  $tmpvatratetoshow[0] = round($tmpvatratetoshow[0], 2);
373 
374  if ($tmpvatratetoshow[0] != 0) {
375  $langs->load("errors");
376  setEventMessages($langs->trans("ErrorLinesCantBeNegativeForOneVATRate", $tmpvatratetoshow[0]), null, 'errors');
377  $error++;
378  $action = '';
379  }
380  }
381  }
382  }
383  }
384  } elseif ($action == 'classin' && $usercancreate) {
385  $object->fetch($id);
386  $object->setProject(GETPOST('projectid', 'int'));
387  } elseif ($action == 'setmode' && $usercancreate) {
388  $object->fetch($id);
389  $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
390  if ($result < 0) {
391  dol_print_error($db, $object->error);
392  }
393  } elseif ($action == 'setretainedwarrantyconditions' && $user->rights->facture->creer) {
394  $object->fetch($id);
395  $object->retained_warranty_fk_cond_reglement = 0; // To clean property
396  $result = $object->setRetainedWarrantyPaymentTerms(GETPOST('retained_warranty_fk_cond_reglement', 'int'));
397  if ($result < 0) {
398  dol_print_error($db, $object->error);
399  }
400 
401  $old_rw_date_lim_reglement = $object->retained_warranty_date_limit;
402  $new_rw_date_lim_reglement = $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
403  if ($new_rw_date_lim_reglement > $old_rw_date_lim_reglement) {
404  $object->retained_warranty_date_limit = $new_rw_date_lim_reglement;
405  }
406  if ($object->retained_warranty_date_limit < $object->date) {
407  $object->retained_warranty_date_limit = $object->date;
408  }
409  $result = $object->update($user);
410  if ($result < 0) {
411  dol_print_error($db, $object->error);
412  }
413  } elseif ($action == 'setretainedwarranty' && $user->rights->facture->creer) {
414  $object->fetch($id);
415  $result = $object->setRetainedWarranty(GETPOST('retained_warranty', 'float'));
416  if ($result < 0) {
417  dol_print_error($db, $object->error);
418  }
419  } elseif ($action == 'setretainedwarrantydatelimit' && $user->rights->facture->creer) {
420  $object->fetch($id);
421  $result = $object->setRetainedWarrantyDateLimit(GETPOST('retained_warranty_date_limit', 'float'));
422  if ($result < 0) {
423  dol_print_error($db, $object->error);
424  }
425  } elseif ($action == 'setmulticurrencycode' && $usercancreate) { // Multicurrency Code
426  $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
427  } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { // Multicurrency rate
428  $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int'));
429  } elseif ($action == 'setinvoicedate' && $usercancreate) {
430  $object->fetch($id);
431  $old_date_lim_reglement = $object->date_lim_reglement;
432  $newdate = dol_mktime(0, 0, 0, GETPOST('invoicedatemonth', 'int'), GETPOST('invoicedateday', 'int'), GETPOST('invoicedateyear', 'int'), 'tzserver');
433  if (empty($newdate)) {
434  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
435  header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate&token='.newToken());
436  exit;
437  }
438  if ($newdate > (dol_now('tzuserrel') + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
439  if (empty($conf->global->INVOICE_MAX_FUTURE_DELAY)) {
440  setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings');
441  } else {
442  setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings');
443  }
444  }
445 
446  $object->date = $newdate;
447  $new_date_lim_reglement = $object->calculate_date_lim_reglement();
448  if ($new_date_lim_reglement > $old_date_lim_reglement) {
449  $object->date_lim_reglement = $new_date_lim_reglement;
450  }
451  if ($object->date_lim_reglement < $object->date) {
452  $object->date_lim_reglement = $object->date;
453  }
454  $result = $object->update($user);
455  if ($result < 0) {
456  dol_print_error($db, $object->error);
457  }
458  } elseif ($action == 'setdate_pointoftax' && $usercancreate) {
459  $object->fetch($id);
460 
461  $date_pointoftax = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'), 'tzserver');
462 
463  $object->date_pointoftax = $date_pointoftax;
464  $result = $object->update($user);
465  if ($result < 0) {
466  dol_print_error($db, $object->error);
467  }
468  } elseif ($action == 'setconditions' && $usercancreate) {
469  $object->fetch($id);
470  $object->cond_reglement_code = 0; // To clean property
471  $object->cond_reglement_id = 0; // To clean property
472 
473  $error = 0;
474 
475  $db->begin();
476 
477  if (!$error) {
478  $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
479  if ($result < 0) {
480  $error++;
481  setEventMessages($object->error, $object->errors, 'errors');
482  }
483  }
484 
485  if (!$error) {
486  $old_date_lim_reglement = $object->date_lim_reglement;
487  $new_date_lim_reglement = $object->calculate_date_lim_reglement();
488  if ($new_date_lim_reglement > $old_date_lim_reglement) {
489  $object->date_lim_reglement = $new_date_lim_reglement;
490  }
491  if ($object->date_lim_reglement < $object->date) {
492  $object->date_lim_reglement = $object->date;
493  }
494  $result = $object->update($user);
495  if ($result < 0) {
496  $error++;
497  setEventMessages($object->error, $object->errors, 'errors');
498  }
499  }
500 
501  if ($error) {
502  $db->rollback();
503  } else {
504  $db->commit();
505  }
506  } elseif ($action == 'setpaymentterm' && $usercancreate) {
507  $object->fetch($id);
508  $object->date_lim_reglement = dol_mktime(12, 0, 0, GETPOST('paymenttermmonth', 'int'), GETPOST('paymenttermday', 'int'), GETPOST('paymenttermyear', 'int'));
509  if ($object->date_lim_reglement < $object->date) {
510  $object->date_lim_reglement = $object->calculate_date_lim_reglement();
511  setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
512  }
513  $result = $object->update($user);
514  if ($result < 0) {
515  dol_print_error($db, $object->error);
516  }
517  } elseif ($action == 'setrevenuestamp' && $usercancreate) {
518  $object->fetch($id);
519  $object->revenuestamp = GETPOST('revenuestamp');
520  $result = $object->update($user);
521  $object->update_price(1);
522  if ($result < 0) {
523  dol_print_error($db, $object->error);
524  } else {
525  // Define output language
526  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
527  $outputlangs = $langs;
528  $newlang = '';
529  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
530  $newlang = GETPOST('lang_id', 'aZ09');
531  }
532  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
533  $newlang = $object->thirdparty->default_lang;
534  }
535  if (!empty($newlang)) {
536  $outputlangs = new Translate("", $conf);
537  $outputlangs->setDefaultLang($newlang);
538  $outputlangs->load('products');
539  }
540  $model = $object->model_pdf;
541  $ret = $object->fetch($id); // Reload to get new records
542 
543  $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
544  if ($result < 0) {
545  setEventMessages($object->error, $object->errors, 'errors');
546  }
547  }
548  }
549  } elseif ($action == 'set_incoterms' && isModEnabled('incoterm')) { // Set incoterm
550  $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
551  } elseif ($action == 'setbankaccount' && $usercancreate) { // bank account
552  $result = $object->setBankAccount(GETPOST('fk_account', 'int'));
553  } elseif ($action == 'setremisepercent' && $usercancreate) {
554  $object->fetch($id);
555  $result = $object->setDiscount($user, price2num(GETPOST('remise_percent'), '', 2));
556  } elseif ($action == "setabsolutediscount" && $usercancreate) {
557  // We have POST[remise_id] or POST[remise_id_for_payment]
558  $db->begin();
559 
560  // We use the credit to reduce amount of invoice
561  if (GETPOST("remise_id", 'int') > 0) {
562  $ret = $object->fetch($id);
563  if ($ret > 0) {
564  $result = $object->insert_discount(GETPOST("remise_id", 'int'));
565  if ($result < 0) {
566  setEventMessages($object->error, $object->errors, 'errors');
567  }
568  } else {
569  $error++;
570  setEventMessages($object->error, $object->errors, 'errors');
571  }
572  }
573  // We use the credit to reduce remain to pay
574  if (GETPOST("remise_id_for_payment", 'int') > 0) {
575  require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
576  $discount = new DiscountAbsolute($db);
577  $discount->fetch(GETPOST("remise_id_for_payment", 'int'));
578 
579  //var_dump($object->getRemainToPay(0));
580  //var_dump($discount->amount_ttc);exit;
581  $remaintopay = $object->getRemainToPay(0);
582  if (price2num($discount->amount_ttc) > price2num($remaintopay)) {
583  // TODO Split the discount in 2 automatically
584  $error++;
585  setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors');
586  }
587 
588  if (!$error) {
589  $result = $discount->link_to_invoice(0, $id);
590  if ($result < 0) {
591  $error++;
592  setEventMessages($discount->error, $discount->errors, 'errors');
593  }
594  }
595 
596  if (!$error) {
597  $newremaintopay = $object->getRemainToPay(0);
598  if ($newremaintopay == 0) {
599  $object->setPaid($user);
600  }
601  }
602  }
603 
604  if (!$error) {
605  $db->commit();
606  } else {
607  $db->rollback();
608  }
609 
610  if (empty($error) && empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
611  $outputlangs = $langs;
612  $newlang = '';
613  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
614  $newlang = GETPOST('lang_id', 'aZ09');
615  }
616  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
617  $newlang = $object->thirdparty->default_lang;
618  }
619  if (!empty($newlang)) {
620  $outputlangs = new Translate("", $conf);
621  $outputlangs->setDefaultLang($newlang);
622  }
623  $ret = $object->fetch($id); // Reload to get new records
624 
625  $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
626  if ($result < 0) {
627  setEventMessages($object->error, $object->errors, 'errors');
628  }
629  }
630  } elseif ($action == 'setref' && $usercancreate) {
631  $object->fetch($id);
632  $object->setValueFrom('ref', GETPOST('ref'), '', null, '', '', $user, 'BILL_MODIFY');
633  } elseif ($action == 'setref_client' && $usercancreate) {
634  $object->fetch($id);
635  $object->set_ref_client(GETPOST('ref_client'));
636  } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) {
637  // Classify to validated
638  $idwarehouse = GETPOST('idwarehouse', 'int');
639 
640  $object->fetch($id);
641  $object->fetch_thirdparty();
642 
643  // Check for warehouse
644  if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
645  $qualified_for_stock_change = 0;
646  if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
647  $qualified_for_stock_change = $object->hasProductsOrServices(2);
648  } else {
649  $qualified_for_stock_change = $object->hasProductsOrServices(1);
650  }
651 
652  if ($qualified_for_stock_change) {
653  if (!$idwarehouse || $idwarehouse == - 1) {
654  $error++;
655  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
656  $action = '';
657  }
658  }
659  }
660 
661  if (!$error) {
662  $result = $object->validate($user, '', $idwarehouse);
663  if ($result >= 0) {
664  // Define output language
665  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
666  $outputlangs = $langs;
667  $newlang = '';
668  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
669  $newlang = GETPOST('lang_id', 'aZ09');
670  }
671  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
672  $newlang = $object->thirdparty->default_lang;
673  }
674  if (!empty($newlang)) {
675  $outputlangs = new Translate("", $conf);
676  $outputlangs->setDefaultLang($newlang);
677  $outputlangs->load('products');
678  }
679  $model = $object->model_pdf;
680 
681  $ret = $object->fetch($id); // Reload to get new records
682 
683  $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
684  if ($result < 0) {
685  setEventMessages($object->error, $object->errors, 'errors');
686  }
687  }
688  } else {
689  if (count($object->errors)) {
690  setEventMessages(null, $object->errors, 'errors');
691  } else {
692  setEventMessages($object->error, $object->errors, 'errors');
693  }
694  }
695  }
696  } elseif ($action == 'confirm_modif' && $usercanunvalidate) {
697  // Go back to draft status (unvalidate)
698  $idwarehouse = GETPOST('idwarehouse', 'int');
699 
700  $object->fetch($id);
701  $object->fetch_thirdparty();
702 
703  // Check parameters
704  if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
705  $qualified_for_stock_change = 0;
706  if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
707  $qualified_for_stock_change = $object->hasProductsOrServices(2);
708  } else {
709  $qualified_for_stock_change = $object->hasProductsOrServices(1);
710  }
711 
712  if ($qualified_for_stock_change) {
713  if (!$idwarehouse || $idwarehouse == - 1) {
714  $error++;
715  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
716  $action = '';
717  }
718  }
719  }
720 
721  if (!$error) {
722  // We check if invoice has payments
723  $sql = 'SELECT pf.amount';
724  $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf';
725  $sql .= ' WHERE pf.fk_facture = '.((int) $object->id);
726 
727  $result = $db->query($sql);
728  if ($result) {
729  $i = 0;
730  $num = $db->num_rows($result);
731 
732  while ($i < $num) {
733  $objp = $db->fetch_object($result);
734  $totalpaid += $objp->amount;
735  $i++;
736  }
737  } else {
738  dol_print_error($db, '');
739  }
740 
741  $resteapayer = $object->total_ttc - $totalpaid;
742 
743  // We check that invlice lines are transferred into accountancy
744  $ventilExportCompta = $object->getVentilExportCompta();
745 
746  // On verifie si aucun paiement n'a ete effectue
747  if ($ventilExportCompta == 0) {
748  if (!empty($conf->global->INVOICE_CAN_BE_EDITED_EVEN_IF_PAYMENT_DONE) || ($resteapayer == $object->total_ttc && empty($object->paye))) {
749  $result = $object->setDraft($user, $idwarehouse);
750  if ($result < 0) {
751  setEventMessages($object->error, $object->errors, 'errors');
752  }
753 
754  // Define output language
755  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
756  $outputlangs = $langs;
757  $newlang = '';
758  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
759  $newlang = GETPOST('lang_id', 'aZ09');
760  }
761  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
762  $newlang = $object->thirdparty->default_lang;
763  }
764  if (!empty($newlang)) {
765  $outputlangs = new Translate("", $conf);
766  $outputlangs->setDefaultLang($newlang);
767  $outputlangs->load('products');
768  }
769  $model = $object->model_pdf;
770  $ret = $object->fetch($id); // Reload to get new records
771 
772  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
773  }
774  }
775  }
776  }
777  } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $usercanissuepayment) {
778  // Classify "paid"
779  $object->fetch($id);
780  $result = $object->setPaid($user);
781  if ($result < 0) {
782  setEventMessages($object->error, $object->errors, 'errors');
783  }
784  } elseif ($action == 'confirm_paid_partially' && $confirm == 'yes' && $usercanissuepayment) {
785  // Classif "paid partialy"
786  $object->fetch($id);
787  $close_code = GETPOST("close_code", 'restricthtml');
788  $close_note = GETPOST("close_note", 'restricthtml');
789  if ($close_code) {
790  $result = $object->setPaid($user, $close_code, $close_note);
791  if ($result < 0) {
792  setEventMessages($object->error, $object->errors, 'errors');
793  }
794  } else {
795  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
796  }
797  } elseif ($action == 'confirm_canceled' && $confirm == 'yes') {
798  // Classify "abandoned"
799  $object->fetch($id);
800  $close_code = GETPOST("close_code", 'restricthtml');
801  $close_note = GETPOST("close_note", 'restricthtml');
802  if ($close_code) {
803  $result = $object->setCanceled($user, $close_code, $close_note);
804  if ($result < 0) {
805  setEventMessages($object->error, $object->errors, 'errors');
806  }
807  } else {
808  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
809  }
810  } elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) {
811  // Convertir en reduc
812  $object->fetch($id);
813  $object->fetch_thirdparty();
814  //$object->fetch_lines(); // Already done into fetch
815 
816  // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
817  $discountcheck = new DiscountAbsolute($db);
818  $result = $discountcheck->fetch(0, $object->id);
819 
820  $canconvert = 0;
821  if ($object->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
822  $canconvert = 1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc)
823  }
824  if (($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) && $object->paye == 0 && empty($discountcheck->id)) {
825  $canconvert = 1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc)
826  }
827 
828  if ($canconvert) {
829  $db->begin();
830 
831  $amount_ht = $amount_tva = $amount_ttc = array();
832  $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
833 
834  // Loop on each vat rate
835  $i = 0;
836  foreach ($object->lines as $line) {
837  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
838  $keyforvatrate = $line->tva_tx.($line->vat_src_code ? ' ('.$line->vat_src_code.')' : '');
839 
840  $amount_ht[$keyforvatrate] += $line->total_ht;
841  $amount_tva[$keyforvatrate] += $line->total_tva;
842  $amount_ttc[$keyforvatrate] += $line->total_ttc;
843  $multicurrency_amount_ht[$keyforvatrate] += $line->multicurrency_total_ht;
844  $multicurrency_amount_tva[$keyforvatrate] += $line->multicurrency_total_tva;
845  $multicurrency_amount_ttc[$keyforvatrate] += $line->multicurrency_total_ttc;
846  $i++;
847  }
848  }
849 
850  // If some payments were already done, we change the amount to pay using same prorate
851  if (!empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) && $object->type == Facture::TYPE_CREDIT_NOTE) {
852  $alreadypaid = $object->getSommePaiement(); // This can be not 0 if we allow to create credit to reuse from credit notes partially refunded.
853  if ($alreadypaid && abs($alreadypaid) < abs($object->total_ttc)) {
854  $ratio = abs(($object->total_ttc - $alreadypaid) / $object->total_ttc);
855  foreach ($amount_ht as $vatrate => $val) {
856  $amount_ht[$vatrate] = price2num($amount_ht[$vatrate] * $ratio, 'MU');
857  $amount_tva[$vatrate] = price2num($amount_tva[$vatrate] * $ratio, 'MU');
858  $amount_ttc[$vatrate] = price2num($amount_ttc[$vatrate] * $ratio, 'MU');
859  $multicurrency_amount_ht[$vatrate] = price2num($multicurrency_amount_ht[$vatrate] * $ratio, 'MU');
860  $multicurrency_amount_tva[$vatrate] = price2num($multicurrency_amount_tva[$vatrate] * $ratio, 'MU');
861  $multicurrency_amount_ttc[$vatrate] = price2num($multicurrency_amount_ttc[$vatrate] * $ratio, 'MU');
862  }
863  }
864  }
865  //var_dump($amount_ht);var_dump($amount_tva);var_dump($amount_ttc);exit;
866 
867  // Insert one discount by VAT rate category
868  $discount = new DiscountAbsolute($db);
869  if ($object->type == Facture::TYPE_CREDIT_NOTE) {
870  $discount->description = '(CREDIT_NOTE)';
871  } elseif ($object->type == Facture::TYPE_DEPOSIT) {
872  $discount->description = '(DEPOSIT)';
873  } elseif ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) {
874  $discount->description = '(EXCESS RECEIVED)';
875  } else {
876  setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
877  }
878  $discount->fk_soc = $object->socid;
879  $discount->fk_facture_source = $object->id;
880 
881  $error = 0;
882 
883  if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) {
884  // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
885 
886  // Total payments
887  $sql = 'SELECT SUM(pf.amount) as total_paiements';
888  $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
889  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
890  $sql .= ' WHERE pf.fk_facture = '.((int) $object->id);
891  $sql .= ' AND pf.fk_paiement = p.rowid';
892  $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
893  $resql = $db->query($sql);
894  if (!$resql) {
895  dol_print_error($db);
896  }
897 
898  $res = $db->fetch_object($resql);
899  $total_paiements = $res->total_paiements;
900 
901  // Total credit note and deposit
902  $total_creditnote_and_deposit = 0;
903  $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
904  $sql .= " re.description, re.fk_facture_source";
905  $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
906  $sql .= " WHERE fk_facture = ".((int) $object->id);
907  $resql = $db->query($sql);
908  if (!empty($resql)) {
909  while ($obj = $db->fetch_object($resql)) {
910  $total_creditnote_and_deposit += $obj->amount_ttc;
911  }
912  } else {
913  dol_print_error($db);
914  }
915 
916  $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $object->total_ttc;
917  $discount->amount_tva = 0;
918  $discount->tva_tx = 0;
919  $discount->vat_src_code = '';
920 
921  $result = $discount->create($user);
922  if ($result < 0) {
923  $error++;
924  }
925  }
926  if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
927  foreach ($amount_ht as $tva_tx => $xxx) {
928  $discount->amount_ht = abs($amount_ht[$tva_tx]);
929  $discount->amount_tva = abs($amount_tva[$tva_tx]);
930  $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
931  $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
932  $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
933  $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
934 
935  // Clean vat code
936  $reg = array();
937  $vat_src_code = '';
938  if (preg_match('/\((.*)\)/', $tva_tx, $reg)) {
939  $vat_src_code = $reg[1];
940  $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx); // Remove code into vatrate.
941  }
942 
943  $discount->tva_tx = abs($tva_tx);
944  $discount->vat_src_code = $vat_src_code;
945 
946  $result = $discount->create($user);
947  if ($result < 0) {
948  $error++;
949  break;
950  }
951  }
952  }
953 
954  if (empty($error)) {
955  if ($object->type != Facture::TYPE_DEPOSIT) {
956  // Classe facture
957  $result = $object->setPaid($user);
958  if ($result >= 0) {
959  $db->commit();
960  } else {
961  setEventMessages($object->error, $object->errors, 'errors');
962  $db->rollback();
963  }
964  } else {
965  $db->commit();
966  }
967  } else {
968  setEventMessages($discount->error, $discount->errors, 'errors');
969  $db->rollback();
970  }
971  }
972  } elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercanissuepayment) {
973  // Delete payment
974  $object->fetch($id);
975  if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0) {
976  $paiement = new Paiement($db);
977  $result = $paiement->fetch(GETPOST('paiement_id', 'int'));
978  if ($result > 0) {
979  $result = $paiement->delete(); // If fetch ok and found
980  if ($result >= 0) {
981  header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
982  exit;
983  }
984  }
985  if ($result < 0) {
986  setEventMessages($paiement->error, $paiement->errors, 'errors');
987  }
988  }
989  } elseif ($action == 'add' && $usercancreate) {
990  // Insert new invoice in database
991  if ($socid > 0) {
992  $object->socid = GETPOST('socid', 'int');
993  }
994  $selectedLines = GETPOST('toselect', 'array');
995 
996  if (GETPOST('type', 'int') === '') {
997  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
998  }
999 
1000  $db->begin();
1001 
1002  $error = 0;
1003  $originentity = GETPOST('originentity');
1004  // Fill array 'array_options' with data from add form
1005  $ret = $extrafields->setOptionalsFromPost(null, $object);
1006  if ($ret < 0) {
1007  $error++;
1008  }
1009 
1010  $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
1011  $date_pointoftax = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'), 'tzserver');
1012 
1013  // Replacement invoice
1014  if (GETPOST('type') == Facture::TYPE_REPLACEMENT) {
1015  if (empty($dateinvoice)) {
1016  $error++;
1017  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
1018  $action = 'create';
1019  } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1020  $error++;
1021  setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
1022  $action = 'create';
1023  }
1024 
1025  if (!(GETPOST('fac_replacement', 'int') > 0)) {
1026  $error++;
1027  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
1028  $action = 'create';
1029  }
1030 
1031  if (!$error) {
1032  // This is a replacement invoice
1033  $result = $object->fetch(GETPOST('fac_replacement', 'int'));
1034  $object->fetch_thirdparty();
1035 
1036  $object->date = $dateinvoice;
1037  $object->date_pointoftax = $date_pointoftax;
1038  $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
1039  $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
1040  $object->ref_client = GETPOST('ref_client', 'alphanohtml');
1041  $object->ref_customer = GETPOST('ref_client', 'alphanohtml');
1042  $object->model_pdf = GETPOST('model', 'alphanohtml');
1043  $object->fk_project = GETPOST('projectid', 'int');
1044  $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
1045  $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
1046  $object->fk_account = GETPOST('fk_account', 'int');
1047  $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU', 2);
1048  $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
1049  $object->fk_incoterms = GETPOST('incoterm_id', 'int');
1050  $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
1051  $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
1052  $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
1053 
1054  // Proprietes particulieres a facture de remplacement
1055  $object->fk_facture_source = GETPOST('fac_replacement', 'int');
1056  $object->type = Facture::TYPE_REPLACEMENT;
1057 
1058  $id = $object->createFromCurrent($user);
1059  if ($id <= 0) {
1060  setEventMessages($object->error, $object->errors, 'errors');
1061  }
1062  }
1063  }
1064 
1065  // Credit note invoice
1066  if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) {
1067  $sourceinvoice = GETPOST('fac_avoir', 'int');
1068  if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
1069  $error++;
1070  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
1071  $action = 'create';
1072  }
1073 
1074  if (empty($dateinvoice)) {
1075  $error++;
1076  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
1077  $action = 'create';
1078  } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1079  $error++;
1080  setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
1081  $action = 'create';
1082  }
1083 
1084  if (!$error) {
1085  if (!empty($originentity)) {
1086  $object->entity = $originentity;
1087  }
1088  $object->socid = GETPOST('socid', 'int');
1089  $object->ref = GETPOST('ref');
1090  $object->date = $dateinvoice;
1091  $object->date_pointoftax = $date_pointoftax;
1092  $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
1093  $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
1094  $object->ref_client = GETPOST('ref_client', 'alphanohtml');
1095  $object->ref_customer = GETPOST('ref_client', 'alphanohtml');
1096  $object->model_pdf = GETPOST('model');
1097  $object->fk_project = GETPOST('projectid', 'int');
1098  $object->cond_reglement_id = 0; // No payment term for a credit note
1099  $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
1100  $object->fk_account = GETPOST('fk_account', 'int');
1101  $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
1102  $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
1103  $object->fk_incoterms = GETPOST('incoterm_id', 'int');
1104  $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
1105  $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
1106  $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
1107 
1108  // Proprietes particulieres a facture avoir
1109  $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
1110  $object->type = Facture::TYPE_CREDIT_NOTE;
1111 
1112  $facture_source = new Facture($db); // fetch origin object
1113  if ($facture_source->fetch($object->fk_facture_source) > 0) {
1114  if ($facture_source->type == Facture::TYPE_SITUATION) {
1115  $object->situation_counter = $facture_source->situation_counter;
1116  $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
1117  $facture_source->fetchPreviousNextSituationInvoice();
1118  }
1119  }
1120 
1121 
1122  $id = $object->create($user);
1123  if ($id < 0) {
1124  $error++;
1125  } else {
1126  // copy internal contacts
1127  if ($object->copy_linked_contact($facture_source, 'internal') < 0) {
1128  $error++;
1129  } elseif ($facture_source->socid == $object->socid) {
1130  // copy external contacts if same company
1131  if ($object->copy_linked_contact($facture_source, 'external') < 0) {
1132  $error++;
1133  }
1134  }
1135  }
1136 
1137  // NOTE: Pb with situation invoice
1138  // NOTE: fields total on situation invoice are stored as cumulative values on total of lines (bad) but delta on invoice total
1139  // NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good)
1140  // NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad)
1141  // NOTE: fields situation_percent on credit note are stored as delta on lines (good)
1142  if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) {
1143  if (!empty($facture_source->lines)) {
1144  $fk_parent_line = 0;
1145 
1146  foreach ($facture_source->lines as $line) {
1147  // Extrafields
1148  if (method_exists($line, 'fetch_optionals')) {
1149  // load extrafields
1150  $line->fetch_optionals();
1151  }
1152 
1153  // Reset fk_parent_line for no child products and special product
1154  if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
1155  $fk_parent_line = 0;
1156  }
1157 
1158 
1159  if ($facture_source->type == Facture::TYPE_SITUATION) {
1160  $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
1161  $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
1162 
1163  if (!empty($facture_source->tab_previous_situation_invoice)) {
1164  // search the last standard invoice in cycle and the possible credit note between this last and facture_source
1165  // TODO Move this out of loop of $facture_source->lines
1166  $tab_jumped_credit_notes = array();
1167  $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
1168  $searchPreviousInvoice = true;
1169  while ($searchPreviousInvoice) {
1170  if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
1171  $searchPreviousInvoice = false; // find, exit;
1172  break;
1173  } else {
1174  if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
1175  $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
1176  }
1177  $lineIndex--; // go to previous invoice in cycle
1178  }
1179  }
1180 
1181  $maxPrevSituationPercent = 0;
1182  foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
1183  if ($prevLine->id == $source_fk_prev_id) {
1184  $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
1185 
1186  //$line->subprice = $line->subprice - $prevLine->subprice;
1187  $line->total_ht = $line->total_ht - $prevLine->total_ht;
1188  $line->total_tva = $line->total_tva - $prevLine->total_tva;
1189  $line->total_ttc = $line->total_ttc - $prevLine->total_ttc;
1190  $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1;
1191  $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2;
1192 
1193  $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice;
1194  $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht;
1195  $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva;
1196  $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc;
1197  }
1198  }
1199 
1200  // prorata
1201  $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
1202 
1203  //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
1204 
1205  // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
1206  $maxPrevSituationPercent = 0;
1207  foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
1208  foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
1209  if ($prevLine->fk_prev_id == $source_fk_prev_id) {
1210  $maxPrevSituationPercent = $prevLine->situation_percent;
1211 
1212  $line->total_ht -= $prevLine->total_ht;
1213  $line->total_tva -= $prevLine->total_tva;
1214  $line->total_ttc -= $prevLine->total_ttc;
1215  $line->total_localtax1 -= $prevLine->total_localtax1;
1216  $line->total_localtax2 -= $prevLine->total_localtax2;
1217 
1218  $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
1219  $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
1220  $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
1221  $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
1222  }
1223  }
1224  }
1225 
1226  // prorata
1227  $line->situation_percent += $maxPrevSituationPercent;
1228 
1229  //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
1230  }
1231  }
1232 
1233  $line->fk_facture = $object->id;
1234  $line->fk_parent_line = $fk_parent_line;
1235 
1236  $line->subprice = -$line->subprice; // invert price for object
1237  $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
1238  $line->total_ht = -$line->total_ht;
1239  $line->total_tva = -$line->total_tva;
1240  $line->total_ttc = -$line->total_ttc;
1241  $line->total_localtax1 = -$line->total_localtax1;
1242  $line->total_localtax2 = -$line->total_localtax2;
1243 
1244  $line->multicurrency_subprice = -$line->multicurrency_subprice;
1245  $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
1246  $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
1247  $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
1248 
1249  $line->context['createcreditnotefrominvoice'] = 1;
1250  $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
1251 
1252  $object->lines[] = $line; // insert new line in current object
1253 
1254  // Defined the new fk_parent_line
1255  if ($result > 0 && $line->product_type == 9) {
1256  $fk_parent_line = $result;
1257  }
1258  }
1259 
1260  $object->update_price(1);
1261  }
1262  }
1263 
1264  if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) {
1265  if ($facture_source->fetch($object->fk_facture_source) > 0) {
1266  $totalpaid = $facture_source->getSommePaiement();
1267  $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
1268  $totaldeposits = $facture_source->getSumDepositsUsed();
1269  $remain_to_pay = abs($facture_source->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits);
1270 
1271  $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 1, 0, 0, 0, 0, 0, '', '', 'TTC');
1272  }
1273  }
1274 
1275  // Add link between credit note and origin
1276  if (!empty($object->fk_facture_source) && $id > 0) {
1277  $facture_source->fetch($object->fk_facture_source);
1278  $facture_source->fetchObjectLinked();
1279 
1280  if (!empty($facture_source->linkedObjectsIds)) {
1281  foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
1282  $object->add_object_linked($sourcetype, current($TIds));
1283  }
1284  }
1285  }
1286  }
1287  }
1288 
1289  // Standard invoice or Deposit invoice, created from a Predefined template invoice
1290  if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT) && GETPOST('fac_rec', 'int') > 0) {
1291  if (empty($dateinvoice)) {
1292  $error++;
1293  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
1294  $action = 'create';
1295  } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1296  $error++;
1297  setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
1298  $action = 'create';
1299  }
1300 
1301  if (!$error) {
1302  $object->socid = GETPOST('socid', 'int');
1303  $object->type = GETPOST('type');
1304  $object->ref = GETPOST('ref');
1305  $object->date = $dateinvoice;
1306  $object->date_pointoftax = $date_pointoftax;
1307  $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
1308  $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
1309  $object->ref_customer = GETPOST('ref_client');
1310  $object->ref_client = $object->ref_customer;
1311  $object->model_pdf = GETPOST('model');
1312  $object->fk_project = GETPOST('projectid', 'int');
1313  $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
1314  $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
1315  $object->fk_account = GETPOST('fk_account', 'int');
1316  $object->amount = price2num(GETPOST('amount'));
1317  $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
1318  $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
1319  $object->fk_incoterms = GETPOST('incoterm_id', 'int');
1320  $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
1321  $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
1322  $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
1323 
1324  // Source facture
1325  $object->fac_rec = GETPOST('fac_rec', 'int');
1326 
1327  $id = $object->create($user); // This include recopy of links from recurring invoice and recurring invoice lines
1328  }
1329  }
1330 
1331  // Standard or deposit invoice, not from a Predefined template invoice
1332  if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT || GETPOST('type') == Facture::TYPE_PROFORMA || (GETPOST('type') == Facture::TYPE_SITUATION && !GETPOST('situations'))) && GETPOST('fac_rec') <= 0) {
1333  $typeamount = GETPOST('typedeposit', 'aZ09');
1334  $valuestandardinvoice = price2num(str_replace('%', '', GETPOST('valuestandardinvoice', 'alpha')), 'MU');
1335  $valuedeposit = price2num(str_replace('%', '', GETPOST('valuedeposit', 'alpha')), 'MU');
1336 
1337  if (GETPOST('socid', 'int') < 1) {
1338  $error++;
1339  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors');
1340  $action = 'create';
1341  }
1342 
1343  if (empty($dateinvoice)) {
1344  $error++;
1345  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
1346  $action = 'create';
1347  } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1348  $error++;
1349  setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
1350  $action = 'create';
1351  }
1352 
1353 
1354  if (GETPOST('type') == Facture::TYPE_STANDARD) {
1355  if ($valuestandardinvoice < 0 || $valuestandardinvoice > 100) {
1356  setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
1357  $error++;
1358  $action = 'create';
1359  }
1360  } elseif (GETPOST('type') == Facture::TYPE_DEPOSIT) {
1361  if ($typeamount && !empty($origin) && !empty($originid)) {
1362  if ($typeamount == 'amount' && $valuedeposit <= 0) {
1363  setEventMessages($langs->trans("ErrorAnAmountWithoutTaxIsRequired"), null, 'errors');
1364  $error++;
1365  $action = 'create';
1366  }
1367  if ($typeamount == 'variable' && $valuedeposit <= 0) {
1368  setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
1369  $error++;
1370  $action = 'create';
1371  }
1372  if ($typeamount == 'variablealllines' && $valuedeposit <= 0) {
1373  setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
1374  $error++;
1375  $action = 'create';
1376  }
1377  }
1378  }
1379 
1380  if (!$error) {
1381  // Si facture standard
1382  $object->socid = GETPOST('socid', 'int');
1383  $object->type = GETPOST('type');
1384  $object->ref = GETPOST('ref');
1385  $object->date = $dateinvoice;
1386  $object->date_pointoftax = $date_pointoftax;
1387  $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
1388  $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
1389  $object->ref_client = GETPOST('ref_client');
1390  $object->ref_customer = GETPOST('ref_client');
1391  $object->model_pdf = GETPOST('model');
1392  $object->fk_project = GETPOST('projectid', 'int');
1393  $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
1394  $object->mode_reglement_id = GETPOST('mode_reglement_id');
1395  $object->fk_account = GETPOST('fk_account', 'int');
1396  $object->amount = price2num(GETPOST('amount'));
1397  $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
1398  $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
1399  $object->fk_incoterms = GETPOST('incoterm_id', 'int');
1400  $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
1401  $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
1402  $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
1403 
1404  if (GETPOST('type') == Facture::TYPE_SITUATION) {
1405  $object->situation_counter = 1;
1406  $object->situation_final = 0;
1407  $object->situation_cycle_ref = $object->newCycle();
1408  }
1409 
1410  if (in_array($object->type, $retainedWarrantyInvoiceAvailableType)) {
1411  $object->retained_warranty = GETPOST('retained_warranty', 'int');
1412  $object->retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
1413  } else {
1414  $object->retained_warranty = 0;
1415  $object->retained_warranty_fk_cond_reglement = 0;
1416  }
1417 
1418  $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit');
1419  if (!empty($retained_warranty_date_limit) && dol_stringtotime($retained_warranty_date_limit)) {
1420  $object->retained_warranty_date_limit = dol_stringtotime($retained_warranty_date_limit);
1421  }
1422  $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
1423 
1424  $object->fetch_thirdparty();
1425 
1426  // If creation from another object of another module (Example: origin=propal, originid=1)
1427  if (!empty($origin) && !empty($originid)) {
1428  $regs = array();
1429  // Parse element/subelement (ex: project_task)
1430  $element = $subelement = $origin;
1431  if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
1432  $element = $regs[1];
1433  $subelement = $regs[2];
1434  }
1435 
1436  // For compatibility
1437  if ($element == 'order') {
1438  $element = $subelement = 'commande';
1439  }
1440  if ($element == 'propal') {
1441  $element = 'comm/propal';
1442  $subelement = 'propal';
1443  }
1444  if ($element == 'contract') {
1445  $element = $subelement = 'contrat';
1446  }
1447  if ($element == 'inter') {
1448  $element = $subelement = 'ficheinter';
1449  }
1450  if ($element == 'shipping') {
1451  $element = $subelement = 'expedition';
1452  }
1453 
1454  $object->origin = $origin;
1455  $object->origin_id = $originid;
1456 
1457  // Possibility to add external linked objects with hooks
1458  $object->linked_objects[$object->origin] = $object->origin_id;
1459  // link with order if it is a shipping invoice
1460  if ($object->origin == 'shipping') {
1461  require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1462  $exp = new Expedition($db);
1463  $exp->fetch($object->origin_id);
1464  $exp->fetchObjectLinked();
1465  if (is_array($exp->linkedObjectsIds['commande']) && count($exp->linkedObjectsIds['commande']) > 0) {
1466  foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
1467  $object->linked_objects['commande'] = $value;
1468  }
1469  }
1470  }
1471 
1472  if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) {
1473  $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
1474  }
1475 
1476  $id = $object->create($user); // This include class to add_object_linked() and add add_contact()
1477 
1478  if ($id > 0) {
1479  dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
1480 
1481  $classname = ucfirst($subelement);
1482  $srcobject = new $classname($db);
1483 
1484  dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines or deposit lines");
1485  $result = $srcobject->fetch($object->origin_id);
1486 
1487  // If deposit invoice - down payment with 1 line (fixed amount or percent)
1488  if (GETPOST('type') == Facture::TYPE_DEPOSIT && in_array($typeamount, array('amount', 'variable'))) {
1489  // Define the array $amountdeposit
1490  $amountdeposit = array();
1491  if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
1492  if ($typeamount == 'amount') {
1493  $amount = $valuedeposit;
1494  } else {
1495  $amount = $srcobject->total_ttc * ($valuedeposit / 100);
1496  }
1497 
1498  $TTotalByTva = array();
1499  foreach ($srcobject->lines as &$line) {
1500  if (!empty($line->special_code)) {
1501  continue;
1502  }
1503  $TTotalByTva[$line->tva_tx] += $line->total_ttc;
1504  }
1505 
1506  foreach ($TTotalByTva as $tva => &$total) {
1507  $coef = $total / $srcobject->total_ttc; // Calc coef
1508  $am = $amount * $coef;
1509  $amount_ttc_diff += $am;
1510  $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
1511  }
1512  } else {
1513  if ($typeamount == 'amount') {
1514  $amountdeposit[0] = $valuedeposit;
1515  } elseif ($typeamount == 'variable') {
1516  if ($result > 0) {
1517  $totalamount = 0;
1518  $lines = $srcobject->lines;
1519  $numlines = count($lines);
1520  for ($i = 0; $i < $numlines; $i++) {
1521  $qualified = 1;
1522  if (empty($lines[$i]->qty)) {
1523  $qualified = 0; // We discard qty=0, it is an option
1524  }
1525  if (!empty($lines[$i]->special_code)) {
1526  $qualified = 0; // We discard special_code (frais port, ecotaxe, option, ...)
1527  }
1528  if ($qualified) {
1529  $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
1530  $tva_tx = $lines[$i]->tva_tx;
1531  $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $valuedeposit) / 100;
1532  }
1533  }
1534 
1535  if ($totalamount == 0) {
1536  $amountdeposit[0] = 0;
1537  }
1538  } else {
1539  setEventMessages($srcobject->error, $srcobject->errors, 'errors');
1540  $error++;
1541  }
1542  }
1543 
1544  $amount_ttc_diff = $amountdeposit[0];
1545  }
1546 
1547  foreach ($amountdeposit as $tva => $amount) {
1548  if (empty($amount)) {
1549  continue;
1550  }
1551 
1552  $arraylist = array(
1553  'amount' => 'FixAmount',
1554  'variable' => 'VarAmount'
1555  );
1556  $descline = '(DEPOSIT)';
1557  //$descline.= ' - '.$langs->trans($arraylist[$typeamount]);
1558  if ($typeamount == 'amount') {
1559  $descline .= ' ('.price($valuedeposit, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).')';
1560  } elseif ($typeamount == 'variable') {
1561  $descline .= ' ('.$valuedeposit.'%)';
1562  }
1563 
1564  $descline .= ' - '.$srcobject->ref;
1565  $result = $object->addline(
1566  $descline,
1567  $amount, // subprice
1568  1, // quantity
1569  $tva, // vat rate
1570  0, // localtax1_tx
1571  0, // localtax2_tx
1572  (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
1573  0, // remise_percent
1574  0, // date_start
1575  0, // date_end
1576  0,
1577  $lines[$i]->info_bits, // info_bits
1578  0,
1579  'HT',
1580  0,
1581  0, // product_type
1582  1,
1583  $lines[$i]->special_code,
1584  $object->origin,
1585  0,
1586  0,
1587  0,
1588  0,
1589  '',
1590  0,
1591  100,
1592  0,
1593  null,
1594  0,
1595  '',
1596  1
1597  );
1598  }
1599 
1600  $diff = $object->total_ttc - $amount_ttc_diff;
1601 
1602  if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
1603  $object->fetch_lines();
1604  $subprice_diff = $object->lines[0]->subprice - $diff / (1 + $object->lines[0]->tva_tx / 100);
1605  $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);
1606  }
1607  }
1608 
1609  // standard invoice, credit note, or down payment from a percent of all lines
1610  if (GETPOST('type') != Facture::TYPE_DEPOSIT || (GETPOST('type') == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines')) {
1611  if ($result > 0) {
1612  $lines = $srcobject->lines;
1613  if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
1614  $srcobject->fetch_lines();
1615  $lines = $srcobject->lines;
1616  }
1617 
1618  // If we create a standard invoice with a percent, we change amount by changing the qty
1619  if (GETPOST('type') == Facture::TYPE_STANDARD && $valuestandardinvoice > 0 && $valuestandardinvoice < 100) {
1620  if (is_array($lines)) {
1621  foreach ($lines as $line) {
1622  // We keep ->subprice and ->pa_ht, but we change the qty
1623  $line->qty = price2num($line->qty * $valuestandardinvoice / 100, 'MS');
1624  }
1625  }
1626  }
1627  // If we create a down payment with a percent on all lines, we change amount by changing the qty
1628  if (GETPOST('type') == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines') {
1629  if (is_array($lines)) {
1630  foreach ($lines as $line) {
1631  // We keep ->subprice and ->pa_ht, but we change the qty
1632  $line->qty = price2num($line->qty * $valuedeposit / 100, 'MS');
1633  }
1634  }
1635  }
1636 
1637  $fk_parent_line = 0;
1638  $num = count($lines);
1639 
1640  for ($i = 0; $i < $num; $i++) {
1641  if (!in_array($lines[$i]->id, $selectedLines)) {
1642  continue; // Skip unselected lines
1643  }
1644 
1645  // Don't add lines with qty 0 when coming from a shipment including all order lines
1646  if ($srcobject->element == 'shipping' && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS && $lines[$i]->qty == 0) {
1647  continue;
1648  }
1649  // Don't add closed lines when coming from a contract (Set constant to '0,5' to exclude also inactive lines)
1650  if (!isset($conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE)) {
1651  $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE = '5';
1652  }
1653  if ($srcobject->element == 'contrat' && in_array($lines[$i]->statut, explode(',', $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE))) {
1654  continue;
1655  }
1656 
1657  $label = (!empty($lines[$i]->label) ? $lines[$i]->label : '');
1658  $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->label);
1659  if ($object->situation_counter == 1) {
1660  $lines[$i]->situation_percent = 0;
1661  }
1662 
1663  if ($lines[$i]->subprice < 0 && empty($conf->global->INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN)) {
1664  // Negative line, we create a discount line
1665  if (empty($desc)) {
1666  $desc = $label ? $label : $langs->trans('Discount');
1667  }
1668 
1669  $discount = new DiscountAbsolute($db);
1670  $discount->fk_soc = $object->socid;
1671  $discount->amount_ht = abs($lines[$i]->total_ht);
1672  $discount->amount_tva = abs($lines[$i]->total_tva);
1673  $discount->amount_ttc = abs($lines[$i]->total_ttc);
1674  $discount->tva_tx = $lines[$i]->tva_tx;
1675  $discount->fk_user = $user->id;
1676  $discount->description = $desc;
1677  $discount->multicurrency_subprice = abs($lines[$i]->multicurrency_subprice);
1678  $discount->multicurrency_amount_ht = abs($lines[$i]->multicurrency_total_ht);
1679  $discount->multicurrency_amount_tva = abs($lines[$i]->multicurrency_total_tva);
1680  $discount->multicurrency_amount_ttc = abs($lines[$i]->multicurrency_total_ttc);
1681 
1682  $discountid = $discount->create($user);
1683  if ($discountid > 0) {
1684  $result = $object->insert_discount($discountid); // This include link_to_invoice
1685  } else {
1686  setEventMessages($discount->error, $discount->errors, 'errors');
1687  $error++;
1688  break;
1689  }
1690  } else {
1691  // Positive line
1692  $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
1693 
1694  // Date start
1695  $date_start = false;
1696  if ($lines[$i]->date_debut_prevue) {
1697  $date_start = $lines[$i]->date_debut_prevue;
1698  }
1699  if ($lines[$i]->date_debut_reel) {
1700  $date_start = $lines[$i]->date_debut_reel;
1701  }
1702  if ($lines[$i]->date_start) {
1703  $date_start = $lines[$i]->date_start;
1704  }
1705 
1706  // Date end
1707  $date_end = false;
1708  if ($lines[$i]->date_fin_prevue) {
1709  $date_end = $lines[$i]->date_fin_prevue;
1710  }
1711  if ($lines[$i]->date_fin_reel) {
1712  $date_end = $lines[$i]->date_fin_reel;
1713  }
1714  if ($lines[$i]->date_end) {
1715  $date_end = $lines[$i]->date_end;
1716  }
1717 
1718  // Reset fk_parent_line for no child products and special product
1719  if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
1720  $fk_parent_line = 0;
1721  }
1722 
1723  // Extrafields
1724  if (method_exists($lines[$i], 'fetch_optionals')) {
1725  $lines[$i]->fetch_optionals();
1726  $array_options = $lines[$i]->array_options;
1727  }
1728 
1729  $tva_tx = $lines[$i]->tva_tx;
1730  if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) {
1731  $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
1732  }
1733 
1734  // View third's localtaxes for NOW and do not use value from origin.
1735  // TODO Is this really what we want ? Yes if source is template invoice but what if proposal or order ?
1736  $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty);
1737  $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty);
1738 
1739  $result = $object->addline(
1740  $desc,
1741  $lines[$i]->subprice,
1742  $lines[$i]->qty,
1743  $tva_tx,
1744  $localtax1_tx,
1745  $localtax2_tx,
1746  $lines[$i]->fk_product,
1747  $lines[$i]->remise_percent,
1748  $date_start,
1749  $date_end,
1750  0,
1751  $lines[$i]->info_bits,
1752  $lines[$i]->fk_remise_except,
1753  'HT',
1754  0,
1755  $product_type,
1756  $lines[$i]->rang,
1757  $lines[$i]->special_code,
1758  $object->origin,
1759  $lines[$i]->rowid,
1760  $fk_parent_line,
1761  $lines[$i]->fk_fournprice,
1762  $lines[$i]->pa_ht,
1763  $label,
1764  $array_options,
1765  $lines[$i]->situation_percent,
1766  $lines[$i]->fk_prev_id,
1767  $lines[$i]->fk_unit,
1768  0,
1769  '',
1770  1
1771  );
1772 
1773  if ($result > 0) {
1774  $lineid = $result;
1775  } else {
1776  $lineid = 0;
1777  $error++;
1778  break;
1779  }
1780 
1781  // Defined the new fk_parent_line
1782  if ($result > 0 && $lines[$i]->product_type == 9) {
1783  $fk_parent_line = $result;
1784  }
1785  }
1786  }
1787  } else {
1788  setEventMessages($srcobject->error, $srcobject->errors, 'errors');
1789  $error++;
1790  }
1791  }
1792 
1793  $object->update_price(1, 'auto', 0, $mysoc);
1794 
1795  // Now we create same links to contact than the ones found on origin object
1796  /* Useless, already into the create
1797  if (!empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN))
1798  {
1799  $originforcontact = $object->origin;
1800  $originidforcontact = $object->origin_id;
1801  if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order
1802  {
1803  $originforcontact=$srcobject->origin;
1804  $originidforcontact=$srcobject->origin_id;
1805  }
1806  $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
1807  $sqlcontact.= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'";
1808 
1809  $resqlcontact = $db->query($sqlcontact);
1810  if ($resqlcontact)
1811  {
1812  while($objcontact = $db->fetch_object($resqlcontact))
1813  {
1814  //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n";
1815  $object->add_contact($objcontact->fk_socpeople, $objcontact->code);
1816  }
1817  }
1818  else dol_print_error($resqlcontact);
1819  }*/
1820 
1821  // Hooks
1822  $parameters = array('objFrom' => $srcobject);
1823  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
1824  // modified by hook
1825  if ($reshook < 0) {
1826  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1827  $error++;
1828  }
1829  } else {
1830  setEventMessages($object->error, $object->errors, 'errors');
1831  $error++;
1832  }
1833  } else { // If some invoice's lines coming from page
1834  $id = $object->create($user);
1835 
1836  for ($i = 1; $i <= $NBLINES; $i++) {
1837  if (GETPOST('idprod'.$i, 'int')) {
1838  $product = new Product($db);
1839  $product->fetch(GETPOST('idprod'.$i, 'int'));
1840  $startday = dol_mktime(12, 0, 0, GETPOST('date_start'.$i.'month'), GETPOST('date_start'.$i.'day'), GETPOST('date_start'.$i.'year'));
1841  $endday = dol_mktime(12, 0, 0, GETPOST('date_end'.$i.'month'), GETPOST('date_end'.$i.'day'), GETPOST('date_end'.$i.'year'));
1842  $result = $object->addline($product->description, $product->price, price2num(GETPOST('qty'.$i), 'MS'), $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, GETPOST('idprod'.$i, 'int'), price2num(GETPOST('remise_percent'.$i), '', 2), $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type, -1, 0, '', 0, 0, null, 0, '', 0, 100, '', $product->fk_unit, 0, '', 1);
1843  }
1844  }
1845 
1846  $object->update_price(1, 'auto', 0, $mysoc);
1847  }
1848  }
1849  }
1850 
1851  // Situation invoices
1852  if (GETPOST('type') == Facture::TYPE_SITUATION && GETPOST('situations')) {
1853  if (empty($dateinvoice)) {
1854  $error++;
1855  $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date"));
1856  setEventMessages($mesg, null, 'errors');
1857  } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
1858  $error++;
1859  setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
1860  $action = 'create';
1861  }
1862 
1863  if (!(GETPOST('situations', 'int') > 0)) {
1864  $error++;
1865  $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceSituation"));
1866  setEventMessages($mesg, null, 'errors');
1867  $action = 'create';
1868  }
1869 
1870  if (!$error) {
1871  $result = $object->fetch(GETPOST('situations', 'int'));
1872  $object->fk_facture_source = GETPOST('situations', 'int');
1873  $object->type = Facture::TYPE_SITUATION;
1874 
1875  if (!empty($origin) && !empty($originid)) {
1876  include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
1877 
1878  $object->origin = $origin;
1879  $object->origin_id = $originid;
1880 
1881  // retained warranty
1882  if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
1883  $retained_warranty = GETPOST('retained_warranty', 'int');
1884  if (price2num($retained_warranty) > 0) {
1885  $object->retained_warranty = price2num($retained_warranty);
1886  }
1887 
1888  if (GETPOST('retained_warranty_fk_cond_reglement', 'int') > 0) {
1889  $object->retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
1890  }
1891 
1892  $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit');
1893  if (!empty($retained_warranty_date_limit) && $db->jdate($retained_warranty_date_limit)) {
1894  $object->retained_warranty_date_limit = $db->jdate($retained_warranty_date_limit);
1895  }
1896  $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
1897  }
1898 
1899  foreach ($object->lines as $i => &$line) {
1900  $line->origin = $object->origin;
1901  $line->origin_id = $line->id;
1902  $line->fk_prev_id = $line->id;
1903  $line->fetch_optionals();
1904  $line->situation_percent = $line->get_prev_progress($object->id); // get good progress including credit note
1905 
1906  // The $line->situation_percent has been modified, so we must recalculate all amounts
1907  $tabprice = calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 0, 'HT', 0, $line->product_type, $mysoc, '', $line->situation_percent);
1908  $line->total_ht = $tabprice[0];
1909  $line->total_tva = $tabprice[1];
1910  $line->total_ttc = $tabprice[2];
1911  $line->total_localtax1 = $tabprice[9];
1912  $line->total_localtax2 = $tabprice[10];
1913  $line->multicurrency_total_ht = $tabprice[16];
1914  $line->multicurrency_total_tva = $tabprice[17];
1915  $line->multicurrency_total_ttc = $tabprice[18];
1916 
1917  // Si fk_remise_except defini on vérifie si la réduction à déjà été appliquée
1918  if ($line->fk_remise_except) {
1919  $discount = new DiscountAbsolute($line->db);
1920  $result = $discount->fetch($line->fk_remise_except);
1921  if ($result > 0) {
1922  // Check if discount not already affected to another invoice
1923  if ($discount->fk_facture_line > 0) {
1924  $line->fk_remise_except = 0;
1925  }
1926  }
1927  }
1928  }
1929  }
1930 
1931  $object->fetch_thirdparty();
1932  $object->date = $dateinvoice;
1933  $object->date_pointoftax = $date_pointoftax;
1934  $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
1935  $object->note = trim(GETPOST('note', 'restricthtml'));
1936  $object->note_private = trim(GETPOST('note', 'restricthtml'));
1937  $object->ref_client = GETPOST('ref_client', 'alpha');
1938  $object->model_pdf = GETPOST('model', 'alpha');
1939  $object->fk_project = GETPOST('projectid', 'int');
1940  $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
1941  $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
1942  $object->remise_absolue =price2num(GETPOST('remise_absolue'), 'MU', 2);
1943  $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
1944 
1945  // Proprietes particulieres a facture de remplacement
1946 
1947  $object->situation_counter = $object->situation_counter + 1;
1948  $id = $object->createFromCurrent($user);
1949  if ($id <= 0) {
1950  $mesg = $object->error;
1951  } else {
1952  $nextSituationInvoice = new Facture($db);
1953  $nextSituationInvoice->fetch($id);
1954 
1955  // create extrafields with data from create form
1956  $extrafields->fetch_name_optionals_label($nextSituationInvoice->table_element);
1957  $ret = $extrafields->setOptionalsFromPost(null, $nextSituationInvoice);
1958  if ($ret > 0) {
1959  $nextSituationInvoice->insertExtraFields();
1960  }
1961  }
1962  }
1963  }
1964 
1965  // End of object creation, we show it
1966  if ($id > 0 && !$error) {
1967  $db->commit();
1968 
1969  // Define output language
1970  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && count($object->lines)) {
1971  $outputlangs = $langs;
1972  $newlang = '';
1973  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
1974  $newlang = GETPOST('lang_id', 'aZ09');
1975  }
1976  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1977  $newlang = $object->thirdparty->default_lang;
1978  }
1979  if (!empty($newlang)) {
1980  $outputlangs = new Translate("", $conf);
1981  $outputlangs->setDefaultLang($newlang);
1982  $outputlangs->load('products');
1983  }
1984  $model = $object->model_pdf;
1985  $ret = $object->fetch($id); // Reload to get new records
1986 
1987  $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1988  if ($result < 0) {
1989  setEventMessages($object->error, $object->errors, 'errors');
1990  }
1991  }
1992 
1993  header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id);
1994  exit();
1995  } else {
1996  $db->rollback();
1997  $action = 'create';
1998  $_GET["origin"] = $_POST["origin"];
1999  $_GET["originid"] = $_POST["originid"];
2000  setEventMessages($object->error, $object->errors, 'errors');
2001  }
2002  } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('vatforalllines', 'alpha') !== '') {
2003  // Define vat_rate
2004  $vat_rate = (GETPOST('vatforalllines') ? GETPOST('vatforalllines') : 0);
2005  $vat_rate = str_replace('*', '', $vat_rate);
2006  $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
2007  $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
2008  foreach ($object->lines as $line) {
2009  $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice);
2010  }
2011  } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('remiseforalllines', 'alpha') !== '' && $usercancreate) {
2012  // Define vat_rate
2013  $remise_percent = (GETPOST('remiseforalllines') ? GETPOST('remiseforalllines') : 0);
2014  $remise_percent = str_replace('*', '', $remise_percent);
2015  foreach ($object->lines as $line) {
2016  $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice);
2017  }
2018  } elseif ($action == 'addline' && $usercancreate) { // Add a new line
2019  $langs->load('errors');
2020  $error = 0;
2021 
2022  // Set if we used free entry or predefined product
2023  $predef = '';
2024  $product_desc =(GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
2025 
2026  $price_ht = '';
2027  $price_ht_devise = '';
2028  $price_ttc = '';
2029  $price_ttc_devise = '';
2030 
2031  if (GETPOST('price_ht') !== '') {
2032  $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
2033  }
2034  if (GETPOST('multicurrency_price_ht') !== '') {
2035  $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
2036  }
2037  if (GETPOST('price_ttc') !== '') {
2038  $price_ttc = price2num(GETPOST('price_ttc'), 'MU', 2);
2039  }
2040  if (GETPOST('multicurrency_price_ttc') !== '') {
2041  $price_ttc_devise = price2num(GETPOST('multicurrency_price_ttc'), 'CU', 2);
2042  }
2043 
2044  $prod_entry_mode = GETPOST('prod_entry_mode', 'aZ09');
2045  if ($prod_entry_mode == 'free') {
2046  $idprod = 0;
2047  $tva_tx = (GETPOSTISSET('tva_tx') ? GETPOST('tva_tx', 'alpha') : 0);
2048  } else {
2049  $idprod = GETPOST('idprod', 'int');
2050  $tva_tx = '';
2051  }
2052 
2053  $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS', 2);
2054  $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef, 'alpha'), '', 2) : 0);
2055  if (empty($remise_percent)) {
2056  $remise_percent = 0;
2057  }
2058 
2059  // Extrafields
2060  $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
2061  $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
2062  // Unset extrafield
2063  if (is_array($extralabelsline)) {
2064  // Get extra fields
2065  foreach ($extralabelsline as $key => $value) {
2066  unset($_POST["options_".$key.$predef]);
2067  }
2068  }
2069 
2070  if ((empty($idprod) || $idprod < 0) && ($price_ht < 0) && ($qty < 0)) {
2071  setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
2072  $error++;
2073  }
2074  if (!$prod_entry_mode) {
2075  if (GETPOST('type') < 0 && !GETPOST('search_idprod')) {
2076  setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors');
2077  $error++;
2078  }
2079  }
2080  if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
2081  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
2082  $error++;
2083  }
2084  if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && (($price_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $price_ht == '') && (($price_ht_devise < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $price_ht_devise == '') && $price_ttc === '' && $price_ttc_devise === '' && $object->type != Facture::TYPE_CREDIT_NOTE) { // Unit price can be 0 but not ''
2085  if (($price_ht < 0 || $price_ttc < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) {
2086  $langs->load("errors");
2087  if ($object->type == $object::TYPE_DEPOSIT) {
2088  // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
2089  setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
2090  } else {
2091  setEventMessages($langs->trans("ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv("UnitPriceHT"), $langs->transnoentitiesnoconv("CustomerAbsoluteDiscountShort")), null, 'errors');
2092  }
2093  $error++;
2094  } else {
2095  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
2096  $error++;
2097  }
2098  }
2099  if ($qty == '') {
2100  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
2101  $error++;
2102  }
2103  if ($prod_entry_mode == 'free' && empty($idprod) && empty($product_desc)) {
2104  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
2105  $error++;
2106  }
2107  if ($qty < 0) {
2108  $langs->load("errors");
2109  setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
2110  $error++;
2111  }
2112 
2113  if (!$error && isModEnabled('variants') && $prod_entry_mode != 'free') {
2114  if ($combinations = GETPOST('combinations', 'array')) {
2115  //Check if there is a product with the given combination
2116  $prodcomb = new ProductCombination($db);
2117 
2118  if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
2119  $idprod = $res->fk_product_child;
2120  } else {
2121  setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
2122  $error++;
2123  }
2124  }
2125  }
2126 
2127  if (!$error && ($qty >= 0) && (!empty($product_desc) || (!empty($idprod) && $idprod > 0))) {
2128  $ret = $object->fetch($id);
2129  if ($ret < 0) {
2130  dol_print_error($db, $object->error);
2131  exit();
2132  }
2133  $ret = $object->fetch_thirdparty();
2134 
2135  // Clean parameters
2136  $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'));
2137  $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'));
2138  $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
2139 
2140  // Define special_code for special lines
2141  $special_code = 0;
2142  // if (!GETPOST(qty)) $special_code=3; // Options should not exists on invoices
2143 
2144  // Ecrase $pu par celui du produit
2145  // Ecrase $desc par celui du produit
2146  // Ecrase $tva_tx par celui du produit
2147  // Ecrase $base_price_type par celui du produit
2148  // Replaces $fk_unit with the product's
2149  if (!empty($idprod) && $idprod > 0) {
2150  $prod = new Product($db);
2151  $prod->fetch($idprod);
2152 
2153  $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
2154 
2155  // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
2156  $pqp = (GETPOST('pbq', 'int') ? GETPOST('pbq', 'int') : 0);
2157 
2158  $datapriceofproduct = $prod->getSellPrice($mysoc, $object->thirdparty, $pqp);
2159 
2160  $pu_ht = $datapriceofproduct['pu_ht'];
2161  $pu_ttc = $datapriceofproduct['pu_ttc'];
2162  $price_min = $datapriceofproduct['price_min'];
2163  $price_min_ttc = (isset($datapriceofproduct['price_min_ttc'])) ? $datapriceofproduct['price_min_ttc'] : null;
2164  $price_base_type = empty($datapriceofproduct['price_base_type']) ? 'HT' : $datapriceofproduct['price_base_type'];
2165  $tva_tx = $datapriceofproduct['tva_tx'];
2166  $tva_npr = $datapriceofproduct['tva_npr'];
2167 
2168  $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
2169  $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
2170 
2171  // Set unit price to use
2172  if (!empty($price_ht) || $price_ht === '0') {
2173  $pu_ht = price2num($price_ht, 'MU');
2174  $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
2175  } elseif (!empty($price_ttc) || $price_ttc === '0') {
2176  $pu_ttc = price2num($price_ttc, 'MU');
2177  $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
2178  } elseif ($tmpvat != $tmpprodvat) {
2179  // Is this still used ?
2180  if ($price_base_type != 'HT') {
2181  $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
2182  } else {
2183  $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
2184  }
2185  }
2186 
2187  $desc = '';
2188 
2189  // Define output language
2190  if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
2191  $outputlangs = $langs;
2192  $newlang = '';
2193  if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
2194  $newlang = GETPOST('lang_id', 'aZ09');
2195  }
2196  if (empty($newlang)) {
2197  $newlang = $object->thirdparty->default_lang;
2198  }
2199  if (!empty($newlang)) {
2200  $outputlangs = new Translate("", $conf);
2201  $outputlangs->setDefaultLang($newlang);
2202  $outputlangs->load('products');
2203  }
2204 
2205  $desc = (!empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description;
2206  } else {
2207  $desc = $prod->description;
2208  }
2209 
2210  //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time
2211  if ($product_desc==$desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) {
2212  $product_desc='';
2213  }
2214 
2215  if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) {
2216  $desc = $product_desc;
2217  } else {
2218  $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
2219  }
2220 
2221  // Add custom code and origin country into description
2222  if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) {
2223  $tmptxt = '(';
2224  // Define output language
2225  if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
2226  $outputlangs = $langs;
2227  $newlang = '';
2228  if (empty($newlang) && GETPOST('lang_id', 'alpha')) {
2229  $newlang = GETPOST('lang_id', 'alpha');
2230  }
2231  if (empty($newlang)) {
2232  $newlang = $object->thirdparty->default_lang;
2233  }
2234  if (!empty($newlang)) {
2235  $outputlangs = new Translate("", $conf);
2236  $outputlangs->setDefaultLang($newlang);
2237  $outputlangs->load('products');
2238  }
2239  if (!empty($prod->customcode)) {
2240  $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
2241  }
2242  if (!empty($prod->customcode) && !empty($prod->country_code)) {
2243  $tmptxt .= ' - ';
2244  }
2245  if (!empty($prod->country_code)) {
2246  $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0);
2247  }
2248  } else {
2249  if (!empty($prod->customcode)) {
2250  $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
2251  }
2252  if (!empty($prod->customcode) && !empty($prod->country_code)) {
2253  $tmptxt .= ' - ';
2254  }
2255  if (!empty($prod->country_code)) {
2256  $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0);
2257  }
2258  }
2259  $tmptxt .= ')';
2260  $desc = dol_concatdesc($desc, $tmptxt);
2261  }
2262 
2263  $type = $prod->type;
2264  $fk_unit = $prod->fk_unit;
2265  } else {
2266  $pu_ht = price2num($price_ht, 'MU');
2267  $pu_ttc = price2num($price_ttc, 'MU');
2268  $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
2269  $tva_tx = str_replace('*', '', $tva_tx);
2270  if (empty($tva_tx)) {
2271  $tva_npr = 0;
2272  }
2273  $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
2274  $desc = $product_desc;
2275  $type = GETPOST('type');
2276  $fk_unit = GETPOST('units', 'alpha');
2277 
2278  $pu_ht_devise = price2num($price_ht_devise, 'MU');
2279  $pu_ttc_devise = price2num($price_ttc_devise, 'MU');
2280 
2281  if ($pu_ttc && !$pu_ht) {
2282  $price_base_type = 'TTC';
2283  }
2284  }
2285 
2286  $pu_ht_devise = price2num($price_ht_devise, 'MU');
2287 
2288  // Margin
2289  $fournprice = price2num(GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : '');
2290  $buyingprice = price2num(GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''); // If buying_price is '0', we must keep this value
2291 
2292  // Local Taxes
2293  $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
2294  $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
2295 
2296  $info_bits = 0;
2297  if ($tva_npr) {
2298  $info_bits |= 0x01;
2299  }
2300 
2301  $price2num_pu_ht = price2num($pu_ht);
2302  $price2num_remise_percent = price2num($remise_percent);
2303  $price2num_price_min = price2num($price_min);
2304  $price2num_price_min_ttc = price2num($price_min_ttc);
2305  if (empty($price2num_pu_ht)) {
2306  $price2num_pu_ht = 0;
2307  }
2308  if (empty($price2num_remise_percent)) {
2309  $price2num_remise_percent = 0;
2310  }
2311  if (empty($price2num_price_min)) {
2312  $price2num_price_min = 0;
2313  }
2314  if (empty($price2num_price_min_ttc)) {
2315  $price2num_price_min_ttc = 0;
2316  }
2317 
2318  // Check price is not lower than minimum (check is done only for standard or replacement invoices)
2319  if ($usermustrespectpricemin && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT)) {
2320  if ($pu_ht && $price_min && ((price2num($pu_ht) * (1 - $remise_percent / 100)) < price2num($price_min))) {
2321  $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
2322  setEventMessages($mesg, null, 'errors');
2323  $error++;
2324  } elseif ($pu_ttc && $price_min_ttc && ((price2num($pu_ttc) * (1 - $remise_percent / 100)) < price2num($price_min_ttc))) {
2325  $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
2326  setEventMessages($mesg, null, 'errors');
2327  $error++;
2328  }
2329  }
2330 
2331  if (!$error) {
2332  // Add batchinfo if the detail_batch array is defined
2333  if (isModEnabled('productbatch') && !empty($lines[$i]->detail_batch) && is_array($lines[$i]->detail_batch) && !empty($conf->global->INVOICE_INCUDE_DETAILS_OF_LOTS_SERIALS)) {
2334  $langs->load('productbatch');
2335  foreach ($lines[$i]->detail_batch as $batchline) {
2336  $desc .= ' '.$langs->trans('Batch').' '.$batchline->batch.' '.$langs->trans('printQty', $batchline->qty).' ';
2337  }
2338  }
2339 
2340  // Insert line
2341  $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $date_start, $date_end, 0, $info_bits, '', $price_base_type, $pu_ttc, $type, min($rank, count($object->lines) + 1), $special_code, '', 0, GETPOST('fk_parent_line'), $fournprice, $buyingprice, $label, $array_options, GETPOST('progress'), '', $fk_unit, $pu_ht_devise);
2342 
2343  if ($result > 0) {
2344  // Define output language and generate document
2345  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
2346  $outputlangs = $langs;
2347  $newlang = '';
2348  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
2349  $newlang = GETPOST('lang_id', 'aZ09');
2350  }
2351  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
2352  $newlang = $object->thirdparty->default_lang;
2353  }
2354  if (!empty($newlang)) {
2355  $outputlangs = new Translate("", $conf);
2356  $outputlangs->setDefaultLang($newlang);
2357  $outputlangs->load('products');
2358  }
2359  $model = $object->model_pdf;
2360  $ret = $object->fetch($id); // Reload to get new records
2361 
2362  $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
2363  if ($result < 0) {
2364  setEventMessages($object->error, $object->errors, 'errors');
2365  }
2366  }
2367 
2368  unset($_POST['prod_entry_mode']);
2369 
2370  unset($_POST['qty']);
2371  unset($_POST['type']);
2372  unset($_POST['remise_percent']);
2373  unset($_POST['price_ht']);
2374  unset($_POST['multicurrency_price_ht']);
2375  unset($_POST['price_ttc']);
2376  unset($_POST['tva_tx']);
2377  unset($_POST['product_ref']);
2378  unset($_POST['product_label']);
2379  unset($_POST['product_desc']);
2380  unset($_POST['fournprice']);
2381  unset($_POST['buying_price']);
2382  unset($_POST['np_marginRate']);
2383  unset($_POST['np_markRate']);
2384  unset($_POST['dp_desc']);
2385  unset($_POST['idprod']);
2386  unset($_POST['units']);
2387 
2388  unset($_POST['date_starthour']);
2389  unset($_POST['date_startmin']);
2390  unset($_POST['date_startsec']);
2391  unset($_POST['date_startday']);
2392  unset($_POST['date_startmonth']);
2393  unset($_POST['date_startyear']);
2394  unset($_POST['date_endhour']);
2395  unset($_POST['date_endmin']);
2396  unset($_POST['date_endsec']);
2397  unset($_POST['date_endday']);
2398  unset($_POST['date_endmonth']);
2399  unset($_POST['date_endyear']);
2400 
2401  unset($_POST['situations']);
2402  unset($_POST['progress']);
2403  } else {
2404  setEventMessages($object->error, $object->errors, 'errors');
2405  }
2406 
2407  $action = '';
2408  }
2409  }
2410  } elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) {
2411  if (!$object->fetch($id) > 0) {
2412  dol_print_error($db);
2413  }
2414  $object->fetch_thirdparty();
2415 
2416  // Clean parameters
2417  $date_start = '';
2418  $date_end = '';
2419  $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
2420  $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
2421  $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml') ? GETPOST('product_desc', 'restricthtml') : GETPOST('desc', 'restricthtml'));
2422  $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
2423  $vat_rate = str_replace('*', '', $vat_rate);
2424 
2425  $pu_ht = price2num(GETPOST('price_ht'), '', 2);
2426  $pu_ttc = price2num(GETPOST('price_ttc'), '', 2);
2427 
2428  $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2);
2429  $pu_ttc_devise = price2num(GETPOST('multicurrency_subprice_ttc'), '', 2);
2430 
2431  $qty = price2num(GETPOST('qty', 'alpha'), 'MS');
2432 
2433  // Define info_bits
2434  $info_bits = 0;
2435  if (preg_match('/\*/', $vat_rate)) {
2436  $info_bits |= 0x01;
2437  }
2438 
2439  // Define vat_rate
2440  $vat_rate = str_replace('*', '', $vat_rate);
2441  $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
2442  $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
2443 
2444  // Add buying price
2445  $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
2446  $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
2447 
2448  // Extrafields
2449  $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
2450  $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
2451  // Unset extrafield
2452  if (is_array($extralabelsline)) {
2453  // Get extra fields
2454  foreach ($extralabelsline as $key => $value) {
2455  unset($_POST["options_".$key]);
2456  }
2457  }
2458 
2459  // Define special_code for special lines
2460  $special_code = GETPOST('special_code', 'int');
2461  if ($special_code == 3) {
2462  $special_code = 0; // Options should not exists on invoices
2463  }
2464 
2465  $line = new FactureLigne($db);
2466  $line->fetch(GETPOST('lineid', 'int'));
2467  $percent = $line->get_prev_progress($object->id);
2468  $progress = price2num(GETPOST('progress', 'alpha'));
2469 
2470  if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->situation_cycle_ref > 0) {
2471  // in case of situation credit note
2472  if ($progress >= 0) {
2473  $mesg = $langs->trans("CantBeNullOrPositive");
2474  setEventMessages($mesg, null, 'warnings');
2475  $error++;
2476  $result = -1;
2477  } elseif ($progress < $line->situation_percent) { // TODO : use a modified $line->get_prev_progress($object->id) result
2478  $mesg = $langs->trans("CantBeLessThanMinPercent");
2479  setEventMessages($mesg, null, 'warnings');
2480  $error++;
2481  $result = -1;
2482  } elseif ($progress < $percent) {
2483  $mesg = '<div class="warning">'.$langs->trans("CantBeLessThanMinPercent").'</div>';
2484  setEventMessages($mesg, null, 'warnings');
2485  $error++;
2486  $result = -1;
2487  }
2488  }
2489 
2490  $remise_percent = price2num(GETPOST('remise_percent'), '', 2);
2491 
2492  // Check minimum price
2493  $productid = GETPOST('productid', 'int');
2494  if (!empty($productid)) {
2495  $product = new Product($db);
2496  $product->fetch($productid);
2497 
2498  $type = $product->type;
2499 
2500  $price_min = $product->price_min;
2501  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) {
2502  $price_min = $product->multiprices_min[$object->thirdparty->price_level];
2503  }
2504  $price_min_ttc = $product->price_min_ttc;
2505  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) {
2506  $price_min_ttc = $product->multiprices_min_ttc[$object->thirdparty->price_level];
2507  }
2508 
2509  $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
2510 
2511  // Check price is not lower than minimum (check is done only for standard or replacement invoices)
2512  if ($usermustrespectpricemin && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT)) {
2513  if ($pu_ht && $price_min && (((float) price2num($pu_ht) * (1 - (float) $remise_percent / 100)) < (float) price2num($price_min))) {
2514  $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
2515  setEventMessages($mesg, null, 'errors');
2516  $error++;
2517  $action = 'editline';
2518  } elseif ($pu_ttc && $price_min_ttc && ((price2num($pu_ttc) * (1 - (float) $remise_percent / 100)) < price2num($price_min_ttc))) {
2519  $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
2520  setEventMessages($mesg, null, 'errors');
2521  $error++;
2522  $action = 'editline';
2523  }
2524  }
2525  } else {
2526  $type = GETPOST('type');
2527  $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
2528 
2529  // Check parameters
2530  if (GETPOST('type') < 0) {
2531  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
2532  $error++;
2533  }
2534  }
2535  if ($qty < 0) {
2536  $langs->load("errors");
2537  setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
2538  $error++;
2539  }
2540  if (empty($productid) && (($pu_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $pu_ht == '') && (($pu_ht_devise < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $pu_ht_devise == '') && $pu_ttc === '' && $pu_ttc_devise === '' && $object->type != Facture::TYPE_CREDIT_NOTE) { // Unit price can be 0 but not ''
2541  if (($pu_ht < 0 || $pu_ttc < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) {
2542  $langs->load("errors");
2543  if ($object->type == $object::TYPE_DEPOSIT) {
2544  // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
2545  setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
2546  } else {
2547  setEventMessages($langs->trans("ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv("UnitPriceHT"), $langs->transnoentitiesnoconv("CustomerAbsoluteDiscountShort")), null, 'errors');
2548  }
2549  $error++;
2550  } else {
2551  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
2552  $error++;
2553  }
2554  }
2555 
2556 
2557  // Update line
2558  if (!$error) {
2559  if (empty($usercancreatemargin)) {
2560  foreach ($object->lines as &$line) {
2561  if ($line->id == GETPOST('lineid', 'int')) {
2562  $fournprice = $line->fk_fournprice;
2563  $buyingprice = $line->pa_ht;
2564  break;
2565  }
2566  }
2567  }
2568 
2569  $price_base_type = 'HT';
2570  $pu = $pu_ht;
2571  if (empty($pu) && !empty($pu_ttc)) {
2572  $pu = $pu_ttc;
2573  $price_base_type = 'TTC';
2574  }
2575 
2576  $result = $object->updateline(
2577  GETPOST('lineid', 'int'),
2578  $description,
2579  $pu,
2580  $qty,
2581  $remise_percent,
2582  $date_start,
2583  $date_end,
2584  $vat_rate,
2585  $localtax1_rate,
2586  $localtax2_rate,
2587  $price_base_type,
2588  $info_bits,
2589  $type,
2590  GETPOST('fk_parent_line', 'int'),
2591  0,
2592  $fournprice,
2593  $buyingprice,
2594  $label,
2595  $special_code,
2596  $array_options,
2597  price2num(GETPOST('progress', 'alpha')),
2598  GETPOST('units', 'alpha'),
2599  $pu_ht_devise
2600  );
2601 
2602  if ($result >= 0) {
2603  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
2604  // Define output language
2605  $outputlangs = $langs;
2606  $newlang = '';
2607  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
2608  $newlang = GETPOST('lang_id', 'aZ09');
2609  }
2610  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
2611  $newlang = $object->thirdparty->default_lang;
2612  }
2613  if (!empty($newlang)) {
2614  $outputlangs = new Translate("", $conf);
2615  $outputlangs->setDefaultLang($newlang);
2616  $outputlangs->load('products');
2617  }
2618 
2619  $ret = $object->fetch($id); // Reload to get new records
2620  $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
2621  }
2622 
2623  unset($_POST['qty']);
2624  unset($_POST['type']);
2625  unset($_POST['productid']);
2626  unset($_POST['remise_percent']);
2627  unset($_POST['price_ht']);
2628  unset($_POST['multicurrency_price_ht']);
2629  unset($_POST['price_ttc']);
2630  unset($_POST['tva_tx']);
2631  unset($_POST['product_ref']);
2632  unset($_POST['product_label']);
2633  unset($_POST['product_desc']);
2634  unset($_POST['fournprice']);
2635  unset($_POST['buying_price']);
2636  unset($_POST['np_marginRate']);
2637  unset($_POST['np_markRate']);
2638 
2639  unset($_POST['dp_desc']);
2640  unset($_POST['idprod']);
2641  unset($_POST['units']);
2642 
2643  unset($_POST['date_starthour']);
2644  unset($_POST['date_startmin']);
2645  unset($_POST['date_startsec']);
2646  unset($_POST['date_startday']);
2647  unset($_POST['date_startmonth']);
2648  unset($_POST['date_startyear']);
2649  unset($_POST['date_endhour']);
2650  unset($_POST['date_endmin']);
2651  unset($_POST['date_endsec']);
2652  unset($_POST['date_endday']);
2653  unset($_POST['date_endmonth']);
2654  unset($_POST['date_endyear']);
2655 
2656  unset($_POST['situations']);
2657  unset($_POST['progress']);
2658  } else {
2659  setEventMessages($object->error, $object->errors, 'errors');
2660  }
2661  }
2662  } elseif ($action == 'updatealllines' && $usercancreate && GETPOST('all_percent') == $langs->trans('Modifier')) { // Update all lines of situation invoice
2663  if (!$object->fetch($id) > 0) {
2664  dol_print_error($db);
2665  }
2666  if (GETPOST('all_progress') != "") {
2667  $all_progress = GETPOST('all_progress', 'int');
2668  foreach ($object->lines as $line) {
2669  $percent = $line->get_prev_progress($object->id);
2670  if (floatval($all_progress) < floatval($percent)) {
2671  $mesg = $langs->trans("Line").' '.$i.' : '.$langs->trans("CantBeLessThanMinPercent");
2672  setEventMessages($mesg, null, 'warnings');
2673  $result = -1;
2674  } else {
2675  $object->update_percent($line, GETPOST('all_progress'), false);
2676  }
2677  }
2678  $object->update_price(1);
2679  }
2680  } elseif ($action == 'updateline' && $usercancreate && !$cancel) {
2681  header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id); // To show again edited page
2682  exit();
2683  } elseif ($action == 'confirm_situationout' && $confirm == 'yes' && $usercancreate) {
2684  // Outing situation invoice from cycle
2685  $object->fetch($id, '', '', '', true);
2686 
2687  if (in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
2688  && $object->type == Facture::TYPE_SITUATION
2689  && $usercancreate
2690  && !$objectidnext
2691  && $object->is_last_in_cycle()
2692  && $usercanunvalidate
2693  ) {
2694  $outingError = 0;
2695  $newCycle = $object->newCycle(); // we need to keep the "situation behavior" so we place it on a new situation cycle
2696  if ($newCycle > 1) {
2697  // Search credit notes
2698  $lastCycle = $object->situation_cycle_ref;
2699  $lastSituationCounter = $object->situation_counter;
2700  $linkedCreditNotesList = array();
2701 
2702  if (count($object->tab_next_situation_invoice) > 0) {
2703  foreach ($object->tab_next_situation_invoice as $next_invoice) {
2704  if ($next_invoice->type == Facture::TYPE_CREDIT_NOTE
2705  && $next_invoice->situation_counter == $object->situation_counter
2706  && $next_invoice->fk_facture_source == $object->id
2707  ) {
2708  $linkedCreditNotesList[] = $next_invoice->id;
2709  }
2710  }
2711  }
2712 
2713  $object->situation_cycle_ref = $newCycle;
2714  $object->situation_counter = 1;
2715  $object->situation_final = 0;
2716  if ($object->update($user) > 0) {
2717  $errors = 0;
2718  if (count($linkedCreditNotesList) > 0) {
2719  // now, credit note must follow
2720  $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
2721  $sql .= ' SET situation_cycle_ref = '.((int) $newCycle);
2722  $sql .= ' , situation_final=0';
2723  $sql .= ' , situation_counter='.((int) $object->situation_counter);
2724  $sql .= ' WHERE rowid IN ('.$db->sanitize(implode(',', $linkedCreditNotesList)).')';
2725 
2726  $resql = $db->query($sql);
2727  if (!$resql) {
2728  $errors++;
2729  }
2730 
2731  // Change each progression persent on each lines
2732  foreach ($object->lines as $line) {
2733  // no traitement for special product
2734  if ($line->product_type == 9) {
2735  continue;
2736  }
2737 
2738 
2739  if (!empty($object->tab_previous_situation_invoice)) {
2740  // search the last invoice in cycle
2741  $lineIndex = count($object->tab_previous_situation_invoice) - 1;
2742  $searchPreviousInvoice = true;
2743  while ($searchPreviousInvoice) {
2744  if ($object->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
2745  $searchPreviousInvoice = false; // find, exit;
2746  break;
2747  } else {
2748  $lineIndex--; // go to previous invoice in cycle
2749  }
2750  }
2751 
2752 
2753  $maxPrevSituationPercent = 0;
2754  foreach ($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
2755  if ($prevLine->id == $line->fk_prev_id) {
2756  $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
2757  }
2758  }
2759 
2760 
2761  $line->situation_percent = $line->situation_percent - $maxPrevSituationPercent;
2762 
2763  if ($line->update() < 0) {
2764  $errors++;
2765  }
2766  }
2767  }
2768  }
2769 
2770  if (!$errors) {
2771  setEventMessages($langs->trans('Updated'), '', 'mesgs');
2772  header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
2773  } else {
2774  setEventMessages($langs->trans('ErrorOutingSituationInvoiceCreditNote'), array(), 'errors');
2775  }
2776  } else {
2777  setEventMessages($langs->trans('ErrorOutingSituationInvoiceOnUpdate'), array(), 'errors');
2778  }
2779  } else {
2780  setEventMessages($langs->trans('ErrorFindNextSituationInvoice'), array(), 'errors');
2781  }
2782  }
2783  } elseif ($action == 'import_lines_from_object'
2784  && $usercancreate
2785  && $object->statut == Facture::STATUS_DRAFT
2786  && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION)) {
2787  // add lines from objectlinked
2788  $fromElement = GETPOST('fromelement');
2789  $fromElementid = GETPOST('fromelementid');
2790  $importLines = GETPOST('line_checkbox');
2791 
2792  if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) {
2793  if ($fromElement == 'commande') {
2794  dol_include_once('/'.$fromElement.'/class/'.$fromElement.'.class.php');
2795  $lineClassName = 'OrderLine';
2796  } elseif ($fromElement == 'propal') {
2797  dol_include_once('/comm/'.$fromElement.'/class/'.$fromElement.'.class.php');
2798  $lineClassName = 'PropaleLigne';
2799  }
2800  $nextRang = count($object->lines) + 1;
2801  $importCount = 0;
2802  $error = 0;
2803  foreach ($importLines as $lineId) {
2804  $lineId = intval($lineId);
2805  $originLine = new $lineClassName($db);
2806  if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) {
2807  $originLine->fetch_optionals();
2808  $desc = $originLine->desc;
2809  $pu_ht = $originLine->subprice;
2810  $qty = $originLine->qty;
2811  $txtva = $originLine->tva_tx;
2812  $txlocaltax1 = $originLine->localtax1_tx;
2813  $txlocaltax2 = $originLine->localtax2_tx;
2814  $fk_product = $originLine->fk_product;
2815  $remise_percent = $originLine->remise_percent;
2816  $date_start = $originLine->date_start;
2817  $date_end = $originLine->date_end;
2818  $ventil = 0;
2819  $info_bits = $originLine->info_bits;
2820  $fk_remise_except = $originLine->fk_remise_except;
2821  $price_base_type = 'HT';
2822  $pu_ttc = 0;
2823  $type = $originLine->product_type;
2824  $rang = $nextRang++;
2825  $special_code = $originLine->special_code;
2826  $origin = $originLine->element;
2827  $origin_id = $originLine->id;
2828  $fk_parent_line = 0;
2829  $fk_fournprice = $originLine->fk_fournprice;
2830  $pa_ht = $originLine->pa_ht;
2831  $label = $originLine->label;
2832  $array_options = $originLine->array_options;
2833  if ($object->type == Facture::TYPE_SITUATION) {
2834  $situation_percent = 0;
2835  } else {
2836  $situation_percent = 100;
2837  }
2838  $fk_prev_id = '';
2839  $fk_unit = $originLine->fk_unit;
2840  $pu_ht_devise = $originLine->multicurrency_subprice;
2841 
2842  $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $ventil, $info_bits, $fk_remise_except, $price_base_type, $pu_ttc, $type, $rang, $special_code, $origin, $origin_id, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $array_options, $situation_percent, $fk_prev_id, $fk_unit, $pu_ht_devise);
2843 
2844  if ($res > 0) {
2845  $importCount++;
2846  } else {
2847  $error++;
2848  }
2849  } else {
2850  $error++;
2851  }
2852  }
2853 
2854  if ($error) {
2855  setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors');
2856  }
2857  }
2858  }
2859 
2860  // Actions when printing a doc from card
2861  include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
2862 
2863  // Actions to send emails
2864  if (empty($id)) {
2865  $id = $facid;
2866  }
2867  $triggersendname = 'BILL_SENTBYMAIL';
2868  $paramname = 'id';
2869  $autocopy = 'MAIN_MAIL_AUTOCOPY_INVOICE_TO';
2870  $trackid = 'inv'.$object->id;
2871  include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
2872 
2873  // Actions to build doc
2874  $upload_dir = $conf->facture->multidir_output[!empty($object->entity) ? $object->entity : $conf->entity];
2875  $permissiontoadd = $usercancreate;
2876  include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
2877 
2878 
2879  if ($action == 'update_extras') {
2880  $object->oldcopy = dol_clone($object);
2881 
2882  // Fill array 'array_options' with data from add form
2883  $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
2884  if ($ret < 0) {
2885  $error++;
2886  }
2887 
2888  if (!$error) {
2889  // Actions on extra fields
2890  $result = $object->insertExtraFields('BILL_MODIFY');
2891  if ($result < 0) {
2892  setEventMessages($object->error, $object->errors, 'errors');
2893  $error++;
2894  }
2895  }
2896 
2897  if ($error) {
2898  $action = 'edit_extras';
2899  }
2900  }
2901 
2902  if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) {
2903  if ($action == 'addcontact') {
2904  $result = $object->fetch($id);
2905 
2906  if ($result > 0 && $id > 0) {
2907  $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
2908  $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
2909  $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
2910  }
2911 
2912  if ($result >= 0) {
2913  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
2914  exit();
2915  } else {
2916  if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2917  $langs->load("errors");
2918  setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
2919  } else {
2920  setEventMessages($object->error, $object->errors, 'errors');
2921  }
2922  }
2923  } elseif ($action == 'swapstatut') {
2924  // bascule du statut d'un contact
2925  if ($object->fetch($id)) {
2926  $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
2927  } else {
2928  dol_print_error($db);
2929  }
2930  } elseif ($action == 'deletecontact') {
2931  // Efface un contact
2932  $object->fetch($id);
2933  $result = $object->delete_contact($lineid);
2934 
2935  if ($result >= 0) {
2936  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
2937  exit();
2938  } else {
2939  dol_print_error($db);
2940  }
2941  }
2942 
2943  if ($error) {
2944  $action = 'edit_extras';
2945  }
2946  }
2947 }
2948 
2949 
2950 /*
2951  * View
2952  */
2953 
2954 
2955 $form = new Form($db);
2956 $formother = new FormOther($db);
2957 $formfile = new FormFile($db);
2958 $formmargin = new FormMargin($db);
2959 $soc = new Societe($db);
2960 $paymentstatic = new Paiement($db);
2961 $bankaccountstatic = new Account($db);
2962 if (isModEnabled('project')) {
2963  $formproject = new FormProjets($db);
2964 }
2965 
2966 $now = dol_now();
2967 
2968 $title = $object->ref." - ".$langs->trans('Card');
2969 if ($action == 'create') {
2970  $title = $langs->trans("NewBill");
2971 }
2972 $help_url = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
2973 
2974 llxHeader('', $title, $help_url);
2975 
2976 // Mode creation
2977 
2978 if ($action == 'create') {
2979  $facturestatic = new Facture($db);
2980  $extrafields->fetch_name_optionals_label($facturestatic->table_element);
2981 
2982  print load_fiche_titre($langs->trans('NewBill'), '', 'bill');
2983 
2984  if ($socid > 0) {
2985  $res = $soc->fetch($socid);
2986  }
2987 
2988  $currency_code = $conf->currency;
2989  $fk_account = 0;
2990 
2991  // Load objectsrc
2992  $remise_absolue = 0;
2993  if (!empty($origin) && !empty($originid)) {
2994  // Parse element/subelement (ex: project_task)
2995  $element = $subelement = $origin;
2996  $regs = array();
2997  if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
2998  $element = $regs[1];
2999  $subelement = $regs[2];
3000  }
3001 
3002  if ($element == 'project') {
3003  $projectid = $originid;
3004 
3005  if (empty($cond_reglement_id)) {
3006  $cond_reglement_id = $soc->cond_reglement_id;
3007  }
3008  if (empty($mode_reglement_id)) {
3009  $mode_reglement_id = $soc->mode_reglement_id;
3010  }
3011  if (empty($fk_account)) {
3012  $fk_account = $soc->fk_account;
3013  }
3014  if (!$remise_percent) {
3015  $remise_percent = $soc->remise_percent;
3016  }
3017  if (!$dateinvoice) {
3018  // Do not set 0 here (0 for a date is 1970)
3019  $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice);
3020  }
3021  } else {
3022  // For compatibility
3023  if ($element == 'order' || $element == 'commande') {
3024  $element = $subelement = 'commande';
3025  }
3026  if ($element == 'propal') {
3027  $element = 'comm/propal';
3028  $subelement = 'propal';
3029  }
3030  if ($element == 'contract') {
3031  $element = $subelement = 'contrat';
3032  }
3033  if ($element == 'shipping') {
3034  $element = $subelement = 'expedition';
3035  }
3036 
3037  dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
3038 
3039  $classname = ucfirst($subelement);
3040  $objectsrc = new $classname($db);
3041  $objectsrc->fetch($originid);
3042  if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
3043  $objectsrc->fetch_lines();
3044  }
3045  $objectsrc->fetch_thirdparty();
3046 
3047  $projectid = (!empty($projectid) ? $projectid : $objectsrc->fk_project);
3048  $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer : ''));
3049 
3050  // only if socid not filled else it's allready done upper
3051  if (empty($socid)) {
3052  $soc = $objectsrc->thirdparty;
3053  }
3054 
3055  $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice);
3056 
3057  if ($element == 'expedition') {
3058  $ref_client = (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer : '');
3059 
3060  $elem = $subelem = $objectsrc->origin;
3061  $expeoriginid = $objectsrc->origin_id;
3062  dol_include_once('/'.$elem.'/class/'.$subelem.'.class.php');
3063  $classname = ucfirst($subelem);
3064 
3065  $expesrc = new $classname($db);
3066  $expesrc->fetch($expeoriginid);
3067 
3068  $cond_reglement_id = (!empty($expesrc->cond_reglement_id) ? $expesrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 1));
3069  $mode_reglement_id = (!empty($expesrc->mode_reglement_id) ? $expesrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
3070  $fk_account = (!empty($expesrc->fk_account) ? $expesrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
3071  $remise_percent = (!empty($expesrc->remise_percent) ? $expesrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0));
3072  $remise_absolue = (!empty($expesrc->remise_absolue) ? $expesrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
3073 
3074  if (!empty($conf->multicurrency->enabled)) {
3075  $currency_code = (!empty($expesrc->multicurrency_code) ? $expesrc->multicurrency_code : (!empty($soc->multicurrency_code) ? $soc->multicurrency_code : $objectsrc->multicurrency_code));
3076  $currency_tx = (!empty($expesrc->multicurrency_tx) ? $expesrc->multicurrency_tx : (!empty($soc->multicurrency_tx) ? $soc->multicurrency_tx : $objectsrc->multicurrency_tx));
3077  }
3078 
3079  //Replicate extrafields
3080  $expesrc->fetch_optionals();
3081  $object->array_options = $expesrc->array_options;
3082  } else {
3083  $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0));
3084  $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
3085  $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
3086  $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0));
3087  $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
3088 
3089  if (isModEnabled('multicurrency')) {
3090  if (!empty($objectsrc->multicurrency_code)) {
3091  $currency_code = $objectsrc->multicurrency_code;
3092  }
3093  if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) {
3094  $currency_tx = $objectsrc->multicurrency_tx;
3095  }
3096  }
3097 
3098  // Replicate extrafields
3099  $objectsrc->fetch_optionals();
3100  $object->array_options = $objectsrc->array_options;
3101  }
3102  }
3103  } else {
3104  $cond_reglement_id = $soc->cond_reglement_id;
3105  $mode_reglement_id = $soc->mode_reglement_id;
3106  $fk_account = $soc->fk_account;
3107  $remise_percent = $soc->remise_percent;
3108  $remise_absolue = 0;
3109  $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice); // Do not set 0 here (0 for a date is 1970)
3110 
3111  if (isModEnabled('multicurrency') && !empty($soc->multicurrency_code)) {
3112  $currency_code = $soc->multicurrency_code;
3113  }
3114  }
3115 
3116  // when payment condition is empty (means not override by payment condition form a other object, like third-party), try to use default value
3117  if (empty($cond_reglement_id)) {
3118  $cond_reglement_id = GETPOST("cond_reglement_id", 'int');
3119  }
3120 
3121  // when payment mode is empty (means not override by payment mode form a other object, like third-party), try to use default value
3122  if (empty($mode_reglement_id)) {
3123  $mode_reglement_id = GETPOST("mode_reglement_id", 'int');
3124  }
3125 
3126  // when bank account is empty (means not override by payment mode form a other object, like third-party), try to use default value
3127  if ($socid > 0 && $fk_account) { // A company has already been set and it has a default fk_account
3128  $fk_account = GETPOSTISSET('fk_account') ? GETPOST("fk_account", 'int') : $fk_account; // The GETPOST is used only if form was posted to avoid to take default value, because in such case, the default must be the one of the company
3129  } else { // No company forced
3130  $fk_account = GETPOST("fk_account", 'int');
3131  }
3132 
3133  if (!empty($soc->id)) {
3134  $absolute_discount = $soc->getAvailableDiscounts();
3135  }
3136  $note_public = $object->getDefaultCreateValueFor('note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_public : null));
3137  $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_private : null));
3138 
3139  if (!empty($conf->use_javascript_ajax)) {
3140  require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
3141  print ajax_combobox('fac_replacement');
3142  print ajax_combobox('fac_avoir');
3143  print ajax_combobox('situations');
3144  }
3145 
3146  if ($origin == 'contrat') {
3147  $langs->load("admin");
3148  $text = $langs->trans("ToCreateARecurringInvoice");
3149  $text .= ' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates"));
3150  if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) {
3151  $text .= ' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name'));
3152  }
3153  print info_admin($text, 0, 0, 0, 'opacitymedium').'<br>';
3154  }
3155 
3156  print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="POST" id="formtocreate" name="formtocreate">';
3157  print '<input type="hidden" name="token" value="'.newToken().'">';
3158  print '<input type="hidden" name="action" id="formtocreateaction" value="add">';
3159  if ($soc->id > 0) {
3160  print '<input type="hidden" name="socid" value="'.$soc->id.'">'."\n";
3161  }
3162  print '<input name="ref" type="hidden" value="provisoire">';
3163  print '<input name="ref_client" type="hidden" value="'.$ref_client.'">';
3164  print '<input name="force_cond_reglement_id" type="hidden" value="0">';
3165  print '<input name="force_mode_reglement_id" type="hidden" value="0">';
3166  print '<input name="force_fk_account" type="hidden" value="0">';
3167  print '<input type="hidden" name="origin" value="'.$origin.'">';
3168  print '<input type="hidden" name="originid" value="'.$originid.'">';
3169  print '<input type="hidden" name="originentity" value="'.GETPOST('originentity').'">';
3170  if (!empty($currency_tx)) {
3171  print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">';
3172  }
3173 
3174  print dol_get_fiche_head('');
3175 
3176  print '<table class="border centpercent">';
3177 
3178  // Ref
3179  //print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td colspan="2">'.$langs->trans('Draft').'</td></tr>';
3180 
3181  $exampletemplateinvoice = new FactureRec($db);
3182  $invoice_predefined = new FactureRec($db);
3183  if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) {
3184  $invoice_predefined->fetch(GETPOST('fac_rec', 'int'));
3185  }
3186 
3187  // Thirdparty
3188  if ($soc->id > 0 && (!GETPOST('fac_rec', 'int') || !empty($invoice_predefined->frequency))) {
3189  // If thirdparty known and not a predefined invoiced without a recurring rule
3190  print '<tr><td class="fieldrequired">'.$langs->trans('Customer').'</td>';
3191  print '<td colspan="2">';
3192  print $soc->getNomUrl(1, 'customer');
3193  print '<input type="hidden" name="socid" value="'.$soc->id.'">';
3194  // Outstanding Bill
3195  $arrayoutstandingbills = $soc->getOutstandingBills();
3196  $outstandingBills = $arrayoutstandingbills['opened'];
3197  print ' - <span class="opacitymedium">'.$langs->trans('CurrentOutstandingBill').':</span> ';
3198  print '<span class="amount">'.price($outstandingBills, '', $langs, 0, 0, -1, $conf->currency).'</span>';
3199  if ($soc->outstanding_limit != '') {
3200  if ($outstandingBills > $soc->outstanding_limit) {
3201  print img_warning($langs->trans("OutstandingBillReached"));
3202  }
3203  print ' / '.price($soc->outstanding_limit, '', $langs, 0, 0, -1, $conf->currency);
3204  }
3205  print '</td>';
3206  print '</tr>'."\n";
3207  } else {
3208  print '<tr><td class="fieldrequired">'.$langs->trans('Customer').'</td>';
3209  print '<td colspan="2">';
3210  print img_picto('', 'company').$form->select_company($soc->id, 'socid', '((s.client = 1 OR s.client = 3) AND s.status = 1)', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
3211  // Option to reload page to retrieve customer informations.
3212  if (empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED)) {
3213  print '<script type="text/javascript">
3214  $(document).ready(function() {
3215  $("#socid").change(function() {
3216  /*
3217  console.log("Submit page");
3218  $(\'input[name="action"]\').val(\'create\');
3219  $(\'input[name="force_cond_reglement_id"]\').val(\'1\');
3220  $(\'input[name="force_mode_reglement_id"]\').val(\'1\');
3221  $(\'input[name="force_fk_account"]\').val(\'1\');
3222  $("#formtocreate").submit(); */
3223 
3224  // For company change, we must submit page with action=create instead of action=add
3225  console.log("We have changed the company - Resubmit page");
3226  jQuery("#formtocreateaction").val("create");
3227  jQuery("#formtocreate").submit();
3228  });
3229  });
3230  </script>';
3231  }
3232  if (!GETPOST('fac_rec', 'int')) {
3233  print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&client=3&fournisseur=0&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
3234  }
3235  print '</td>';
3236  print '</tr>'."\n";
3237  }
3238 
3239  // Overwrite some values if creation of invoice is from a predefined invoice
3240  if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) {
3241  $invoice_predefined->fetch(GETPOST('fac_rec', 'int'));
3242 
3243  $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later
3244  if (empty($projectid)) {
3245  $projectid = $invoice_predefined->fk_project;
3246  }
3247  $cond_reglement_id = $invoice_predefined->cond_reglement_id;
3248  $mode_reglement_id = $invoice_predefined->mode_reglement_id;
3249  $fk_account = $invoice_predefined->fk_account;
3250  $note_public = $invoice_predefined->note_public;
3251  $note_private = $invoice_predefined->note_private;
3252 
3253  if (!empty($invoice_predefined->multicurrency_code)) {
3254  $currency_code = $invoice_predefined->multicurrency_code;
3255  }
3256  if (!empty($invoice_predefined->multicurrency_tx)) {
3257  $currency_tx = $invoice_predefined->multicurrency_tx;
3258  }
3259 
3260  $sql = 'SELECT r.rowid, r.titre as title, r.total_ttc';
3261  $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as r';
3262  $sql .= ' WHERE r.fk_soc = '.((int) $invoice_predefined->socid);
3263 
3264  $resql = $db->query($sql);
3265  if ($resql) {
3266  $num = $db->num_rows($resql);
3267  $i = 0;
3268 
3269  if ($num > 0) {
3270  print '<tr><td>'.$langs->trans('CreateFromRepeatableInvoice').'</td><td>';
3271  //print '<input type="hidden" name="fac_rec" id="fac_rec" value="'.GETPOST('fac_rec', 'int').'">';
3272  print '<select class="flat" id="fac_rec" name="fac_rec">'; // We may want to change the template to use
3273  print '<option value="0" selected></option>';
3274  while ($i < $num) {
3275  $objp = $db->fetch_object($resql);
3276  print '<option value="'.$objp->rowid.'"';
3277  if (GETPOST('fac_rec', 'int') == $objp->rowid) {
3278  print ' selected';
3279  $exampletemplateinvoice->fetch(GETPOST('fac_rec', 'int'));
3280  }
3281  print '>'.$objp->title.' ('.price($objp->total_ttc).' '.$langs->trans("TTC").')</option>';
3282  $i++;
3283  }
3284  print '</select>';
3285 
3286  print ajax_combobox("fac_rec");
3287 
3288  // Option to reload page to retrieve customer informations. Note, this clear other input
3289  if (empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE_DISABLED)) {
3290  print '<script type="text/javascript">
3291  $(document).ready(function() {
3292  $("#fac_rec").change(function() {
3293  console.log("We have changed the template invoice - Reload page");
3294  var fac_rec = $(this).val();
3295  var socid = $(\'#socid\').val();
3296  // 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.
3297  window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
3298  });
3299  });
3300  </script>';
3301  }
3302  print '</td></tr>';
3303  }
3304  $db->free($resql);
3305  } else {
3306  dol_print_error($db);
3307  }
3308  }
3309 
3310  print '<tr><td class="tdtop fieldrequired">'.$langs->trans('Type').'</td><td colspan="2">';
3311  print '<div class="tagtable">'."\n";
3312 
3313  // Standard invoice
3314  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3315  $tmp = '<input type="radio" id="radio_standard" name="type" value="0"'.(GETPOST('type', 'int') ? '' : ' checked').'> ';
3316  $tmp = $tmp.'<label for="radio_standard" >'.$langs->trans("InvoiceStandardAsk").'</label>';
3317  $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3, 'standardonsmartphone');
3318  print '<table class="nobordernopadding"><tr>';
3319  print '<td>';
3320  print $desc;
3321  print '</td>';
3322  if ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid))) {
3323  /*print '<td class="nowrap" style="padding-left: 5px">';
3324  $arraylist = array(
3325  //'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
3326  //'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
3327  'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
3328  );
3329  print $form->selectarray('typestandard', $arraylist, GETPOST('typestandard', 'aZ09'), 0, 0, 0, '', 1);
3330  print '</td>';*/
3331  print '<td class="nowrap" style="padding-left: 15px">';
3332  print '<span class="opacitymedium">'.$langs->trans('PercentOfOriginalObject').'</span>:<input class="right" placeholder="100%" type="text" id="valuestandardinvoice" name="valuestandardinvoice" size="3" value="'.(GETPOSTISSET('valuestandardinvoice') ? GETPOST('valuestandardinvoice', 'alpha') : '100%').'"/>';
3333  print '</td>';
3334  }
3335  print '</tr></table>';
3336  print '</div></div>';
3337 
3338  if ((empty($origin)) || ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid)))) {
3339  // Deposit - Down payment
3340  if (empty($conf->global->INVOICE_DISABLE_DEPOSIT)) {
3341  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3342  $tmp = '<input type="radio" id="radio_deposit" name="type" value="3"'.(GETPOST('type') == 3 ? ' checked' : '').'> ';
3343  print '<script type="text/javascript">
3344  jQuery(document).ready(function() {
3345  jQuery("#typestandardinvoice, #valuestandardinvoice").click(function() {
3346  jQuery("#radio_standard").prop("checked", true);
3347  });
3348  jQuery("#typedeposit, #valuedeposit").click(function() {
3349  jQuery("#radio_deposit").prop("checked", true);
3350  });
3351  jQuery("#typedeposit").change(function() {
3352  console.log("We change type of down payment");
3353  jQuery("#radio_deposit").prop("checked", true);
3354  setRadioForTypeOfIncoice();
3355  });
3356  jQuery("#radio_standard, #radio_deposit, #radio_replacement, #radio_creditnote, #radio_template").change(function() {
3357  setRadioForTypeOfIncoice();
3358  });
3359  function setRadioForTypeOfIncoice() {
3360  console.log("Change radio");
3361  if (jQuery("#radio_deposit").prop("checked") && (jQuery("#typedeposit").val() == \'amount\' || jQuery("#typedeposit").val() == \'variable\')) {
3362  jQuery(".checkforselect").prop("disabled", true);
3363  jQuery(".checkforselect").prop("checked", false);
3364  } else {
3365  jQuery(".checkforselect").prop("disabled", false);
3366  jQuery(".checkforselect").prop("checked", true);
3367  }
3368  };
3369  });
3370  </script>';
3371 
3372  print '<table class="nobordernopadding"><tr>';
3373  print '<td>';
3374  $tmp = $tmp.'<label for="radio_deposit">'.$langs->trans("InvoiceDeposit").'</label>';
3375  $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3, 'depositonsmartphone');
3376  print $desc;
3377  print '</td>';
3378  if (($origin == 'propal') || ($origin == 'commande')) {
3379  print '<td class="nowrap" style="padding-left: 15px">';
3380  $arraylist = array(
3381  'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
3382  'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
3383  'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
3384  );
3385  $typedeposit = GETPOST('typedeposit', 'aZ09');
3386  $valuedeposit = GETPOST('valuedeposit', 'int');
3387  if (empty($typedeposit) && !empty($objectsrc->deposit_percent)) {
3388  $origin_payment_conditions_deposit_percent = getDictionaryValue('c_payment_term', 'deposit_percent', $objectsrc->cond_reglement_id);
3389  if (!empty($origin_payment_conditions_deposit_percent)) {
3390  $typedeposit = 'variable';
3391  }
3392  }
3393  if (empty($valuedeposit) && $typedeposit == 'variable' && !empty($objectsrc->deposit_percent)) {
3394  $valuedeposit = $objectsrc->deposit_percent;
3395  }
3396  print $form->selectarray('typedeposit', $arraylist, $typedeposit, 0, 0, 0, '', 1);
3397  print '</td>';
3398  print '<td class="nowrap" style="padding-left: 5px">';
3399  print '<span class="opacitymedium paddingleft">'.$langs->trans("AmountOrPercent").'</span><input type="text" id="valuedeposit" name="valuedeposit" class="width75 right" value="'.$valuedeposit.'"/>';
3400  print '</td>';
3401  }
3402  print '</tr></table>';
3403 
3404  print '</div></div>';
3405  }
3406  }
3407 
3408  if ($socid > 0) {
3409  if (!empty($conf->global->INVOICE_USE_SITUATION)) {
3410  // First situation invoice
3411  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3412  $tmp = '<input id="radio_situation" type="radio" name="type" value="5"'.(GETPOST('type') == 5 ? ' checked' : '').'> ';
3413  $tmp = $tmp.'<label for="radio_situation" >'.$langs->trans("InvoiceFirstSituationAsk").'</label>';
3414  $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3, 'firstsituationonsmartphone');
3415  print $desc;
3416  print '</div></div>';
3417 
3418  // Next situation invoice
3419  $opt = $form->selectSituationInvoices(GETPOST('originid', 'int'), $socid);
3420 
3421  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3422  $tmp = '<input type="radio" name="type" value="5"'.(GETPOST('type') == 5 && GETPOST('originid', 'int') ? ' checked' : '');
3423  if ($opt == ('<option value ="0" selected>'.$langs->trans('NoSituations').'</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) {
3424  $tmp .= ' disabled';
3425  }
3426  $tmp .= '> ';
3427  $text = $tmp.'<label>'.$langs->trans("InvoiceSituationAsk").'</label> ';
3428  $text .= '<select class="flat" id="situations" name="situations"';
3429  if ($opt == ('<option value ="0" selected>'.$langs->trans('NoSituations').'</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) {
3430  $text .= ' disabled';
3431  }
3432  $text .= '>';
3433  $text .= $opt;
3434  $text .= '</select>';
3435  $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceSituationDesc"), 1, 'help', '', 0, 3);
3436  print $desc;
3437  print '</div></div>';
3438  }
3439 
3440  // Replacement
3441  if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT)) {
3442  // Type de facture
3443  $facids = $facturestatic->list_replacable_invoices($soc->id);
3444  if ($facids < 0) {
3445  dol_print_error($db, $facturestatic->error, $facturestatic->errors);
3446  exit();
3447  }
3448  $options = "";
3449  if (is_array($facids)) {
3450  foreach ($facids as $facparam) {
3451  $options .= '<option value="'.$facparam ['id'].'"';
3452  if ($facparam['id'] == GETPOST('fac_replacement', 'int')) {
3453  $options .= ' selected';
3454  }
3455  $options .= '>'.$facparam['ref'];
3456  $options .= ' ('.$facturestatic->LibStatut($facparam['paid'], $facparam['status'], 0, $facparam['alreadypaid']).')';
3457  $options .= '</option>';
3458  }
3459  }
3460 
3461  print '<!-- replacement line -->';
3462  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3463  $tmp = '<input type="radio" name="type" id="radio_replacement" value="1"'.(GETPOST('type') == 1 ? ' checked' : '');
3464  if (!$options || $invoice_predefined->id > 0) {
3465  $tmp .= ' disabled';
3466  }
3467  $tmp .= '> ';
3468  print '<script type="text/javascript">
3469  jQuery(document).ready(function() {
3470  jQuery("#fac_replacement").change(function() {
3471  jQuery("#radio_replacement").prop("checked", true);
3472  });
3473  });
3474  </script>';
3475  $text = $tmp.'<label for="radio_replacement">'.$langs->trans("InvoiceReplacementAsk").'</label>';
3476  $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
3477  if (!$options || $invoice_predefined->id > 0) {
3478  $text .= ' disabled';
3479  }
3480  $text .= '>';
3481  if ($options) {
3482  $text .= '<option value="-1">&nbsp;</option>';
3483  $text .= $options;
3484  } else {
3485  $text .= '<option value="-1">'.$langs->trans("NoReplacableInvoice").'</option>';
3486  }
3487  $text .= '</select>';
3488  $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
3489  print $desc;
3490  print '</div></div>';
3491  }
3492  } else {
3493  if (!empty($conf->global->INVOICE_USE_SITUATION)) {
3494  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3495  $tmp = '<input type="radio" name="type" id="radio_situation" value="0" disabled> ';
3496  $text = $tmp.'<label>'.$langs->trans("InvoiceSituationAsk").'</label> ';
3497  $text .= '<span class="opacitymedium">('.$langs->trans("YouMustCreateInvoiceFromThird").')</span> ';
3498  $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3, 'firstsituationonsmartphone');
3499  print $desc;
3500  print '</div></div>';
3501  }
3502 
3503  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3504  $tmp = '<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
3505  $text = $tmp.'<label for="radio_replacement" class="opacitymedium">'.$langs->trans("InvoiceReplacement").'</label> ';
3506  //$text .= '<span class="opacitymedium hideonsmartphone">('.$langs->trans("YouMustCreateInvoiceFromThird").')</span> ';
3507  $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc").'<br><br>'.$langs->trans("YouMustCreateInvoiceFromThird"), 1, 'help', '', 0, 3, 'replacementonsmartphone');
3508  print $desc;
3509  print '</div></div>';
3510  }
3511 
3512  if (empty($origin)) {
3513  if ($socid > 0) {
3514  // Credit note
3515  if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) {
3516  // Show link for credit note
3517  $facids = $facturestatic->list_qualified_avoir_invoices($soc->id);
3518  if ($facids < 0) {
3519  dol_print_error($db, $facturestatic->error, $facturestatic->errors);
3520  exit;
3521  }
3522  $optionsav = "";
3523  $newinvoice_static = new Facture($db);
3524  foreach ($facids as $key => $valarray) {
3525  $newinvoice_static->id = $key;
3526  $newinvoice_static->ref = $valarray ['ref'];
3527  $newinvoice_static->statut = $valarray ['status'];
3528  $newinvoice_static->type = $valarray ['type'];
3529  $newinvoice_static->paye = $valarray ['paye'];
3530 
3531  $optionsav .= '<option value="'.$key.'"';
3532  if ($key == GETPOST('fac_avoir')) {
3533  $optionsav .= ' selected';
3534 
3535  // pre-filled extra fields with selected credit note
3536  $newinvoice_static->fetch_optionals($key);
3537  $object->array_options = $newinvoice_static->array_options;
3538  }
3539  $optionsav .= '>';
3540  $optionsav .= $newinvoice_static->ref;
3541  $optionsav .= ' ('.$newinvoice_static->getLibStatut(1, $valarray ['paymentornot']).')';
3542  $optionsav .= '</option>';
3543  }
3544 
3545  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3546  $tmp = '<input type="radio" id="radio_creditnote" name="type" value="2"'.(GETPOST('type') == 2 ? ' checked' : '');
3547  if ((!$optionsav && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) || $invoice_predefined->id > 0) {
3548  $tmp .= ' disabled';
3549  }
3550  $tmp .= '> ';
3551  // Show credit note options only if we checked credit note
3552  print '<script type="text/javascript">
3553  jQuery(document).ready(function() {
3554  if (! jQuery("#radio_creditnote").is(":checked"))
3555  {
3556  jQuery("#credit_note_options").hide();
3557  }
3558  jQuery("#radio_creditnote").click(function() {
3559  jQuery("#credit_note_options").show();
3560  });
3561  jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() {
3562  jQuery("#credit_note_options").hide();
3563  });
3564  });
3565  </script>';
3566  $text = '<label>'.$tmp.$langs->transnoentities("InvoiceAvoirAsk").'</label> ';
3567  $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
3568  if (!$optionsav || $invoice_predefined->id > 0) {
3569  $text .= ' disabled';
3570  }
3571  $text .= '>';
3572  if ($optionsav) {
3573  $text .= '<option value="-1"></option>';
3574  $text .= $optionsav;
3575  } else {
3576  $text .= '<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
3577  }
3578  $text .= '</select>';
3579  $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
3580  print $desc;
3581 
3582  print '<div id="credit_note_options" class="clearboth paddingtop marginbottomonly">';
3583  print '&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOST('invoiceAvoirWithLines', 'int') > 0 ? 'checked' : '').' /> <label for="invoiceAvoirWithLines">'.$langs->trans('invoiceAvoirWithLines')."</label>";
3584  print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') > 0 ? 'checked' : '').' /> <label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label>";
3585  print '</div>';
3586 
3587  print '</div></div>';
3588  }
3589  } else {
3590  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3591  if (empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
3592  $tmp = '<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
3593  } else {
3594  $tmp = '<input type="radio" name="type" id="radio_creditnote" value="2" > ';
3595  }
3596  $text = $tmp.'<label class="opacitymedium" for="radio_creditnote">'.$langs->trans("InvoiceAvoir").'</label> ';
3597  //$text .= '<span class="opacitymedium hideonsmartphone">('.$langs->trans("YouMustCreateInvoiceFromThird").')</span> ';
3598  $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc").'<br><br>'.$langs->trans("YouMustCreateInvoiceFromThird"), 1, 'help', '', 0, 3, 'creditnoteonsmartphone');
3599  print $desc;
3600  print '</div></div>'."\n";
3601  }
3602  }
3603 
3604  // Template invoice
3605  print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
3606  $tmp = '<input type="radio" name="type" id="radio_template" value="0" disabled> ';
3607  $text = $tmp.'<label class="opacitymedium" for="radio_template">'.$langs->trans("RepeatableInvoice").'</label> ';
3608  $desc = $form->textwithpicto($text, $langs->transnoentities("YouMustCreateStandardInvoiceFirstDesc"), 1, 'help', '', 0, 3, 'templateonsmartphone');
3609  print $desc;
3610  print '</div></div>';
3611 
3612  print '</div>';
3613 
3614 
3615  if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) { // Hidden conf
3616  // Add auto select default document model
3618  $jsListType = '';
3619  foreach ($listtType as $type) {
3620  $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$type;
3621  $curent = !empty($conf->global->{$thisTypeConfName}) ? $conf->global->{$thisTypeConfName}:$conf->global->FACTURE_ADDON_PDF;
3622  $jsListType .= (!empty($jsListType) ? ',' : '').'"'.$type.'":"'.$curent.'"';
3623  }
3624 
3625  print '<script type="text/javascript">
3626  $(document).ready(function() {
3627  var listType = {'.$jsListType.'};
3628  $("[name=\'type\'").change(function() {
3629  console.log("change name=type");
3630  if ($( this ).prop("checked"))
3631  {
3632  if(($( this ).val() in listType))
3633  {
3634  $("#model").val(listType[$( this ).val()]);
3635  }
3636  else
3637  {
3638  $("#model").val("'.$conf->global->FACTURE_ADDON_PDF.'");
3639  }
3640  }
3641  });
3642  });
3643  </script>';
3644  }
3645 
3646 
3647  print '</td></tr>';
3648 
3649  if ($socid > 0) {
3650  // Discounts for third party
3651  print '<tr><td>'.$langs->trans('DiscountStillRemaining').'</td><td colspan="2">';
3652 
3653  $thirdparty = $soc;
3654  $discount_type = 0;
3655  $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$thirdparty->id.'&action='.$action.'&origin='.GETPOST('origin', 'alpha').'&originid='.GETPOST('originid', 'int'));
3656  include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
3657 
3658  print '</td></tr>';
3659  }
3660 
3661  $newdateinvoice = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'), 'tzserver');
3662  $date_pointoftax = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'), 'tzserver');
3663 
3664  // Date invoice
3665  print '<tr><td class="fieldrequired">'.$langs->trans('DateInvoice').'</td><td colspan="2">';
3666  print $form->selectDate($newdateinvoice ? $newdateinvoice : $dateinvoice, '', '', '', '', "add", 1, 1);
3667  print '</td></tr>';
3668 
3669  // Date point of tax
3670  if (!empty($conf->global->INVOICE_POINTOFTAX_DATE)) {
3671  print '<tr><td class="fieldrequired">'.$langs->trans('DatePointOfTax').'</td><td colspan="2">';
3672  print $form->selectDate($date_pointoftax ? $date_pointoftax : -1, 'date_pointoftax', '', '', '', "add", 1, 1);
3673  print '</td></tr>';
3674  }
3675 
3676  // Payment term
3677  print '<tr><td class="nowrap fieldrequired">'.$langs->trans('PaymentConditionsShort').'</td><td colspan="2">';
3678  print $form->getSelectConditionsPaiements(GETPOSTISSET('cond_reglement_id') ? GETPOST('cond_reglement_id', 'int') : $cond_reglement_id, 'cond_reglement_id');
3679  print '</td></tr>';
3680 
3681 
3682  if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
3683  $rwStyle = 'display:none;';
3684  if (in_array(GETPOST('type', 'int'), $retainedWarrantyInvoiceAvailableType)) {
3685  $rwStyle = '';
3686  }
3687 
3688  $retained_warranty = GETPOST('retained_warranty', 'int');
3689  if (empty($retained_warranty)) {
3690  if (!empty($objectsrc->retained_warranty)) { // use previous situation value
3691  $retained_warranty = $objectsrc->retained_warranty;
3692  }
3693  }
3694  $retained_warranty_js_default = !empty($retained_warranty) ? $retained_warranty : $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_PERCENT;
3695 
3696  print '<tr class="retained-warranty-line" style="'.$rwStyle.'" ><td class="nowrap">'.$langs->trans('RetainedWarranty').'</td><td colspan="2">';
3697  print '<input id="new-situation-invoice-retained-warranty" name="retained_warranty" type="number" value="'.$retained_warranty.'" step="0.01" min="0" max="100" />%';
3698 
3699  // Retained warranty payment term
3700  print '<tr class="retained-warranty-line" style="'.$rwStyle.'" ><td class="nowrap">'.$langs->trans('PaymentConditionsShortRetainedWarranty').'</td><td colspan="2">';
3701  $retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
3702  if (empty($retained_warranty_fk_cond_reglement)) {
3703  $retained_warranty_fk_cond_reglement = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
3704  if (!empty($objectsrc->retained_warranty_fk_cond_reglement)) { // use previous situation value
3705  $retained_warranty_fk_cond_reglement = $objectsrc->retained_warranty_fk_cond_reglement;
3706  } else {
3707  $retained_warranty_fk_cond_reglement = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
3708  }
3709  }
3710  print $form->getSelectConditionsPaiements($retained_warranty_fk_cond_reglement, 'retained_warranty_fk_cond_reglement', -1, 1);
3711  print '</td></tr>';
3712 
3713  print '<script type="text/javascript">
3714  $(document).ready(function() {
3715  $("[name=\'type\']").change(function() {
3716  if($( this ).prop("checked") && $.inArray($( this ).val(), '.json_encode($retainedWarrantyInvoiceAvailableType).' ) !== -1)
3717  {
3718  $(".retained-warranty-line").show();
3719  $("#new-situation-invoice-retained-warranty").val("'.floatval($retained_warranty_js_default).'");
3720  }
3721  else{
3722  $(".retained-warranty-line").hide();
3723  $("#new-situation-invoice-retained-warranty").val("");
3724  }
3725  });
3726 
3727  $("[name=\'type\']:checked").trigger("change");
3728  });
3729  </script>';
3730  }
3731 
3732  // Payment mode
3733  print '<tr><td>'.$langs->trans('PaymentMode').'</td><td colspan="2">';
3734  print img_picto('', 'payment', 'class="pictofixedwidth"');
3735  print $form->select_types_paiements(GETPOSTISSET('mode_reglement_id') ? GETPOST('mode_reglement_id') : $mode_reglement_id, 'mode_reglement_id', 'CRDT', 0, 1, 0, 0, 1, 'maxwidth200 widthcentpercentminusx', 1);
3736  print '</td></tr>';
3737 
3738  // Bank Account
3739  if (isModEnabled("banque")) {
3740  print '<tr><td>'.$langs->trans('BankAccount').'</td><td colspan="2">';
3741  print img_picto('', 'bank_account', 'class="pictofixedwidth"');
3742  print $form->select_comptes(($fk_account < 0 ? '' : $fk_account), 'fk_account', 0, '', 1, '', 0, 'maxwidth200 widthcentpercentminusx', 1);
3743  print '</td></tr>';
3744  }
3745 
3746  // Project
3747  if (isModEnabled('project')) {
3748  $langs->load('projects');
3749  print '<tr><td>'.$langs->trans('Project').'</td><td colspan="2">';
3750  print img_picto('', 'project').$formproject->select_projects(($socid > 0 ? $socid : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx');
3751  print ' <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$soc->id.'&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id.($fac_rec ? '&fac_rec='.$fac_rec : '')).'"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans("AddProject").'"></span></a>';
3752  print '</td></tr>';
3753  }
3754 
3755  // Incoterms
3756  if (isModEnabled('incoterm')) {
3757  print '<tr>';
3758  print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), !empty($objectsrc->label_incoterms) ? $objectsrc->label_incoterms : '', 1).'</label></td>';
3759  print '<td colspan="2" class="maxwidthonsmartphone">';
3760  $incoterm_id = GETPOST('incoterm_id');
3761  $incoterm_location = GETPOST('location_incoterms');
3762  if (empty($incoterm_id)) {
3763  $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms);
3764  $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms);
3765  }
3766  print $form->select_incoterms($incoterm_id, $incoterm_location);
3767  print '</td></tr>';
3768  }
3769 
3770  // Other attributes
3771  $parameters = array('objectsrc' => !empty($objectsrc) ? $objectsrc : 0, 'colspan' => ' colspan="2"', 'cols' => '2', 'socid'=>$socid);
3772  $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
3773  print $hookmanager->resPrint;
3774  if (empty($reshook)) {
3775  if (!empty($conf->global->THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE) && !empty($soc->id)) {
3776  // copy from thirdparty
3777  $tpExtrafields = new Extrafields($db);
3778  $tpExtrafieldLabels = $tpExtrafields->fetch_name_optionals_label($soc->table_element);
3779  if ($soc->fetch_optionals() > 0) {
3780  $object->array_options = array_merge($object->array_options, $soc->array_options);
3781  }
3782  };
3783 
3784  print $object->showOptionals($extrafields, 'create', $parameters);
3785  }
3786 
3787  // Template to use by default
3788  print '<tr><td>'.$langs->trans('Model').'</td>';
3789  print '<td colspan="2">';
3790  print img_picto('', 'pdf', 'class="pictofixedwidth"');
3791  include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
3792  $liste = ModelePDFFactures::liste_modeles($db);
3793  if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) {
3794  // Hidden conf
3795  $paramkey = 'FACTURE_ADDON_PDF_'.$object->type;
3796  $preselected = !empty($conf->global->$paramkey) ? $conf->global->$paramkey : $conf->global->FACTURE_ADDON_PDF;
3797  } else {
3798  $preselected = $conf->global->FACTURE_ADDON_PDF;
3799  }
3800  print $form->selectarray('model', $liste, $preselected, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth200 widthcentpercentminusx', 1);
3801  print "</td></tr>";
3802 
3803  // Multicurrency
3804  if (isModEnabled('multicurrency')) {
3805  print '<tr>';
3806  print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
3807  print '<td colspan="2" class="maxwidthonsmartphone">';
3808  print img_picto('', 'currency', 'class="pictofixedwidth"');
3809  print $form->selectMultiCurrency($currency_code, 'multicurrency_code');
3810  print '</td></tr>';
3811  }
3812 
3813  // Help of substitution key
3814  $htmltext = '';
3815  if (GETPOST('fac_rec', 'int') > 0) {
3816  $dateexample = ($newdateinvoice ? $newdateinvoice : $dateinvoice);
3817  if (empty($dateexample)) {
3818  $dateexample = dol_now();
3819  }
3820  $substitutionarray = array(
3821  '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')',
3822  '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')',
3823  '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%m').')',
3824  '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%m').')',
3825  '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%m').')',
3826  '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%B').')',
3827  '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%B').')',
3828  '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')',
3829  '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'), '%Y').')',
3830  '__INVOICE_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%Y').')',
3831  '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'), '%Y').')'
3832  );
3833 
3834  $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
3835  foreach ($substitutionarray as $key => $val) {
3836  $htmltext .= $key.' = '.$langs->trans($val).'<br>';
3837  }
3838  $htmltext .= '</i>';
3839  }
3840 
3841  // Public note
3842  print '<tr>';
3843  print '<td class="tdtop">';
3844  print $form->textwithpicto($langs->trans('NotePublic'), $htmltext);
3845  print '</td>';
3846  print '<td valign="top" colspan="2">';
3847  $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%');
3848  print $doleditor->Create(1);
3849 
3850  // Private note
3851  if (empty($user->socid)) {
3852  print '<tr>';
3853  print '<td class="tdtop">';
3854  print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext);
3855  print '</td>';
3856  print '<td valign="top" colspan="2">';
3857  $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%');
3858  print $doleditor->Create(1);
3859  // print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
3860  print '</td></tr>';
3861  }
3862 
3863  // Lines from source (TODO Show them also when creating invoice from template invoice)
3864  if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
3865  $langs->loadLangs(array('orders', 'propal'));
3866 
3867  // TODO for compatibility
3868  if ($origin == 'contrat') {
3869  // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
3870  $objectsrc->remise_absolue = $remise_absolue;
3871  $objectsrc->remise_percent = $remise_percent;
3872  $objectsrc->update_price(1, 'auto', 1);
3873  }
3874 
3875  print "\n<!-- Show ref of origin ".$classname." -->\n";
3876  print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n";
3877  print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n";
3878  print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n";
3879  // The commented lines below are fields already added as hidden parameters before
3880  //print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
3881  //print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
3882 
3883  switch (get_class($objectsrc)) {
3884  case 'Propal':
3885  $newclassname = 'CommercialProposal';
3886  break;
3887  case 'Commande':
3888  $newclassname = 'Order';
3889  break;
3890  case 'Expedition':
3891  $newclassname = 'Sending';
3892  break;
3893  case 'Contrat':
3894  $newclassname = 'Contract';
3895  break;
3896  case 'Fichinter':
3897  $newclassname = 'Intervention';
3898  break;
3899  default:
3900  $newclassname = get_class($objectsrc);
3901  }
3902 
3903  // Ref of origin
3904  print '<tr><td>'.$langs->trans($newclassname).'</td>';
3905  print '<td colspan="2">';
3906  print $objectsrc->getNomUrl(1);
3907  // We check if Origin document (id and type is known) has already at least one invoice attached to it
3908  $objectsrc->fetchObjectLinked($originid, $origin, '', 'facture');
3909  if (isset($objectsrc->linkedObjects['facture']) && is_array($objectsrc->linkedObjects['facture']) && count($objectsrc->linkedObjects['facture']) >= 1) {
3910  setEventMessages('WarningBillExist', null, 'warnings');
3911  echo ' - '.$langs->trans('LatestRelatedBill').' '.end($objectsrc->linkedObjects['facture'])->getNomUrl(1);
3912  }
3913  echo '</td></tr>';
3914  print '<tr><td>'.$langs->trans('AmountHT').'</td><td colspan="2">'.price($objectsrc->total_ht).'</td></tr>';
3915  print '<tr><td>'.$langs->trans('AmountVAT').'</td><td colspan="2">'.price($objectsrc->total_tva)."</td></tr>";
3916  if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1
3917  print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax1)."</td></tr>";
3918  }
3919 
3920  if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2
3921  print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax2)."</td></tr>";
3922  }
3923  print '<tr><td>'.$langs->trans('AmountTTC').'</td><td colspan="2">'.price($objectsrc->total_ttc)."</td></tr>";
3924 
3925  if (isModEnabled('multicurrency')) {
3926  print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_ht).'</td></tr>';
3927  print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_tva)."</td></tr>";
3928  print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_ttc)."</td></tr>";
3929  }
3930  }
3931 
3932  print "</table>\n";
3933 
3934  print dol_get_fiche_end();
3935 
3936  print $form->buttonsSaveCancel("CreateDraft");
3937 
3938  // Show origin lines
3939  if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
3940  print '<br>';
3941 
3942  $title = $langs->trans('ProductsAndServices');
3943  print load_fiche_titre($title);
3944 
3945  print '<div class="div-table-responsive-no-min">';
3946  print '<table class="noborder centpercent">';
3947 
3948  $objectsrc->printOriginLinesList('', $selectedLines);
3949 
3950  print '</table>';
3951  print '</div>';
3952  }
3953 
3954  print "</form>\n";
3955 } elseif ($id > 0 || !empty($ref)) {
3956  if (empty($object->id)) {
3957  $langs->load('errors');
3958  echo '<div class="error">'.$langs->trans("ErrorRecordNotFound").'</div>';
3959  llxFooter();
3960  exit;
3961  }
3962 
3963  /*
3964  * Show object in view mode
3965  */
3966 
3967  $result = $object->fetch($id, $ref);
3968  if ($result <= 0) {
3969  dol_print_error($db, $object->error, $object->errors);
3970  exit();
3971  }
3972 
3973  // fetch optionals attributes and labels
3974  $extrafields->fetch_name_optionals_label($object->table_element);
3975 
3976  if ($user->socid > 0 && $user->socid != $object->socid) {
3977  accessforbidden('', 0, 1);
3978  }
3979 
3980  $result = $object->fetch_thirdparty();
3981 
3982  $result = $soc->fetch($object->socid);
3983  if ($result < 0) {
3984  dol_print_error($db);
3985  }
3986  $selleruserevenustamp = $mysoc->useRevenueStamp();
3987 
3988  $totalpaid = $object->getSommePaiement();
3989  $totalcreditnotes = $object->getSumCreditNotesUsed();
3990  $totaldeposits = $object->getSumDepositsUsed();
3991  //print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
3992  // selleruserrevenuestamp=".$selleruserevenustamp;
3993 
3994  // We can also use bcadd to avoid pb with floating points
3995  // For example print 239.2 - 229.3 - 9.9; does not return 0.
3996  // $resteapayer=bcadd($object->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT);
3997  // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
3998  $resteapayer = price2num($object->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
3999 
4000  // Multicurrency
4001  if (isModEnabled('multicurrency')) {
4002  $multicurrency_totalpaid = $object->getSommePaiement(1);
4003  $multicurrency_totalcreditnotes = $object->getSumCreditNotesUsed(1);
4004  $multicurrency_totaldeposits = $object->getSumDepositsUsed(1);
4005  $multicurrency_resteapayer = price2num($object->multicurrency_total_ttc - $multicurrency_totalpaid - $multicurrency_totalcreditnotes - $multicurrency_totaldeposits, 'MT');
4006  // Code to fix case of corrupted data
4007  // TODO We should not need this. Also data comes from a not reliable value of $object->multicurrency_total_ttc that may be wrong if it was
4008  // 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)
4009  if ($resteapayer == 0 && $multicurrency_resteapayer != 0 && $object->multicurrency_code != $conf->currency) {
4010  $resteapayer = price2num($multicurrency_resteapayer / $object->multicurrency_tx, 'MT');
4011  }
4012  }
4013 
4014  if ($object->paye) {
4015  $resteapayer = 0;
4016  }
4017  $resteapayeraffiche = $resteapayer;
4018 
4019  if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this
4020  $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
4021  $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
4022  } else {
4023  $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
4024  $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
4025  }
4026 
4027  $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount);
4028  $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote);
4029  $absolute_discount = price2num($absolute_discount, 'MT');
4030  $absolute_creditnote = price2num($absolute_creditnote, 'MT');
4031 
4032  $author = new User($db);
4033  if ($object->user_author) {
4034  $author->fetch($object->user_author);
4035  }
4036 
4037  $objectidnext = $object->getIdReplacingInvoice();
4038 
4039  $head = facture_prepare_head($object);
4040 
4041  print dol_get_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), -1, 'bill');
4042 
4043  $formconfirm = '';
4044 
4045  // Confirmation de la conversion de l'avoir en reduc
4046  if ($action == 'converttoreduc') {
4047  if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) {
4048  $type_fac = 'ExcessReceived';
4049  } elseif ($object->type == Facture::TYPE_CREDIT_NOTE) {
4050  $type_fac = 'CreditNote';
4051  } elseif ($object->type == Facture::TYPE_DEPOSIT) {
4052  $type_fac = 'Deposit';
4053  }
4054  $text = $langs->trans('ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac)));
4055  $text .= '<br>'.$langs->trans('ConfirmConvertToReduc2');
4056  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2);
4057  }
4058 
4059  // Confirmation to delete invoice
4060  if ($action == 'delete') {
4061  $text = $langs->trans('ConfirmDeleteBill', $object->ref);
4062  $formquestion = array();
4063 
4064  if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $object->statut >= 1) {
4065  $qualified_for_stock_change = 0;
4066  if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
4067  $qualified_for_stock_change = $object->hasProductsOrServices(2);
4068  } else {
4069  $qualified_for_stock_change = $object->hasProductsOrServices(1);
4070  }
4071 
4072  if ($qualified_for_stock_change) {
4073  $langs->load("stocks");
4074  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
4075  $formproduct = new FormProduct($db);
4076  $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
4077  $forcecombo = 0;
4078  if ($conf->browser->name == 'ie') {
4079  $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
4080  }
4081  $formquestion = array(
4082  // 'text' => $langs->trans("ConfirmClone"),
4083  // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
4084  // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
4085  array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, $langs->trans("NoStockAction"), 0, $forcecombo))
4086  );
4087  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', $formquestion, "yes", 1);
4088  } else {
4089  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', 'no', 1);
4090  }
4091  } else {
4092  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', 'no', 1);
4093  }
4094  }
4095 
4096  // Confirmation to remove invoice from cycle
4097  if ($action == 'situationout') {
4098  $text = $langs->trans('ConfirmRemoveSituationFromCycle', $object->ref);
4099  $label = $langs->trans("ConfirmOuting");
4100  $formquestion = array();
4101  // remove situation from cycle
4102  if (in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
4103  && $usercancreate
4104  && !$objectidnext
4105  && $object->is_last_in_cycle()
4106  && $usercanunvalidate
4107  ) {
4108  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $label, $text, 'confirm_situationout', $formquestion, "yes", 1);
4109  }
4110  }
4111 
4112  // Confirmation of validation
4113  if ($action == 'valid') {
4114  // we check object has a draft number
4115  $objectref = substr($object->ref, 1, 4);
4116  if ($objectref == 'PROV') {
4117  $savdate = $object->date;
4118  if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
4119  $object->date = dol_now();
4120  $object->date_lim_reglement = $object->calculate_date_lim_reglement();
4121  }
4122  $numref = $object->getNextNumRef($soc);
4123  // $object->date=$savdate;
4124  } else {
4125  $numref = $object->ref;
4126  }
4127 
4128  $text = $langs->trans('ConfirmValidateBill', $numref);
4129  if (isModEnabled('notification')) {
4130  require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
4131  $notify = new Notify($db);
4132  $text .= '<br>';
4133  $text .= $notify->confirmMessage('BILL_VALIDATE', $object->socid, $object);
4134  }
4135  $formquestion = array();
4136 
4137  if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
4138  $qualified_for_stock_change = 0;
4139  if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
4140  $qualified_for_stock_change = $object->hasProductsOrServices(2);
4141  } else {
4142  $qualified_for_stock_change = $object->hasProductsOrServices(1);
4143  }
4144 
4145  if ($qualified_for_stock_change) {
4146  $langs->load("stocks");
4147  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
4148  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
4149  $formproduct = new FormProduct($db);
4150  $warehouse = new Entrepot($db);
4151  $warehouse_array = $warehouse->list_array();
4152  if (count($warehouse_array) == 1) {
4153  $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
4154  $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
4155  } else {
4156  $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
4157  $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
4158  }
4159  $formquestion = array(
4160  // 'text' => $langs->trans("ConfirmClone"),
4161  // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
4162  // 1),
4163  // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
4164  // => 1),
4165  array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value));
4166  }
4167  }
4168  if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->total_ttc < 0) { // Can happen only if $conf->global->FACTURE_ENABLE_NEGATIVE is on
4169  $text .= '<br>'.img_warning().' '.$langs->trans("ErrorInvoiceOfThisTypeMustBePositive");
4170  }
4171 
4172  // mandatoryPeriod
4173  $nbMandated = 0;
4174  foreach ($object->lines as $line) {
4175  $res = $line->fetch_product();
4176  if ($res > 0 ) {
4177  if ($line->product->isService() && $line->product->isMandatoryPeriod() && (empty($line->date_start) || empty($line->date_end) )) {
4178  $nbMandated++;
4179  break;
4180  }
4181  }
4182  }
4183  if ($nbMandated > 0 ) $text .= '<div><span class="clearboth nowraponall warning">'.$langs->trans("mandatoryPeriodNeedTobeSetMsgValidate").'</span></div>';
4184 
4185 
4186  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, (($object->type != Facture::TYPE_CREDIT_NOTE && $object->total_ttc < 0) ? "no" : "yes"), 2);
4187  }
4188 
4189  // Confirm back to draft status
4190  if ($action == 'modif') {
4191  $text = $langs->trans('ConfirmUnvalidateBill', $object->ref);
4192  $formquestion = array();
4193 
4194  if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
4195  $qualified_for_stock_change = 0;
4196  if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
4197  $qualified_for_stock_change = $object->hasProductsOrServices(2);
4198  } else {
4199  $qualified_for_stock_change = $object->hasProductsOrServices(1);
4200  }
4201 
4202  if ($qualified_for_stock_change) {
4203  $langs->load("stocks");
4204  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
4205  require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
4206  $formproduct = new FormProduct($db);
4207  $warehouse = new Entrepot($db);
4208  $warehouse_array = $warehouse->list_array();
4209  if (count($warehouse_array) == 1) {
4210  $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
4211  $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
4212  } else {
4213  $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
4214  $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
4215  }
4216  $formquestion = array(
4217  // 'text' => $langs->trans("ConfirmClone"),
4218  // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
4219  // 1),
4220  // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
4221  // => 1),
4222  array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value));
4223  }
4224  }
4225 
4226  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('UnvalidateBill'), $text, 'confirm_modif', $formquestion, "yes", 1);
4227  }
4228 
4229  // Confirmation du classement paye
4230  if ($action == 'paid' && ($resteapayer <= 0 || (!empty($conf->global->INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $resteapayer == $object->total_ttc))) {
4231  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', "yes", 1);
4232  }
4233  if ($action == 'paid' && $resteapayer > 0 && (empty($conf->global->INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) || $resteapayer != $object->total_ttc)) {
4234  $close = array();
4235  // Code
4236  $i = 0;
4237  $close[$i]['code'] = 'discount_vat'; // escompte
4238  $i++;
4239  $close[$i]['code'] = 'badcustomer';
4240  $i++;
4241  $close[$i]['code'] = 'bankcharge';
4242  $i++;
4243  $close[$i]['code'] = 'other';
4244  $i++;
4245  // Help
4246  $i = 0;
4247  $close[$i]['label'] = $langs->trans("HelpEscompte").'<br><br>'.$langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
4248  $i++;
4249  $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
4250  $i++;
4251  $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBankChargeDesc");
4252  $i++;
4253  $close[$i]['label'] = $langs->trans("Other");
4254  $i++;
4255  // Texte
4256  $i = 0;
4257  $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
4258  $i++;
4259  $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
4260  $i++;
4261  $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBankCharge", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
4262  $i++;
4263  $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("Other"), $close[$i]['label'], 1);
4264  $i++;
4265  // arrayreasons[code]=reason
4266  foreach ($close as $key => $val) {
4267  $arrayreasons[$close[$key]['code']] = $close[$key]['reason'];
4268  }
4269 
4270  // Cree un tableau formulaire
4271  $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'));
4272  // Paiement incomplet. On demande si motif = escompte ou autre
4273  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes", 1, 340, 600);
4274  }
4275 
4276  // Confirmation du classement abandonne
4277  if ($action == 'canceled') {
4278  // S'il y a une facture de remplacement pas encore validee (etat brouillon),
4279  // on ne permet pas de classer abandonner la facture.
4280  if ($objectidnext) {
4281  $facturereplacement = new Facture($db);
4282  $facturereplacement->fetch($objectidnext);
4283  $statusreplacement = $facturereplacement->statut;
4284  }
4285  if ($objectidnext && $statusreplacement == 0) {
4286  print '<div class="error">'.$langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated").'</div>';
4287  } else {
4288  // Code
4289  $close[1]['code'] = 'badcustomer';
4290  $close[2]['code'] = 'abandon';
4291  // Help
4292  $close[1]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
4293  $close[2]['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
4294  // Texte
4295  $close[1]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $object->ref), $close[1]['label'], 1);
4296  $close[2]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close[2]['label'], 1);
4297  // arrayreasons
4298  $arrayreasons[$close[1]['code']] = $close[1]['reason'];
4299  $arrayreasons[$close[2]['code']] = $close[2]['reason'];
4300 
4301  // Cree un tableau formulaire
4302  $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'));
4303 
4304  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes", 1, 270);
4305  }
4306  }
4307 
4308  if ($action == 'deletepayment') {
4309  $payment_id = GETPOST('paiement_id');
4310  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 'no', 1);
4311  }
4312 
4313  // Confirmation de la suppression d'une ligne produit
4314  if ($action == 'ask_deleteline') {
4315  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
4316  }
4317 
4318  // Clone confirmation
4319  if ($action == 'clone') {
4320  // Create an array for form
4321  $formquestion = array(
4322  array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company($object->socid, 'socid', '(s.client=1 OR s.client=2 OR s.client=3)', 1)),
4323  array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now())
4324  );
4325  // Request confirmation to clone
4326  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 250);
4327  }
4328 
4329  if ($action == "remove_file_comfirm") {
4330  $file = GETPOST('file', 'alpha');
4331 
4332  $formconfirm = $form->formconfirm(
4333  $_SERVER["PHP_SELF"].'?facid='.$object->id.'&file='.$file,
4334  $langs->trans('DeleteFileHeader'),
4335  $langs->trans('DeleteFileText')."<br><br>".$file,
4336  'remove_file',
4337  '',
4338  'no',
4339  2
4340  );
4341  }
4342 
4343  // Call Hook formConfirm
4344  $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid, 'remainingtopay' => &$resteapayer);
4345  $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
4346  if (empty($reshook)) {
4347  $formconfirm .= $hookmanager->resPrint;
4348  } elseif ($reshook > 0) {
4349  $formconfirm = $hookmanager->resPrint;
4350  }
4351 
4352  // Print form confirm
4353  print $formconfirm;
4354 
4355  // Invoice content
4356 
4357  $linkback = '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
4358 
4359  $morehtmlref = '<div class="refidno">';
4360  // Ref invoice
4361  if ($object->status == $object::STATUS_DRAFT && !$mysoc->isInEEC() && !empty($conf->global->INVOICE_ALLOW_FREE_REF)) {
4362  $morehtmlref .= $form->editfieldkey("Ref", 'ref', $object->ref, $object, $usercancreate, 'string', '', 0, 1);
4363  $morehtmlref .= $form->editfieldval("Ref", 'ref', $object->ref, $object, $usercancreate, 'string', '', null, null, '', 1);
4364  $morehtmlref .= '<br>';
4365  }
4366  // Ref customer
4367  $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1);
4368  $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string'.(isset($conf->global->THIRDPARTY_REF_INPUT_SIZE) ? ':'.$conf->global->THIRDPARTY_REF_INPUT_SIZE : ''), '', null, null, '', 1);
4369  // Thirdparty
4370  $morehtmlref .= '<br>'.$object->thirdparty->getNomUrl(1, 'customer');
4371  if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
4372  $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->thirdparty->id.'&search_societe='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)';
4373  }
4374  // Project
4375  if (isModEnabled('project')) {
4376  $langs->load("projects");
4377  $morehtmlref .= '<br>';
4378  if ($usercancreate) {
4379  $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
4380  if ($action != 'classify') {
4381  $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> ';
4382  }
4383  $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
4384  } else {
4385  if (!empty($object->fk_project)) {
4386  $proj = new Project($db);
4387  $proj->fetch($object->fk_project);
4388  $morehtmlref .= $proj->getNomUrl(1);
4389  if ($proj->title) {
4390  $morehtmlref .= '<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).'</span>';
4391  }
4392  }
4393  }
4394  }
4395  $morehtmlref .= '</div>';
4396 
4397  $object->totalpaid = $totalpaid; // To give a chance to dol_banner_tab to use already paid amount to show correct status
4398 
4399  dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '');
4400 
4401  print '<div class="fichecenter">';
4402  print '<div class="fichehalfleft">';
4403  print '<div class="underbanner clearboth"></div>';
4404 
4405  print '<table class="border centpercent tableforfield">';
4406 
4407  // Type
4408  print '<tr><td class="titlefield fieldname_type">'.$langs->trans('Type').'</td><td class="valuefield fieldname_type">';
4409  print $object->getLibType(2);
4410  if ($object->module_source) {
4411  print ' <span class="opacitymediumbycolor paddingleft">('.$langs->trans("POS").' '.ucfirst($object->module_source).' - '.$langs->trans("Terminal").' '.$object->pos_source.')</span>';
4412  }
4413  if ($object->type == Facture::TYPE_REPLACEMENT) {
4414  $facreplaced = new Facture($db);
4415  $facreplaced->fetch($object->fk_facture_source);
4416  print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).'</span>';
4417  }
4418  if ($object->type == Facture::TYPE_CREDIT_NOTE && !empty($object->fk_facture_source)) {
4419  $facusing = new Facture($db);
4420  $facusing->fetch($object->fk_facture_source);
4421  print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).'</span>';
4422  }
4423 
4424  $facidavoir = $object->getListIdAvoirFromInvoice();
4425  if (count($facidavoir) > 0) {
4426  print ' <span class="opacitymediumbycolor paddingleft">'.$langs->transnoentities("InvoiceHasAvoir");
4427  $i = 0;
4428  foreach ($facidavoir as $id) {
4429  if ($i == 0) {
4430  print ' ';
4431  } else {
4432  print ',';
4433  }
4434  $facavoir = new Facture($db);
4435  $facavoir->fetch($id);
4436  print $facavoir->getNomUrl(1);
4437  }
4438  print '</span>';
4439  }
4440  if ($objectidnext > 0) {
4441  $facthatreplace = new Facture($db);
4442  $facthatreplace->fetch($objectidnext);
4443  print ' <span class="opacitymediumbycolor paddingleft">'.str_replace('{s1}', $facthatreplace->getNomUrl(1), $langs->transnoentities("ReplacedByInvoice", '{s1}')).'</span>';
4444  }
4445 
4446  if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
4447  $discount = new DiscountAbsolute($db);
4448  $result = $discount->fetch(0, $object->id);
4449  if ($result > 0) {
4450  print ' <span class="opacitymediumbycolor paddingleft">';
4451  $s = $langs->trans("CreditNoteConvertedIntoDiscount", '{s1}', '{s2}');
4452  $s = str_replace('{s1}', $object->getLibType(0), $s);
4453  $s = str_replace('{s2}', $discount->getNomUrl(1, 'discount'), $s);
4454  print $s;
4455  print '</span><br>';
4456  }
4457  }
4458 
4459  if ($object->fk_fac_rec_source > 0) {
4460  $tmptemplate = new FactureRec($db);
4461  $result = $tmptemplate->fetch($object->fk_fac_rec_source);
4462  if ($result > 0) {
4463  print ' <span class="opacitymediumbycolor paddingleft">';
4464  $s = $langs->transnoentities("GeneratedFromTemplate", '{s1}');
4465  $s = str_replace('{s1}', '<a href="'.DOL_URL_ROOT.'/compta/facture/card-rec.php?facid='.$tmptemplate->id.'">'.dol_escape_htmltag($tmptemplate->ref).'</a>', $s);
4466  print $s;
4467  print '</span>';
4468  }
4469  }
4470  print '</td></tr>';
4471 
4472  // Relative and absolute discounts
4473  print '<!-- Discounts -->'."\n";
4474  print '<tr><td>'.$langs->trans('DiscountStillRemaining').'</td>';
4475  print '<td>';
4476  $thirdparty = $soc;
4477  $discount_type = 0;
4478  $backtopage = urlencode($_SERVER["PHP_SELF"].'?facid='.$object->id);
4479  include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
4480  print '</td></tr>';
4481 
4482  // Date invoice
4483  print '<tr><td>';
4484  print '<table class="nobordernopadding centpercent"><tr><td>';
4485  print $langs->trans('DateInvoice');
4486  print '</td>';
4487  if ($action != 'editinvoicedate' && !empty($object->brouillon) && $usercancreate && empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
4488  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editinvoicedate&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
4489  }
4490  print '</tr></table>';
4491  print '</td><td>';
4492 
4493  if ($action == 'editinvoicedate') {
4494  $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->date, 'invoicedate');
4495  } else {
4496  print '<span class="valuedate">'.dol_print_date($object->date, 'day').'</span>';
4497  }
4498  print '</td>';
4499 
4500  print '</tr>';
4501 
4502  if (!empty($conf->global->INVOICE_POINTOFTAX_DATE)) {
4503  // Date invoice point of tax
4504  print '<tr><td>';
4505  print '<table class="nobordernopadding centpercent"><tr><td>';
4506  print $langs->trans('DatePointOfTax');
4507  print '</td>';
4508  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_pointoftax&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
4509  print '</tr></table>';
4510  print '</td><td>';
4511  if ($action == 'editdate_pointoftax') {
4512  $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->date_pointoftax, 'date_pointoftax');
4513  } else {
4514  print '<span class="valuedate">'.dol_print_date($object->date_pointoftax, 'day').'</span>';
4515  }
4516  print '</td></tr>';
4517  }
4518 
4519  // Payment term
4520  print '<tr><td>';
4521  print '<table class="nobordernopadding centpercent"><tr><td>';
4522  print $langs->trans('PaymentConditionsShort');
4523  print '</td>';
4524  if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && $usercancreate) {
4525  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>';
4526  }
4527  print '</tr></table>';
4528  print '</td><td>';
4529  if ($object->type != Facture::TYPE_CREDIT_NOTE) {
4530  if ($action == 'editconditions') {
4531  $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->cond_reglement_id, 'cond_reglement_id');
4532  } else {
4533  $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->cond_reglement_id, 'none');
4534  }
4535  } else {
4536  print '&nbsp;';
4537  }
4538  print '</td></tr>';
4539 
4540  // Date payment term
4541  print '<tr><td>';
4542  print '<table class="nobordernopadding centpercent"><tr><td>';
4543  print $langs->trans('DateMaxPayment');
4544  print '</td>';
4545  if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editpaymentterm' && $usercancreate) {
4546  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editpaymentterm&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
4547  }
4548  print '</tr></table>';
4549  print '</td><td>';
4550  if ($object->type != Facture::TYPE_CREDIT_NOTE) {
4551  if ($action == 'editpaymentterm') {
4552  $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->date_lim_reglement, 'paymentterm');
4553  } else {
4554  print '<span class="valuedate">'.dol_print_date($object->date_lim_reglement, 'day').'</span>';
4555  if ($object->hasDelay()) {
4556  print img_warning($langs->trans('Late'));
4557  }
4558  }
4559  } else {
4560  print '&nbsp;';
4561  }
4562  print '</td></tr>';
4563 
4564  // Payment mode
4565  print '<tr><td>';
4566  print '<table class="nobordernopadding centpercent"><tr><td>';
4567  print $langs->trans('PaymentMode');
4568  print '</td>';
4569  if ($action != 'editmode' && $usercancreate) {
4570  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
4571  }
4572  print '</tr></table>';
4573  print '</td><td>';
4574  if ($action == 'editmode') {
4575  $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1);
4576  } else {
4577  $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'none', 'CRDT');
4578  }
4579  print '</td></tr>';
4580 
4581  // Multicurrency
4582  if (isModEnabled('multicurrency')) {
4583  // Multicurrency code
4584  print '<tr>';
4585  print '<td>';
4586  print '<table class="nobordernopadding centpercent"><tr><td>';
4587  print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0);
4588  print '</td>';
4589  if ($usercancreate && $action != 'editmulticurrencycode' && !empty($object->brouillon)) {
4590  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>';
4591  }
4592  print '</tr></table>';
4593  print '</td><td>';
4594  $htmlname = (($usercancreate && $action == 'editmulticurrencycode') ? 'multicurrency_code' : 'none');
4595  $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, $htmlname);
4596  print '</td></tr>';
4597 
4598  // Multicurrency rate
4599  if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
4600  print '<tr>';
4601  print '<td>';
4602  print '<table class="nobordernopadding" width="100%"><tr><td>';
4603  print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0);
4604  print '</td>';
4605  if ($usercancreate && $action != 'editmulticurrencyrate' && !empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
4606  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>';
4607  }
4608  print '</tr></table>';
4609  print '</td><td>';
4610  if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
4611  if ($action == 'actualizemulticurrencyrate') {
4612  list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
4613  }
4614  $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, ($usercancreate ? 'multicurrency_tx' : 'none'), $object->multicurrency_code);
4615  } else {
4616  $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
4617  if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
4618  print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
4619  print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
4620  print '</div>';
4621  }
4622  }
4623  print '</td></tr>';
4624  }
4625  }
4626 
4627  // Bank Account
4628  if (isModEnabled("banque")) {
4629  print '<tr><td class="nowrap">';
4630  print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
4631  print $langs->trans('BankAccount');
4632  print '<td>';
4633  if (($action != 'editbankaccount') && $usercancreate) {
4634  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>';
4635  }
4636  print '</tr></table>';
4637  print '</td><td>';
4638  if ($action == 'editbankaccount') {
4639  $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
4640  } else {
4641  $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
4642  }
4643  print "</td>";
4644  print '</tr>';
4645  }
4646 
4647  // Incoterms
4648  if (isModEnabled('incoterm')) {
4649  print '<tr><td>';
4650  print '<table class="nobordernopadding centpercent"><tr><td>';
4651  print $langs->trans('IncotermLabel');
4652  print '<td><td class="right">';
4653  if ($usercancreate) {
4654  print '<a class="editfielda" href="'.DOL_URL_ROOT.'/compta/facture/card.php?facid='.$object->id.'&action=editincoterm&token='.newToken().'">'.img_edit().'</a>';
4655  } else {
4656  print '&nbsp;';
4657  }
4658  print '</td></tr></table>';
4659  print '</td>';
4660  print '<td>';
4661  if ($action != 'editincoterm') {
4662  print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
4663  } else {
4664  print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
4665  }
4666  print '</td></tr>';
4667  }
4668 
4669 
4670 
4671  if (!empty($object->retained_warranty) || !empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
4672  $displayWarranty = true;
4673  if (!in_array($object->type, $retainedWarrantyInvoiceAvailableType) && empty($object->retained_warranty)) {
4674  $displayWarranty = false;
4675  }
4676 
4677  if ($displayWarranty) {
4678  // Retained Warranty
4679  print '<tr class="retained-warranty-lines" ><td>';
4680  print '<table id="retained-warranty-table" class="nobordernopadding centpercent"><tr><td>';
4681  print $langs->trans('RetainedWarranty');
4682  print '</td>';
4683  if ($action != 'editretainedwarranty' && $user->rights->facture->creer && $object->statut == Facture::STATUS_DRAFT) {
4684  print '<td align="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editretainedwarranty&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('setretainedwarranty'), 1).'</a></td>';
4685  }
4686 
4687  print '</tr></table>';
4688  print '</td><td>';
4689  if ($action == 'editretainedwarranty' && $object->statut == Facture::STATUS_DRAFT) {
4690  print '<form id="retained-warranty-form" method="POST" action="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'">';
4691  print '<input type="hidden" name="action" value="setretainedwarranty">';
4692  print '<input type="hidden" name="token" value="'.newToken().'">';
4693  print '<input name="retained_warranty" type="number" step="0.01" min="0" max="100" value="'.$object->retained_warranty.'" >';
4694  print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4695  print '</form>';
4696  } else {
4697  print price($object->retained_warranty).'%';
4698  }
4699  print '</td></tr>';
4700 
4701  // Retained warranty payment term
4702  print '<tr class="retained-warranty-lines" ><td>';
4703  print '<table id="retained-warranty-cond-reglement-table" class="nobordernopadding" width="100%"><tr><td>';
4704  print $langs->trans('PaymentConditionsShortRetainedWarranty');
4705  print '</td>';
4706  if ($action != 'editretainedwarrantypaymentterms' && $user->rights->facture->creer && $object->statut == Facture::STATUS_DRAFT) {
4707  print '<td align="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editretainedwarrantypaymentterms&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('setPaymentConditionsShortRetainedWarranty'), 1).'</a></td>';
4708  }
4709 
4710  print '</tr></table>';
4711  print '</td><td>';
4712  $defaultDate = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : strtotime('-1 years', $object->date_lim_reglement);
4713  if ($object->date > $defaultDate) {
4714  $defaultDate = $object->date;
4715  }
4716 
4717  if ($action == 'editretainedwarrantypaymentterms' && $object->statut == Facture::STATUS_DRAFT) {
4718  //date('Y-m-d',$object->date_lim_reglement)
4719  print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'">';
4720  print '<input type="hidden" name="action" value="setretainedwarrantyconditions">';
4721  print '<input type="hidden" name="token" value="'.newToken().'">';
4722  $retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
4723  $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : $object->retained_warranty_fk_cond_reglement;
4724  $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
4725  print $form->getSelectConditionsPaiements($retained_warranty_fk_cond_reglement, 'retained_warranty_fk_cond_reglement', -1, 1);
4726  print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4727  print '</form>';
4728  } else {
4729  $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->retained_warranty_fk_cond_reglement, 'none');
4730  if (!$displayWarranty) {
4731  print img_picto($langs->trans('RetainedWarrantyNeed100Percent'), 'warning.png', 'class="pictowarning valignmiddle" ');
4732  }
4733  }
4734  print '</td></tr>';
4735 
4736  // Retained Warranty payment date limit
4737  print '<tr class="retained-warranty-lines" ><td>';
4738  print '<table id="retained-warranty-date-limit-table" class="nobordernopadding" width="100%"><tr><td>';
4739  print $langs->trans('RetainedWarrantyDateLimit');
4740  print '</td>';
4741  if ($action != 'editretainedwarrantydatelimit' && $user->rights->facture->creer && $object->statut == Facture::STATUS_DRAFT) {
4742  print '<td align="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editretainedwarrantydatelimit&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('setretainedwarrantyDateLimit'), 1).'</a></td>';
4743  }
4744 
4745  print '</tr></table>';
4746  print '</td><td>';
4747  $defaultDate = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : strtotime('-1 years', $object->date_lim_reglement);
4748  if ($object->date > $defaultDate) {
4749  $defaultDate = $object->date;
4750  }
4751 
4752  if ($action == 'editretainedwarrantydatelimit' && $object->statut == Facture::STATUS_DRAFT) {
4753  //date('Y-m-d',$object->date_lim_reglement)
4754  print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'">';
4755  print '<input type="hidden" name="action" value="setretainedwarrantydatelimit">';
4756  print '<input type="hidden" name="token" value="'.newToken().'">';
4757  print '<input name="retained_warranty_date_limit" type="date" step="1" min="'.dol_print_date($object->date, '%Y-%m-%d').'" value="'.dol_print_date($defaultDate, '%Y-%m-%d').'" >';
4758  print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4759  print '</form>';
4760  } else {
4761  print dol_print_date($object->retained_warranty_date_limit, 'day');
4762  }
4763  print '</td></tr>';
4764  }
4765  }
4766 
4767 
4768  // Other attributes
4769  $cols = 2;
4770  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
4771 
4772  print '</table>';
4773 
4774  print '</div>';
4775  print '<div class="fichehalfright">';
4776 
4777  print '<!-- amounts -->'."\n";
4778  print '<div class="underbanner clearboth"></div>'."\n";
4779  print '<table class="border tableforfield centpercent">';
4780 
4781  $sign = 1;
4782  if (!empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE_SCREEN) && $object->type == $object::TYPE_CREDIT_NOTE) {
4783  $sign = -1; // We invert sign for output
4784  }
4785 
4786  if (isModEnabled('multicurrency') && ($object->multicurrency_code != $conf->currency)) {
4787  // Multicurrency Amount HT
4788  print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>';
4789  print '<td class="nowrap right amountcard">'.price($sign * $object->multicurrency_total_ht, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
4790  print '</tr>';
4791 
4792  // Multicurrency Amount VAT
4793  print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).'</td>';
4794  print '<td class="nowrap right amountcard">'.price($sign * $object->multicurrency_total_tva, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
4795  print '</tr>';
4796 
4797  // Multicurrency Amount TTC
4798  print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).'</td>';
4799  print '<td class="nowrap right amountcard">'.price($sign * $object->multicurrency_total_ttc, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
4800  print '</tr>';
4801  }
4802 
4803  // Amount
4804  print '<tr><td class="titlefieldmiddle">'.$langs->trans('AmountHT').'</td>';
4805  print '<td class="nowrap right amountcard">'.price($sign * $object->total_ht, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
4806 
4807  // Vat
4808  print '<tr><td>'.$langs->trans('AmountVAT').'</td><td colspan="3" class="nowrap right amountcard">'.price($sign * $object->total_tva, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
4809  print '</tr>';
4810 
4811  // Amount Local Taxes
4812  if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) { // Localtax1
4813  print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>';
4814  print '<td class="nowrap right amountcard">'.price($sign * $object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
4815  }
4816  if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) { // Localtax2
4817  print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>';
4818  print '<td class="nowrap right amountcard">'.price($sign * $object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
4819  }
4820 
4821  // Revenue stamp
4822  if ($selleruserevenustamp) { // Test company use revenue stamp
4823  print '<tr><td>';
4824  print '<table class="nobordernopadding" width="100%"><tr><td>';
4825  print $langs->trans('RevenueStamp');
4826  print '</td>';
4827  if ($action != 'editrevenuestamp' && !empty($object->brouillon) && $usercancreate) {
4828  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editrevenuestamp&token='.newToken().'&facid='.$object->id.'">'.img_edit($langs->trans('SetRevenuStamp'), 1).'</a></td>';
4829  }
4830  print '</tr></table>';
4831  print '</td><td>';
4832  if ($action == 'editrevenuestamp') {
4833  print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
4834  print '<input type="hidden" name="token" value="'.newToken().'">';
4835  print '<input type="hidden" name="action" value="setrevenuestamp">';
4836  print '<input type="hidden" name="revenuestamp" id="revenuestamp_val" value="'.price2num($object->revenuestamp).'">';
4837  print $formother->select_revenue_stamp('', 'revenuestamp_type', $mysoc->country_code);
4838  print ' &rarr; <span id="revenuestamp_span"></span>';
4839  print ' <input type="submit" class="button buttongen button-save" value="'.$langs->trans('Modify').'">';
4840  print '</form>';
4841  print " <script>
4842  $(document).ready(function(){
4843  js_recalculate_revenuestamp();
4844  $('select[name=revenuestamp_type]').on('change',function(){
4845  js_recalculate_revenuestamp();
4846  });
4847  });
4848  function js_recalculate_revenuestamp(){
4849  var valselected = $('select[name=revenuestamp_type]').val();
4850  console.log('Calculate revenue stamp from '+valselected);
4851  var revenue = 0;
4852  if (valselected.indexOf('%') == -1)
4853  {
4854  revenue = valselected;
4855  }
4856  else
4857  {
4858  var revenue_type = parseFloat(valselected);
4859  var amount_net = ".round($object->total_ht, 2).";
4860  revenue = revenue_type * amount_net / 100;
4861  revenue = revenue.toFixed(2);
4862  }
4863  $('#revenuestamp_val').val(revenue);
4864  $('#revenuestamp_span').html(revenue);
4865  }
4866  </script>";
4867  } else {
4868  print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency);
4869  }
4870  print '</td></tr>';
4871  }
4872 
4873  // Total with tax
4874  print '<tr><td>'.$langs->trans('AmountTTC').'</td><td class="nowrap right amountcard">'.price($sign * $object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
4875 
4876  print '</table>';
4877 
4878 
4879  $nbrows = 8;
4880  $nbcols = 3;
4881  if (isModEnabled('project')) {
4882  $nbrows++;
4883  }
4884  if (isModEnabled("banque")) {
4885  $nbrows++;
4886  $nbcols++;
4887  }
4888  if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) {
4889  $nbrows++;
4890  }
4891  if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) {
4892  $nbrows++;
4893  }
4894  if ($selleruserevenustamp) {
4895  $nbrows++;
4896  }
4897  if (isModEnabled('multicurrency')) {
4898  $nbrows += 5;
4899  }
4900  if (isModEnabled('incoterm')) {
4901  $nbrows += 1;
4902  }
4903 
4904  // List of previous situation invoices
4905  if (($object->situation_cycle_ref > 0) && !empty($conf->global->INVOICE_USE_SITUATION)) {
4906  print '<!-- List of situation invoices -->';
4907  print '<table class="noborder situationstable" width="100%">';
4908 
4909  print '<tr class="liste_titre">';
4910  print '<td>'.$langs->trans('ListOfSituationInvoices').'</td>';
4911  print '<td></td>';
4912  print '<td class="center">'.$langs->trans('Situation').'</td>';
4913  if (isModEnabled("banque")) {
4914  print '<td class="right"></td>';
4915  }
4916  print '<td class="right">'.$langs->trans('AmountHT').'</td>';
4917  print '<td class="right">'.$langs->trans('AmountTTC').'</td>';
4918  print '<td width="18">&nbsp;</td>';
4919  print '</tr>';
4920 
4921  $total_prev_ht = $total_prev_ttc = 0;
4922  $total_global_ht = $total_global_ttc = 0;
4923 
4924  if (count($object->tab_previous_situation_invoice) > 0) {
4925  // List of previous invoices
4926 
4927  $current_situation_counter = array();
4928  foreach ($object->tab_previous_situation_invoice as $prev_invoice) {
4929  $tmptotalpaidforthisinvoice = $prev_invoice->getSommePaiement();
4930  $total_prev_ht += $prev_invoice->total_ht;
4931  $total_prev_ttc += $prev_invoice->total_ttc;
4932  $current_situation_counter[] = (($prev_invoice->type == Facture::TYPE_CREDIT_NOTE) ?-1 : 1) * $prev_invoice->situation_counter;
4933  print '<tr class="oddeven">';
4934  print '<td>'.$prev_invoice->getNomUrl(1).'</td>';
4935  print '<td></td>';
4936  print '<td align="center" >'.(($prev_invoice->type == Facture::TYPE_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')).$prev_invoice->situation_counter.'</td>';
4937  if (isModEnabled("banque")) {
4938  print '<td class="right"></td>';
4939  }
4940  print '<td class="right"><span class="amount">'.price($prev_invoice->total_ht).'</span></td>';
4941  print '<td class="right"><span class="amount">'.price($prev_invoice->total_ttc).'</span></td>';
4942  print '<td class="right">'.$prev_invoice->getLibStatut(3, $tmptotalpaidforthisinvoice).'</td>';
4943  print '</tr>';
4944  }
4945  }
4946 
4947 
4948  $total_global_ht += $total_prev_ht;
4949  $total_global_ttc += $total_prev_ttc;
4950  $total_global_ht += $object->total_ht;
4951  $total_global_ttc += $object->total_ttc;
4952  $current_situation_counter[] = (($object->type == Facture::TYPE_CREDIT_NOTE) ?-1 : 1) * $object->situation_counter;
4953  print '<tr class="oddeven">';
4954  print '<td>'.$object->getNomUrl(1).'</td>';
4955  print '<td></td>';
4956  print '<td class="center">'.(($object->type == Facture::TYPE_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')).$object->situation_counter.'</td>';
4957  if (isModEnabled("banque")) {
4958  print '<td class="right"></td>';
4959  }
4960  print '<td class="right"><span class="amount">'.price($object->total_ht).'</span></td>';
4961  print '<td class="right"><span class="amount">'.price($object->total_ttc).'</span></td>';
4962  print '<td class="right">'.$object->getLibStatut(3, $object->getSommePaiement()).'</td>';
4963  print '</tr>';
4964 
4965 
4966  print '<tr class="oddeven">';
4967  print '<td colspan="2" class="left"><b>'.$langs->trans('CurrentSituationTotal').'</b></td>';
4968  print '<td>';
4969  $i = 0;
4970  foreach ($current_situation_counter as $sit) {
4971  $curSign = $sit > 0 ? '+' : '-';
4972  $curType = $sit > 0 ? $langs->trans('situationInvoiceShortcode_S') : $langs->trans('situationInvoiceShortcode_AS');
4973  if ($i > 0) {
4974  print ' '.$curSign.' ';
4975  }
4976  print $curType.abs($sit);
4977  $i++;
4978  }
4979  print '</td>';
4980  if (isModEnabled("banque")) {
4981  print '<td></td>';
4982  }
4983  print '<td class="right"><b>'.price($total_global_ht).'</b></td>';
4984  print '<td class="right"><b>'.price($total_global_ttc).'</b></td>';
4985  print '<td width="18">&nbsp;</td>';
4986  print '</tr>';
4987 
4988 
4989  if (count($object->tab_next_situation_invoice) > 0) {
4990  // List of next invoices
4991  /*print '<tr class="liste_titre">';
4992  print '<td>' . $langs->trans('ListOfNextSituationInvoices') . '</td>';
4993  print '<td></td>';
4994  print '<td></td>';
4995  if (isModEnabled('banque')) print '<td class="right"></td>';
4996  print '<td class="right">' . $langs->trans('AmountHT') . '</td>';
4997  print '<td class="right">' . $langs->trans('AmountTTC') . '</td>';
4998  print '<td width="18">&nbsp;</td>';
4999  print '</tr>';*/
5000 
5001  $total_next_ht = $total_next_ttc = 0;
5002 
5003  foreach ($object->tab_next_situation_invoice as $next_invoice) {
5004  $totalpaid = $next_invoice->getSommePaiement();
5005  $total_next_ht += $next_invoice->total_ht;
5006  $total_next_ttc += $next_invoice->total_ttc;
5007 
5008  print '<tr class="oddeven">';
5009  print '<td>'.$next_invoice->getNomUrl(1).'</td>';
5010  print '<td></td>';
5011  print '<td class="center">'.(($next_invoice->type == Facture::TYPE_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')).$next_invoice->situation_counter.'</td>';
5012  if (isModEnabled("banque")) {
5013  print '<td class="right"></td>';
5014  }
5015  print '<td class="right"><span class="amount">'.price($next_invoice->total_ht).'</span></td>';
5016  print '<td class="right"><span class="amount">'.price($next_invoice->total_ttc).'</span></td>';
5017  print '<td class="right">'.$next_invoice->getLibStatut(3, $totalpaid).'</td>';
5018  print '</tr>';
5019  }
5020 
5021  $total_global_ht += $total_next_ht;
5022  $total_global_ttc += $total_next_ttc;
5023 
5024  print '<tr class="oddeven">';
5025  print '<td colspan="3" class="right"></td>';
5026  if (isModEnabled("banque")) {
5027  print '<td class="right"></td>';
5028  }
5029  print '<td class="right"><b>'.price($total_global_ht).'</b></td>';
5030  print '<td class="right"><b>'.price($total_global_ttc).'</b></td>';
5031  print '<td width="18">&nbsp;</td>';
5032  print '</tr>';
5033  }
5034 
5035  print '</table>';
5036  }
5037 
5038  $sign = 1;
5039  if ($object->type == $object::TYPE_CREDIT_NOTE) {
5040  $sign = -1;
5041  }
5042 
5043  // List of payments already done
5044 
5045  print '<!-- List of payments already done -->';
5046  print '<div class="div-table-responsive-no-min">';
5047  print '<table class="noborder paymenttable centpercent">';
5048 
5049  print '<tr class="liste_titre">';
5050  print '<td class="liste_titre">'.($object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>';
5051  print '<td class="liste_titre"><span class="hideonsmartphone">'.$langs->trans('Date').'</span></td>';
5052  print '<td class="liste_titre"><span class="hideonsmartphone">'.$langs->trans('Type').'</span></td>';
5053  if (isModEnabled("banque")) {
5054  print '<td class="liste_titre"><span class="hideonsmartphone">'.$langs->trans('BankAccount').'</span></td>';
5055  }
5056  print '<td class="liste_titre right">'.$langs->trans('Amount').'</td>';
5057  print '<td class="liste_titre" width="18">&nbsp;</td>';
5058  print '</tr>';
5059 
5060  // Payments already done (from payment on this invoice)
5061  $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,';
5062  $sql .= ' c.code as payment_code, c.libelle as payment_label,';
5063  $sql .= ' pf.amount,';
5064  $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal, ba.currency_code as bacurrency_code';
5065  $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
5066  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
5067  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
5068  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
5069  $sql .= ' WHERE pf.fk_facture = '.((int) $object->id).' AND pf.fk_paiement = p.rowid';
5070  $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
5071  $sql .= ' ORDER BY p.datep, p.tms';
5072 
5073  $result = $db->query($sql);
5074  if ($result) {
5075  $num = $db->num_rows($result);
5076  $i = 0;
5077 
5078  if ($num > 0) {
5079  while ($i < $num) {
5080  $objp = $db->fetch_object($result);
5081 
5082  $paymentstatic->id = $objp->rowid;
5083  $paymentstatic->datepaye = $db->jdate($objp->dp);
5084  $paymentstatic->ref = $objp->ref;
5085  $paymentstatic->num_payment = $objp->num_payment;
5086  $paymentstatic->paiementcode = $objp->payment_code;
5087 
5088  print '<tr class="oddeven"><td class="nowraponall">';
5089  print $paymentstatic->getNomUrl(1);
5090  print '</td>';
5091  print '<td>';
5092  $dateofpayment = $db->jdate($objp->dp);
5093  $tmparray = dol_getdate($dateofpayment);
5094  if ($tmparray['seconds'] == 0 && $tmparray['minutes'] == 0 && ($tmparray['hours'] == 0 || $tmparray['hours'] == 12)) { // We set hours to 0:00 or 12:00 because we don't know it
5095  print dol_print_date($dateofpayment, 'day');
5096  } else { // Hours was set to real date of payment (special case for POS for example)
5097  print dol_print_date($dateofpayment, 'dayhour', 'tzuser');
5098  }
5099  print '</td>';
5100  $label = ($langs->trans("PaymentType".$objp->payment_code) != ("PaymentType".$objp->payment_code)) ? $langs->trans("PaymentType".$objp->payment_code) : $objp->payment_label;
5101  print '<td>'.$label.' '.$objp->num_payment.'</td>';
5102  if (isModEnabled("banque")) {
5103  $bankaccountstatic->id = $objp->baid;
5104  $bankaccountstatic->ref = $objp->baref;
5105  $bankaccountstatic->label = $objp->baref;
5106  $bankaccountstatic->number = $objp->banumber;
5107  $bankaccountstatic->currency_code = $objp->bacurrency_code;
5108 
5109  if (isModEnabled('accounting')) {
5110  $bankaccountstatic->account_number = $objp->account_number;
5111 
5112  $accountingjournal = new AccountingJournal($db);
5113  $accountingjournal->fetch($objp->fk_accountancy_journal);
5114  $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
5115  }
5116 
5117  print '<td class="nowraponall">';
5118  if ($bankaccountstatic->id) {
5119  print $bankaccountstatic->getNomUrl(1, 'transactions');
5120  }
5121  print '</td>';
5122  }
5123  print '<td class="right"><span class="amount">'.price($sign * $objp->amount).'</span></td>';
5124  print '<td class="center">';
5125  if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) {
5126  print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deletepayment&token='.newToken().'&paiement_id='.$objp->rowid.'">';
5127  print img_delete();
5128  print '</a>';
5129  }
5130  print '</td>';
5131  print '</tr>';
5132  $i++;
5133  }
5134  }
5135 
5136  $db->free($result);
5137  } else {
5138  dol_print_error($db);
5139  }
5140 
5141  if ($object->type != Facture::TYPE_CREDIT_NOTE) {
5142  // Total already paid
5143  print '<tr><td colspan="'.$nbcols.'" class="right">';
5144  print '<span class="opacitymedium">';
5145  if ($object->type != Facture::TYPE_DEPOSIT) {
5146  print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
5147  } else {
5148  print $langs->trans('AlreadyPaid');
5149  }
5150  print '</span></td><td class="right'.(($totalpaid > 0) ? ' amountalreadypaid' : '').'">'.price($totalpaid).'</td><td>&nbsp;</td></tr>';
5151 
5152  $resteapayeraffiche = $resteapayer;
5153  $cssforamountpaymentcomplete = 'amountpaymentcomplete';
5154 
5155  // Loop on each credit note or deposit amount applied
5156  $creditnoteamount = 0;
5157  $depositamount = 0;
5158  $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
5159  $sql .= " re.description, re.fk_facture_source";
5160  $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
5161  $sql .= " WHERE fk_facture = ".((int) $object->id);
5162  $resql = $db->query($sql);
5163  if ($resql) {
5164  $num = $db->num_rows($resql);
5165  $i = 0;
5166  $invoice = new Facture($db);
5167  while ($i < $num) {
5168  $obj = $db->fetch_object($resql);
5169  $invoice->fetch($obj->fk_facture_source);
5170  print '<tr><td colspan="'.$nbcols.'" class="right">';
5171  print '<span class="opacitymedium">';
5172  if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
5173  print $langs->trans("CreditNote").' ';
5174  }
5175  if ($invoice->type == Facture::TYPE_DEPOSIT) {
5176  print $langs->trans("Deposit").' ';
5177  }
5178  print $invoice->getNomUrl(0);
5179  print '</span>';
5180  print '</td>';
5181  print '<td class="right"><span class="amount">'.price($obj->amount_ttc).'</span></td>';
5182  print '<td class="right">';
5183  print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&token='.newToken().'&discountid='.$obj->rowid.'">'.img_delete().'</a>';
5184  print '</td></tr>';
5185  $i++;
5186  if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
5187  $creditnoteamount += $obj->amount_ttc;
5188  }
5189  if ($invoice->type == Facture::TYPE_DEPOSIT) {
5190  $depositamount += $obj->amount_ttc;
5191  }
5192  }
5193  } else {
5194  dol_print_error($db);
5195  }
5196 
5197  // Paye partiellement 'escompte'
5198  if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'discount_vat') {
5199  print '<tr><td colspan="'.$nbcols.'" class="nowrap right">';
5200  print '<span class="opacitymedium">';
5201  print $form->textwithpicto($langs->trans("Discount"), $langs->trans("HelpEscompte"), - 1);
5202  print '</span>';
5203  print '</td><td class="right"><span class="amount">'.price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')).'</span></td><td>&nbsp;</td></tr>';
5204  $resteapayeraffiche = 0;
5205  $cssforamountpaymentcomplete = 'amountpaymentneutral';
5206  }
5207  // Paye partiellement ou Abandon 'badcustomer'
5208  if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') {
5209  print '<tr><td colspan="'.$nbcols.'" class="nowrap right">';
5210  print '<span class="opacitymedium">';
5211  print $form->textwithpicto($langs->trans("Abandoned"), $langs->trans("HelpAbandonBadCustomer"), - 1);
5212  print '</span>';
5213  print '</td><td class="right">'.price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')).'</td><td>&nbsp;</td></tr>';
5214  // $resteapayeraffiche=0;
5215  $cssforamountpaymentcomplete = 'amountpaymentneutral';
5216  }
5217  // Paye partiellement ou Abandon 'product_returned'
5218  if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') {
5219  print '<tr><td colspan="'.$nbcols.'" class="nowrap right">';
5220  print '<span class="opacitymedium">';
5221  print $form->textwithpicto($langs->trans("ProductReturned"), $langs->trans("HelpAbandonProductReturned"), - 1);
5222  print '</span>';
5223  print '</td><td class="right"><span class="amount">'.price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')).'</span></td><td>&nbsp;</td></tr>';
5224  $resteapayeraffiche = 0;
5225  $cssforamountpaymentcomplete = 'amountpaymentneutral';
5226  }
5227  // Paye partiellement ou Abandon 'abandon'
5228  if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') {
5229  print '<tr><td colspan="'.$nbcols.'" class="nowrap right">';
5230  $text = $langs->trans("HelpAbandonOther");
5231  if ($object->close_note) {
5232  $text .= '<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note;
5233  }
5234  print '<span class="opacitymedium">';
5235  print $form->textwithpicto($langs->trans("Abandoned"), $text, - 1);
5236  print '</span>';
5237  print '</td><td class="right"><span class="amount">'.price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaid, 'MT')).'</span></td><td>&nbsp;</td></tr>';
5238  $resteapayeraffiche = 0;
5239  $cssforamountpaymentcomplete = 'amountpaymentneutral';
5240  }
5241 
5242  // Billed
5243  print '<tr><td colspan="'.$nbcols.'" class="right">';
5244  print '<span class="opacitymedium">';
5245  print $langs->trans("Billed");
5246  print '</td><td class="right">'.price($object->total_ttc).'</td><td>&nbsp;</td></tr>';
5247  // Remainder to pay
5248  print '<tr><td colspan="'.$nbcols.'" class="right">';
5249  print '<span class="opacitymedium">';
5250  print $langs->trans('RemainderToPay');
5251  if ($resteapayeraffiche < 0) {
5252  print ' ('.$langs->trans('NegativeIfExcessReceived').')';
5253  }
5254  print '</span>';
5255  print '</td>';
5256  print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($resteapayeraffiche).'</td><td>&nbsp;</td></tr>';
5257 
5258  // Remainder to pay Multicurrency
5259  if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
5260  print '<tr><td colspan="'.$nbcols.'" class="right">';
5261  print '<span class="opacitymedium">';
5262  print $langs->trans('RemainderToPayMulticurrency');
5263  if ($resteapayeraffiche < 0) {
5264  print ' ('.$langs->trans('NegativeIfExcessReceived').')';
5265  }
5266  print '</span>';
5267  print '</td>';
5268  print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">';
5269  //print (empty($object->multicurrency_code) ? $conf->currency : $object->multicurrency_code).' ';
5270  print price(price2num($object->multicurrency_tx*$resteapayeraffiche, 'MT'), 1, $langs, 1, -1, -1, (empty($object->multicurrency_code) ? $conf->currency : $object->multicurrency_code)).'</td><td>&nbsp;</td></tr>';
5271  }
5272 
5273  // Retained warranty : usualy use on construction industry
5274  if (!empty($object->situation_final) && !empty($object->retained_warranty) && $displayWarranty) {
5275  // Billed - retained warranty
5276  if ($object->type == Facture::TYPE_SITUATION) {
5277  $retainedWarranty = $total_global_ttc * $object->retained_warranty / 100;
5278  } else {
5279  // Because one day retained warranty could be used on standard invoices
5280  $retainedWarranty = $object->total_ttc * $object->retained_warranty / 100;
5281  }
5282 
5283  $billedWithRetainedWarranty = $object->total_ttc - $retainedWarranty;
5284 
5285  print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans("ToPayOn", dol_print_date($object->date_lim_reglement, 'day')).' :</td><td align="right">'.price($billedWithRetainedWarranty).'</td><td>&nbsp;</td></tr>';
5286 
5287  // retained warranty
5288  print '<tr><td colspan="'.$nbcols.'" align="right">';
5289  print $langs->trans("RetainedWarranty").' ('.$object->retained_warranty.'%)';
5290  print !empty($object->retained_warranty_date_limit) ? ' '.$langs->trans("ToPayOn", dol_print_date($object->retained_warranty_date_limit, 'day')) : '';
5291  print ' :</td><td align="right">'.price($retainedWarranty).'</td><td>&nbsp;</td></tr>';
5292  }
5293  } else { // Credit note
5294  $resteapayeraffiche = $resteapayer;
5295  $cssforamountpaymentcomplete = 'amountpaymentneutral';
5296 
5297  // Total already paid back
5298  print '<tr><td colspan="'.$nbcols.'" class="right">';
5299  print '<span class="opacitymedium">'.$langs->trans('AlreadyPaidBack').'</span>';
5300  print '</td><td class="right"><span class="amount">'.price($sign * $totalpaid).'</span></td><td>&nbsp;</td></tr>';
5301 
5302  // Billed
5303  print '<tr><td colspan="'.$nbcols.'" class="right"><span class="opacitymedium">'.$langs->trans("Billed").'</span></td><td class="right">'.price($sign * $object->total_ttc).'</td><td>&nbsp;</td></tr>';
5304 
5305  // Remainder to pay back
5306  print '<tr><td colspan="'.$nbcols.'" class="right">';
5307  print '<span class="opacitymedium">'.$langs->trans('RemainderToPayBack');
5308  if ($resteapayeraffiche > 0) {
5309  print ' ('.$langs->trans('NegativeIfExcessRefunded').')';
5310  }
5311  print '</span></td>';
5312  print '<td class="right'.($resteapayeraffiche ? ' amountremaintopayback' : (' '.$cssforamountpaymentcomplete)).'">'.price($sign * $resteapayeraffiche).'</td>';
5313  print '<td class="nowrap">&nbsp;</td></tr>';
5314 
5315  // Remainder to pay back Multicurrency
5316  if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
5317  print '<tr><td colspan="'.$nbcols.'" class="right">';
5318  print '<span class="opacitymedium">'.$langs->trans('RemainderToPayBackMulticurrency');
5319  if ($resteapayeraffiche > 0) {
5320  print ' ('.$langs->trans('NegativeIfExcessRefunded').')';
5321  }
5322  print '</span>';
5323  print '</td>';
5324  print '<td class="right'.($resteapayeraffiche ? ' amountremaintopayback' : (' '.$cssforamountpaymentcomplete)).'">'.(!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency).' '.price(price2num($sign * $object->multicurrency_tx * $resteapayeraffiche, 'MT')).'</td><td>&nbsp;</td></tr>';
5325  }
5326 
5327  // Sold credit note
5328  // print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('TotalTTC').' :</td>';
5329  // print '<td class="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
5330  // $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
5331  }
5332 
5333  print '</table>';
5334  print '</div>';
5335 
5336  // Margin Infos
5337  if (isModEnabled('margin')) {
5338  $formmargin->displayMarginInfos($object);
5339  }
5340 
5341  print '</div>';
5342  print '</div>';
5343 
5344  print '<div class="clearboth"></div><br><br>';
5345 
5346  if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
5347  $blocname = 'contacts';
5348  $title = $langs->trans('ContactsAddresses');
5349  include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
5350  }
5351