PageRenderTime 104ms CodeModel.GetById 22ms app.highlight 65ms RepoModel.GetById 1ms app.codeStats 1ms

/htdocs/contrat/card.php

https://github.com/atm-maximep/dolibarr
PHP | 1951 lines | 1473 code | 288 blank | 190 comment | 451 complexity | 40ed9ceb0cb5b753b93111c383985ee0 MD5 | raw file
   1<?php
   2/* Copyright (C) 2003-2004	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
   3 * Copyright (C) 2004-2014	Laurent Destailleur		<eldy@users.sourceforge.net>
   4 * Copyright (C) 2005-2014	Regis Houssin			<regis.houssin@capnetworks.com>
   5 * Copyright (C) 2006		Andre Cianfarani		<acianfa@free.fr>
   6 * Copyright (C) 2010-2014	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		Ferran Marcet		  	<fmarcet@2byte.es>
  10 * Copyright (C) 2014       Marcos García           <marcosgdf@gmail.com>
  11 * Copyright (C) 2015           Jean-François Ferry		<jfefe@aternatik.fr>
  12 *
  13 * This program is free software; you can redistribute it and/or modify
  14 * it under the terms of the GNU General Public License as published by
  15 * the Free Software Foundation; either version 3 of the License, or
  16 * (at your option) any later version.
  17 *
  18 * This program is distributed in the hope that it will be useful,
  19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  21 * GNU General Public License for more details.
  22 *
  23 * You should have received a copy of the GNU General Public License
  24 * along with this program. If not, see <http://www.gnu.org/licenses/>.
  25 */
  26
  27/**
  28 *       \file       htdocs/contrat/card.php
  29 *       \ingroup    contrat
  30 *       \brief      Page of a contract
  31 */
  32
  33require ("../main.inc.php");
  34require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  35require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  36require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php';
  37require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
  38require_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
  39require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  40require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  41require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  42if (! empty($conf->propal->enabled))  require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  43if (! empty($conf->projet->enabled)) {
  44	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  45	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  46}
  47require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
  48
  49$langs->load("contracts");
  50$langs->load("orders");
  51$langs->load("companies");
  52$langs->load("bills");
  53$langs->load("products");
  54$langs->load('compta');
  55
  56$action=GETPOST('action','alpha');
  57$confirm=GETPOST('confirm','alpha');
  58$socid = GETPOST('socid','int');
  59$id = GETPOST('id','int');
  60$ref=GETPOST('ref','alpha');
  61
  62$datecontrat='';
  63
  64// Security check
  65if ($user->societe_id) $socid=$user->societe_id;
  66$result=restrictedArea($user,'contrat',$id);
  67
  68$usehm=(! empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE)?$conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE:0);
  69
  70// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
  71$hookmanager->initHooks(array('contractcard','globalcard'));
  72
  73$object = new Contrat($db);
  74$extrafields = new ExtraFields($db);
  75
  76// Load object
  77if ($id > 0 || ! empty($ref) && $action!='add') {
  78	$ret = $object->fetch($id, $ref);
  79	if ($ret > 0)
  80		$ret = $object->fetch_thirdparty();
  81	if ($ret < 0)
  82		dol_print_error('', $object->error);
  83}
  84
  85// fetch optionals attributes and labels
  86$extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
  87
  88// fetch optionals attributes lines and labels
  89$extrafieldsline = new ExtraFields($db);
  90$extralabelslines=$extrafieldsline->fetch_name_optionals_label($object->table_element_line);
  91
  92$permissionnote=$user->rights->contrat->creer;	// Used by the include of actions_setnotes.inc.php
  93
  94
  95/*
  96 * Actions
  97 */
  98
  99include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php';	// Must be include, not includ_once
 100
 101if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer)
 102{
 103    $result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment'));
 104
 105    if ($result > 0)
 106    {
 107        header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
 108        exit;
 109    }
 110    else {
 111        setEventMessage($object->error,'errors');
 112    }
 113}
 114
 115else if ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer)
 116{
 117	if (! GETPOST('dateend'))
 118	{
 119		$error++;
 120		setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateEnd")),'errors');
 121	}
 122	if (! $error)
 123	{
 124	    $result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment')));
 125	    if ($result > 0)
 126	    {
 127	        header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
 128	        exit;
 129	    }
 130	    else {
 131	        setEventMessage($object->error,'errors');
 132	    }
 133	}
 134}
 135
 136// Si ajout champ produit predefini
 137if (GETPOST('mode')=='predefined')
 138{
 139    $date_start='';
 140    $date_end='';
 141    if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear'))
 142    {
 143        $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
 144    }
 145    if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear'))
 146    {
 147        $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
 148    }
 149}
 150
 151// Si ajout champ produit libre
 152if (GETPOST('mode')=='libre')
 153{
 154    $date_start_sl='';
 155    $date_end_sl='';
 156    if (GETPOST('date_start_slmonth') && GETPOST('date_start_slday') && GETPOST('date_start_slyear'))
 157    {
 158        $date_start_sl=dol_mktime(GETPOST('date_start_slhour'), GETPOST('date_start_slmin'), 0, GETPOST('date_start_slmonth'), GETPOST('date_start_slday'), GETPOST('date_start_slyear'));
 159    }
 160    if (GETPOST('date_end_slmonth') && GETPOST('date_end_slday') && GETPOST('date_end_slyear'))
 161    {
 162        $date_end_sl=dol_mktime(GETPOST('date_end_slhour'), GETPOST('date_end_slmin'), 0, GETPOST('date_end_slmonth'), GETPOST('date_end_slday'), GETPOST('date_end_slyear'));
 163    }
 164}
 165
 166// Param dates
 167$date_contrat='';
 168$date_start_update='';
 169$date_end_update='';
 170$date_start_real_update='';
 171$date_end_real_update='';
 172if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear'))
 173{
 174    $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'));
 175}
 176if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear'))
 177{
 178    $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'));
 179}
 180if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear'))
 181{
 182    $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'));
 183}
 184if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear'))
 185{
 186    $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'));
 187}
 188if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear'))
 189{
 190    $datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
 191}
 192
 193// Add contract
 194if ($action == 'add' && $user->rights->contrat->creer)
 195{
 196	// Check
 197	if (empty($datecontrat))
 198	{
 199		$error++;
 200		setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Date")),'errors');
 201		$action='create';
 202	}
 203
 204	if ($socid<1)
 205	{
 206		setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Customer")),'errors');
 207		$action='create';
 208		$error++;
 209	}
 210
 211	// Fill array 'array_options' with data from add form
 212	$ret = $extrafields->setOptionalsFromPost($extralabels, $object);
 213	if ($ret < 0) {
 214		$error ++;
 215		$action = 'create';
 216	}
 217
 218	if (! $error)
 219	{
 220		$object->socid						= $socid;
 221    	$object->date_contrat				= $datecontrat;
 222
 223    	$object->commercial_suivi_id		= GETPOST('commercial_suivi_id','int');
 224    	$object->commercial_signature_id	= GETPOST('commercial_signature_id','int');
 225
 226    	$object->note_private				= GETPOST('note_private','alpha');
 227    	$object->note_public				= GETPOST('note_public','alpha');
 228    	$object->fk_project					= GETPOST('projectid','int');
 229    	$object->remise_percent				= GETPOST('remise_percent','alpha');
 230    	$object->ref						= GETPOST('ref','alpha');
 231    	$object->ref_supplier				= GETPOST('ref_supplier','alpha');
 232
 233	    // If creation from another object of another module (Example: origin=propal, originid=1)
 234	    if ($_POST['origin'] && $_POST['originid'])
 235	    {
 236	        // Parse element/subelement (ex: project_task)
 237	        $element = $subelement = $_POST['origin'];
 238	        if (preg_match('/^([^_]+)_([^_]+)/i',$_POST['origin'],$regs))
 239	        {
 240	            $element = $regs[1];
 241	            $subelement = $regs[2];
 242	        }
 243
 244	        // For compatibility
 245	        if ($element == 'order')    { $element = $subelement = 'commande'; }
 246	        if ($element == 'propal')   { $element = 'comm/propal'; $subelement = 'propal'; }
 247
 248	        $object->origin    = $_POST['origin'];
 249	        $object->origin_id = $_POST['originid'];
 250
 251	        // Possibility to add external linked objects with hooks
 252	        $object->linked_objects[$object->origin] = $object->origin_id;
 253	        if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects']))
 254	        {
 255	        	$object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
 256	        }
 257
 258	        $id = $object->create($user);
 259	        if ($id < 0) {
 260	        	setEventMessage($object->error,'errors');
 261	        }
 262
 263	        if ($id > 0)
 264	        {
 265	            dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
 266
 267	            $classname = ucfirst($subelement);
 268	            $srcobject = new $classname($db);
 269
 270	            dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
 271	            $result=$srcobject->fetch($object->origin_id);
 272	            if ($result > 0)
 273	            {
 274	                $srcobject->fetch_thirdparty();
 275					$lines = $srcobject->lines;
 276	                if (empty($lines) && method_exists($srcobject,'fetch_lines'))
 277	                {
 278	                	$srcobject->fetch_lines();
 279	                	$lines = $srcobject->lines;
 280	                }
 281
 282	                $fk_parent_line=0;
 283	                $num=count($lines);
 284
 285	                for ($i=0;$i<$num;$i++)
 286	                {
 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							{
 293								$product_static = new Product($db);
 294
 295								// Define output language
 296								if (! empty($conf->global->MAIN_MULTILANGS) && ! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE))
 297								{
 298									$prod = new Product($db);
 299									$prod->id=$lines[$i]->fk_product;
 300									$prod->getMultiLangs();
 301
 302									$outputlangs = $langs;
 303									$newlang='';
 304									if (empty($newlang) && GETPOST('lang_id')) $newlang=GETPOST('lang_id');
 305									if (empty($newlang)) $newlang=$srcobject->thirdparty->default_lang;
 306									if (! empty($newlang))
 307									{
 308										$outputlangs = new Translate("",$conf);
 309										$outputlangs->setDefaultLang($newlang);
 310									}
 311
 312									$label = (! empty($prod->multilangs[$outputlangs->defaultlang]["libelle"])) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $lines[$i]->product_label;
 313								}
 314								else
 315								{
 316									$label = $lines[$i]->product_label;
 317								}
 318
 319								if ($conf->global->PRODUIT_DESC_IN_FORM)
 320									$desc .= ($lines[$i]->desc && $lines[$i]->desc!=$lines[$i]->libelle)?dol_htmlentitiesbr($lines[$i]->desc):'';
 321							}
 322							else {
 323							    $desc = dol_htmlentitiesbr($lines[$i]->desc);
 324					        }
 325
 326		                    $result = $object->addline(
 327				                $desc,
 328				                $lines[$i]->subprice,
 329				                $lines[$i]->qty,
 330				                $lines[$i]->tva_tx,
 331				                $lines[$i]->localtax1_tx,
 332				                $lines[$i]->localtax2_tx,
 333				                $lines[$i]->fk_product,
 334				                $lines[$i]->remise_percent,
 335				                $lines[$i]->date_start,
 336				                $lines[$i]->date_end,
 337				                'HT',
 338				                0,
 339				                $lines[$i]->info_bits,
 340			                    $lines[$i]->fk_fournprice,
 341			                    $lines[$i]->pa_ht,
 342		                        array(),
 343			                    $lines[$i]->fk_unit
 344		                    );
 345
 346		                    if ($result < 0)
 347		                    {
 348		                        $error++;
 349		                        break;
 350		                    }
 351
 352						}
 353	                }
 354	            }
 355	            else
 356	            {
 357	                setEventMessage($srcobject->error,'errors');
 358	                $error++;
 359	            }
 360	        }
 361	        else
 362	        {
 363	            setEventMessage($object->error,'errors');
 364	            $error++;
 365	        }
 366	    }
 367	    else
 368	    {
 369	        $result = $object->create($user);
 370	        if ($result > 0)
 371	        {
 372	            header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
 373	            exit;
 374	        }
 375	        else {
 376	        	setEventMessage($object->error,'errors');
 377	        }
 378	        $action='create';
 379		}
 380    }
 381}
 382
 383else if ($action == 'classin' && $user->rights->contrat->creer)
 384{
 385    $object->setProject(GETPOST('projectid'));
 386}
 387
 388// Add a new line
 389else if ($action == 'addline' && $user->rights->contrat->creer)
 390{
 391	// Set if we used free entry or predefined product
 392	$predef='';
 393	$product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
 394	if (GETPOST('prod_entry_mode') == 'free')
 395	{
 396		$idprod=0;
 397		$price_ht = GETPOST('price_ht');
 398		$tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
 399	}
 400	else
 401	{
 402		$idprod=GETPOST('idprod', 'int');
 403		$price_ht = '';
 404		$tva_tx = '';
 405	}
 406
 407	$qty = GETPOST('qty'.$predef);
 408	$remise_percent=GETPOST('remise_percent'.$predef);
 409
 410    if ($qty == '')
 411    {
 412    	setEventMessage($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")),'errors');
 413    	$error++;
 414    }
 415    if (GETPOST('prod_entry_mode') == 'free' && empty($idprod) && empty($product_desc))
 416    {
 417    	setEventMessage($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")),'errors');
 418    	$error++;
 419    }
 420
 421    // Extrafields
 422    $extrafieldsline = new ExtraFields($db);
 423    $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
 424    $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
 425    // Unset extrafield
 426    if (is_array($extralabelsline)) {
 427    	// Get extra fields
 428    	foreach ($extralabelsline as $key => $value) {
 429    		unset($_POST["options_" . $key]);
 430    	}
 431    }
 432
 433    if (! $error)
 434    {
 435		// Clean parameters
 436		$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'));
 437		$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'));
 438		$price_base_type = (GETPOST('price_base_type', 'alpha')?GETPOST('price_base_type', 'alpha'):'HT');
 439
 440        // Ecrase $pu par celui du produit
 441        // Ecrase $desc par celui du produit
 442        // Ecrase $txtva par celui du produit
 443        // Ecrase $base_price_type par celui du produit
 444        if ($idprod > 0)
 445        {
 446            $prod = new Product($db);
 447            $prod->fetch($idprod);
 448
 449            $tva_tx = get_default_tva($mysoc,$object->thirdparty,$prod->id);
 450            $tva_npr = get_default_npr($mysoc,$object->thirdparty,$prod->id);
 451            $pu_ht = $prod->price;
 452            $pu_ttc = $prod->price_ttc;
 453            $price_min = $prod->price_min;
 454            $price_base_type = $prod->price_base_type;
 455
 456            // On defini prix unitaire
 457            if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level)
 458            {
 459                $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
 460                $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
 461                $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
 462                $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
 463            }
 464        	elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES))
 465			{
 466				require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
 467
 468				$prodcustprice = new Productcustomerprice($db);
 469
 470				$filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id);
 471
 472				$result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
 473				if ($result) {
 474					if (count($prodcustprice->lines) > 0) {
 475						$pu_ht = price($prodcustprice->lines [0]->price);
 476						$pu_ttc = price($prodcustprice->lines [0]->price_ttc);
 477						$price_base_type = $prodcustprice->lines [0]->price_base_type;
 478						$prod->tva_tx = $prodcustprice->lines [0]->tva_tx;
 479					}
 480				}
 481			}
 482
 483            // On reevalue prix selon taux tva car taux tva transaction peut etre different
 484            // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
 485            if ($tva_tx != $prod->tva_tx)
 486            {
 487                if ($price_base_type != 'HT')
 488                {
 489                    $pu_ht = price2num($pu_ttc / (1 + ($tva_tx/100)), 'MU');
 490                }
 491                else
 492              {
 493                    $pu_ttc = price2num($pu_ht * (1 + ($tva_tx/100)), 'MU');
 494                }
 495            }
 496
 497           	$desc=$prod->description;
 498           	$desc=dol_concatdesc($desc,$product_desc);
 499	        $fk_unit = $prod->fk_unit;
 500        }
 501        else
 502		{
 503            $pu_ht=GETPOST('price_ht');
 504            $price_base_type = 'HT';
 505            $tva_tx=GETPOST('tva_tx')?str_replace('*','',GETPOST('tva_tx')):0;		// tva_tx field may be disabled, so we use vat rate 0
 506            $tva_npr=preg_match('/\*/',GETPOST('tva_tx'))?1:0;
 507            $desc=$product_desc;
 508			$fk_unit= GETPOST('units', 'alpha');
 509        }
 510
 511        $localtax1_tx=get_localtax($tva_tx,1,$object->thirdparty);
 512        $localtax2_tx=get_localtax($tva_tx,2,$object->thirdparty);
 513
 514		// ajout prix achat
 515		$fk_fournprice = $_POST['fournprice'];
 516		if ( ! empty($_POST['buying_price']) )
 517		  $pa_ht = $_POST['buying_price'];
 518		else
 519		  $pa_ht = null;
 520
 521        $info_bits=0;
 522        if ($tva_npr) $info_bits |= 0x01;
 523
 524        if($price_min && (price2num($pu_ht)*(1-price2num($remise_percent)/100) < price2num($price_min)))
 525        {
 526            $object->error = $langs->trans("CantBeLessThanMinPrice",price(price2num($price_min,'MU'),0,$langs,0,0,-1,$conf->currency));
 527            $result = -1 ;
 528        }
 529        else
 530		{
 531            // Insert line
 532            $result = $object->addline(
 533                $desc,
 534                $pu_ht,
 535                $qty,
 536                $tva_tx,
 537                $localtax1_tx,
 538                $localtax2_tx,
 539                $idprod,
 540                $remise_percent,
 541                $date_start,
 542                $date_end,
 543                $price_base_type,
 544                $pu_ttc,
 545                $info_bits,
 546      			$fk_fournprice,
 547      			$pa_ht,
 548            	$array_options,
 549	            $fk_unit
 550            );
 551        }
 552
 553        if ($result > 0)
 554        {
 555        	// Define output language
 556			if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
 557			{
 558				$outputlangs = $langs;
 559				$newlang = '';
 560				if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha');
 561				if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $object->thirdparty->default_lang;
 562				if (! empty($newlang)) {
 563					$outputlangs = new Translate("", $conf);
 564					$outputlangs->setDefaultLang($newlang);
 565				}
 566
 567				$ret = $object->fetch($id); // Reload to get new records
 568
 569				$object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
 570			}
 571
 572			unset($_POST ['prod_entry_mode']);
 573
 574			unset($_POST['qty']);
 575			unset($_POST['type']);
 576			unset($_POST['remise_percent']);
 577			unset($_POST['price_ht']);
 578			unset($_POST['price_ttc']);
 579			unset($_POST['tva_tx']);
 580			unset($_POST['product_ref']);
 581			unset($_POST['product_label']);
 582			unset($_POST['product_desc']);
 583			unset($_POST['fournprice']);
 584			unset($_POST['buying_price']);
 585			unset($_POST ['np_marginRate']);
 586			unset($_POST ['np_markRate']);
 587			unset($_POST['dp_desc']);
 588			unset($_POST['idprod']);
 589
 590	    	unset($_POST['date_starthour']);
 591	    	unset($_POST['date_startmin']);
 592	    	unset($_POST['date_startsec']);
 593	    	unset($_POST['date_startday']);
 594	    	unset($_POST['date_startmonth']);
 595	    	unset($_POST['date_startyear']);
 596	    	unset($_POST['date_endhour']);
 597	    	unset($_POST['date_endmin']);
 598	    	unset($_POST['date_endsec']);
 599	    	unset($_POST['date_endday']);
 600	    	unset($_POST['date_endmonth']);
 601	    	unset($_POST['date_endyear']);
 602        }
 603        else
 604        {
 605        	setEventMessage($object->error,'errors');
 606        }
 607    }
 608}
 609
 610else if ($action == 'updateligne' && $user->rights->contrat->creer && ! GETPOST('cancel'))
 611{
 612    $objectline = new ContratLigne($db);
 613    if ($objectline->fetch(GETPOST('elrowid')))
 614    {
 615        $db->begin();
 616
 617        if ($date_start_real_update == '') $date_start_real_update=$objectline->date_ouverture;
 618        if ($date_end_real_update == '')   $date_end_real_update=$objectline->date_cloture;
 619
 620		$localtax1_tx=get_localtax(GETPOST('eltva_tx'),1,$object->thirdparty);
 621        $localtax2_tx=get_localtax(GETPOST('eltva_tx'),2,$object->thirdparty);
 622
 623	  	// ajout prix d'achat
 624	  	$fk_fournprice = $_POST['fournprice'];
 625	  	if ( ! empty($_POST['buying_price']) )
 626	  	  $pa_ht = $_POST['buying_price'];
 627	  	else
 628	  	  $pa_ht = null;
 629
 630	    $fk_unit = GETPOST('unit', 'alpha');
 631
 632        $objectline->description=GETPOST('product_desc');
 633        $objectline->price_ht=GETPOST('elprice');
 634        $objectline->subprice=GETPOST('elprice');
 635        $objectline->qty=GETPOST('elqty');
 636        $objectline->remise_percent=GETPOST('elremise_percent');
 637        $objectline->tva_tx=GETPOST('eltva_tx')?GETPOST('eltva_tx'):0;	// Field may be disabled, so we use vat rate 0
 638        $objectline->localtax1_tx=$localtax1_tx;
 639        $objectline->localtax2_tx=$localtax2_tx;
 640        $objectline->date_ouverture_prevue=$date_start_update;
 641        $objectline->date_ouverture=$date_start_real_update;
 642        $objectline->date_fin_validite=$date_end_update;
 643        $objectline->date_cloture=$date_end_real_update;
 644        $objectline->fk_user_cloture=$user->id;
 645        $objectline->fk_fournprice=$fk_fournprice;
 646        $objectline->pa_ht=$pa_ht;
 647
 648	    if ($fk_unit > 0) {
 649		    $objectline->fk_unit = GETPOST('unit');
 650	    } else {
 651		    $objectline->fk_unit = null;
 652	    }
 653
 654        // Extrafields
 655        $extrafieldsline = new ExtraFields($db);
 656        $extralabelsline = $extrafieldsline->fetch_name_optionals_label($objectline->table_element);
 657        $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
 658        $objectline->array_options=$array_options;
 659
 660        // TODO verifier price_min si fk_product et multiprix
 661
 662        $result=$objectline->update($user);
 663        if ($result > 0)
 664        {
 665            $db->commit();
 666        }
 667        else
 668        {
 669        	setEventMessage($objectline->error,'errors');
 670            $db->rollback();
 671        }
 672    }
 673    else
 674    {
 675    	setEventMessage($objectline->error,'errors');
 676    }
 677}
 678
 679else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer)
 680{
 681    $result = $object->deleteline(GETPOST('lineid'),$user);
 682
 683    if ($result >= 0)
 684    {
 685        header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
 686        exit;
 687    }
 688    else
 689    {
 690    	setEventMessage($object->error,'errors');
 691    }
 692}
 693
 694else if ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer)
 695{
 696    $result = $object->validate($user);
 697}
 698
 699// Close all lines
 700else if ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer)
 701{
 702    $object->cloture($user);
 703}
 704
 705else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer)
 706{
 707	$result=$object->delete($user);
 708	if ($result >= 0)
 709	{
 710		header("Location: index.php");
 711		return;
 712	}
 713	else
 714	{
 715		setEventMessage($object->error,'errors');
 716	}
 717}
 718
 719else if ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contrat->creer)
 720{
 721	if (GETPOST('newcid') > 0)
 722	{
 723		$contractline = new ContratLigne($db);
 724		$result=$contractline->fetch(GETPOST('lineid'));
 725		$contractline->fk_contrat = GETPOST('newcid');
 726		$result=$contractline->update($user,1);
 727		if ($result >= 0)
 728		{
 729			header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
 730			return;
 731		}
 732		else
 733		{
 734			setEventMessage($object->error,'errors');
 735		}
 736	}
 737	else
 738	{
 739		setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("RefNewContract")),'errors');
 740	}
 741} else if ($action == 'update_extras') {
 742	// Fill array 'array_options' with data from update form
 743	$extralabels = $extrafields->fetch_name_optionals_label($object->table_element);
 744	$ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute'));
 745	if ($ret < 0)
 746		$error ++;
 747
 748	if (! $error) {
 749
 750			$result = $object->insertExtraFields();
 751			if ($result < 0) {
 752				$error ++;
 753			}
 754		} else if ($reshook < 0)
 755			$error ++;
 756
 757	if ($error) {
 758		$action = 'edit_extras';
 759		setEventMessage($object->error,'errors');
 760	}
 761} elseif ($action=='setref_supplier') {
 762
 763	$cancelbutton = GETPOST('cancel');
 764
 765	if (!$cancelbutton) {
 766
 767		$result = $object->fetch($id);
 768		if ($result < 0) {
 769			setEventMessage($object->errors, 'errors');
 770		}
 771		$object->ref_supplier = GETPOST('ref_supplier', 'alpha');
 772
 773		$result = $object->update($user);
 774		if ($result < 0) {
 775			setEventMessage($object->errors, 'errors');
 776			$action = 'editref_supplier';
 777		} else {
 778			header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
 779			exit;
 780		}
 781	}
 782} elseif ($action=='setref') {
 783	$object->ref=GETPOST('ref','alpha');
 784
 785	$result = $object->update($user);
 786	if ($result < 0) {
 787		setEventMessage($object->errors,'errors');
 788		$action='editref';
 789	} else {
 790		header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
 791		exit;
 792	}
 793}
 794
 795// Generation doc (depuis lien ou depuis cartouche doc)
 796else if ($action == 'builddoc' && $user->rights->contrat->creer) {
 797	if (GETPOST('model')) {
 798		$object->setDocModel($user, GETPOST('model'));
 799	}
 800
 801	// Define output language
 802	$outputlangs = $langs;
 803	if (! empty($conf->global->MAIN_MULTILANGS)) {
 804		$outputlangs = new Translate("", $conf);
 805		$newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->thirdparty->default_lang);
 806		$outputlangs->setDefaultLang($newlang);
 807	}
 808	$ret = $object->fetch($id); // Reload to get new records
 809	$result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
 810	if ($result <= 0)
 811	{
 812		setEventMessages($object->error, $object->errors, 'errors');
 813        $action='';
 814	}
 815}
 816
 817// Remove file in doc form
 818else if ($action == 'remove_file' && $user->rights->contrat->creer) {
 819	if ($object->id > 0) {
 820		require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
 821
 822		$langs->load("other");
 823		$upload_dir = $conf->contrat->dir_output;
 824		$file = $upload_dir . '/' . GETPOST('file');
 825		$ret = dol_delete_file($file, 0, 0, 0, $object);
 826		if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('file')));
 827		else setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), 'errors');
 828	}
 829}
 830
 831if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer)
 832{
 833	if ($action == 'addcontact')
 834	{
 835		$contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
 836		$result = $object->add_contact($contactid, GETPOST('type'), GETPOST('source'));
 837
 838		if ($result >= 0)
 839		{
 840			header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
 841			exit;
 842		}
 843		else
 844		{
 845			if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
 846			{
 847				$langs->load("errors");
 848				setEventMessage($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"),'errors');
 849			}
 850			else
 851			{
 852				setEventMessage($object->error,'errors');
 853			}
 854		}
 855	}
 856
 857	// bascule du statut d'un contact
 858	else if ($action == 'swapstatut')
 859	{
 860		$result=$object->swapContactStatus(GETPOST('ligne'));
 861	}
 862
 863	// Efface un contact
 864	else if ($action == 'deletecontact')
 865	{
 866		$result = $object->delete_contact(GETPOST('lineid'));
 867
 868		if ($result >= 0)
 869		{
 870			header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
 871			exit;
 872		}
 873		else {
 874			setEventMessage($object->error,'errors');
 875		}
 876	}
 877}
 878
 879
 880/*
 881 * View
 882 */
 883
 884llxHeader('',$langs->trans("ContractCard"),"Contrat");
 885
 886$form = new Form($db);
 887$formfile = new FormFile($db);
 888
 889$objectlignestatic=new ContratLigne($db);
 890
 891// Load object modContract
 892$module=(! empty($conf->global->CONTRACT_ADDON)?$conf->global->CONTRACT_ADDON:'mod_contract_serpis');
 893if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php')
 894{
 895	$module = substr($module, 0, dol_strlen($module)-4);
 896}
 897$result=dol_include_once('/core/modules/contract/'.$module.'.php');
 898if ($result > 0)
 899{
 900	$modCodeContract = new $module();
 901}
 902
 903
 904/*********************************************************************
 905 *
 906 * Mode creation
 907 *
 908 *********************************************************************/
 909if ($action == 'create')
 910{
 911	print_fiche_titre($langs->trans('AddContract'),'','title_commercial.png');
 912
 913    $soc = new Societe($db);
 914    if ($socid>0) $soc->fetch($socid);
 915
 916    if (GETPOST('origin') && GETPOST('originid'))
 917    {
 918        // Parse element/subelement (ex: project_task)
 919        $element = $subelement = GETPOST('origin');
 920        if (preg_match('/^([^_]+)_([^_]+)/i',GETPOST('origin'),$regs))
 921        {
 922            $element = $regs[1];
 923            $subelement = $regs[2];
 924        }
 925
 926        if ($element == 'project')
 927        {
 928            $projectid=GETPOST('originid');
 929        }
 930        else
 931        {
 932            // For compatibility
 933            if ($element == 'order' || $element == 'commande')    { $element = $subelement = 'commande'; }
 934            if ($element == 'propal')   { $element = 'comm/propal'; $subelement = 'propal'; }
 935
 936            dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
 937
 938            $classname = ucfirst($subelement);
 939            $objectsrc = new $classname($db);
 940            $objectsrc->fetch(GETPOST('originid'));
 941            if (empty($objectsrc->lines) && method_exists($objectsrc,'fetch_lines'))  $objectsrc->fetch_lines();
 942            $objectsrc->fetch_thirdparty();
 943
 944            $projectid          = (!empty($objectsrc->fk_project)?$objectsrc->fk_project:'');
 945
 946            $soc = $objectsrc->client;
 947
 948            $note_private		= (! empty($objectsrc->note_private) ? $objectsrc->note_private : '');
 949            $note_public		= (! empty($objectsrc->note_public) ? $objectsrc->note_public : '');
 950
 951            // Object source contacts list
 952            $srccontactslist = $objectsrc->liste_contact(-1,'external',1);
 953        }
 954    }
 955    else {
 956		$projectid = GETPOST('projectid','int');
 957		$note_private = GETPOST("note_private");
 958		$note_public = GETPOST("note_public");
 959	}
 960
 961    $object->date_contrat = dol_now();
 962
 963    print '<form name="form_contract" action="'.$_SERVER["PHP_SELF"].'" method="post">';
 964    print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 965
 966    print '<input type="hidden" name="action" value="add">';
 967    print '<input type="hidden" name="socid" value="'.$soc->id.'">'."\n";
 968    print '<input type="hidden" name="remise_percent" value="0">';
 969
 970    dol_fiche_head();
 971
 972    print '<table class="border" width="100%">';
 973
 974    // Ref
 975    if (! empty($modCodeContract->code_auto)) {
 976    	$tmpcode=$langs->trans("Draft");
 977    } else {
 978    	$tmpcode='<input name="ref" size="20" maxlength="128" value="'.dol_escape_htmltag(GETPOST('ref')?GETPOST('ref'):$tmpcode).'">';
 979    }
 980	print '<tr><td class="fieldrequired">'.$langs->trans('Ref').'</td><td colspan="2">'.$tmpcode.'</td></tr>';
 981
 982	// Ref supplier
 983	print '<tr><td>'.$langs->trans('RefSupplier').'</td>';
 984	print '<td colspan="2"><input type="text" size="5" name="ref_supplier" id="ref_supplier" value="'.GETPOST('ref_supplier','alpha').'"></td></tr>';
 985
 986    // Customer
 987	print '<tr>';
 988	print '<td class="fieldrequired">'.$langs->trans('Customer').'</td>';
 989	if($socid>0)
 990	{
 991		print '<td colspan="2">';
 992		print $soc->getNomUrl(1);
 993		print '<input type="hidden" name="socid" value="'.$soc->id.'">';
 994		print '</td>';
 995	}
 996	else
 997	{
 998		print '<td colspan="2">';
 999		print $form->select_company('','socid','s.client = 1 OR s.client = 3',1);
1000		print '</td>';
1001	}
1002	print '</tr>'."\n";
1003
1004	if($socid>0)
1005	{
1006		// Ligne info remises tiers
1007		print '<tr><td>'.$langs->trans('Discounts').'</td><td colspan="2">';
1008		if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_percent);
1009		else print $langs->trans("CompanyHasNoRelativeDiscount");
1010		print '. ';
1011		$absolute_discount=$soc->getAvailableDiscounts();
1012		if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency));
1013		else print $langs->trans("CompanyHasNoAbsoluteDiscount");
1014		print '.';
1015		print '</td></tr>';
1016	}
1017
1018    // Commercial suivi
1019    print '<tr><td width="20%" class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").'</span></td><td>';
1020    print $form->select_dolusers(GETPOST("commercial_suivi_id")?GETPOST("commercial_suivi_id"):$user->id,'commercial_suivi_id',1,'');
1021    print '</td></tr>';
1022
1023    // Commercial signature
1024    print '<tr><td width="20%" class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").'</span></td><td>';
1025    print $form->select_dolusers(GETPOST("commercial_signature_id")?GETPOST("commercial_signature_id"):$user->id,'commercial_signature_id',1,'');
1026    print '</td></tr>';
1027
1028    print '<tr><td><span class="fieldrequired">'.$langs->trans("Date").'</span></td><td>';
1029    $form->select_date($datecontrat,'',0,0,'',"contrat");
1030    print "</td></tr>";
1031
1032    if (! empty($conf->projet->enabled))
1033    {
1034    	$formproject=new FormProjets($db);
1035
1036        print '<tr><td>'.$langs->trans("Project").'</td><td>';
1037        $formproject->select_projects($soc->id,$projectid,"projectid");
1038        print "</td></tr>";
1039    }
1040
1041    print '<tr><td>'.$langs->trans("NotePublic").'</td><td valign="top">';
1042
1043
1044    $doleditor=new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, 70);
1045    print $doleditor->Create(1);
1046
1047
1048    if (empty($user->societe_id))
1049    {
1050        print '<tr><td>'.$langs->trans("NotePrivate").'</td><td valign="top">';
1051        $doleditor=new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, true, ROWS_3, 70);
1052        print $doleditor->Create(1);
1053        print '</td></tr>';
1054    }
1055
1056    // Other attributes
1057    $parameters=array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"');
1058    $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
1059
1060    // Other attributes
1061    if (empty($reshook) && ! empty($extrafields->attribute_label)) {
1062    	print $object->showOptionals($extrafields, 'edit');
1063    }
1064
1065    print "</table>\n";
1066
1067    dol_fiche_end();
1068
1069    print '<div align="center"><input type="submit" class="button" value="'.$langs->trans("Create").'"></div>';
1070
1071    if (is_object($objectsrc))
1072    {
1073        print '<input type="hidden" name="origin"         value="'.$objectsrc->element.'">';
1074        print '<input type="hidden" name="originid"       value="'.$objectsrc->id.'">';
1075
1076        if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS))
1077        {
1078        	print '<br>'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed");
1079        }
1080	}
1081
1082    print "</form>\n";
1083}
1084else
1085/* *************************************************************************** */
1086/*                                                                             */
1087/* Mode vue et edition                                                         */
1088/*                                                                             */
1089/* *************************************************************************** */
1090{
1091    $now=dol_now();
1092
1093    if ($object->id > 0)
1094    {
1095    	$object->fetch_thirdparty();
1096
1097        $result=$object->fetch_lines();	// This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed
1098        if ($result < 0) dol_print_error($db,$object->error);
1099
1100        $nbofservices=count($object->lines);
1101
1102        $author = new User($db);
1103        $author->fetch($object->user_author_id);
1104
1105        $commercial_signature = new User($db);
1106        $commercial_signature->fetch($object->commercial_signature_id);
1107
1108        $commercial_suivi = new User($db);
1109        $commercial_suivi->fetch($object->commercial_suivi_id);
1110
1111        $head = contract_prepare_head($object);
1112
1113        $hselected = 0;
1114
1115        dol_fiche_head($head, $hselected, $langs->trans("Contract"), 0, 'contract');
1116
1117
1118        /*
1119         * Confirmation de la suppression du contrat
1120         */
1121        if ($action == 'delete')
1122        {
1123            print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("DeleteAContract"),$langs->trans("ConfirmDeleteAContract"),"confirm_delete",'',0,1);
1124
1125        }
1126
1127        /*
1128         * Confirmation de la validation
1129         */
1130        if ($action == 'valid')
1131        {
1132        	$ref = substr($object->ref, 1, 4);
1133        	if ($ref == 'PROV' && !empty($modCodeContract->code_auto))
1134        	{
1135        		$numref = $object->getNextNumRef($object->thirdparty);
1136        	}
1137        	else
1138        	{
1139        		$numref = $object->ref;
1140        	}
1141
1142        	$text=$langs->trans('ConfirmValidateContract',$numref);
1143
1144            print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("ValidateAContract"),$text,"confirm_valid",'',0,1);
1145
1146        }
1147
1148        /*
1149         * Confirmation de la fermeture
1150         */
1151        if ($action == 'close')
1152        {
1153            print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id,$langs->trans("CloseAContract"),$langs->trans("ConfirmCloseContract"),"confirm_close",'',0,1);
1154
1155        }
1156
1157        /*
1158         *   Contrat
1159         */
1160        if (! empty($object->brouillon) && $user->rights->contrat->creer)
1161        {
1162            print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="POST">';
1163            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1164            print '<input type="hidden" name="action" value="setremise">';
1165        }
1166
1167        print '<table class="border" width="100%">';
1168
1169        $linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php'.(! empty($socid)?'?socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
1170
1171        // Ref du contrat
1172        if (!empty($modCodeContract->code_auto)) {
1173	        print '<tr><td width="25%">'.$langs->trans("Ref").'</td><td colspan="3">';
1174	        print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', '');
1175	        print "</td></tr>";
1176        } else {
1177        	print '<tr>';
1178        	print '<td  width="20%">';
1179        	print $form->editfieldkey("Ref",'ref',$object->ref,$object,$user->rights->contrat->creer);
1180        	print '</td><td>';
1181        	print $form->editfieldval("Ref",'ref',$object->ref,$object,$user->rights->contrat->creer);
1182        	print '</td>';
1183        	print '</tr>';
1184        }
1185
1186        print '<tr>';
1187		print '<td  width="20%">';
1188		print $form->editfieldkey("RefSupplier",'ref_supplier',$object->ref_supplier,$object,$user->rights->contrat->creer);
1189		print '</td><td>';
1190		print $form->editfieldval("RefSupplier",'ref_supplier',$object->ref_supplier,$object,$user->rights->contrat->creer);
1191		print '</td>';
1192		print '</tr>';
1193
1194        // Customer
1195        print "<tr><td>".$langs->trans("Customer")."</td>";
1196        print '<td colspan="3">'.$object->thirdparty->getNomUrl(1).'</td></tr>';
1197
1198        // Ligne info remises tiers
1199        print '<tr><td>'.$langs->trans('Discount').'</td><td colspan="3">';
1200        if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$object->thirdparty->remise_percent);
1201        else print $langs->trans("CompanyHasNoRelativeDiscount");
1202        $absolute_discount=$object->thirdparty->getAvailableDiscounts();
1203        print '. ';
1204        if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->trans("Currency".$conf->currency));
1205        else print $langs->trans("CompanyHasNoAbsoluteDiscount");
1206        print '.';
1207        print '</td></tr>';
1208
1209        // Statut contrat
1210        print '<tr><td>'.$langs->trans("Status").'</td><td colspan="3">';
1211        if ($object->statut==0) print $object->getLibStatut(2);
1212        else print $object->getLibStatut(4);
1213        print "</td></tr>";
1214
1215        // Date
1216        print '<tr><td>'.$langs->trans("Date").'</td>';
1217        print '<td colspan="3">'.dol_print_date($object->date_contrat,"dayhour")."</td></tr>\n";
1218
1219        // Projet
1220        if (! empty($conf->projet->enabled))
1221        {
1222            $langs->load("projects");
1223            print '<tr><td>';
1224            print '<table width="100%" class="nobordernopadding"><tr><td>';
1225            print $langs->trans("Project");
1226            print '</td>';
1227            if ($action != "classify" && $user->rights->projet->creer) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->trans("SetProject")).'</a></td>';
1228            print '</tr></table>';
1229            print '</td><td colspan="3">';
1230            if ($action == "classify")
1231            {
1232                $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id,$object->socid,$object->fk_project,"projectid", 0, 0, 1);
1233            }
1234            else
1235            {
1236                $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id,$object->socid,$object->fk_project,"none", 0, 0);
1237            }
1238            print "</td></tr>";
1239        }
1240
1241        // Other attributes
1242        $cols = 3;
1243        include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
1244
1245        print "</table>";
1246
1247        if (! empty($object->brouillon) && $user->rights->contrat->creer)
1248        {
1249            print '</form>';
1250        }
1251
1252        echo '<br>';
1253
1254        if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
1255        {
1256        	$blocname = 'contacts';
1257        	$title = $langs->trans('ContactsAddresses');
1258        	include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1259        }
1260
1261        if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
1262        {
1263        	$blocname = 'notes';
1264        	$title = $langs->trans('Notes');
1265        	include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1266        }
1267
1268
1269        $colorb='666666';
1270
1271        $arrayothercontracts=$object->getListOfContracts('others');
1272
1273        /*
1274         * Lines of contracts
1275         */
1276
1277		$productstatic=new Product($db);
1278
1279        $usemargins=0;
1280		if (! empty($conf->margin->enabled) && ! empty($object->element) && in_array($object->element,array('facture','propal','commande'))) $usemargins=1;
1281
1282        $var=false;
1283
1284		// Title line for service
1285        $cursorline=1;
1286        while ($cursorline <= $nbofservices)
1287        {
1288            print '<form name="update" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="post">';
1289            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1290            print '<input type="hidden" name="action" value="updateligne">';
1291            print '<input type="hidden" name="elrowid" value="'.GETPOST('rowid').'">';
1292            print '<input type="hidden" name="idprod" value="'.($objp->fk_product?$objp->fk_product:'0').'">';
1293            print '<input type="hidden" name="fournprice" value="'.($objp->fk_fournprice?$objp->fk_fournprice:'0').'">';
1294
1295            // Area with common detail of line
1296            print '<table class="notopnoleftnoright allwidth tableforservicepart1" width="100%">';
1297
1298            $sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.description, cd.price_ht, cd.qty,";
1299            $sql.= " cd.tva_tx, cd.remise_percent, cd.info_bits, cd.subprice,";
1300            $sql.= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,";
1301            $sql.= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,";
1302            $sql.= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,";
1303	        $sql.= " cd.fk_unit,";
1304            $sql.= " p.rowid as pid, p.ref as pref, p.label as label, p.fk_product_type as ptype";
1305            $sql.= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
1306            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
1307            $sql.= " WHERE cd.rowid = ".$object->lines[$cursorline-1]->id;
1308
1309            $result = $db->query($sql);
1310            if ($result)
1311            {
1312                $total = 0;
1313
1314                print '<tr class="liste_titre">';
1315                print '<td>'.$langs->trans("ServiceNb",$cursorline).'</td>';
1316                print '<td width="50" align="center">'.$langs->trans("VAT").'</td>';
1317                print '<td width="50" align="right">'.$langs->trans("PriceUHT").'</td>';
1318                print '<td width="30" align="center">'.$langs->trans("Qty").'</td>';
1319	            if ($conf->global->PRODUCT_USE_UNITS) print '<td width="30" align="left">'.$langs->trans("Unit").'</td>';
1320                print '<td width="50" align="right">'.$langs->trans("ReductionShort").'</td>';
1321				if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td width="50" align="right">'.$langs->trans("BuyingPrice").'</td>';
1322                print '<td width="30">&nbsp;</td>';
1323                print "</tr>\n";
1324
1325                $objp = $db->fetch_object($result);
1326
1327                $var=!$var;
1328
1329                if ($action != 'editline' || GETPOST('rowid') != $objp->rowid)
1330                {
1331                    print '<tr '.$bc[$var].' valign="top">';
1332                    // Libelle
1333                    if ($objp->fk_product > 0)
1334                    {
1335                        print '<td>';
1336                        $productstatic->id=$objp->fk_product;
1337                        $productstatic->type=$objp->ptype;
1338                        $productstatic->ref=$objp->pref;
1339                        $text = $productstatic->getNomUrl(1,'',20);
1340                        if ($objp->label)
1341                        {
1342                        	$text .= ' - ';
1343                        	$productstatic->ref=$objp->label;
1344                        	$text .= $productstatic->getNomUrl(0,'',16);
1345                        }
1346                        $description = $objp->description;
1347
1348	                    // Add description in form
1349						if (! empty($conf->global->PRODUIT_DESC_IN_FORM))
1350						{
1351							$text .= (! empty($objp->description) && $objp->description!=$objp->product_label)?'<br>'.dol_htmlentitiesbr($objp->description):'';
1352							$description = '';	// Already added into main visible desc
1353						}
1354
1355                        echo $form->textwithtooltip($text,$description,3,'','',$cursorline,0,(!empty($line->fk_parent_line)?img_picto('', 'rightarrow'):''));
1356
1357                        print '</td>';
1358                    }
1359                    else
1360					{
1361                        print '<td>'.dol_htmlentitiesbr($objp->description)."</td>\n";
1362                    }
1363                    // TVA
1364                    print '<td align="center">'.vatrate($objp->tva_tx,'%',$objp->info_bits).'</td>';
1365                    // Prix
1366                    print '<td align="right">'.($objp->subprice != '' ? price($objp->subprice) : '')."</td>\n";
1367                    // Quantite
1368                    print '<td align="center">'.$objp->qty.'</td>';
1369	                // Unit
1370	                if($conf->global->PRODUCT_USE_UNITS) print '<td align="left">'.$langs->trans($object->lines[$cursorline-1]->getLabelOfUnit()).'</td>';
1371                    // Remise
1372                    if ($objp->remise_percent > 0)
1373                    {
1374                        print '<td align="right" '.$bc[$var].'>'.$objp->remise_percent."%</td>\n";
1375                    }
1376                    else
1377                    {
1378                        print '<td>&nbsp;</td>';
1379                    }
1380
1381					// Margin
1382					if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print '<td align="right" class="nowrap">'.price($objp->pa_ht).'</td>';
1383
1384                    // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme)
1385                    print '<td align="right" class="nowrap">';
1386                    if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0))
1387                    {
1388                        print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=move&amp;rowid='.$objp->rowid.'">';
1389                        print img_picto($langs->trans("MoveToAnotherContract"),'uparrow');
1390                        print '</a>';
1391                    }
1392                    else {
1393                        print '&nbsp;';
1394                    }
1395                    if ($user->rights->contrat->creer && ($object->statut >= 0))
1396                    {
1397                        print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=editline&amp;rowid='.$objp->rowid.'">';
1398                        print img_edit();
1399                        print '</a>';
1400                    }
1401                    else {
1402                        print '&nbsp;';
1403                    }
1404                    if ( $user->rights->contrat->creer && ($object->statut >= 0))
1405                    {
1406                        print '&nbsp;';
1407                        print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=deleteline&amp;rowid='.$objp->rowid.'">';
1408                        print img_delete();
1409                        print '</a>';
1410                    }
1411                    print '</td>';
1412
1413                    print "</tr>\n";
1414
1415                    // Dates de en service prevues et effectives
1416                    if ($objp->subprice >= 0)
1417                    {
1418	                    $colspan = 6;
1419
1420	                    if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) {
1421		                    $colspan = 8;
1422	                    } elseif ($conf->margin->enabled || $conf->global->PRODUCT_USE_UNITS) {
1423		                    $colspan = 7;
1424	                    }
1425
1426                        print '<tr '.$bc[$var].'>';
1427                        print '<td colspan="'.$colspan.'">';
1428
1429                        // Date planned
1430                        print $langs->trans("DateStartPlanned").': ';
1431                        if ($objp->date_debut)
1432                        {
1433                            print dol_print_date($db->jdate($objp->date_debut));
1434                            // Warning si date prevu passee et pas en service
1435                            if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) { print " ".img_warning($langs->trans("Late")); }
1436                        }
1437                        else print $langs->trans("Unknown");
1438                        print ' &nbsp;-&nbsp; ';
1439                        print $langs->trans("DateEndPlanned").': ';
1440                        if ($objp->date_fin)
1441                        {
1442                            print dol_print_date($db->jdate($objp->date_fin));
1443                            if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) { print " ".img_warning($langs->trans("Late")); }
1444                        }
1445                        else print $langs->trans("Unknown");
1446
1447                        print '</td>';
1448                        print '</tr>';
1449                    }
1450
1451
1452                    //Display lines extrafields
1453                    if (is_array($extralabelslines) && count($extralabelslines)>0) {
1454                    	print '<tr '.$bc[$var].'>';
1455                    	$line = new ContratLigne($db);
1456                    	$line->fetch_optionals($objp->rowid,$extralabelslines);
1457                    	print $line->showOptionals($extrafieldsline, 'view', array('style'=>$bc[$var], 'colspan'=>$colspan));
1458                    	print '</tr>';
1459                    }
1460                }
1461                // Ligne en mode update
1462                else
1463              {
1464                    // Ligne carac
1465                    print "<tr ".$bc[$var].">";
1466                    print '<td>';
1467                    if ($objp->fk_product)
1468                    {
1469                        $productstatic->id=$objp->fk_product;
1470                        $productstatic->type=$objp->ptype;
1471                        $productstatic->ref=$objp->pref;
1472                        print $productstatic->getNomUrl(1,'',20);
1473                        print $objp->label?' - '.dol_trunc($objp->label,16):'';
1474                        print '<br>';
1475                    }
1476                    else
1477                    {
1478                        print $objp->label?$objp->label.'<br>':'';
1479                    }
1480
1481                    // editeur wysiwyg
1482                    require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1483                    $nbrows=ROWS_2;
1484                    if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT;
1485                    $enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0);
1486                    $doleditor=new DolEditor('product_desc',$objp->description,'',92,'dolibarr_details','',false,true,$enable,$nbrows,70);
1487                    $doleditor->Create();
1488
1489                    print '</td>';
1490                    print '<td align="right">';
1491                    print $form->load_tva("eltva_tx",$objp->tva_tx,$mysoc,$object->thirdparty);
1492                    print '</td>';
1493                    print '<td align="right"><input size="5" type="text" name="elprice" value="'.price($objp->subprice).'"></td>';
1494                    print '<td align="center"><input size="2" type="text" name="elqty" value="'.$objp->qty.'"></td>';
1495                    if ($conf->global->PRODUCT_USE_UNITS)
1496                    {
1497                    	print '<td align="left">';
1498                    	print $form->selectUnits($objp->fk_unit, "unit");
1499                    	print '</td>';
1500                    }
1501                    print '<td align="right" class="nowrap"><input size="1" type="text" name="elremise_percent" value="'.$objp->remise_percent.'">%</td>';
1502					if (! empty($usemargins))
1503					{
1504					    print '<td align="right">';
1505					    if ($objp->fk_product) print '<select id="fournprice" name="fournprice"></select>';
1506						print '<input id="buying_price" type="text" size="5" name="buying_price" value="'.price($objp->pa_ht,0,'',0).'"></td>';
1507					}
1508                    print '<td align="center" rowspan="2" valign="middle"><input type="submit" class="button" name="save" value="'.$langs->trans("Modify").'">';
1509                    print '<br><input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
1510                    print '</td>';
1511
1512                    $colspan=5;
1513                    if (! empty($conf->margin->enabled) && ! empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++;
1514	              if($conf->global->PRODUCT_USE_UNITS) $colspan++;
1515
1516                    // Ligne dates prevues
1517                    print "<tr ".$bc[$var].">";
1518                    print '<td colspan="'.$colspan.'">';
1519                    print $langs->trans("DateStartPlanned").' ';
1520                    $form->select_date($db->jdate($objp->date_debut),"date_start_update",$usehm,$usehm,($db->jdate($objp->date_debut)>0?0:1),"update");
1521                    print ' &nbsp;&nbsp;'.$langs->trans("DateEndPlanned").' ';
1522                    $form->select_date($db->jdate($objp->date_fin),"date_end_update",$usehm,$usehm,($db->jdate($objp->date_fin)>0?0:1),"update");
1523                    print '</td>';
1524
1525                    if (is_array($extralabelslines) && count($extralabelslines)>0) {
1526                    	print '<tr '.$bc[$var].'>';
1527                    	$line = new ContratLigne($db);
1528                    	$line->fetch_optionals($objp->rowid,$extralabelslines);
1529                    	print $line->showOptionals($extrafieldsline, 'edit', array('style'=>$bc[$var], 'colspan'=>$colspan));
1530                    	print '</tr>';
1531                    }
1532
1533                    print '</tr>';
1534                }
1535
1536                $db->free($result);
1537            }
1538            else
1539			{
1540                dol_print_error($db);
1541            }
1542
1543            if ($object->statut > 0)
1544            {
1545                print '<tr '.$bc[$var].'>';
1546                print '<td colspan="'.($conf->margin->enabled?7:6).'"><hr></td>';
1547                print "</tr>\n";
1548            }
1549
1550            print "</table>";
1551
1552            print "</form>\n";
1553
1554
1555            /*
1556             * Confirmation to delete service line of contract
1557             */
1558            if ($action == 'deleteline' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid'))
1559            {
1560                print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("DeleteContractLine"),$langs->trans("ConfirmDeleteContractLine"),"confirm_deleteline",'',0,1);
1561                if ($ret == 'html') print '<table class="notopnoleftnoright" width="100%"><tr '.$bc[$var].' height="6"><td></td></tr></table>';
1562            }
1563
1564            /*
1565             * Confirmation to move service toward another contract
1566             */
1567            if ($action == 'move' && ! $_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline-1]->id == GETPOST('rowid'))
1568            {
1569                $arraycontractid=array();
1570                foreach($arrayothercontracts as $contractcursor)
1571                {
1572                    $arraycontractid[$contractcursor->id]=$contractcursor->ref;
1573                }
1574                //var_dump($arraycontractid);
1575                // Cree un tableau formulaire
1576                $formquestion=array(
1577				'text' => $langs->trans("ConfirmMoveToAnotherContractQuestion"),
1578                array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid));
1579
1580                $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'),$langs->trans("MoveToAnotherContract"),$langs->trans("ConfirmMoveToAnotherContract"),"confirm_move",$formquestion);
1581                print '<table class="notopnoleftnoright" width="100%"><tr '.$bc[$var].' height="6"><td></td></tr></table>';
1582            }
1583
1584            /*
1585             * Confirmation de la validation activation
1586             */
1587            if ($action == 'active' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1588            {
1589                $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1590                $dateactend   = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1591                $comment      = GETPOST('comment');
1592                $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment),$langs->trans("ActivateService"),$langs->trans("ConfirmActivateService",dol_print_date($dateactstart,"%A %d %B %Y")),"confirm_active", '', 0, 1);
1593                print '<table class="notopnoleftnoright" width="100%"><tr '.$bc[$var].' height="6"><td></td></tr></table>';
1594            }
1595
1596            /*
1597             * Confirmation de la validation fermeture
1598             */
1599            if ($action == 'closeline' && ! $_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1600            {
1601                $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1602                $dateactend   = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1603                $comment      = GETPOST('comment');
1604                $form->form_confirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne')."&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);
1605                print '<table class="notopnoleftnoright" width="100%"><tr '.$bc[$var].' height="6"><td></td></tr></table>';
1606            }
1607
1608
1609            // Area with status and activation info of line
1610            if ($object->statut > 0)
1611            {
1612                print '<table class="notopnoleftnoright tableforservicepart2" width="100%">';
1613
1614                print '<tr '.$bc[$var].'>';
1615                print '<td>'.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline-1]->getLibStatut(4).'</td>';
1616                print '<td width="30" align="right">';
1617                if ($user->societe_id == 0)
1618                {
1619                    if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline')
1620                    {
1621                        $tmpaction='activateline';
1622                        if ($objp->statut == 4) $tmpaction='unactivateline';
1623                        print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline-1]->id.'&amp;action='.$tmpaction.'">';
1624                        print img_edit();
1625                        print '</a>';
1626                    }
1627                }
1628                print '</td>';
1629                print "</tr>\n";
1630
1631                print '<tr '.$bc[$var].'>';
1632
1633                print '<td>';
1634                // Si pas encore active
1635                if (! $objp->date_debut_reelle) {
1636                    print $langs->trans("DateStartReal").': ';
1637                    if ($objp->date_debut_reelle) print dol_print_date($objp->date_debut_reelle);
1638                    else print $langs->trans("ContractStatusNotRunning");
1639                }
1640                // Si active et en cours
1641                if ($objp->date_debut_reelle && ! $objp->date_fin_reelle) {
1642                    print $langs->trans("DateStartReal").': ';
1643                    print dol_print_date($objp->date_debut_reelle);
1644                }
1645                // Si desactive
1646                if ($objp->date_debut_reelle && $objp->date_fin_reelle) {
1647                    print $langs->trans("DateStartReal").': ';
1648                    print dol_print_date($objp->date_debut_reelle);
1649                    print ' &nbsp;-&nbsp; ';
1650                    print $langs->trans("DateEndReal").': ';
1651                    print dol_print_date($objp->date_fin_reelle);
1652                }
1653                if (! empty($objp->comment)) print "<br>".$objp->comment;
1654                print '</td>';
1655
1656                print '<td align="center">&nbsp;</td>';
1657
1658                print '</tr>';
1659                print '</table>';
1660            }
1661
1662            if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1663            {
1664                /**
1665                 * Activer la ligne de contrat
1666                 */
1667                print '<form name="active" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.GETPOST('ligne').'&amp;action=active" method="post">';
1668                print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1669
1670                print '<table class="notopnoleftnoright tableforservicepart2" width="100%">';
1671
1672                // Definie date debut et fin par defaut
1673                $dateactstart = $objp->date_debut;
1674                if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1675                elseif (! $dateactstart) $dateactstart = time();
1676
1677                $dateactend = $objp->date_fin;
1678                if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1679                elseif (! $dateactend)
1680                {
1681                    if ($objp->fk_product > 0)
1682                    {
1683                        $product=new Product($db);
1684                        $product->fetch($objp->fk_product);
1685                        $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
1686                    }
1687                }
1688
1689                print '<tr '.$bc[$var].'><td>'.$langs->trans("DateServiceActivate").'</td><td>';
1690                print $form->select_date($dateactstart,'',$usehm,$usehm,'',"active");
1691                print '</td>';
1692
1693                print '<td>'.$langs->trans("DateEndPlanned").'</td><td>';
1694                print $form->select_date($dateactend,"end",$usehm,$usehm,'',"active");
1695                print '</td>';
1696
1697                print '<td align="center" rowspan="2" valign="middle">';
1698                print '<input type="submit" class="button" name="activate" value="'.$langs->trans("Activate").'"><br>';
1699                print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
1700                print '</td>';
1701
1702                print '</tr>';
1703
1704                print '<tr '.$bc[$var].'><td>'.$langs->trans("Comment").'</td><td colspan="'.($conf->margin->enabled?4:3).'"><input size="80" type="text" name="comment" value="'.$_POST["comment"].'"></td></tr>';
1705
1706                print '</table>';
1707
1708                print '</form>';
1709            }
1710
1711            if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline-1]->id == GETPOST('ligne'))
1712            {
1713                /**
1714                 * Desactiver la ligne de contrat
1715                 */
1716                print '<form name="closeline" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline-1]->id.'&amp;action=closeline" method="post">';
1717
1718                print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1719
1720                print '<table class="noborder tableforservicepart2" width="100%">';
1721
1722                // Definie date debut et fin par defaut
1723                $dateactstart = $objp->date_debut_reelle;
1724                if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
1725                elseif (! $dateactstart) $dateactstart = time();
1726
1727                $dateactend = $objp->date_fin_reelle;
1728                if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
1729                elseif (! $dateactend)
1730                {
1731                    if ($objp->fk_product > 0)
1732                    {
1733                        $product=new Product($db);
1734                        $product->fetch($objp->fk_product);
1735                        $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
1736                    }
1737                }
1738                $now=dol_now();
1739                if ($dateactend > $now) $dateactend=$now;
1740
1741                print '<tr '.$bc[$var].'><td colspan="2">';
1742                if ($objp->statut >= 4)
1743                {
1744                    if ($objp->statut == 4)
1745                    {
1746                        print $langs->trans("DateEndReal").' ';
1747                        $form->select_date($dateactend,"end",$usehm,$usehm,($objp->date_fin_reelle>0?0:1),"closeline",1,1);
1748                    }
1749                }
1750                print '</td>';
1751
1752                print '<td align="right" rowspan="2"><input type="submit" class="button" name="close" value="'.$langs->trans("Close").'"><br>';
1753                print '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
1754                print '</td></tr>';
1755
1756                print '<tr '.$bc[$var].'><td>'.$langs->trans("Comment").'</td><td><input size="70" type="text" class="flat" name="comment" value="'.GETPOST('comment').'"></td></tr>';
1757                print '</table>';
1758
1759                print '</form>';
1760            }
1761
1762            $cursorline++;
1763        }
1764
1765		// Form to add new line
1766        if ($user->rights->contrat->creer && ($object->statut == 0))
1767        {
1768        	$dateSelector=1;
1769
1770			print "\n";
1771			print '	<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline')?'#add':'#line_'.GETPOST('lineid')).'" method="POST">
1772			<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">
1773			<input type="hidden" name="action" value="'.(($action != 'editline')?'addline':'updateligne').'">
1774			<input type="hidden" name="mode" value="">
1775			<input type="hidden" name="id" value="'.$object->id.'">
1776			';
1777
1778			print '<br>';
1779            print '<table id="tablelines" class="noborder noshadow" width="100%">';	// Array with (n*2)+1 lines
1780
1781            // Trick to not show product entries
1782            $savproductenabled=$conf->product->enabled;
1783            if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) $conf->product->enabled = 0;
1784
1785        	// Form to add new line
1786       		if ($action != 'editline')
1787			{
1788				$var = true;
1789
1790				// Add free products/services
1791				$object->formAddObjectLine(1, $mysoc, $soc);
1792
1793				$parameters = array();
1794				$reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1795			}
1796
1797        	// Restore correct setup
1798        	$conf->product->enabled = $savproductenabled;
1799
1800            print '</table>';
1801
1802            print '</form>';
1803        }
1804
1805		dol_fiche_end();
1806
1807
1808        /*
1809         * Buttons
1810         */
1811
1812        if ($user->societe_id == 0)
1813        {
1814            print '<div class="tabsAction">';
1815
1816            $parameters=array();
1817            $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
1818
1819            if ($object->statut == 0 && $nbofservices)
1820            {
1821                if ($user->rights->contrat->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid">'.$langs->trans("Validate").'</a></div>';
1822                else print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("Validate").'</a></div>';
1823            }
1824
1825            if (! empty($conf->facture->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices)
1826            {
1827                $langs->load("bills");
1828                if ($user->rights->facture->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id.'">'.$langs->trans("CreateBill").'</a></div>';
1829                else print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateBill").'</a></div>';
1830            }
1831
1832            if ($object->nbofservicesclosed < $nbofservices)
1833            {
1834                //if (! $numactive)
1835                //{
1836                print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=close">'.$langs->trans("CloseAllContracts").'</a></div>';
1837                //}
1838                //else
1839                //{
1840                //	print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.$langs->trans("CloseRefusedBecauseOneServiceActive").'">'.$langs->trans("Close").'</a></div>';
1841                //}
1842            }
1843
1844            // On peut supprimer entite si
1845            // - Droit de creer + mode brouillon (erreur creation)
1846            // - Droit de supprimer
1847            if (($user->rights->contrat->creer && $object->statut == 0) || $user->rights->contrat->supprimer)
1848            {
1849                print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete">'.$langs->trans("Delete").'</a></div>';
1850            }
1851            else
1852            {
1853            	print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("Delete").'</a></div>';
1854            }
1855
1856            print "</div>";
1857        }
1858
1859        print '<div class="fichecenter"><div class="fichehalfleft">';
1860
1861        /*
1862         * Documents generes
1863        */
1864        $filename = dol_sanitizeFileName($object->ref);
1865        $filedir = $conf->contrat->dir_output . "/" . dol_sanitizeFileName($object->ref);
1866        $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id;
1867        $genallowed = $user->rights->contrat->creer;
1868        $delallowed = $user->rights->contrat->supprimer;
1869
1870        $var = true;
1871
1872        $somethingshown = $formfile->show_documents('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang);
1873
1874		// Linked object block
1875		$somethingshown = $form->showLinkedObjectBlock($object);
1876
1877		// Show links to link elements
1878		$linktoelem = $form->showLinkToObjectBlock($object);
1879		if ($linktoelem) print '<br>'.$linktoelem;
1880
1881
1882        print '</div><div class="fichehalfright"><div class="ficheaddleft">';
1883
1884        print '</div></div></div>';
1885    }
1886}
1887
1888
1889llxFooter();
1890
1891$db->close();
1892?>
1893
1894<?php
1895if ($conf->margin->enabled && $action == 'editline')
1896{
1897?>
1898
1899<script type="text/javascript">
1900$(document).ready(function() {
1901  var idprod = $("input[name='idprod']").val();
1902  var fournprice = $("input[name='fournprice']").val();
1903  if (idprod > 0) {
1904	  $.post('<?php echo DOL_URL_ROOT; ?>/fourn/ajax/getSupplierPrices.php', {'idprod': idprod}, function(data) {
1905	    if (data.length > 0) {
1906	      var options = '';
1907	      var trouve=false;
1908	      $(data).each(function() {
1909	        options += '<option value="'+this.id+'" price="'+this.price+'"';
1910	        if (fournprice > 0) {
1911		        if (this.id == fournprice) {
1912		          options += ' selected';
1913		          $("#buying_price").val(this.price);
1914		          trouve = true;
1915		        }
1916	        }
1917	        options += '>'+this.label+'</option>';
1918	      });
1919	      options += '<option value=null'+(trouve?'':' selected')+'><?php echo $langs->trans("InputPrice"); ?></option>';
1920	      $("#fournprice").html(options);
1921	      if (trouve) {
1922	        $("#buying_price").hide();
1923	        $("#fournprice").show();
1924	      }
1925	      else {
1926	        $("#buying_price").show();
1927	      }
1928	      $("#fournprice").change(function() {
1929	        var selval = $(this).find('option:selected').attr("price");
1930	        if (selval)
1931	          $("#buying_price").val(selval).hide();
1932	        else
1933	          $('#buying_price').show();
1934	      });
1935	    }
1936	    else {
1937	      $("#fournprice").hide();
1938	      $('#buying_price').show();
1939	    }
1940	  },
1941	  'json');
1942	}
1943    else {
1944      $("#fournprice").hide();
1945      $('#buying_price').show();
1946    }
1947});
1948</script>
1949
1950<?php
1951}