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