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