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