dolibarr  13.0.2
card.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2003-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2019 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
5  * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
6  * Copyright (C) 2010-2017 Juanjo Menent <jmenent@2byte.es>
7  * Copyright (C) 2013 Christophe Battarel <christophe.battarel@altairis.fr>
8  * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
9  * Copyright (C) 2014-2020 Ferran Marcet <fmarcet@2byte.es>
10  * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
11  * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
12  * Copyright (C) 2018-2020 Frédéric France <frederic.france@netlogic.fr>
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 3 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program. If not, see <https://www.gnu.org/licenses/>.
26  */
27 
34 require "../main.inc.php";
35 require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
36 require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
37 require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php';
38 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
39 require_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
40 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
42 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
43 if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
44 if (!empty($conf->projet->enabled)) {
45  require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
46  require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
47 }
48 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
49 
50 // Load translation files required by the page
51 $langs->loadLangs(array("contracts", "orders", "companies", "bills", "products", 'compta'));
52 
53 $action = GETPOST('action', 'aZ09');
54 $confirm = GETPOST('confirm', 'alpha');
55 $socid = GETPOST('socid', 'int');
56 $id = GETPOST('id', 'int');
57 $ref = GETPOST('ref', 'alpha');
58 $origin = GETPOST('origin', 'alpha');
59 $originid = GETPOST('originid', 'int');
60 
61 $datecontrat = '';
62 $usehm = (!empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0);
63 
64 // Security check
65 if ($user->socid) $socid = $user->socid;
66 $result = restrictedArea($user, 'contrat', $id);
67 
68 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
69 $hookmanager->initHooks(array('contractcard', 'globalcard'));
70 
71 $object = new Contrat($db);
72 $extrafields = new ExtraFields($db);
73 
74 // Load object
75 if ($id > 0 || !empty($ref) && $action != 'add') {
76  $ret = $object->fetch($id, $ref);
77  if ($ret > 0)
78  $ret = $object->fetch_thirdparty();
79  if ($ret < 0)
80  dol_print_error('', $object->error);
81 }
82 
83 // fetch optionals attributes and labels
84 $extrafields->fetch_name_optionals_label($object->table_element);
85 
86 // fetch optionals attributes lines and labels
87 $extralabelslines = $extrafields->fetch_name_optionals_label($object->table_element_line);
88 
89 $permissionnote = $user->rights->contrat->creer; // Used by the include of actions_setnotes.inc.php
90 $permissiondellink = $user->rights->contrat->creer; // Used by the include of actions_dellink.inc.php
91 
92 $error = 0;
93 
94 
95 /*
96  * Actions
97  */
98 
99 $parameters = array('socid' => $socid);
100 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
101 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
102 if (empty($reshook))
103 {
104  include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once
105 
106  include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
107 
108  if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer)
109  {
110  $result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment'));
111 
112  if ($result > 0)
113  {
114  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
115  exit;
116  } else {
117  setEventMessages($object->error, $object->errors, 'errors');
118  }
119  } elseif ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer)
120  {
121  if (!GETPOST('dateend'))
122  {
123  $error++;
124  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors');
125  }
126  if (!$error)
127  {
128  $result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment')));
129  if ($result > 0)
130  {
131  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
132  exit;
133  } else {
134  setEventMessages($object->error, $object->errors, 'errors');
135  }
136  }
137  }
138 
139  // Si ajout champ produit predefini
140  if (GETPOST('mode') == 'predefined')
141  {
142  $date_start = '';
143  $date_end = '';
144  if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear'))
145  {
146  $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
147  }
148  if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear'))
149  {
150  $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
151  }
152  }
153 
154  // Param dates
155  $date_start_update = '';
156  $date_end_update = '';
157  $date_start_real_update = '';
158  $date_end_real_update = '';
159  if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear'))
160  {
161  $date_start_update = dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear'));
162  }
163  if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear'))
164  {
165  $date_end_update = dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear'));
166  }
167  if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear'))
168  {
169  $date_start_real_update = dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear'));
170  }
171  if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear'))
172  {
173  $date_end_real_update = dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear'));
174  }
175  if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear'))
176  {
177  $datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
178  }
179 
180  // Add contract
181  if ($action == 'add' && $user->rights->contrat->creer)
182  {
183  // Check
184  if (empty($datecontrat))
185  {
186  $error++;
187  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
188  $action = 'create';
189  }
190 
191  if ($socid < 1)
192  {
193  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors');
194  $action = 'create';
195  $error++;
196  }
197 
198  // Fill array 'array_options' with data from add form
199  $ret = $extrafields->setOptionalsFromPost(null, $object);
200  if ($ret < 0) {
201  $error++;
202  $action = 'create';
203  }
204 
205  if (!$error)
206  {
207  $object->socid = $socid;
208  $object->date_contrat = $datecontrat;
209 
210  $object->commercial_suivi_id = GETPOST('commercial_suivi_id', 'int');
211  $object->commercial_signature_id = GETPOST('commercial_signature_id', 'int');
212 
213  $object->note_private = GETPOST('note_private', 'alpha');
214  $object->note_public = GETPOST('note_public', 'alpha');
215  $object->fk_project = GETPOST('projectid', 'int');
216  $object->remise_percent = GETPOST('remise_percent', 'alpha');
217  $object->ref = GETPOST('ref', 'alpha');
218  $object->ref_customer = GETPOST('ref_customer', 'alpha');
219  $object->ref_supplier = GETPOST('ref_supplier', 'alpha');
220 
221  // If creation from another object of another module (Example: origin=propal, originid=1)
222  if (!empty($origin) && !empty($originid))
223  {
224  // Parse element/subelement (ex: project_task)
225  $element = $subelement = $origin;
226  if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs))
227  {
228  $element = $regs[1];
229  $subelement = $regs[2];
230  }
231 
232  // For compatibility
233  if ($element == 'order') { $element = $subelement = 'commande'; }
234  if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; }
235 
236  $object->origin = $origin;
237  $object->origin_id = $originid;
238 
239  // Possibility to add external linked objects with hooks
240  $object->linked_objects[$object->origin] = $object->origin_id;
241  if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects']))
242  {
243  $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
244  }
245 
246  $id = $object->create($user);
247  if ($id < 0) {
248  setEventMessages($object->error, $object->errors, 'errors');
249  }
250 
251  if ($id > 0)
252  {
253  dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
254 
255  $classname = ucfirst($subelement);
256  $srcobject = new $classname($db);
257 
258  dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
259  $result = $srcobject->fetch($object->origin_id);
260  if ($result > 0)
261  {
262  $srcobject->fetch_thirdparty();
263  $lines = $srcobject->lines;
264  if (empty($lines) && method_exists($srcobject, 'fetch_lines'))
265  {
266  $srcobject->fetch_lines();
267  $lines = $srcobject->lines;
268  }
269 
270  $fk_parent_line = 0;
271  $num = count($lines);
272 
273  for ($i = 0; $i < $num; $i++)
274  {
275  $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
276 
277  if ($product_type == 1 || (!empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0, 1)))) { // TODO Exclude also deee
278  // service prédéfini
279  if ($lines[$i]->fk_product > 0)
280  {
281  $product_static = new Product($db);
282 
283  // Define output language
284  if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE))
285  {
286  $prod = new Product($db);
287  $prod->id = $lines[$i]->fk_product;
288  $prod->getMultiLangs();
289 
290  $outputlangs = $langs;
291  $newlang = '';
292  if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
293  if (empty($newlang)) $newlang = $srcobject->thirdparty->default_lang;
294  if (!empty($newlang))
295  {
296  $outputlangs = new Translate("", $conf);
297  $outputlangs->setDefaultLang($newlang);
298  }
299 
300  $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["libelle"])) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $lines[$i]->product_label;
301  } else {
302  $label = $lines[$i]->product_label;
303  }
304  $desc = ($lines[$i]->desc && $lines[$i]->desc != $lines[$i]->libelle) ?dol_htmlentitiesbr($lines[$i]->desc) : '';
305  } else {
306  $desc = dol_htmlentitiesbr($lines[$i]->desc);
307  }
308 
309  // Extrafields
310  $array_options = array();
311  // For avoid conflicts if trigger used
312  if (method_exists($lines[$i], 'fetch_optionals')) {
313  $lines[$i]->fetch_optionals();
314  $array_options = $lines[$i]->array_options;
315  }
316 
317  $txtva = $lines[$i]->vat_src_code ? $lines[$i]->tva_tx.' ('.$lines[$i]->vat_src_code.')' : $lines[$i]->tva_tx;
318 
319  // View third's localtaxes for now
320  $localtax1_tx = get_localtax($txtva, 1, $object->thirdparty);
321  $localtax2_tx = get_localtax($txtva, 2, $object->thirdparty);
322 
323  $result = $object->addline(
324  $desc,
325  $lines[$i]->subprice,
326  $lines[$i]->qty,
327  $txtva,
328  $localtax1_tx,
329  $localtax2_tx,
330  $lines[$i]->fk_product,
331  $lines[$i]->remise_percent,
332  $lines[$i]->date_start,
333  $lines[$i]->date_end,
334  'HT',
335  0,
336  $lines[$i]->info_bits,
337  $lines[$i]->fk_fournprice,
338  $lines[$i]->pa_ht,
339  $array_options,
340  $lines[$i]->fk_unit
341  );
342 
343  if ($result < 0)
344  {
345  $error++;
346  break;
347  }
348  }
349  }
350  } else {
351  setEventMessages($srcobject->error, $srcobject->errors, 'errors');
352  $error++;
353  }
354 
355  // Hooks
356  $parameters = array('objFrom' => $srcobject);
357  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
358  // modified by hook
359  if ($reshook < 0)
360  $error++;
361  } else {
362  setEventMessages($object->error, $object->errors, 'errors');
363  $error++;
364  }
365  } else {
366  $result = $object->create($user);
367  if ($result > 0)
368  {
369  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
370  exit;
371  } else {
372  setEventMessages($object->error, $object->errors, 'errors');
373  }
374  $action = 'create';
375  }
376  }
377  } elseif ($action == 'classin' && $user->rights->contrat->creer) {
378  $object->setProject(GETPOST('projectid'));
379  }
380 
381  // Add a new line
382  elseif ($action == 'addline' && $user->rights->contrat->creer)
383  {
384  // Set if we used free entry or predefined product
385  $predef = '';
386  $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
387  $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
388  $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
389  if (GETPOST('prod_entry_mode', 'alpha') == 'free')
390  {
391  $idprod = 0;
392  $tva_tx = (GETPOST('tva_tx', 'alpha') ? GETPOST('tva_tx', 'alpha') : 0);
393  } else {
394  $idprod = GETPOST('idprod', 'int');
395  $tva_tx = '';
396  }
397 
398  $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS');
399  $remise_percent = ((GETPOST('remise_percent'.$predef) != '') ? GETPOST('remise_percent'.$predef) : 0);
400 
401  if ($qty == '')
402  {
403  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors');
404  $error++;
405  }
406  if (GETPOST('prod_entry_mode', 'alpha') == 'free' && empty($idprod) && empty($product_desc))
407  {
408  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors');
409  $error++;
410  }
411 
412  $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'));
413  $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'));
414  if (!empty($date_start) && !empty($date_end) && $date_start > $date_end)
415  {
416  setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
417  $error++;
418  }
419 
420  // Extrafields
421  $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
422  $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
423  // Unset extrafield
424  if (is_array($extralabelsline)) {
425  // Get extra fields
426  foreach ($extralabelsline as $key => $value) {
427  unset($_POST["options_".$key]);
428  }
429  }
430 
431  if (!$error)
432  {
433  // Clean parameters
434  $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'));
435  $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'));
436  $price_base_type = (GETPOST('price_base_type', 'alpha') ?GETPOST('price_base_type', 'alpha') : 'HT');
437 
438  // Ecrase $pu par celui du produit
439  // Ecrase $desc par celui du produit
440  // Ecrase $tva_tx par celui du produit
441  // Ecrase $base_price_type par celui du produit
442  if ($idprod > 0)
443  {
444  $prod = new Product($db);
445  $prod->fetch($idprod);
446 
447  // Update if prices fields are defined
448  $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
449  $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
450  if (empty($tva_tx)) $tva_npr = 0;
451 
452  $pu_ht = $prod->price;
453  $pu_ttc = $prod->price_ttc;
454  $price_min = $prod->price_min;
455  $price_base_type = $prod->price_base_type;
456 
457  // On defini prix unitaire
458  if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level)
459  {
460  $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
461  $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
462  $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
463  $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
464  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES))
465  {
466  require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
467 
468  $prodcustprice = new Productcustomerprice($db);
469 
470  $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $object->thirdparty->id);
471 
472  $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
473  if ($result) {
474  if (count($prodcustprice->lines) > 0) {
475  $pu_ht = price($prodcustprice->lines [0]->price);
476  $pu_ttc = price($prodcustprice->lines [0]->price_ttc);
477  $price_base_type = $prodcustprice->lines [0]->price_base_type;
478  $tva_tx = $prodcustprice->lines [0]->tva_tx;
479  if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
480  $tva_npr = $prodcustprice->lines[0]->recuperableonly;
481  if (empty($tva_tx)) $tva_npr = 0;
482  }
483  }
484  }
485 
486  $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
487  $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
488 
489  // On reevalue prix selon taux tva car taux tva transaction peut etre different
490  // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
491  if ($tmpvat != $tmpprodvat)
492  {
493  if ($price_base_type != 'HT')
494  {
495  $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
496  } else {
497  $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
498  }
499  }
500 
501  $desc = $prod->description;
502  if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $desc = $product_desc;
503  else $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
504 
505  $fk_unit = $prod->fk_unit;
506  } else {
507  $pu_ht = GETPOST('price_ht');
508  $price_base_type = 'HT';
509  $tva_tx = GETPOST('tva_tx') ?str_replace('*', '', GETPOST('tva_tx')) : 0; // tva_tx field may be disabled, so we use vat rate 0
510  $tva_npr = preg_match('/\*/', GETPOST('tva_tx')) ? 1 : 0;
511  $desc = $product_desc;
512  $fk_unit = GETPOST('units', 'alpha');
513  }
514 
515  $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
516  $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
517 
518  // ajout prix achat
519  $fk_fournprice = $_POST['fournprice'];
520  if (!empty($_POST['buying_price']))
521  $pa_ht = $_POST['buying_price'];
522  else $pa_ht = null;
523 
524  $info_bits = 0;
525  if ($tva_npr) $info_bits |= 0x01;
526 
527  if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance))
528  || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && ($price_min && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min))))
529  {
530  $object->error = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
531  $result = -1;
532  } else {
533  // Insert line
534  $result = $object->addline(
535  $desc,
536  $pu_ht,
537  $qty,
538  $tva_tx,
539  $localtax1_tx,
540  $localtax2_tx,
541  $idprod,
542  $remise_percent,
543  $date_start,
544  $date_end,
545  $price_base_type,
546  $pu_ttc,
547  $info_bits,
548  $fk_fournprice,
549  $pa_ht,
550  $array_options,
551  $fk_unit
552  );
553  }
554 
555  if ($result > 0)
556  {
557  // Define output language
558  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && !empty($conf->global->CONTRACT_ADDON_PDF)) // No generation if default type not defined
559  {
560  $outputlangs = $langs;
561  $newlang = '';
562  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
563  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
564  if (!empty($newlang)) {
565  $outputlangs = new Translate("", $conf);
566  $outputlangs->setDefaultLang($newlang);
567  }
568 
569  $ret = $object->fetch($id); // Reload to get new records
570 
571  $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
572  }
573 
574  unset($_POST['prod_entry_mode']);
575 
576  unset($_POST['qty']);
577  unset($_POST['type']);
578  unset($_POST['remise_percent']);
579  unset($_POST['price_ht']);
580  unset($_POST['multicurrency_price_ht']);
581  unset($_POST['price_ttc']);
582  unset($_POST['tva_tx']);
583  unset($_POST['product_ref']);
584  unset($_POST['product_label']);
585  unset($_POST['product_desc']);
586  unset($_POST['fournprice']);
587  unset($_POST['buying_price']);
588  unset($_POST['np_marginRate']);
589  unset($_POST['np_markRate']);
590  unset($_POST['dp_desc']);
591  unset($_POST['idprod']);
592 
593  unset($_POST['date_starthour']);
594  unset($_POST['date_startmin']);
595  unset($_POST['date_startsec']);
596  unset($_POST['date_startday']);
597  unset($_POST['date_startmonth']);
598  unset($_POST['date_startyear']);
599  unset($_POST['date_endhour']);
600  unset($_POST['date_endmin']);
601  unset($_POST['date_endsec']);
602  unset($_POST['date_endday']);
603  unset($_POST['date_endmonth']);
604  unset($_POST['date_endyear']);
605  } else {
606  setEventMessages($object->error, $object->errors, 'errors');
607  }
608  }
609  } elseif ($action == 'updateline' && $user->rights->contrat->creer && !GETPOST('cancel', 'alpha')) {
610  $error = 0;
611 
612  if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update)
613  {
614  setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
615  $action = 'editline';
616  $_GET['rowid'] = GETPOST('elrowid');
617  $error++;
618  }
619 
620  if (!$error)
621  {
622  $objectline = new ContratLigne($db);
623  if ($objectline->fetch(GETPOST('elrowid', 'int')) < 0)
624  {
625  setEventMessages($objectline->error, $objectline->errors, 'errors');
626  $error++;
627  }
628  $objectline->fetch_optionals();
629  }
630 
631  $db->begin();
632 
633  if (!$error)
634  {
635  if ($date_start_real_update == '') $date_start_real_update = $objectline->date_ouverture;
636  if ($date_end_real_update == '') $date_end_real_update = $objectline->date_cloture;
637 
638  $vat_rate = GETPOST('eltva_tx');
639  // Define info_bits
640  $info_bits = 0;
641  if (preg_match('/\*/', $vat_rate)) {
642  $info_bits |= 0x01;
643  }
644 
645  // Define vat_rate
646  $vat_rate = str_replace('*', '', $vat_rate);
647  $localtax1_tx = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
648  $localtax2_tx = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
649 
650  $txtva = $vat_rate;
651 
652  // Clean vat code
653  $reg = array();
654  $vat_src_code = '';
655  if (preg_match('/\((.*)\)/', $txtva, $reg))
656  {
657  $vat_src_code = $reg[1];
658  $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
659  }
660 
661  // ajout prix d'achat
662  $fk_fournprice = GETPOST('fournprice');
663  if (GETPOST('buying_price')) {
664  $pa_ht = price2num(GETPOST('buying_price'), '', 2);
665  } else {
666  $pa_ht = null;
667  }
668 
669  $fk_unit = GETPOST('unit', 'alpha');
670 
671  $objectline->fk_product = GETPOST('idprod', 'int');
672  $objectline->description = GETPOST('product_desc', 'restricthtml');
673  $objectline->price_ht = GETPOST('elprice');
674  $objectline->subprice = GETPOST('elprice');
675  $objectline->qty = GETPOST('elqty');
676  $objectline->remise_percent = GETPOST('elremise_percent');
677  $objectline->tva_tx = ($txtva ? $txtva : 0); // Field may be disabled, so we use vat rate 0
678  $objectline->vat_src_code = $vat_src_code;
679  $objectline->localtax1_tx = is_numeric($localtax1_tx) ? $localtax1_tx : 0;
680  $objectline->localtax2_tx = is_numeric($localtax2_tx) ? $localtax2_tx : 0;
681  $objectline->date_ouverture_prevue = $date_start_update;
682  $objectline->date_ouverture = $date_start_real_update;
683  $objectline->date_fin_validite = $date_end_update;
684  $objectline->date_cloture = $date_end_real_update;
685  $objectline->fk_user_cloture = $user->id;
686  $objectline->fk_fournprice = $fk_fournprice;
687  $objectline->pa_ht = $pa_ht;
688 
689  if ($fk_unit > 0) {
690  $objectline->fk_unit = GETPOST('unit');
691  } else {
692  $objectline->fk_unit = null;
693  }
694 
695  // Extrafields
696  $extralabelsline = $extrafields->fetch_name_optionals_label($objectline->table_element);
697  $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
698 
699  if (is_array($array_options) && count($array_options) > 0) {
700  // We replace values in this->line->array_options only for entries defined into $array_options
701  foreach ($array_options as $key => $value) {
702  $objectline->array_options[$key] = $array_options[$key];
703  }
704  }
705 
706  // TODO verifier price_min si fk_product et multiprix
707 
708  $result = $objectline->update($user);
709  if ($result < 0)
710  {
711  $error++;
712  setEventMessages($objectline->error, $objectline->errors, 'errors');
713  }
714  }
715 
716  if (!$error)
717  {
718  $db->commit();
719  } else {
720  $db->rollback();
721  }
722  } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer)
723  {
724  $result = $object->deleteline(GETPOST('lineid'), $user);
725 
726  if ($result >= 0)
727  {
728  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
729  exit;
730  } else {
731  setEventMessages($object->error, $object->errors, 'errors');
732  }
733  } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer)
734  {
735  $result = $object->validate($user);
736 
737  if ($result > 0)
738  {
739  // Define output language
740  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
741  {
742  $outputlangs = $langs;
743  $newlang = '';
744  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
745  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
746  if (!empty($newlang)) {
747  $outputlangs = new Translate("", $conf);
748  $outputlangs->setDefaultLang($newlang);
749  }
750  $model = $object->model_pdf;
751  $ret = $object->fetch($id); // Reload to get new records
752 
753  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
754  }
755  } else {
756  setEventMessages($object->error, $object->errors, 'errors');
757  }
758  } elseif ($action == 'reopen' && $user->rights->contrat->creer)
759  {
760  $result = $object->reopen($user);
761  if ($result < 0)
762  {
763  setEventMessages($object->error, $object->errors, 'errors');
764  }
765  }
766 
767  // Close all lines
768  elseif ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer)
769  {
770  $result = $object->closeAll($user);
771  if ($result < 0)
772  {
773  setEventMessages($object->error, $object->errors, 'errors');
774  }
775  }
776 
777  // Close all lines
778  elseif ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer)
779  {
780  $result = $object->activateAll($user);
781  if ($result < 0)
782  {
783  setEventMessages($object->error, $object->errors, 'errors');
784  }
785  } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer)
786  {
787  $result = $object->delete($user);
788  if ($result >= 0)
789  {
790  header("Location: list.php?restore_lastsearch_values=1");
791  return;
792  } else {
793  setEventMessages($object->error, $object->errors, 'errors');
794  }
795  } elseif ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contrat->creer)
796  {
797  if (GETPOST('newcid') > 0)
798  {
799  $contractline = new ContratLigne($db);
800  $result = $contractline->fetch(GETPOST('lineid'));
801  $contractline->fk_contrat = GETPOST('newcid');
802  $result = $contractline->update($user, 1);
803  if ($result >= 0)
804  {
805  header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
806  return;
807  } else {
808  setEventMessages($object->error, $object->errors, 'errors');
809  }
810  } else {
811  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("RefNewContract")), null, 'errors');
812  }
813  } elseif ($action == 'update_extras')
814  {
815  $object->oldcopy = dol_clone($object);
816 
817  // Fill array 'array_options' with data from update form
818  $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
819  if ($ret < 0) $error++;
820 
821  if (!$error) {
822  $result = $object->insertExtraFields('CONTRACT_MODIFY');
823  if ($result < 0)
824  {
825  setEventMessages($object->error, $object->errors, 'errors');
826  $error++;
827  }
828  }
829 
830  if ($error) {
831  $action = 'edit_extras';
832  }
833  } elseif ($action == 'setref_supplier')
834  {
835  $cancelbutton = GETPOST('cancel', 'alpha');
836  if (!$cancelbutton) {
837  $object->oldcopy = dol_clone($object);
838 
839  $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
840  if ($result < 0) {
841  setEventMessages($object->error, $object->errors, 'errors');
842  $action = 'editref_supplier';
843  } else {
844  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
845  exit;
846  }
847  } else {
848  header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
849  exit;
850  }
851  } elseif ($action == 'setref_customer')
852  {
853  $cancelbutton = GETPOST('cancel', 'alpha');
854 
855  if (!$cancelbutton)
856  {
857  $object->oldcopy = dol_clone($object);
858 
859  $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
860  if ($result < 0) {
861  setEventMessages($object->error, $object->errors, 'errors');
862  $action = 'editref_customer';
863  } else {
864  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
865  exit;
866  }
867  } else {
868  header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
869  exit;
870  }
871  } elseif ($action == 'setref')
872  {
873  $cancelbutton = GETPOST('cancel', 'alpha');
874 
875  if (!$cancelbutton) {
876  $result = $object->fetch($id);
877  if ($result < 0) {
878  setEventMessages($object->error, $object->errors, 'errors');
879  }
880 
881  $old_ref = $object->ref;
882 
883  $result = $object->setValueFrom('ref', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
884  if ($result < 0) {
885  setEventMessages($object->error, $object->errors, 'errors');
886  $action = 'editref';
887  } else {
888  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
889  $old_filedir = $conf->contrat->multidir_output[$object->entity].'/'.dol_sanitizeFileName($old_ref);
890  $new_filedir = $conf->contrat->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
891 
892  $files = dol_dir_list($old_filedir);
893  if (!empty($files))
894  {
895  if (!is_dir($new_filedir)) dol_mkdir($new_filedir);
896  foreach ($files as $file)
897  {
898  dol_move($file['fullname'], $new_filedir.'/'.$file['name']);
899  }
900  }
901 
902  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
903  exit;
904  }
905  } else {
906  header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
907  exit;
908  }
909  } elseif ($action == 'setdate_contrat')
910  {
911  $cancelbutton = GETPOST('cancel', 'alpha');
912 
913  if (!$cancelbutton) {
914  $result = $object->fetch($id);
915  if ($result < 0) {
916  setEventMessages($object->error, $object->errors, 'errors');
917  }
918  $datacontrat = dol_mktime(GETPOST('date_contrathour'), GETPOST('date_contratmin'), 0, GETPOST('date_contratmonth'), GETPOST('date_contratday'), GETPOST('date_contratyear'));
919  $result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY');
920  if ($result < 0) {
921  setEventMessages($object->error, $object->errors, 'errors');
922  $action = 'editdate_contrat';
923  } else {
924  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
925  exit;
926  }
927  } else {
928  header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
929  exit;
930  }
931  }
932 
933 
934  // Actions to build doc
935  $upload_dir = $conf->contrat->multidir_output[$object->entity];
936  $permissiontoadd = $user->rights->contrat->creer;
937  include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
938 
939  // Actions to send emails
940  $triggersendname = 'CONTRACT_SENTBYMAIL';
941  $paramname = 'id';
942  $mode = 'emailfromcontract';
943  $trackid = 'con'.$object->id;
944  include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
945 
946 
947  if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer)
948  {
949  if ($action == 'addcontact')
950  {
951  $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
952  $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
953  $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
954 
955  if ($result >= 0)
956  {
957  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
958  exit;
959  } else {
960  if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
961  {
962  $langs->load("errors");
963  setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
964  } else {
965  setEventMessages($object->error, $object->errors, 'errors');
966  }
967  }
968  }
969 
970  // bascule du statut d'un contact
971  elseif ($action == 'swapstatut')
972  {
973  $result = $object->swapContactStatus(GETPOST('ligne'));
974  }
975 
976  // Efface un contact
977  elseif ($action == 'deletecontact')
978  {
979  $result = $object->delete_contact(GETPOST('lineid'));
980 
981  if ($result >= 0)
982  {
983  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
984  exit;
985  } else {
986  setEventMessages($object->error, $object->errors, 'errors');
987  }
988  }
989  }
990 
991  // Action clone object
992  if ($action == 'confirm_clone' && $confirm == 'yes')
993  {
994  if (!GETPOST('socid', 3))
995  {
996  setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
997  } else {
998  if ($object->id > 0) {
999  $result = $object->createFromClone($user, $socid);
1000  if ($result > 0) {
1001  header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
1002  exit();
1003  } else {
1004  if (count($object->errors) > 0) setEventMessages($object->error, $object->errors, 'errors');
1005  $action = '';
1006  }
1007  }
1008  }
1009  }
1010 }
1011 
1012 
1013 /*
1014  * View
1015  */
1016 
1017 llxHeader('', $langs->trans("Contract"), "");
1018 
1019 $form = new Form($db);
1020 $formfile = new FormFile($db);
1021 if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db);
1022 
1023 // Load object modContract
1024 $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
1025 if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php')
1026 {
1027  $module = substr($module, 0, dol_strlen($module) - 4);
1028 }
1029 $result = dol_include_once('/core/modules/contract/'.$module.'.php');
1030 if ($result > 0)
1031 {
1032  $modCodeContract = new $module();
1033 }
1034 
1035 // Create
1036 if ($action == 'create')
1037 {
1038  print load_fiche_titre($langs->trans('AddContract'), '', 'contract');
1039 
1040  $soc = new Societe($db);
1041  if ($socid > 0) $soc->fetch($socid);
1042 
1043  if (GETPOST('origin') && GETPOST('originid'))
1044  {
1045  // Parse element/subelement (ex: project_task)
1046  $regs = array();
1047  $element = $subelement = GETPOST('origin');
1048  if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'), $regs))
1049  {
1050  $element = $regs[1];
1051  $subelement = $regs[2];
1052  }
1053 
1054  if ($element == 'project')
1055  {
1056  $projectid = GETPOST('originid');
1057  } else {
1058  // For compatibility
1059  if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; }
1060  if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; }
1061 
1062  dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
1063 
1064  $classname = ucfirst($subelement);
1065  $objectsrc = new $classname($db);
1066  $objectsrc->fetch($originid);
1067  if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) $objectsrc->fetch_lines();
1068  $objectsrc->fetch_thirdparty();
1069 
1070  // Replicate extrafields
1071  $objectsrc->fetch_optionals();
1072  $object->array_options = $objectsrc->array_options;
1073 
1074  $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : '');
1075 
1076  $soc = $objectsrc->thirdparty;
1077 
1078  $note_private = (!empty($objectsrc->note_private) ? $objectsrc->note_private : '');
1079  $note_public = (!empty($objectsrc->note_public) ? $objectsrc->note_public : '');
1080 
1081  // Object source contacts list
1082  $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1);
1083  }
1084  } else {
1085  $projectid = GETPOST('projectid', 'int');
1086  $note_private = GETPOST("note_private");
1087  $note_public = GETPOST("note_public");
1088  }
1089 
1090  $object->date_contrat = dol_now();
1091 
1092  print '<form name="form_contract" action="'.$_SERVER["PHP_SELF"].'" method="post">';
1093  print '<input type="hidden" name="token" value="'.newToken().'">';
1094 
1095  print '<input type="hidden" name="action" value="add">';
1096  print '<input type="hidden" name="socid" value="'.$soc->id.'">'."\n";
1097  print '<input type="hidden" name="remise_percent" value="0">';
1098 
1100 
1101  print '<table class="border centpercent">';
1102 
1103  // Ref
1104  print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td>';
1105  if (!empty($modCodeContract->code_auto)) {
1106  $tmpcode = $langs->trans("Draft");
1107  } else {
1108  $tmpcode = '<input name="ref" class="maxwidth100" maxlength="128" value="'.dol_escape_htmltag(GETPOST('ref') ?GETPOST('ref') : $tmpcode).'">';
1109  }
1110  print $tmpcode;
1111  print '</td></tr>';
1112 
1113  // Ref customer
1114  print '<tr><td>'.$langs->trans('RefCustomer').'</td>';
1115  print '<td><input type="text" class="maxwidth150" name="ref_customer" id="ref_customer" value="'.dol_escape_htmltag(GETPOST('ref_customer', 'alpha')).'"></td></tr>';
1116 
1117  // Ref supplier
1118  print '<tr><td>'.$langs->trans('RefSupplier').'</td>';
1119  print '<td><input type="text" class="maxwidth150" name="ref_supplier" id="ref_supplier" value="'.dol_escape_htmltag(GETPOST('ref_supplier', 'alpha')).'"></td></tr>';
1120 
1121  // Thirdparty
1122  print '<tr>';
1123  print '<td class="fieldrequired">'.$langs->trans('ThirdParty').'</td>';
1124  if ($socid > 0)
1125  {
1126  print '<td>';
1127  print $soc->getNomUrl(1);
1128  print '<input type="hidden" name="socid" value="'.$soc->id.'">';
1129  print '</td>';
1130  } else {
1131  print '<td>';
1132  print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300');
1133  print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
1134  print '</td>';
1135  }
1136  print '</tr>'."\n";
1137 
1138  if ($socid > 0)
1139  {
1140  // Ligne info remises tiers
1141  print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
1142  if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent);
1143  else print $langs->trans("CompanyHasNoRelativeDiscount");
1144  print '. ';
1145  $absolute_discount = $soc->getAvailableDiscounts();
1146  if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency));
1147  else print $langs->trans("CompanyHasNoAbsoluteDiscount");
1148  print '.';
1149  print '</td></tr>';
1150  }
1151 
1152  // Commercial suivi
1153  print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").'</span></td><td>';
1154  print $form->select_dolusers(GETPOST("commercial_suivi_id") ?GETPOST("commercial_suivi_id") : $user->id, 'commercial_suivi_id', 1, '');
1155  print '</td></tr>';
1156 
1157  // Commercial signature
1158  print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").'</span></td><td>';
1159  print $form->select_dolusers(GETPOST("commercial_signature_id") ?GETPOST("commercial_signature_id") : $user->id, 'commercial_signature_id', 1, '');
1160  print '</td></tr>';
1161 
1162  print '<tr><td><span class="fieldrequired">'.$langs->trans("Date").'</span></td><td>';
1163  print $form->selectDate($datecontrat, '', 0, 0, '', "contrat");
1164  print "</td></tr>";
1165 
1166  // Project
1167  if (!empty($conf->projet->enabled))
1168  {
1169  $langs->load('projects');
1170 
1171  $formproject = new FormProjets($db);
1172 
1173  print '<tr><td>'.$langs->trans("Project").'</td><td>';
1174  $formproject->select_projects(($soc->id > 0 ? $soc->id : -1), $projectid, "projectid", 0, 0, 1, 1);
1175  print ' &nbsp; <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).'"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans("AddProject").'"></span></a>';
1176  print "</td></tr>";
1177  }
1178 
1179  print '<tr><td>'.$langs->trans("NotePublic").'</td><td class="tdtop">';
1180  $doleditor = new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%');
1181  print $doleditor->Create(1);
1182  print '</td></tr>';
1183 
1184  if (empty($user->socid))
1185  {
1186  print '<tr><td>'.$langs->trans("NotePrivate").'</td><td class="tdtop">';
1187  $doleditor = new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, '90%');
1188  print $doleditor->Create(1);
1189  print '</td></tr>';
1190  }
1191 
1192  // Other attributes
1193  $parameters = array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"', 'cols' => '3');
1194  $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1195  print $hookmanager->resPrint;
1196 
1197  // Other attributes
1198  if (empty($reshook)) {
1199  print $object->showOptionals($extrafields, 'create', $parameters);
1200  }
1201 
1202  print "</table>\n";
1203 
1205 
1206  print '<div class="center">';
1207  print '<input type="submit" class="button" value="'.$langs->trans("Create").'">';
1208  print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1209  print '<input type="button" class="button button-cancel" value="'.$langs->trans("Cancel").'" onClick="javascript:history.go(-1)">';
1210  print '</div>';
1211 
1212  if (is_object($objectsrc))
1213  {
1214  print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
1215  print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
1216 
1217  if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS))
1218  {
1219  print '<br>'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed");
1220  }
1221  }
1222 
1223  print "</form>\n";
1224 } else /* *************************************************************************** */
1225 /* */
1226 /* Mode vue et edition */
1227 /* */
1228 /* *************************************************************************** */
1229 {
1230  $now = dol_now();
1231 
1232  if ($object->id > 0)
1233  {
1234  $object->fetch_thirdparty();
1235 
1236  $soc = $object->thirdparty; // $soc is used later
1237 
1238  $result = $object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed
1239  if ($result < 0) {
1240  dol_print_error($db, $object->error);
1241  }
1242 
1243  $nbofservices = count($object->lines);
1244 
1245  $author = new User($db);
1246  $author->fetch($object->user_author_id);
1247 
1248  $commercial_signature = new User($db);
1249  $commercial_signature->fetch($object->commercial_signature_id);
1250 
1251  $commercial_suivi = new User($db);
1252  $commercial_suivi->fetch($object->commercial_suivi_id);
1253 
1254  $head = contract_prepare_head($object);
1255 
1256  $hselected = 0;
1257  $formconfirm = '';
1258 
1259  print dol_get_fiche_head($head, $hselected, $langs->trans("Contract"), -1, 'contract');
1260 
1261 
1262  if ($action == 'delete') {
1263  //Confirmation de la suppression du contrat
1264  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("DeleteAContract"), $langs->trans("ConfirmDeleteAContract"), "confirm_delete", '', 0, 1);
1265  } elseif ($action == 'valid') {
1266  //Confirmation de la validation
1267  $ref = substr($object->ref, 1, 4);
1268  if ($ref == 'PROV' && !empty($modCodeContract->code_auto)) {
1269  $numref = $object->getNextNumRef($object->thirdparty);
1270  } else {
1271  $numref = $object->ref;
1272  }
1273  $text = $langs->trans('ConfirmValidateContract', $numref);
1274  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ValidateAContract"), $text, "confirm_valid", '', 0, 1);
1275  } elseif ($action == 'close') {
1276  // Confirmation de la fermeture
1277  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("CloseAContract"), $langs->trans("ConfirmCloseContract"), "confirm_close", '', 0, 1);
1278  } elseif ($action == 'activate') {
1279  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ActivateAllOnContract"), $langs->trans("ConfirmActivateAllOnContract"), "confirm_activate", '', 0, 1);
1280  } elseif ($action == 'clone') {
1281  // Clone confirmation
1282  $formquestion = array(array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)')));
1283  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneContract', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
1284  }
1285 
1286 
1287  // Call Hook formConfirm
1288  $parameters = array(
1289  'formConfirm' => $formconfirm,
1290  'id' => $id,
1291  //'lineid' => $lineid,
1292  );
1293  // Note that $action and $object may have been modified by hook
1294  $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action);
1295  if (empty($reshook)) {
1296  $formconfirm .= $hookmanager->resPrint;
1297  } elseif ($reshook > 0) {
1298  $formconfirm = $hookmanager->resPrint;
1299  }
1300 
1301  // Print form confirm
1302  print $formconfirm;
1303 
1304  /*
1305  * Contrat
1306  */
1307  if (!empty($object->brouillon) && $user->rights->contrat->creer)
1308  {
1309  print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="POST">';
1310  print '<input type="hidden" name="token" value="'.newToken().'">';
1311  print '<input type="hidden" name="action" value="setremise">';
1312  }
1313 
1314  // Contract card
1315 
1316  $linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
1317 
1318 
1319  $morehtmlref = '';
1320  if (!empty($modCodeContract->code_auto)) {
1321  $morehtmlref .= $object->ref;
1322  } else {
1323  $morehtmlref .= $form->editfieldkey("", 'ref', $object->ref, $object, $user->rights->contrat->creer, 'string', '', 0, 3);
1324  $morehtmlref .= $form->editfieldval("", 'ref', $object->ref, $object, $user->rights->contrat->creer, 'string', '', 0, 2);
1325  }
1326 
1327  $morehtmlref .= '<div class="refidno">';
1328  // Ref customer
1329  $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->contrat->creer, 'string', '', 0, 1);
1330  $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1, 'getFormatedCustomerRef');
1331  // Ref supplier
1332  $morehtmlref .= '<br>';
1333  $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', 0, 1);
1334  $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1, 'getFormatedSupplierRef');
1335  // Thirdparty
1336  $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
1337  if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->thirdparty->id.'&search_name='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherContracts").'</a>)';
1338  // Project
1339  if (!empty($conf->projet->enabled))
1340  {
1341  $langs->load("projects");
1342  $morehtmlref .= '<br>'.$langs->trans('Project').' ';
1343  if ($user->rights->contrat->creer)
1344  {
1345  if ($action != 'classify') {
1346  $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
1347  }
1348  if ($action == 'classify') {
1349  //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
1350  $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
1351  $morehtmlref .= '<input type="hidden" name="action" value="classin">';
1352  $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
1353  $morehtmlref .= $formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
1354  $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
1355  $morehtmlref .= '</form>';
1356  } else {
1357  $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
1358  }
1359  } else {
1360  if (!empty($object->fk_project)) {
1361  $proj = new Project($db);
1362  $proj->fetch($object->fk_project);
1363  $morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
1364  $morehtmlref .= $proj->ref;
1365  $morehtmlref .= '</a>';
1366  } else {
1367  $morehtmlref .= '';
1368  }
1369  }
1370  }
1371  $morehtmlref .= '</div>';
1372 
1373 
1374  dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);
1375 
1376 
1377  print '<div class="fichecenter">';
1378  print '<div class="underbanner clearboth"></div>';
1379 
1380 
1381  print '<table class="border tableforfield" width="100%">';
1382 
1383  // Line info of thirdparty discounts
1384  print '<tr><td class="titlefield">'.$langs->trans('Discount').'</td><td colspan="3">';
1385  if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent);
1386  else print $langs->trans("CompanyHasNoRelativeDiscount");
1387  $absolute_discount = $object->thirdparty->getAvailableDiscounts();
1388  print '. ';
1389  if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency));
1390  else print $langs->trans("CompanyHasNoAbsoluteDiscount");
1391  print '.';
1392  print '</td></tr>';
1393 
1394  // Date
1395  print '<tr>';
1396  print '<td class="titlefield">';
1397  print $form->editfieldkey("Date", 'date_contrat', $object->date_contrat, $object, $user->rights->contrat->creer);
1398  print '</td><td>';
1399  print $form->editfieldval("Date", 'date_contrat', $object->date_contrat, $object, $user->rights->contrat->creer, 'datehourpicker');
1400  print '</td>';
1401  print '</tr>';
1402 
1403  // Other attributes
1404  $cols = 3;
1405  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
1406 
1407  print "</table>";
1408 
1409  print '</div>';
1410 
1411  if (!empty($object->brouillon) && $user->rights->contrat->creer)
1412  {
1413  print '</form>';
1414  }
1415 
1416  echo '<br>';
1417 
1418  if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
1419  {
1420  $blocname = 'contacts';
1421  $title = $langs->trans('ContactsAddresses');
1422  include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1423  }
1424 
1425  if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB))
1426  {
1427  $blocname = 'notes';
1428  $title = $langs->trans('Notes');
1429  include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1430  }
1431 
1432 
1433  $arrayothercontracts = $object->getListOfContracts('others');
1434 
1435  /*
1436  * Lines of contracts
1437  */
1438 
1439  $productstatic = new Product($db);
1440 
1441  $usemargins = 0;
1442  if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'propal', 'commande'))) $usemargins = 1;
1443 
1444  // Title line for service
1445  $cursorline = 1;
1446  print '<div id="contrat-lines-container" data-contractid="'.$object->id.'" data-element="'.$object->element.'" >';
1447  while ($cursorline <= $nbofservices)
1448  {
1449  print '<div id="contrat-line-container'.$object->lines[$cursorline - 1]->id.'" data-contratlineid = "'.$object->lines[$cursorline - 1]->id.'" data-element="'.$object->lines[$cursorline - 1]->element.'" >';
1450  print '<form name="update" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="post">';
1451  print '<input type="hidden" name="token" value="'.newToken().'">';
1452  print '<input type="hidden" name="action" value="updateline">';
1453  print '<input type="hidden" name="elrowid" value="'.$object->lines[$cursorline - 1]->id.'">';
1454  print '<input type="hidden" name="fournprice" value="'.(!empty($object->lines[$cursorline - 1]->fk_fournprice) ? $object->lines[$cursorline - 1]->fk_fournprice : 0).'">';
1455 
1456  // Area with common detail of line
1457  print '<div class="div-table-responsive-no-min">';
1458  print '<table class="notopnoleftnoright allwidth tableforservicepart1" width="100%">';
1459 
1460  $sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.price_ht, cd.qty,";
1461  $sql .= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,";
1462  $sql .= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,";
1463  $sql .= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,";
1464  $sql .= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,";
1465  $sql .= " cd.fk_unit,";
1466  $sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity, p.tosell, p.tobuy, p.tobatch";
1467  $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
1468  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
1469  $sql .= " WHERE cd.rowid = ".$object->lines[$cursorline - 1]->id;
1470 
1471  $result = $db->query($sql);
1472  if ($result)
1473  {
1474  $total = 0;
1475 
1476  print '<tr class="liste_titre'.($cursorline ? ' liste_titre_add' : '').'">';
1477  print '<td>'.$langs->trans("ServiceNb", $cursorline).'</td>';
1478  print '<td width="80" class="center">'.$langs->trans("VAT").'</td>';
1479  print '<td width="80" class="right">'.$langs->trans("PriceUHT").'</td>';
1480  //if (!empty($conf->multicurrency->enabled)) {
1481  // print '<td width="80" class="right">'.$langs->trans("PriceUHTCurrency").'</td>';
1482  //}
1483  print '<td width="30" class="center">'.$langs->trans("Qty").'</td>';
1484  if (!empty($conf->global->PRODUCT_USE_UNITS)) print '<td width="30" class="left">'.$langs->trans("Unit").'</td>';
1485  print '<td width="50" class="right">'.$langs->trans("ReductionShort").'</td>';
1486  if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td width="50" class="right">'.$langs->trans("BuyingPrice").'</td>';
1487  print '<td width="30">&nbsp;</td>';
1488  print "</tr>\n";
1489 
1490  $objp = $db->fetch_object($result);
1491 
1492  // Line in view mode
1493  if ($action != 'editline' || GETPOST('rowid') != $objp->rowid)
1494  {
1495  $moreparam = '';
1496  if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $objp->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') $moreparam = 'style="display: none;"';
1497  print '<tr class="tdtop oddeven" '.$moreparam.'>';
1498  // Label
1499  if ($objp->fk_product > 0)
1500  {
1501  $productstatic->id = $objp->fk_product;
1502  $productstatic->type = $objp->ptype;
1503  $productstatic->ref = $objp->pref;
1504  $productstatic->entity = $objp->pentity;
1505  $productstatic->label = $objp->plabel;
1506  $productstatic->status = $objp->tosell;
1507  $productstatic->status_buy = $objp->tobuy;
1508  $productstatic->status_batch = $objp->tobatch;
1509 
1510  print '<td>';
1511  $text = $productstatic->getNomUrl(1, '', 32);
1512  if ($objp->plabel)
1513  {
1514  $text .= ' - ';
1515  $text .= $objp->plabel;
1516  }
1517  $description = $objp->description;
1518 
1519  // Add description in form
1520  if (!empty($conf->global->PRODUIT_DESC_IN_FORM))
1521  {
1522  $text .= (!empty($objp->description) && $objp->description != $objp->plabel) ? '<br>'.dol_htmlentitiesbr($objp->description) : '';
1523  $description = ''; // Already added into main visible desc
1524  }
1525 
1526  echo $form->textwithtooltip($text, $description, 3, '', '', $cursorline, 0, (!empty($line->fk_parent_line) ?img_picto('', 'rightarrow') : ''));
1527 
1528  print '</td>';
1529  } else {
1530  print '<td>'.img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description)."</td>\n";
1531  }
1532  // VAT
1533  print '<td class="center">';
1534  print vatrate($objp->tva_tx.($objp->vat_src_code ? (' ('.$objp->vat_src_code.')') : ''), '%', $objp->info_bits);
1535  print '</td>';
1536  // Price
1537  print '<td class="right">'.($objp->subprice != '' ? price($objp->subprice) : '')."</td>\n";
1538  // Price multicurrency
1539  /*if (!empty($conf->multicurrency->enabled)) {
1540  print '<td class="linecoluht_currency nowrap right">'.price($objp->multicurrency_subprice).'</td>';
1541  }*/
1542  // Quantity
1543  print '<td class="center">'.$objp->qty.'</td>';
1544  // Unit
1545  if (!empty($conf->global->PRODUCT_USE_UNITS)) print '<td class="left">'.$langs->trans($object->lines[$cursorline - 1]->getLabelOfUnit()).'</td>';
1546  // Discount
1547  if ($objp->remise_percent > 0)
1548  {
1549  print '<td class="right">'.$objp->remise_percent."%</td>\n";
1550  } else {
1551  print '<td>&nbsp;</td>';
1552  }
1553 
1554  // Margin
1555  if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td class="right nowrap">'.price($objp->pa_ht).'</td>';
1556 
1557  // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme)
1558  print '<td class="nowrap right">';
1559  if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0))
1560  {
1561  print '<!-- link to move service line into another contract -->';
1562  print '<a class="reposition" style="padding-left: 5px;" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=move&amp;rowid='.$objp->rowid.'">';
1563  print img_picto($langs->trans("MoveToAnotherContract"), 'uparrow');
1564  print '</a>';
1565  }
1566  if ($user->rights->contrat->creer && ($object->statut >= 0))
1567  {
1568  print '<a class="reposition marginrightonly editfielda" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=editline&amp;rowid='.$objp->rowid.'">';
1569  print img_edit();
1570  print '</a>';
1571  }
1572  if ($user->rights->contrat->creer && ($object->statut >= 0))
1573  {
1574  print '<a class="reposition marginrightonly" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=deleteline&amp;token='.newToken().'&amp;rowid='.$objp->rowid.'">';
1575  print img_delete();
1576  print '</a>';
1577  }
1578  print '</td>';
1579 
1580  print "</tr>\n";
1581 
1582  // Dates of service planed and real
1583  if ($objp->subprice >= 0)
1584  {
1585  $colspan = 6;
1586 
1587  if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) {
1588  $colspan = 8;
1589  } elseif ($conf->margin->enabled || $conf->global->PRODUCT_USE_UNITS) {
1590  $colspan = 7;
1591  }
1592 
1593  print '<tr class="oddeven" '.$moreparam.'>';
1594  print '<td colspan="'.$colspan.'">';
1595 
1596  // Date planned
1597  print $langs->trans("DateStartPlanned").': ';
1598  if ($objp->date_debut)
1599  {
1600  print dol_print_date($db->jdate($objp->date_debut), 'day');
1601  // Warning si date prevu passee et pas en service
1602  if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) {
1603  $warning_delay = $conf->contrat->services->inactifs->warning_delay / 3600 / 24;
1604  $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
1605  print " ".img_warning($textlate);
1606  }
1607  } else print $langs->trans("Unknown");
1608  print ' &nbsp;-&nbsp; ';
1609  print $langs->trans("DateEndPlanned").': ';
1610  if ($objp->date_fin)
1611  {
1612  print dol_print_date($db->jdate($objp->date_fin), 'day');
1613  if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) {
1614  $warning_delay = $conf->contrat->services->expires->warning_delay / 3600 / 24;
1615  $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
1616  print " ".img_warning($textlate);
1617  }
1618  } else print $langs->trans("Unknown");
1619 
1620  print '</td>';
1621  print '</tr>';
1622  }
1623 
1624  // Display lines extrafields
1625  if (is_array($extralabelslines) && count($extralabelslines) > 0) {
1626  $line = new ContratLigne($db);
1627  $line->id = $objp->rowid;
1628  $line->fetch_optionals();
1629  print $line->showOptionals($extrafields, 'view', array('class'=>'oddeven', 'style'=>$moreparam, 'colspan'=>$colspan), '', '', 1);
1630  }
1631  }
1632  // Line in mode update
1633  else {
1634  // Ligne carac
1635  print '<tr class="oddeven">';
1636  print '<td>';
1637  if ($objp->fk_product > 0)
1638  {
1639  $canchangeproduct = 1;
1640  if (empty($canchangeproduct)) {
1641  $productstatic->id = $objp->fk_product;
1642  $productstatic->type = $objp->ptype;
1643  $productstatic->ref = $objp->pref;
1644  $productstatic->entity = $objp->pentity;
1645  print $productstatic->getNomUrl(1, '', 32);
1646  print $objp->label ? ' - '.dol_trunc($objp->label, 32) : '';
1647  print '<input type="hidden" name="idprod" value="'.(!empty($object->lines[$cursorline - 1]->fk_product) ? $object->lines[$cursorline - 1]->fk_product : 0).'">';
1648  } else {
1649  $senderissupplier = 0;
1650  if (empty($senderissupplier)) {
1651  print $form->select_produits((!empty($object->lines[$cursorline - 1]->fk_product) ? $object->lines[$cursorline - 1]->fk_product : 0), 'idprod');
1652  } else {
1653  print $form->select_produits_fournisseurs((!empty($object->lines[$cursorline - 1]->fk_product) ? $object->lines[$cursorline - 1]->fk_product : 0), 'idprod');
1654  }
1655  }
1656  print '<br>';
1657  } else {
1658  print $objp->label ? $objp->label.'<br>' : '';
1659  print '<input type="hidden" name="idprod" value="'.(!empty($object->lines[$cursorline - 1]->fk_product) ? $object->lines[$cursorline - 1]->fk_product : 0).'">';
1660  }
1661 
1662  // editeur wysiwyg
1663  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1664  $nbrows = ROWS_2;
1665  if (!empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows = $conf->global->MAIN_INPUT_DESC_HEIGHT;
1666  $enable = (isset($conf->global->FCKEDITOR_ENABLE_DETAILS) ? $conf->global->FCKEDITOR_ENABLE_DETAILS : 0);
1667  $doleditor = new DolEditor('product_desc', $objp->description, '', 92, 'dolibarr_details', '', false, true, $enable, $nbrows, '90%');
1668  $doleditor->Create();
1669 
1670  print '</td>';
1671 
1672  // VAT
1673  print '<td class="right">';
1674  print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code ? (' ('.$objp->vat_src_code.')') : ''), $mysoc, $object->thirdparty, $objp->fk_product, $objp->info_bits, $objp->product_type, 0, 1);
1675  print '</td>';
1676 
1677  // Price
1678  print '<td class="right"><input size="5" type="text" name="elprice" value="'.price($objp->subprice).'"></td>';
1679 
1680  // Price multicurrency
1681  /*if (!empty($conf->multicurrency->enabled)) {
1682  print '<td class="linecoluht_currency nowrap right">'.price($objp->multicurrency_subprice).'</td>';
1683  }*/
1684 
1685  // Quantity
1686  print '<td class="center"><input size="2" type="text" name="elqty" value="'.$objp->qty.'"></td>';
1687 
1688  // Unit
1689  if (!empty($conf->global->PRODUCT_USE_UNITS))
1690  {
1691  print '<td class="left">';
1692  print $form->selectUnits($objp->fk_unit, "unit");
1693  print '</td>';
1694  }
1695 
1696  // Discount
1697  print '<td class="nowrap right"><input size="1" type="text" name="elremise_percent" value="'.$objp->remise_percent.'">%</td>';
1698 
1699  if (!empty($usemargins))
1700  {
1701  print '<td class="right">';
1702  if ($objp->fk_product) print '<select id="fournprice" name="fournprice"></select>';
1703  print '<input id="buying_price" type="text" size="5" name="buying_price" value="'.price($objp->pa_ht, 0, '', 0).'"></td>';
1704  }
1705  print '<td class="center">';
1706  print '<input type="submit" class="button margintoponly marginbottomonly" name="save" value="'.$langs->trans("Modify").'">';
1707  print '<br><input type="submit" class="button margintoponly marginbottomonly button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
1708  print '</td>';
1709  print '</tr>';
1710 
1711  $colspan = 6;
1712  if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++;
1713  if (!empty($conf->global->PRODUCT_USE_UNITS)) $colspan++;
1714 
1715  // Ligne dates prevues
1716  print '<tr class="oddeven">';
1717  print '<td colspan="'.$colspan.'">';
1718  print $langs->trans("DateStartPlanned").' ';
1719  print $form->selectDate($db->jdate($objp->date_debut), "date_start_update", $usehm, $usehm, ($db->jdate($objp->date_debut) > 0 ? 0 : 1), "update");
1720  print ' &nbsp;&nbsp;'.$langs->trans("DateEndPlanned").' ';
1721  print $form->selectDate($db->jdate($objp->date_fin), "date_end_update", $usehm, $usehm, ($db->jdate($objp->date_fin) > 0 ? 0 : 1), "update");
1722  print '</td>';
1723  print '</tr>';
1724 
1725  if (is_array($extralabelslines) && count($extralabelslines) > 0) {
1726  $line = new ContratLigne($db);
1727  $line->id = $objp->rowid;
1728  $line->fetch_optionals();
1729  print $line->showOptionals($extrafields, 'edit', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', 1);
1730  }
1731  }
1732 
1733  $db->free($result);
1734  } else {
1735  dol_print_error($db);
1736  }
1737 
1738  if ($object->statut > 0)
1739  {
1740  $moreparam = '';
1741  if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->lines[$cursorline - 1]->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') $moreparam = 'style="display: none;"';
1742  print '<tr class="oddeven" '.$moreparam.'>';
1743  print '<td class="tdhrthin" colspan="'.($conf->margin->enabled ? 7 : 6).'"><hr class="opacitymedium tdhrthin"></td>';
1744  print "</tr>\n";
1745  }
1746 
1747  print "</table>";
1748  print '</div>';
1749 
1750  print "</form>\n";
1751 
1752 
1753  /*
1754  * Confirmation to delete service line of contract
1755  */
1756  if ($action == 'deleteline' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid'))
1757  {
1758  print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'), $langs->trans("DeleteContractLine"), $langs->trans("ConfirmDeleteContractLine"), "confirm_deleteline", '', 0, 1);
1759  if ($ret == 'html') print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1760  }
1761 
1762  /*
1763  * Confirmation to move service toward another contract
1764  */
1765  if ($action == 'move' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid'))
1766  {
1767  $arraycontractid = array();
1768  foreach ($arrayothercontracts as $contractcursor)
1769  {
1770  $arraycontractid[$contractcursor->id] = $contractcursor->ref;
1771  }
1772  //var_dump($arraycontractid);
1773  // Cree un tableau formulaire
1774  $formquestion = array(
1775  'text' => $langs->trans("ConfirmMoveToAnotherContractQuestion"),
1776  array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid));
1777 
1778  print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'), $langs->trans("MoveToAnotherContract"), $langs->trans("ConfirmMoveToAnotherContract"), "confirm_move", $formquestion);
1779  print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1780  }
1781 
1782  /*
1783  * Confirmation de la validation activation
1784  */
1785  if ($action == 'active' && !$_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne'))
1786  {
1787  $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1788  $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1789  $comment = GETPOST('comment', 'alpha');
1790  print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("ActivateService"), $langs->trans("ConfirmActivateService", dol_print_date($dateactstart, "%A %d %B %Y")), "confirm_active", '', 0, 1);
1791  print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1792  }
1793 
1794  /*
1795  * Confirmation de la validation fermeture
1796  */
1797  if ($action == 'closeline' && !$_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne'))
1798  {
1799  $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1800  $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1801  $comment = GETPOST('comment', 'alpha');
1802 
1803  if (empty($dateactend))
1804  {
1805  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors');
1806  } else {
1807  print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne', 'int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService", dol_print_date($dateactend, "%A %d %B %Y")), "confirm_closeline", '', 0, 1);
1808  }
1809  print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
1810  }
1811 
1812 
1813  // Area with status and activation info of line
1814  if ($object->statut > 0)
1815  {
1816  print '<table class="notopnoleftnoright tableforservicepart2'.($cursorline < $nbofservices ? ' boxtablenobottom' : '').'" width="100%">';
1817 
1818  print '<tr class="oddeven" '.$moreparam.'>';
1819  print '<td>'.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline - 1]->getLibStatut(4).'</td>';
1820  print '<td width="30" class="right">';
1821  if ($user->socid == 0)
1822  {
1823  if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline')
1824  {
1825  $tmpaction = 'activateline';
1826  $tmpactionpicto = 'play';
1827  $tmpactiontext = $langs->trans("Activate");
1828  if ($objp->statut == 4)
1829  {
1830  $tmpaction = 'unactivateline';
1831  $tmpactionpicto = 'playstop';
1832  $tmpactiontext = $langs->trans("Disable");
1833  }
1834  if (($tmpaction == 'activateline' && $user->rights->contrat->activer) || ($tmpaction == 'unactivateline' && $user->rights->contrat->desactiver))
1835  {
1836  print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline - 1]->id.'&amp;action='.$tmpaction.'">';
1837  print img_picto($tmpactiontext, $tmpactionpicto);
1838  print '</a>';
1839  }
1840  }
1841  }
1842  print '</td>';
1843  print "</tr>\n";
1844 
1845  print '<tr class="oddeven" '.$moreparam.'>';
1846 
1847  print '<td>';
1848  // Si pas encore active
1849  if (!$objp->date_debut_reelle) {
1850  print $langs->trans("DateStartReal").': ';
1851  if ($objp->date_debut_reelle) print dol_print_date($db->jdate($objp->date_debut_reelle), 'day');
1852  else print $langs->trans("ContractStatusNotRunning");
1853  }
1854  // Si active et en cours
1855  if ($objp->date_debut_reelle && !$objp->date_fin_reelle) {
1856  print $langs->trans("DateStartReal").': ';
1857  print dol_print_date($db->jdate($objp->date_debut_reelle), 'day');
1858  }
1859  // Si desactive
1860  if ($objp->date_debut_reelle && $objp->date_fin_reelle) {
1861  print $langs->trans("DateStartReal").': ';
1862  print dol_print_date($db->jdate($objp->date_debut_reelle), 'day');
1863  print ' &nbsp;-&nbsp; ';
1864  print $langs->trans("DateEndReal").': ';
1865  print dol_print_date($db->jdate($objp->date_fin_reelle), 'day');
1866  }
1867  if (!empty($objp->comment)) print " &nbsp;-&nbsp; ".$objp->comment;
1868  print '</td>';
1869 
1870  print '<td class="center">&nbsp;</td>';
1871 
1872  print '</tr>';
1873  print '</table>';
1874  }
1875 
1876  // Form to activate line
1877  if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne'))
1878  {
1879  print '<form name="active" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.GETPOST('ligne').'&amp;action=active" method="post">';
1880  print '<input type="hidden" name="token" value="'.newToken().'">';
1881 
1882  print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ? ' boxtablenobottom' : '').'" width="100%">';
1883 
1884  // Definie date debut et fin par defaut
1885  $dateactstart = $objp->date_debut;
1886  if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1887  elseif (!$dateactstart) $dateactstart = time();
1888 
1889  $dateactend = $objp->date_fin;
1890  if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1891  elseif (!$dateactend)
1892  {
1893  if ($objp->fk_product > 0)
1894  {
1895  $product = new Product($db);
1896  $product->fetch($objp->fk_product);
1897  $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
1898  }
1899  }
1900 
1901  print '<tr class="oddeven">';
1902  print '<td class="nohover">'.$langs->trans("DateServiceActivate").'</td><td class="nohover">';
1903  print $form->selectDate($dateactstart, '', $usehm, $usehm, '', "active", 1, 0);
1904  print '</td>';
1905  print '<td class="nohover">'.$langs->trans("DateEndPlanned").'</td><td class="nohover">';
1906  print $form->selectDate($dateactend, "end", $usehm, $usehm, '', "active", 1, 0);
1907  print '</td>';
1908  print '<td class="center nohover">';
1909  print '</td>';
1910 
1911  print '</tr>';
1912 
1913  print '<tr class="oddeven">';
1914  print '<td class="nohover">'.$langs->trans("Comment").'</td><td colspan="3" class="nohover" colspan="'.($conf->margin->enabled ? 4 : 3).'"><input type="text" class="minwidth300" name="comment" value="'.dol_escape_htmltag(GETPOST("comment", 'alphanohtml')).'"></td>';
1915  print '<td class="nohover right">';
1916  print '<input type="submit" class="button" name="activate" value="'.$langs->trans("Activate").'"> &nbsp; ';
1917  print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
1918  print '</td>';
1919  print '</tr>';
1920 
1921  print '</table>';
1922 
1923  print '</form>';
1924  }
1925 
1926  if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne'))
1927  {
1931  print '<!-- Form to disabled a line -->'."\n";
1932  print '<form name="closeline" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline - 1]->id.'" method="post">';
1933 
1934  print '<input type="hidden" name="token" value="'.newToken().'">';
1935  print '<input type="hidden" name="action" value="closeline">';
1936 
1937  print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ? ' boxtablenobottom' : '').'" width="100%">';
1938 
1939  // Definie date debut et fin par defaut
1940  $dateactstart = $objp->date_debut_reelle;
1941  if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1942  elseif (!$dateactstart) $dateactstart = time();
1943 
1944  $dateactend = $objp->date_fin_reelle;
1945  if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1946  elseif (!$dateactend)
1947  {
1948  if ($objp->fk_product > 0)
1949  {
1950  $product = new Product($db);
1951  $product->fetch($objp->fk_product);
1952  $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
1953  }
1954  }
1955  $now = dol_now();
1956  if ($dateactend > $now) $dateactend = $now;
1957 
1958  print '<tr class="oddeven"><td colspan="2" class="nohover">';
1959  if ($objp->statut >= 4)
1960  {
1961  if ($objp->statut == 4)
1962  {
1963  print $langs->trans("DateEndReal").' ';
1964  print $form->selectDate($dateactend, "end", $usehm, $usehm, ($objp->date_fin_reelle > 0 ? 0 : 1), "closeline", 1, 1);
1965  }
1966  }
1967  print '</td>';
1968  print '<td class="center nohover">';
1969  print '</td></tr>';
1970 
1971  print '<tr class="oddeven">';
1972  print '<td class="nohover">'.$langs->trans("Comment").'</td><td class="nohover"><input size="70" type="text" class="flat" name="comment" value="'.dol_escape_htmltag(GETPOST('comment', 'alpha')).'"></td>';
1973  print '<td class="nohover right">';
1974  print '<input type="submit" class="button" name="close" value="'.$langs->trans("Disable").'"> &nbsp; ';
1975  print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
1976  print '</td>';
1977  print '</tr>';
1978 
1979  print '</table>';
1980 
1981  print '</form>';
1982  }
1983  print '</div>';
1984  $cursorline++;
1985  }
1986  print '</div>';
1987 
1988  // Form to add new line
1989  if ($user->rights->contrat->creer && ($object->statut == 0))
1990  {
1991  $dateSelector = 1;
1992 
1993  print "\n";
1994  print ' <form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#add' : '#line_'.GETPOST('lineid')).'" method="POST">
1995  <input type="hidden" name="token" value="'.newToken().'">
1996  <input type="hidden" name="action" value="'.(($action != 'editline') ? 'addline' : 'updateline').'">
1997  <input type="hidden" name="mode" value="">
1998  <input type="hidden" name="id" value="'.$object->id.'">
1999  ';
2000 
2001  print '<div class="div-table-responsive-no-min">';
2002  print '<table id="tablelines" class="noborder noshadow" width="100%">'; // Array with (n*2)+1 lines
2003 
2004  // Form to add new line
2005  if ($action != 'editline')
2006  {
2007  $forcetoshowtitlelines = 1;
2008  if (empty($object->multicurrency_code)) $object->multicurrency_code = $conf->currency; // TODO Remove this when multicurrency supported on contracts
2009 
2010  // Add free products/services
2011  $object->formAddObjectLine(1, $mysoc, $soc);
2012 
2013  $parameters = array();
2014  $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2015  }
2016 
2017  print '</table>';
2018  print '</div>';
2019  print '</form>';
2020  }
2021 
2022  print dol_get_fiche_end();
2023 
2024 
2025  /*
2026  * Buttons
2027  */
2028 
2029  if ($user->socid == 0)
2030  {
2031  print '<div class="tabsAction">';
2032 
2033  $parameters = array();
2034  $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2035 
2036  if (empty($reshook))
2037  {
2038  // Send
2039  if (empty($user->socid)) {
2040  if ($object->statut == 1) {
2041  if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->contrat->creer)) {
2042  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>';
2043  } else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('SendMail').'</a></div>';
2044  }
2045  }
2046 
2047  if ($object->statut == 0 && $nbofservices)
2048  {
2049  if ($user->rights->contrat->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid">'.$langs->trans("Validate").'</a></div>';
2050  else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Validate").'</a></div>';
2051  }
2052  if ($object->statut == 1)
2053  {
2054  if ($user->rights->contrat->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Modify").'</a></div>';
2055  else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Modify").'</a></div>';
2056  }
2057 
2058  if (!empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices)
2059  {
2060  $langs->load("orders");
2061  if ($user->rights->commande->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/commande/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateOrder").'</a></div>';
2062  else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateOrder").'</a></div>';
2063  }
2064 
2065  if (!empty($conf->facture->enabled) && $object->statut > 0)
2066  {
2067  $langs->load("bills");
2068  if ($user->rights->facture->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateBill").'</a></div>';
2069  else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateBill").'</a></div>';
2070  }
2071 
2072  if ($object->nbofservicesclosed > 0 || $object->nbofserviceswait > 0)
2073  {
2074  if ($user->rights->contrat->activer)
2075  {
2076  print '<div class="inline-block divButAction"><a class="butAction" id="btnactivateall" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=activate">'.$langs->trans("ActivateAllContracts").'</a></div>';
2077  } else {
2078  print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" id="btnactivateall" href="#">'.$langs->trans("ActivateAllContracts").'</a></div>';
2079  }
2080  }
2081  if ($object->nbofservicesclosed < $nbofservices)
2082  {
2083  if ($user->rights->contrat->desactiver)
2084  {
2085  print '<div class="inline-block divButAction"><a class="butAction" id="btncloseall" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=close">'.$langs->trans("CloseAllContracts").'</a></div>';
2086  } else {
2087  print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" id="btncloseall" href="#">'.$langs->trans("CloseAllContracts").'</a></div>';
2088  }
2089 
2090  //if (! $numactive)
2091  //{
2092  //}
2093  //else
2094  //{
2095  // print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("CloseRefusedBecauseOneServiceActive").'">'.$langs->trans("Close").'</a></div>';
2096  //}
2097  }
2098 
2099  if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->nbofservicesclosed > 0)
2100  {
2101  if ($action == 'showclosedlines') print '<div class="inline-block divButAction"><a class="butAction" id="btnhideclosedlines" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=hideclosedlines">'.$langs->trans("HideClosedServices").'</a></div>';
2102  else print '<div class="inline-block divButAction"><a class="butAction" id="btnshowclosedlines" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=showclosedlines">'.$langs->trans("ShowClosedServices").'</a></div>';
2103  }
2104 
2105  // Clone
2106  if ($user->rights->contrat->creer) {
2107  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$object->socid.'&amp;action=clone&amp;object='.$object->element.'">'.$langs->trans("ToClone").'</a></div>';
2108  }
2109 
2110  // On peut supprimer entite si
2111  // - Droit de creer + mode brouillon (erreur creation)
2112  // - Droit de supprimer
2113  if (($user->rights->contrat->creer && $object->statut == $object::STATUS_DRAFT) || $user->rights->contrat->supprimer)
2114  {
2115  print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans("Delete").'</a></div>';
2116  } else {
2117  print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("Delete").'</a></div>';
2118  }
2119  }
2120 
2121  print "</div>";
2122  }
2123 
2124  // Select mail models is same action as presend
2125  if (GETPOST('modelselected')) {
2126  $action = 'presend';
2127  }
2128 
2129  if ($action != 'presend')
2130  {
2131  print '<div class="fichecenter"><div class="fichehalfleft">';
2132 
2133  /*
2134  * Documents generes
2135  */
2136  $filename = dol_sanitizeFileName($object->ref);
2137  $filedir = $conf->contrat->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref);
2138  $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
2139  $genallowed = $user->rights->contrat->lire;
2140  $delallowed = $user->rights->contrat->creer;
2141 
2142 
2143  print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, ($object->model_pdf ? $object->model_pdf : $conf->global->CONTRACT_ADDON_PDF), 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang, '', $object);
2144 
2145 
2146  // Show links to link elements
2147  $linktoelem = $form->showLinkToObjectBlock($object, null, array('contrat'));
2148  $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
2149 
2150 
2151  print '</div><div class="fichehalfright"><div class="ficheaddleft">';
2152 
2153  $MAXEVENT = 10;
2154 
2155  $morehtmlcenter = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-list-alt imgforviewmode', DOL_URL_ROOT.'/contrat/agenda.php?id='.$object->id);
2156 
2157  // List of actions on element
2158  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
2159  $formactions = new FormActions($db);
2160  $somethingshown = $formactions->showactions($object, 'contract', $socid, 1, 'listactions', $MAXEVENT, '', $morehtmlcenter);
2161 
2162  print '</div></div></div>';
2163  }
2164 
2165  // Presend form
2166  $modelmail = 'contract';
2167  $defaulttopic = 'SendContractRef';
2168  $diroutput = $conf->contrat->multidir_output[$object->entity];
2169  $trackid = 'con'.$object->id;
2170 
2171  include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
2172  }
2173 }
2174 
2175 
2176 llxFooter();
2177 
2178 $db->close();
2179 ?>
2180 
2181 <?php
2182 if (!empty($conf->margin->enabled) && $action == 'editline')
2183 {
2184  // TODO Why this ? To manage margin on contracts ?
2185  ?>
2186 <script type="text/javascript">
2187 $(document).ready(function() {
2188  var idprod = $("input[name='idprod']").val();
2189  var fournprice = $("input[name='fournprice']").val();
2190  var token = '<?php echo currentToken(); ?>'; // For AJAX Call we use old 'token' and not 'newtoken'
2191  if (idprod > 0) {
2192  $.post('<?php echo DOL_URL_ROOT; ?>/fourn/ajax/getSupplierPrices.php', {
2193  'idprod': idprod,
2194  'token': token
2195  }, function(data) {
2196  if (data.length > 0) {
2197  var options = '';
2198  var trouve=false;
2199  $(data).each(function() {
2200  options += '<option value="'+this.id+'" price="'+this.price+'"';
2201  if (fournprice > 0) {
2202  if (this.id == fournprice) {
2203  options += ' selected';
2204  $("#buying_price").val(this.price);
2205  trouve = true;
2206  }
2207  }
2208  options += '>'+this.label+'</option>';
2209  });
2210  options += '<option value=null'+(trouve?'':' selected')+'><?php echo $langs->trans("InputPrice"); ?></option>';
2211  $("#fournprice").html(options);
2212  if (trouve) {
2213  $("#buying_price").hide();
2214  $("#fournprice").show();
2215  }
2216  else {
2217  $("#buying_price").show();
2218  }
2219  $("#fournprice").change(function() {
2220  var selval = $(this).find('option:selected').attr("price");
2221  if (selval)
2222  $("#buying_price").val(selval).hide();
2223  else
2224  $('#buying_price').show();
2225  });
2226  }
2227  else {
2228  $("#fournprice").hide();
2229  $('#buying_price').show();
2230  }
2231  },
2232  'json');
2233  }
2234  else {
2235  $("#fournprice").hide();
2236  $('#buying_price').show();
2237  }
2238 });
2239 </script>
2240  <?php
2241 }
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname= '')
Make an include_once using default root and alternate root if it fails.
File of class to manage predefined price products or services by customer.
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
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.
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.
dolGetButtonTitle($label, $helpText= '', $iconClass= 'fa fa-file', $url= '', $id= '', $status=1, $params=array())
Function dolGetButtonTitle : this kind of buttons are used in title in list.
Class to manage products or services.
dol_now($mode= 'auto')
Return date for now.
Class to manage Dolibarr users.
Definition: user.class.php:44
Class to manage contracts.
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for properties) With native = 0: P...
dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom= 'UTF-8', $removelasteolbr=1)
This function is called to encode a string into a HTML string but differs from htmlentities because a...
contract_prepare_head(Contrat $object)
Prepare array with list of tabs.
Class to manage lines of contracts.
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Fonction qui renvoie si tva doit etre tva percue recuperable.
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.
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...
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
Move a file into another name.
Definition: files.lib.php:817
llxHeader()
Empty header.
Definition: wrapper.php:45
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.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage projects.
load_fiche_titre($titre, $morehtmlright= '', $picto= 'generic', $pictoisfullpath=0, $id= '', $morecssontable= '', $morehtmlcenter= '')
Load a title with picto.
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
Class to manage building of HTML components.
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.
restrictedArea($user, $features, $objectid=0, $tableandshare= '', $feature2= '', $dbt_keyfield= 'fk_soc', $dbt_select= 'rowid', $isdraft=0)
Check permissions of a user to show a page and an object.
Class to manage translations.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
Class to offer components to list and upload files.
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0)
Return a string with VAT rate label formated for view output Used into pdf and HTML pages...
print $_SERVER["PHP_SELF"]
Edit parameters.
dol_get_fiche_head($links=array(), $active= '', $title= '', $notab=0, $picto= '', $pictoisfullpath=0, $morehtmlright= '', $morecss= '', $limittoshow=0, $moretabssuffix= '')
Show tabs of a record.
print
Draft customers invoices.
Definition: index.php:89
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) Si ...
newToken()
Return the value of token currently saved into session with name &#39;newtoken&#39;.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Class to manage a WYSIWYG editor.
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:59
dol_time_plus_duree($time, $duration_value, $duration_unit)
Add a delay to a date.
Definition: date.lib.php:114
img_delete($titlealt= 'default', $other= 'class="pictodelete"', $morecss= '')
Show delete logo.
if(!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN'
Draft customers invoices.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition: repair.php:105
dol_mkdir($dir, $dataroot= '', $newmask=null)
Creation of a directory (this can create recursive subdir)
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $keepmoretags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...