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