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