dolibarr 24.0.3
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-2026 Frédéric France <frederic.france@free.fr>
13 * Copyright (C) 2023-2026 Charlene Benke <charlene@patas-monkey.com>
14 * Copyright (C) 2023 Nick Fragoulis
15 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
16 * Copyright (C) 2024-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
17 * Copyright (C) 2025 William Mead <william@m34d.com>
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 3 of the License, or
22 * (at your option) any later version.
23 *
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 * GNU General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License
30 * along with this program. If not, see <https://www.gnu.org/licenses/>.
31 */
32
39require "../main.inc.php";
50require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
51require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
52require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php';
53require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
54require_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
55require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
56require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
57require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
58require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
59require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
60if (isModEnabled("propal")) {
61 require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
62}
63if (isModEnabled('project')) {
64 require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
65 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
66}
67
68// Load translation files required by the page
69$langs->loadLangs(array("contracts", "orders", "companies", "bills", "products", 'compta', 'propal'));
70
71$action = GETPOST('action', 'aZ09');
72$confirm = GETPOST('confirm', 'alpha');
73$cancel = GETPOST('cancel', 'alpha');
74$backtopage = GETPOST('backtopage', 'alpha');
75$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha');
76
77$socid = GETPOSTINT('socid');
78$id = GETPOSTINT('id');
79$ref = GETPOST('ref', 'alpha');
80$origin = GETPOST('origin', 'alpha');
81$originid = GETPOSTINT('originid');
82$idline = GETPOSTINT('elrowid') ? GETPOSTINT('elrowid') : GETPOSTINT('rowid');
83$attribute = GETPOST('attribute', 'aZ09');
84
85// PDF
86$hidedetails = (GETPOSTINT('hidedetails') ? GETPOSTINT('hidedetails') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0));
87$hidedesc = (GETPOSTINT('hidedesc') ? GETPOSTINT('hidedesc') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0));
88$hideref = (GETPOSTINT('hideref') ? GETPOSTINT('hideref') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0));
89
90
91$datecontrat = '';
92$moreparam = '';
93$note_public = '';
94$note_private = '';
95$usehm = getDolGlobalInt('MAIN_USE_HOURMIN_IN_DATE_RANGE');
96
97// Security check
98if ($user->socid) {
99 $socid = $user->socid;
100}
101
102// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
103$hookmanager->initHooks(array('contractcard', 'globalcard'));
104
105$object = new Contrat($db);
106
107$ret = 0;
108$pu_ht = null; // Init for static analysis
109$pu_ttc = null; // Init for static analysis
110
111// Load object
112if ($id > 0 || !empty($ref) && $action != 'add') {
113 $ret = $object->fetch($id, $ref);
114 if ($ret > 0) {
115 $ret = $object->fetch_thirdparty();
116 }
117 if ($ret < 0) {
118 dol_print_error(null, $object->error);
119 }
120}
121
122// fetch optionals attributes and labels
123$extrafields->fetch_name_optionals_label($object->table_element);
124
125// fetch optionals attributes lines and labels
126$extralabelslines = $extrafields->fetch_name_optionals_label($object->table_element_line);
127
128$permissionnote = $user->hasRight('contrat', 'creer'); // Used by the include of actions_setnotes.inc.php
129$permissiondellink = $user->hasRight('contrat', 'creer'); // Used by the include of actions_dellink.inc.php
130$permissiontodelete = ($user->hasRight('contrat', 'creer') && $object->status == $object::STATUS_DRAFT) || $user->hasRight('contrat', 'supprimer');
131$permissiontoadd = $user->hasRight('contrat', 'creer'); // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
132$permissiontoedit = $permissiontoadd;
133$permissiontoactivate = $user->hasRight('contrat', 'activer');
134$permissiontodisable = $user->hasRight('contrat', 'desactiver'); // TODO use same than $permissiontoactivate
135$permissiontoeditextra = $permissiontoadd;
136if (GETPOST('attribute', 'aZ09') && isset($extrafields->attributes[$object->table_element]['perms'][GETPOST('attribute', 'aZ09')])) {
137 // For action 'update_extras', is there a specific permission set for the attribute to update
138 $permissiontoeditextra = dol_eval((string) $extrafields->attributes[$object->table_element]['perms'][GETPOST('attribute', 'aZ09')]);
139}
140
141$error = 0;
142
143// Security check
144$result = restrictedArea($user, 'contrat', $object->id);
145
146if (!($object->id > 0) && ($action == 'view' || $action == '')) {
148}
149
150
151/*
152 * Actions
153 */
154
155$parameters = array('socid' => $socid);
156$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
157if ($reshook < 0) {
158 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
159}
160if (empty($reshook)) {
161 $backurlforlist = dolBuildUrl(DOL_URL_ROOT . '/contrat/list.php');
162
163 if (empty($backtopage) || ($cancel && empty($id))) {
164 if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
165 if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
166 $backtopage = $backurlforlist;
167 } else {
168 $backtopage = dolBuildUrl(DOL_URL_ROOT . '/contrat/card.php', ['id'=> ((!empty($id) && $id > 0) ? $id : '__ID__')]);
169 }
170 }
171 }
172
173 if ($cancel) {
174 if (!empty($backtopageforcancel)) {
175 header("Location: ".$backtopageforcancel);
176 exit;
177 } elseif (!empty($backtopage)) {
178 header("Location: ".$backtopage);
179 exit;
180 }
181 $action = '';
182 }
183
184 include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once
185
186 include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be 'include', not 'include_once'
187
188 include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be 'include', not 'include_once'
189
190 if ($action == 'confirm_active' && $confirm == 'yes' && $permissiontoactivate) {
191 $date_start = '';
192 $date_end = '';
193 if (GETPOST('startmonth') && GETPOST('startday') && GETPOST('startyear')) {
194 $date_start = dol_mktime(GETPOSTINT('starthour'), GETPOSTINT('startmin'), 0, GETPOSTINT('startmonth'), GETPOSTINT('startday'), GETPOSTINT('startyear'));
195 }
196 if (GETPOST('endmonth') && GETPOST('endday') && GETPOST('endyear')) {
197 $date_end = dol_mktime(GETPOSTINT('endhour'), GETPOSTINT('endmin'), 0, GETPOSTINT('endmonth'), GETPOSTINT('endday'), GETPOSTINT('endyear'));
198 }
199
200 $result = $object->active_line($user, GETPOSTINT('ligne'), $date_start, $date_end, GETPOST('comment'));
201
202 if ($result > 0) {
203 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
204 exit;
205 } else {
206 setEventMessages($object->error, $object->errors, 'errors');
207 }
208 } elseif ($action == 'confirm_sign' && $confirm == 'yes' && $user->hasRight('contract', 'creer')) {
209 $result = $object->setSignedStatus($user, GETPOSTINT('signed_status'), 0, 'CONTRACT_MODIFY');
210 if ($result >= 0) {
211 header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id);
212 exit;
213 } else {
214 setEventMessages($object->error, $object->errors, 'errors');
215 }
216 } elseif ($action == 'confirm_unsign' && $confirm == 'yes' && $user->hasRight('contract', 'creer')) {
217 $result = $object->setSignedStatus($user, Contrat::$SIGNED_STATUSES['STATUS_NO_SIGNATURE'], 0, 'CONTRACT_MODIFY');
218 if ($result >= 0) {
219 header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id);
220 exit;
221 } else {
222 setEventMessages($object->error, $object->errors, 'errors');
223 }
224 } elseif ($action == 'confirm_closeline' && $confirm == 'yes' && $permissiontodisable) {
225 $date_end = '';
226 if (GETPOST('endmonth') && GETPOST('endday') && GETPOST('endyear')) {
227 $date_end = dol_mktime(GETPOSTINT('endhour'), GETPOSTINT('endmin'), 0, GETPOSTINT('endmonth'), GETPOSTINT('endday'), GETPOSTINT('endyear'));
228 }
229 if (!$date_end) {
230 $error++;
231 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors');
232 }
233 if (!$error) {
234 $result = $object->close_line($user, GETPOSTINT('ligne'), $date_end, urldecode(GETPOST('comment')));
235 if ($result > 0) {
236 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
237 exit;
238 } else {
239 setEventMessages($object->error, $object->errors, 'errors');
240 }
241 }
242 }
243
244 if (GETPOST('mode') == 'predefined') {
245 $date_start = '';
246 $date_end = '';
247 if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear')) {
248 $date_start = dol_mktime(GETPOSTINT('date_starthour'), GETPOSTINT('date_startmin'), 0, GETPOSTINT('date_startmonth'), GETPOSTINT('date_startday'), GETPOSTINT('date_startyear'));
249 }
250 if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear')) {
251 $date_end = dol_mktime(GETPOSTINT('date_endhour'), GETPOSTINT('date_endmin'), 0, GETPOSTINT('date_endmonth'), GETPOSTINT('date_endday'), GETPOSTINT('date_endyear'));
252 }
253 }
254
255 // Param dates
256 $date_start_update = '';
257 $date_end_update = '';
258 $date_start_real_update = '';
259 $date_end_real_update = '';
260 if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear')) {
261 $date_start_update = dol_mktime(GETPOSTINT('date_start_updatehour'), GETPOSTINT('date_start_updatemin'), 0, GETPOSTINT('date_start_updatemonth'), GETPOSTINT('date_start_updateday'), GETPOSTINT('date_start_updateyear'));
262 }
263 if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear')) {
264 $date_end_update = dol_mktime(GETPOSTINT('date_end_updatehour'), GETPOSTINT('date_end_updatemin'), 0, GETPOSTINT('date_end_updatemonth'), GETPOSTINT('date_end_updateday'), GETPOSTINT('date_end_updateyear'));
265 }
266 if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear')) {
267 $date_start_real_update = dol_mktime(GETPOSTINT('date_start_real_updatehour'), GETPOSTINT('date_start_real_updatemin'), 0, GETPOSTINT('date_start_real_updatemonth'), GETPOSTINT('date_start_real_updateday'), GETPOSTINT('date_start_real_updateyear'));
268 }
269 if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear')) {
270 $date_end_real_update = dol_mktime(GETPOSTINT('date_end_real_updatehour'), GETPOSTINT('date_end_real_updatemin'), 0, GETPOSTINT('date_end_real_updatemonth'), GETPOSTINT('date_end_real_updateday'), GETPOSTINT('date_end_real_updateyear'));
271 }
272 if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear')) {
273 $datecontrat = dol_mktime(GETPOSTINT('rehour'), GETPOSTINT('remin'), 0, GETPOSTINT('remonth'), GETPOSTINT('reday'), GETPOSTINT('reyear'));
274 }
275
276 // Add contract
277 if ($action == 'add' && $user->hasRight('contrat', 'creer')) {
278 // Check
279 if (empty($datecontrat)) {
280 $error++;
281 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
282 $action = 'create';
283 }
284
285 if ($socid < 1) {
286 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors');
287 $action = 'create';
288 $error++;
289 }
290
291 // Fill array 'array_options' with data from add form
292 $ret = $extrafields->setOptionalsFromPost(null, $object);
293 if ($ret < 0) {
294 $error++;
295 $action = 'create';
296 }
297
298 if (!$error) {
299 $object->socid = $socid;
300 $object->date_contrat = $datecontrat;
301
302 $object->commercial_suivi_id = GETPOSTINT('commercial_suivi_id');
303 $object->commercial_signature_id = GETPOSTINT('commercial_signature_id');
304
305 $object->note_private = GETPOST('note_private', 'alpha');
306 $object->note_public = GETPOST('note_public', 'alpha');
307 $object->fk_project = GETPOSTINT('projectid');
308 $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
309 $object->ref = GETPOST('ref', 'alpha');
310 $object->ref_customer = GETPOST('ref_customer', 'alpha');
311 $object->ref_supplier = GETPOST('ref_supplier', 'alpha');
312
313 // If creation from another object of another module (Example: origin=propal, originid=1)
314 if (!empty($origin) && !empty($originid)) {
315 // Parse element/subelement (ex: project_task)
316 $element = $subelement = $origin;
317 $regs = array();
318 if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
319 $element = $regs[1];
320 $subelement = $regs[2];
321 }
322
323 // For compatibility
324 $classname = '';
325 if ($element == 'order') {
326 $element = $subelement = 'commande';
327 }
328 if ($element == 'propal') {
329 $element = 'comm/propal';
330 $subelement = 'propal';
331 }
332 if ($element == 'invoice' || $element == 'facture') {
333 $element = 'compta/facture';
334 $subelement = 'facture';
335 }
336 if ($element == 'facturerec' || $element == 'facture_rec') {
337 // FactureRec lives in compta/facture/class/facture-rec.class.php (#34775)
338 $element = 'compta/facture';
339 $subelement = 'facture-rec';
340 $classname = 'FactureRec';
341 }
342 if ($element == 'facture_fourn_rec' || $element == 'invoice_supplier_rec') {
343 $element = 'fourn';
344 $subelement = 'fournisseur.facture-rec';
345 $classname = 'FactureFournisseurRec';
346 }
347
348 $object->origin = $origin;
349 $object->origin_id = $originid;
350
351 // Possibility to add external linked objects with hooks
352 $object->linked_objects[$object->origin] = $object->origin_id;
353 if (GETPOSTISARRAY('other_linked_objects')) {
354 $object->linked_objects = array_merge($object->linked_objects, GETPOST('other_linked_objects', 'array:int'));
355 }
356
357 $id = $object->create($user);
358 if ($id > 0) {
359 dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
360
361 if (empty($classname)) {
362 $classname = ucfirst($subelement);
363 }
364 $srcobject = new $classname($db);
365 '@phan-var-force Commande|Propal|Facture $srcobject'; // Can be other class, but CommonObject is too Generic
366
367 dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
368 $result = $srcobject->fetch($object->origin_id);
369 if ($result > 0) {
370 $srcobject->fetch_thirdparty();
371 $lines = $srcobject->lines;
372 if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
373 $srcobject->fetch_lines();
374 $lines = $srcobject->lines;
375 }
376
377 $fk_parent_line = 0;
378 $num = count($lines);
379 $rang = 0;
380
381 for ($i = 0; $i < $num; $i++) {
382 $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
383
384 if ($product_type == 1 || (getDolGlobalString('CONTRACT_SUPPORT_PRODUCTS') && in_array($product_type, array(0, 1)))) { // TODO Exclude also deee
385 // predefined service
386 if ($lines[$i]->fk_product > 0) {
387 // Define output language
388 if (getDolGlobalInt('MAIN_MULTILANGS') && getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
389 $prod = new Product($db);
390 $prod->id = $lines[$i]->fk_product;
391 $prod->getMultiLangs();
392
393 $outputlangs = $langs;
394 $newlang = '';
395 if (/* empty($newlang) && */ GETPOST('lang_id', 'aZ09')) {
396 $newlang = GETPOST('lang_id', 'aZ09');
397 }
398 if (empty($newlang)) {
399 $newlang = $srcobject->thirdparty->default_lang;
400 }
401 if (!empty($newlang)) {
402 $outputlangs = new Translate("", $conf);
403 $outputlangs->setDefaultLang($newlang);
404 }
405
406 $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["libelle"])) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $lines[$i]->product_label;
407 } else {
408 $label = $lines[$i]->product_label;
409 }
410 $desc = ($lines[$i]->desc && $lines[$i]->desc != $lines[$i]->label) ? dol_htmlentitiesbr($lines[$i]->desc) : '';
411 } else {
412 $desc = dol_htmlentitiesbr($lines[$i]->desc);
413 }
414
415 // Extrafields
416 $array_options = array();
417 // For avoid conflicts if trigger used
418 if (method_exists($lines[$i], 'fetch_optionals')) {
419 $lines[$i]->fetch_optionals();
420 $array_options = $lines[$i]->array_options;
421 }
422
423 $txtva = $lines[$i]->vat_src_code ? $lines[$i]->tva_tx.' ('.$lines[$i]->vat_src_code.')' : $lines[$i]->tva_tx;
424
425 // View third's localtaxes for now
426 $localtax1_tx = get_localtax($txtva, 1, $object->thirdparty);
427 $localtax2_tx = get_localtax($txtva, 2, $object->thirdparty);
428
429 $result = $object->addline(
430 $desc,
431 $lines[$i]->subprice,
432 $lines[$i]->qty,
433 $txtva,
434 $localtax1_tx,
435 $localtax2_tx,
436 $lines[$i]->fk_product,
437 $lines[$i]->remise_percent,
438 $lines[$i]->date_start,
439 $lines[$i]->date_end,
440 'HT',
441 0,
442 $lines[$i]->info_bits,
443 $lines[$i]->fk_fournprice,
444 $lines[$i]->pa_ht,
445 $array_options,
446 (int) $lines[$i]->fk_unit,
447 $rang++
448 );
449
450 if ($result < 0) {
451 $error++;
452 break;
453 }
454 }
455 }
456 } else {
457 setEventMessages($srcobject->error, $srcobject->errors, 'errors');
458 $error++;
459 }
460
461 // Hooks
462 $parameters = array('objFrom' => $srcobject);
463 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
464 // modified by hook
465 if ($reshook < 0) {
466 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
467 $error++;
468 }
469 } else {
470 setEventMessages($object->error, $object->errors, 'errors');
471 $error++;
472 }
473 if ($error) {
474 $action = 'create';
475 }
476 } else {
477 $result = $object->create($user);
478 if ($result > 0) {
479 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
480 exit;
481 } else {
482 setEventMessages($object->error, $object->errors, 'errors');
483 }
484 $action = 'create';
485 }
486 }
487 } elseif ($action == 'classin' && $user->hasRight('contrat', 'creer')) {
488 $object->setProject(GETPOSTINT('projectid'));
489 } elseif ($action == 'addline' && $user->hasRight('contrat', 'creer')) {
490 // Add a new line
491 // Set if we used free entry or predefined product
492 $predef = '';
493 $line_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
494
495 $price_ht = '';
496 $price_ht_devise = '';
497 $price_ttc = '';
498 $price_ttc_devise = '';
499
500 $rang = count($object->lines) + 1;
501
502 if (GETPOST('price_ht') !== '') {
503 $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
504 }
505 if (GETPOST('multicurrency_price_ht') !== '') {
506 $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
507 }
508 if (GETPOST('price_ttc') !== '') {
509 $price_ttc = price2num(GETPOST('price_ttc'), 'MU', 2);
510 }
511 if (GETPOST('multicurrency_price_ttc') !== '') {
512 $price_ttc_devise = price2num(GETPOST('multicurrency_price_ttc'), 'CU', 2);
513 }
514
515 if (GETPOST('prod_entry_mode', 'alpha') == 'free') {
516 $idprod = 0;
517 } else {
518 $idprod = GETPOSTINT('idprod');
519
520 if (getDolGlobalString('MAIN_DISABLE_FREE_LINES') && $idprod <= 0) {
521 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors');
522 $error++;
523 }
524 }
525
526 $tva_tx = GETPOST('tva_tx', 'alpha');
527
528 $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS');
529 $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef), '', 2) : 0);
530 if (empty($remise_percent)) {
531 $remise_percent = 0;
532 }
533
534 if ($qty == '') {
535 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors');
536 $error++;
537 }
538 if (GETPOST('prod_entry_mode', 'alpha') == 'free' && (empty($idprod) || $idprod < 0) && empty($line_desc)) {
539 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors');
540 $error++;
541 }
542
543 $date_start = dol_mktime(GETPOSTINT('date_start'.$predef.'hour'), GETPOSTINT('date_start'.$predef.'min'), GETPOSTINT('date_start'.$predef.'sec'), GETPOSTINT('date_start'.$predef.'month'), GETPOSTINT('date_start'.$predef.'day'), GETPOSTINT('date_start'.$predef.'year'));
544 $date_end = dol_mktime(GETPOSTINT('date_end'.$predef.'hour'), GETPOSTINT('date_end'.$predef.'min'), GETPOSTINT('date_end'.$predef.'sec'), GETPOSTINT('date_end'.$predef.'month'), GETPOSTINT('date_end'.$predef.'day'), GETPOSTINT('date_end'.$predef.'year'));
545 if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) {
546 setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
547 $error++;
548 }
549
550 // Extrafields
551 $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
552 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
553 // Unset extrafield
554 if (is_array($extralabelsline)) {
555 // Get extra fields
556 foreach ($extralabelsline as $key => $value) {
557 unset($_POST["options_".$key]);
558 }
559 }
560
561 if (!$error) {
562 // Clean parameters
563 $date_start = dol_mktime(GETPOSTINT('date_start'.$predef.'hour'), GETPOSTINT('date_start'.$predef.'min'), GETPOSTINT('date_start'.$predef.'sec'), GETPOSTINT('date_start'.$predef.'month'), GETPOSTINT('date_start'.$predef.'day'), GETPOSTINT('date_start'.$predef.'year'));
564 $date_end = dol_mktime(GETPOSTINT('date_end'.$predef.'hour'), GETPOSTINT('date_end'.$predef.'min'), GETPOSTINT('date_end'.$predef.'sec'), GETPOSTINT('date_end'.$predef.'month'), GETPOSTINT('date_end'.$predef.'day'), GETPOSTINT('date_end'.$predef.'year'));
565
566 $price_base_type = '';
567 $price_min = '';
568 // Ecrase $tva_tx par celui du produit. TODO Remove this once vat selection is open
569 // Get and check minimum price
570 if ($idprod > 0) {
571 $prod = new Product($db);
572 $prod->fetch($idprod);
573
574 // Update if prices fields are defined
575 /*$tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
576 $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
577 if (empty($tva_tx)) {
578 }*/
579 $tva_npr = 0;
580
581 $price_min = $prod->price_min;
582 $price_min_ttc = $prod->price_min_ttc;
583
584 // On defini prix unitaire
585 if (getDolGlobalString('PRODUIT_MULTIPRICES') && $object->thirdparty->price_level) {
586 $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
587 $price_min_ttc = $prod->multiprices_min_ttc[$object->thirdparty->price_level];
588 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
589 // If price per customer
590 require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
591
592 $prodcustprice = new ProductCustomerPrice($db);
593
594 $filter = array('t.fk_product' => (string) $prod->id, 't.fk_soc' => (string) $object->thirdparty->id);
595
596 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
597 if ($result) {
598 if (count($prodcustprice->lines) > 0) {
599 $date_now = (int) floor(dol_now() / 86400) * 86400; // date without hours
600 foreach ($prodcustprice->lines as $k => $custprice_line) {
601 if ($custprice_line->date_begin <= $date_now && (empty($custprice_line->date_end) || $date_now <= $custprice_line->date_end)) {
602 $price_min = price($custprice_line->price_min);
603 $price_min_ttc = price($custprice_line->price_min_ttc);
604 /*$tva_tx = $custprice_line->tva_tx;
605 if ($custprice_line->default_vat_code && !preg_match('/\‍(.*\‍)/', $tva_tx)) {
606 $tva_tx .= ' ('.$custprice_line->default_vat_code.')';
607 }
608 $tva_npr = $custprice_line->recuperableonly;
609 if (empty($tva_tx)) {
610 $tva_npr = 0;
611 }*/
612 break;
613 }
614 }
615 }
616 }
617 }
618
619 $tmpvat = price2num(preg_replace('/\s*\‍(.*\‍)/', '', $tva_tx));
620 $tmpprodvat = price2num(preg_replace('/\s*\‍(.*\‍)/', '', (string) $prod->tva_tx));
621
622 // Set unit price to use
623 if (!empty($price_ht) || $price_ht === '0') {
624 $pu_ht = price2num($price_ht, 'MU');
625 $pu_ttc = price2num((float) $pu_ht * (1 + ((float) $tmpvat / 100)), 'MU');
626 $price_base_type = 'HT';
627 } elseif (!empty($price_ttc) || $price_ttc === '0') {
628 $pu_ttc = price2num($price_ttc, 'MU');
629 $pu_ht = price2num((float) $pu_ttc / (1 + ((float) $tmpvat / 100)), 'MU');
630 $price_base_type = 'TTC';
631 }
632
633 $desc = $prod->description;
634
635 if (getDolGlobalInt('PRODUIT_AUTOFILL_DESC') == 0) {
636 // 'DoNotAutofillButAutoConcat'
637 $desc = dol_concatdesc($desc, $line_desc, false, getDolGlobalString('MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION') ? true : false);
638 } else {
639 //'AutoFillFormFieldBeforeSubmit' or 'DoNotUseDescriptionOfProdut' => User has already done the modification they want
640 $desc = $line_desc;
641 }
642
643 $fk_unit = $prod->fk_unit;
644 } else {
645 $pu_ht = price2num($price_ht, 'MU');
646 $pu_ttc = price2num($price_ttc, 'MU');
647 $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
648 if (empty($tva_tx)) {
649 $tva_npr = 0;
650 }
651 $tva_tx = str_replace('*', '', $tva_tx);
652 $desc = $line_desc;
653 $fk_unit = GETPOSTINT('units');
654 $pu_ht_devise = price2num($price_ht_devise, 'MU');
655 $pu_ttc_devise = price2num($price_ttc_devise, 'MU');
656
657 $tmpvat = price2num(preg_replace('/\s*\‍(.*\‍)/', '', $tva_tx));
658
659 // Set unit price to use
660 if (!empty($price_ht) || $price_ht === '0') {
661 $pu_ht = price2num($price_ht, 'MU');
662 $pu_ttc = price2num((float) $pu_ht * (1 + ((float) $tmpvat / 100)), 'MU');
663 $price_base_type = 'HT';
664 } elseif (!empty($price_ttc) || $price_ttc === '0') {
665 $pu_ttc = price2num($price_ttc, 'MU');
666 $pu_ht = price2num((float) $pu_ttc / (1 + ((float) $tmpvat / 100)), 'MU');
667 $price_base_type = 'TTC';
668 }
669 }
670
671 $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
672 $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
673
674 // ajout prix achat
675 $fk_fournprice = GETPOST('fournprice');
676 if (GETPOST('buying_price')) {
677 $pa_ht = GETPOST('buying_price');
678 } else {
679 $pa_ht = null;
680 }
681
682 $info_bits = 0;
683 if ($tva_npr) {
684 $info_bits |= 0x01;
685 }
686
687 if (((getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('produit', 'ignore_price_min_advance'))
688 || !getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) && ($price_min && ((float) price2num((string) $pu_ht) * (1 - (float) price2num($remise_percent) / 100) < (float) price2num($price_min)))) {
689 $object->error = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
690 $result = -1;
691 } else {
692 // Insert line
693 $result = $object->addline(
694 $desc,
695 (float) $pu_ht,
696 (float) $qty,
697 $tva_tx,
698 $localtax1_tx,
699 $localtax2_tx,
700 $idprod,
701 $remise_percent,
703 $date_end,
704 $price_base_type,
705 (float) $pu_ttc,
706 $info_bits,
707 (int) $fk_fournprice,
708 (float) $pa_ht,
709 $array_options,
710 (int) $fk_unit,
711 $rang
712 );
713 }
714
715 if ($result > 0) {
716 // Define output language
717 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE') && getDolGlobalString('CONTRACT_ADDON_PDF')) { // No generation if default type not defined
718 $outputlangs = $langs;
719 $newlang = '';
720 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
721 $newlang = GETPOST('lang_id', 'aZ09');
722 }
723 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
724 $newlang = $object->thirdparty->default_lang;
725 }
726 if (!empty($newlang)) {
727 $outputlangs = new Translate("", $conf);
728 $outputlangs->setDefaultLang($newlang);
729 }
730
731 $ret = $object->fetch($id); // Reload to get new records
732
733 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
734 }
735
736 unset($_POST['prod_entry_mode']);
737
738 unset($_POST['qty']);
739 unset($_POST['type']);
740 unset($_POST['remise_percent']);
741 unset($_POST['price_ht']);
742 unset($_POST['multicurrency_price_ht']);
743 unset($_POST['price_ttc']);
744 unset($_POST['tva_tx']);
745 unset($_POST['product_ref']);
746 unset($_POST['product_label']);
747 unset($_POST['product_desc']);
748 unset($_POST['fournprice']);
749 unset($_POST['buying_price']);
750 unset($_POST['np_marginRate']);
751 unset($_POST['np_markRate']);
752 unset($_POST['dp_desc']);
753 unset($_POST['idprod']);
754
755 unset($_POST['date_starthour']);
756 unset($_POST['date_startmin']);
757 unset($_POST['date_startsec']);
758 unset($_POST['date_startday']);
759 unset($_POST['date_startmonth']);
760 unset($_POST['date_startyear']);
761 unset($_POST['date_endhour']);
762 unset($_POST['date_endmin']);
763 unset($_POST['date_endsec']);
764 unset($_POST['date_endday']);
765 unset($_POST['date_endmonth']);
766 unset($_POST['date_endyear']);
767 } else {
768 setEventMessages($object->error, $object->errors, 'errors');
769 }
770 }
771 } elseif ($action == 'updateline' && $user->hasRight('contrat', 'creer') && !GETPOST('cancel', 'alpha')) {
772 $error = 0;
773 $predef = '';
774
775 if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) {
776 setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
777 $action = 'editline';
778 $error++;
779 }
780
781 if (!$error) {
782 $objectline = new ContratLigne($db);
783 if ($objectline->fetch($idline) < 0) {
784 setEventMessages($objectline->error, $objectline->errors, 'errors');
785 $error++;
786 }
787 $objectline->fetch_optionals();
788
789 $objectline->oldcopy = dol_clone($objectline, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
790 } else {
791 $objectline = null;
792 }
793
794 $db->begin();
795
796 if (!$error) {
797 if ($date_start_real_update == '') {
798 $date_start_real_update = $objectline->date_start_real;
799 }
800 if ($date_end_real_update == '') {
801 $date_end_real_update = $objectline->date_end_real;
802 }
803
804 $vat_rate = GETPOST('eltva_tx', 'alpha');
805 // Define info_bits
806 $info_bits = 0;
807 if (preg_match('/\*/', $vat_rate)) {
808 $info_bits |= 0x01;
809 }
810
811 // Define vat_rate
812 $vat_rate = str_replace('*', '', $vat_rate);
813 $localtax1_tx = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
814 $localtax2_tx = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
815
816 $txtva = $vat_rate;
817
818 // Clean vat code
819 $reg = array();
820 $vat_src_code = '';
821 if (preg_match('/\‍((.*)\‍)/', $txtva, $reg)) {
822 $vat_src_code = $reg[1];
823 $txtva = preg_replace('/\s*\‍(.*\‍)/', '', $txtva); // Remove code into vatrate.
824 }
825
826 // ajout prix d'achat
827 if (GETPOST('buying_price')) {
828 $pa_ht = price2num(GETPOST('buying_price'), '', 2);
829 } else {
830 $pa_ht = 0;
831 }
832
833 $fk_unit = GETPOSTINT('unit');
834
835 // TODO Use object->updateline instead objectline->update
836
837 $remise_percent = price2num(GETPOST('elremise_percent'), '', 2);
838
839 $objectline->fk_product = GETPOSTINT('idprod');
840 $objectline->description = GETPOST('product_desc', 'restricthtml');
841 $objectline->subprice = (float) price2num(GETPOST('elprice'), 'MU');
842 $objectline->qty = (float) price2num(GETPOST('elqty'), 'MS');
843 $objectline->remise_percent = $remise_percent;
844 $objectline->tva_tx = ($txtva ? $txtva : 0); // Field may be disabled, so we use vat rate 0
845 $objectline->vat_src_code = $vat_src_code;
846 $objectline->localtax1_tx = is_numeric($localtax1_tx) ? $localtax1_tx : 0;
847 $objectline->localtax2_tx = is_numeric($localtax2_tx) ? $localtax2_tx : 0;
848 $objectline->date_start = $date_start_update;
849 $objectline->date_start_real = $date_start_real_update;
850 $objectline->date_end = $date_end_update;
851 $objectline->date_end_real = $date_end_real_update;
852 $objectline->user_closing_id = $user->id;
853 //$objectline->fk_fournprice = $fk_fournprice;
854 $objectline->pa_ht = $pa_ht;
855 // $objectline->rang = $objectline->rang;
856
857 if ($fk_unit > 0) {
858 $objectline->fk_unit = GETPOSTINT('unit');
859 } else {
860 $objectline->fk_unit = null;
861 }
862
863 // Extrafields
864 $extralabelsline = $extrafields->fetch_name_optionals_label($objectline->table_element);
865 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
866
867 if (is_array($array_options) && count($array_options) > 0) {
868 // We replace values in this->line->array_options only for entries defined into $array_options
869 foreach ($array_options as $key => $value) {
870 $objectline->array_options[$key] = $array_options[$key];
871 }
872 }
873
874 // TODO verifier price_min si fk_product et multiprix
875
876 $result = $objectline->update($user);
877 if ($result < 0) {
878 $error++;
879 $action = 'editline';
880 $_GET['rowid'] = GETPOST('elrowid');
881 setEventMessages($objectline->error, $objectline->errors, 'errors');
882 }
883 }
884
885 if (!$error) {
886 $db->commit();
887 } else {
888 $db->rollback();
889 }
890 } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->hasRight('contrat', 'creer')) {
891 $result = $object->deleteLine(GETPOSTINT('lineid'), $user);
892
893 if ($result >= 0) {
894 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
895 exit;
896 } else {
897 setEventMessages($object->error, $object->errors, 'errors');
898 }
899 } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $user->hasRight('contrat', 'creer')) {
900 $result = $object->validate($user);
901
902 if ($result > 0) {
903 // Define output language
904 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
905 $outputlangs = $langs;
906 $newlang = '';
907 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
908 $newlang = GETPOST('lang_id', 'aZ09');
909 }
910 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
911 $newlang = $object->thirdparty->default_lang;
912 }
913 if (!empty($newlang)) {
914 $outputlangs = new Translate("", $conf);
915 $outputlangs->setDefaultLang($newlang);
916 }
917 $model = $object->model_pdf;
918 $ret = $object->fetch($id); // Reload to get new records
919
920 $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
921 }
922 } else {
923 setEventMessages($object->error, $object->errors, 'errors');
924 }
925 } elseif ($action == 'reopen' && $user->hasRight('contrat', 'creer')) {
926 $result = $object->reopen($user);
927 if ($result < 0) {
928 setEventMessages($object->error, $object->errors, 'errors');
929 }
930 } elseif ($action == 'confirm_close' && $confirm == 'yes' && $permissiontodisable) {
931 // Close all lines
932 $result = $object->closeAll($user);
933 if ($result < 0) {
934 setEventMessages($object->error, $object->errors, 'errors');
935 }
936 } elseif ($action == 'confirm_activate' && $confirm == 'yes' && $permissiontoactivate) {
937 $date_start = dol_mktime(12, 0, 0, GETPOSTINT('d_startmonth'), GETPOSTINT('d_startday'), GETPOSTINT('d_startyear'));
938 $date_end = dol_mktime(12, 0, 0, GETPOSTINT('d_endmonth'), GETPOSTINT('d_endday'), GETPOSTINT('d_endyear'));
939 $comment = GETPOST('comment', 'alpha');
940 $result = $object->activateAll($user, $date_start, 0, $comment, $date_end);
941 if ($result < 0) {
942 setEventMessages($object->error, $object->errors, 'errors');
943 }
944 } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $permissiontodelete) {
945 $result = $object->delete($user);
946 if ($result >= 0) {
947 header("Location: list.php?restore_lastsearch_values=1");
948 return;
949 } else {
950 setEventMessages($object->error, $object->errors, 'errors');
951 }
952 } elseif ($action == 'confirm_move' && $confirm == 'yes' && $permissiontoedit) {
953 if (GETPOST('newcid') > 0) {
954 $newcid = GETPOSTINT('newcid');
955
956 // Check the user can access the target contract
957 $result = restrictedArea($user, 'contrat', $newcid);
958
959 $newcontract = new Contrat($db);
960 $resultnewcontract = $newcontract->fetch($newcid);
961
962 $contractline = new ContratLigne($db);
963 $result = $contractline->fetch(GETPOSTINT('lineid'));
964
965 // The line must belong to the current contract and the target contract must be another contract of the same thirdparty
966 if ($result <= 0 || $resultnewcontract <= 0 || $contractline->fk_contrat != $object->id || $newcontract->id == $object->id || $newcontract->socid != $object->socid) {
967 setEventMessages($langs->trans("ErrorBadValueForParameter", GETPOSTINT('lineid').'/'.$newcid, 'lineid/newcid'), null, 'errors');
968 } else {
969 $contractline->fk_contrat = $newcontract->id;
970 $result = $contractline->update($user, 1);
971 if ($result >= 0) {
972 header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
973 return;
974 } else {
975 setEventMessages($contractline->error, $contractline->errors, 'errors');
976 }
977 }
978 } else {
979 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("RefNewContract")), null, 'errors');
980 }
981 } elseif ($action == 'update_extras' && $permissiontoeditextra) {
982 $object->oldcopy = dol_clone($object, 2);
983
984 $attribute = GETPOST('attribute', 'aZ09');
985
986 // Fill array 'array_options' with data from update form
987 $ret = $extrafields->setOptionalsFromPost(null, $object, $attribute);
988 if ($ret < 0) {
989 setEventMessages($extrafields->error, $object->errors, 'errors');
990 $error++;
991 }
992
993 if (!$error) {
994 $result = $object->updateExtraField($attribute, 'CONTRACT_MODIFY');
995 if ($result < 0) {
996 setEventMessages($object->error, $object->errors, 'errors');
997 $error++;
998 }
999 }
1000
1001 if ($error) {
1002 $action = 'edit_extras';
1003 }
1004 } elseif ($action == 'setref_supplier' && $permissiontoadd) {
1005 if (!$cancel) {
1006 $object->oldcopy = dol_clone($object, 2);
1007
1008 $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
1009 if ($result < 0) {
1010 setEventMessages($object->error, $object->errors, 'errors');
1011 $action = 'editref_supplier';
1012 } else {
1013 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1014 exit;
1015 }
1016 } else {
1017 header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
1018 exit;
1019 }
1020 } elseif ($action == 'setref_customer' && $permissiontoadd) {
1021 if (!$cancel) {
1022 $object->oldcopy = dol_clone($object, 2);
1023
1024 $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
1025 if ($result < 0) {
1026 setEventMessages($object->error, $object->errors, 'errors');
1027 $action = 'editref_customer';
1028 } else {
1029 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1030 exit;
1031 }
1032 } else {
1033 header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
1034 exit;
1035 }
1036 } elseif ($action == 'setref' && $permissiontoadd) {
1037 if (!$cancel) {
1038 $result = $object->fetch($id);
1039 if ($result < 0) {
1040 setEventMessages($object->error, $object->errors, 'errors');
1041 }
1042
1043 $old_ref = $object->ref;
1044
1045 $result = $object->setValueFrom('ref', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
1046 if ($result < 0) {
1047 setEventMessages($object->error, $object->errors, 'errors');
1048 $action = 'editref';
1049 } else {
1050 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1051 $old_filedir = $conf->contrat->multidir_output[$object->entity ?? $conf->entity].'/'.dol_sanitizeFileName($old_ref);
1052 $new_filedir = $conf->contrat->multidir_output[$object->entity ?? $conf->entity].'/'.dol_sanitizeFileName($object->ref);
1053
1054 // Rename directory of contract with new name
1055 dol_move_dir($old_filedir, $new_filedir);
1056
1057 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1058 exit;
1059 }
1060 } else {
1061 header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
1062 exit;
1063 }
1064 } elseif ($action == 'setdate_contrat' && $permissiontoadd) {
1065 if (!$cancel) {
1066 $result = $object->fetch($id);
1067 if ($result < 0) {
1068 setEventMessages($object->error, $object->errors, 'errors');
1069 }
1070 $datacontrat = dol_mktime(GETPOSTINT('date_contrathour'), GETPOSTINT('date_contratmin'), 0, GETPOSTINT('date_contratmonth'), GETPOSTINT('date_contratday'), GETPOSTINT('date_contratyear'));
1071 $result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY');
1072 if ($result < 0) {
1073 setEventMessages($object->error, $object->errors, 'errors');
1074 $action = 'editdate_contrat';
1075 } else {
1076 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1077 exit;
1078 }
1079 } else {
1080 header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
1081 exit;
1082 }
1083 }
1084
1085 // Actions when printing a doc from card
1086 include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
1087
1088 // Actions to build doc
1089 $upload_dir = $conf->contrat->multidir_output[!empty($object->entity) ? $object->entity : $conf->entity];
1090 include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
1091
1092 // Actions to send emails
1093 $triggersendname = 'CONTRACT_SENTBYMAIL';
1094 $paramname = 'id';
1095 $mode = 'emailfromcontract';
1096 $trackid = 'con'.$object->id;
1097 include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
1098
1099
1100 if (getDolGlobalString('MAIN_DISABLE_CONTACTS_TAB')) {
1101 if ($action == 'addcontact' && $user->hasRight('contrat', 'creer')) {
1102 $contactid = (GETPOST('userid') ? GETPOSTINT('userid') : GETPOSTINT('contactid'));
1103 $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
1104 $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
1105
1106 if ($result >= 0) {
1107 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1108 exit;
1109 } else {
1110 if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1111 $langs->load("errors");
1112 setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
1113 } else {
1114 setEventMessages($object->error, $object->errors, 'errors');
1115 }
1116 }
1117 } elseif ($action == 'swapstatut' && $user->hasRight('contrat', 'creer')) {
1118 // bascule du statut d'un contact
1119 $result = $object->swapContactStatus(GETPOSTINT('ligne'));
1120 } elseif ($action == 'deletecontact' && $user->hasRight('contrat', 'creer')) {
1121 // Efface un contact
1122 $result = $object->delete_contact(GETPOSTINT('lineid'));
1123
1124 if ($result >= 0) {
1125 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1126 exit;
1127 } else {
1128 setEventMessages($object->error, $object->errors, 'errors');
1129 }
1130 }
1131 }
1132
1133 // Action clone object
1134 if ($action == 'confirm_clone' && $confirm == 'yes' && $user->hasRight('contrat', 'creer')) {
1135 if (!GETPOSTINT('socid', 3)) {
1136 setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
1137 } else {
1138 if ($object->id > 0) {
1139 $result = $object->createFromClone($user, $socid);
1140 if ($result > 0) {
1141 header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
1142 exit();
1143 } else {
1144 if (count($object->errors) > 0) {
1145 setEventMessages($object->error, $object->errors, 'errors');
1146 }
1147 $action = '';
1148 }
1149 }
1150 }
1151 }
1152}
1153
1154
1155/*
1156 * View
1157 */
1158
1159$title = $object->ref." - ".$langs->trans('Contract');
1160if ($action == 'create') {
1161 $title = $langs->trans("NewContract");
1162}
1163$help_url = 'EN:Module_Contracts|FR:Module_Contrat|ES:Contratos_de_servicio';
1164
1165llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-contrat page-card');
1166
1167$form = new Form($db);
1168$formfile = new FormFile($db);
1169$staticcontractline = new ContratLigne($db);
1170if (isModEnabled('project')) {
1171 $formproject = new FormProjets($db);
1172}
1173
1174// Load object modContract
1175$module = getDolGlobalString('CONTRACT_ADDON', 'mod_contract_serpis');
1176if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
1177 $module = substr($module, 0, dol_strlen($module) - 4);
1178}
1179$result = dol_include_once('/core/modules/contract/'.$module.'.php');
1180$modCodeContract = null;
1181if ($result > 0) {
1182 $modCodeContract = new $module();
1184 '@phan-var-force ModelNumRefContracts $modCodeContract';
1185}
1186
1187// Create
1188if ($action == 'create') {
1189 $objectsrc = null;
1190 print load_fiche_titre($langs->trans('NewContract'), '', 'contract');
1191
1192 $soc = new Societe($db);
1193 if ($socid > 0) {
1194 $soc->fetch($socid);
1195 }
1196
1197 if (GETPOST('origin') && GETPOSTINT('originid')) {
1198 // Parse element/subelement (ex: project_task)
1199 $regs = array();
1200 $element = $subelement = GETPOST('origin');
1201 if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'), $regs)) {
1202 $element = $regs[1];
1203 $subelement = $regs[2];
1204 }
1205
1206 if ($element == 'project') {
1207 $projectid = GETPOSTINT('originid');
1208 } else {
1209 // For compatibility
1210 if ($element == 'order' || $element == 'commande') {
1211 $element = $subelement = 'commande';
1212 }
1213 if ($element == 'propal') {
1214 $element = 'comm/propal';
1215 $subelement = 'propal';
1216 }
1217 if ($element == 'invoice' || $element == 'facture') {
1218 $element = 'compta/facture';
1219 $subelement = 'facture';
1220 }
1221 $classname = '';
1222 if ($element == 'facturerec' || $element == 'facture_rec') {
1223 $element = 'compta/facture';
1224 $subelement = 'facture-rec';
1225 $classname = 'FactureRec';
1226 }
1227 if ($element == 'facture_fourn_rec' || $element == 'invoice_supplier_rec') {
1228 $element = 'fourn';
1229 $subelement = 'fournisseur.facture-rec';
1230 $classname = 'FactureFournisseurRec';
1231 }
1232
1233 dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
1234
1235 if (empty($classname)) {
1236 $classname = ucfirst($subelement);
1237 }
1238 $objectsrc = new $classname($db);
1239 '@phan-var-force Commande|Propal|Facture $objectsrc';
1240 $objectsrc->fetch($originid);
1241 if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
1242 $objectsrc->fetch_lines();
1243 }
1244 $objectsrc->fetch_thirdparty();
1245
1246 // Replicate extrafields
1247 $objectsrc->fetch_optionals();
1248 $object->array_options = $objectsrc->array_options;
1249
1250 $projectid = (int) $objectsrc->fk_project;
1251
1252 $soc = $objectsrc->thirdparty;
1253
1254 $note_private = (!empty($objectsrc->note_private) ? $objectsrc->note_private : '');
1255 $note_public = (!empty($objectsrc->note_public) ? $objectsrc->note_public : '');
1256
1257 // Object source contacts list
1258 $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1);
1259 }
1260 } else {
1261 $projectid = GETPOSTINT('projectid');
1262 $note_private = GETPOST("note_private", "alpha");
1263 $note_public = GETPOST("note_public", "alpha");
1264 }
1265
1266 $object->date_contrat = dol_now();
1267
1268 print '<form name="form_contract" action="'.$_SERVER["PHP_SELF"].'" method="post">';
1269 print '<input type="hidden" name="token" value="'.newToken().'">';
1270 print '<input type="hidden" name="action" value="add">';
1271 print '<input type="hidden" name="socid" value="'.$soc->id.'">'."\n";
1272 print '<input type="hidden" name="remise_percent" value="0">';
1273 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
1274
1275 print dol_get_fiche_head();
1276
1277 print '<table class="border centpercent">';
1278
1279 // Ref
1280 if (empty($modCodeContract->code_auto)) {
1281 print '<tr><td class="titlefield fieldrequired">'.$langs->trans('Ref').'</td><td>';
1282 //if (!empty($modCodeContract->code_auto)) {
1283 // $tmpcode = $langs->trans("Draft");
1284 //} else {
1285 $tmpcode = '<input name="ref" class="maxwidth100" maxlength="128" value="'.dol_escape_htmltag(GETPOST('ref', 'alpha')).'">';
1286 //}
1287 print $tmpcode;
1288 print '</td></tr>';
1289 }
1290
1291 if (getDolGlobalString('COINTRACT_ASK_CONTRACT_REF_FOR_CUSTOMER_AT_CREATION')) {
1292 // Ref customer
1293 print '<tr><td>'.$langs->trans('RefCustomer').'</td>';
1294 print '<td><input type="text" class="maxwidth150" name="ref_customer" id="ref_customer" value="'.dol_escape_htmltag(GETPOST('ref_customer', 'alpha')).'"></td></tr>';
1295 }
1296 if (getDolGlobalString('COINTRACT_ASK_CONTRACT_REF_FOR_SUPPLIER_AT_CREATION')) {
1297 // Ref supplier
1298 print '<tr><td>'.$langs->trans('RefSupplier').'</td>';
1299 print '<td><input type="text" class="maxwidth150" name="ref_supplier" id="ref_supplier" value="'.dol_escape_htmltag(GETPOST('ref_supplier', 'alpha')).'"></td></tr>';
1300 }
1301
1302 // Thirdparty
1303 print '<tr>';
1304 print '<td class="fieldrequired">'.$langs->trans('ThirdParty').'</td>';
1305 if ($socid > 0) {
1306 print '<td>';
1307 print $soc->getNomUrl(1);
1308 print '<input type="hidden" name="socid" value="'.$soc->id.'">';
1309 print '</td>';
1310 } else {
1311 print '<td>';
1312 print img_picto('', 'company', 'class="pictofixedwidth"');
1313 print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, array(), 0, 'minwidth150 widthcentpercentminusxx maxwidth500');
1314 print ' <a href="'.dolBuildUrl(DOL_URL_ROOT . '/societe/card.php', ['action' => 'create', 'customer' => 3, 'backtopage' => dolBuildUrl($_SERVER["PHP_SELF"], ['action' => 'create'])]).'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
1315 print '</td>';
1316 }
1317 print '</tr>'."\n";
1318
1319 if ($socid > 0) {
1320 // Third-party discount info
1321 print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
1322 if ($soc->remise_percent) {
1323 print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent).' ';
1324 } else {
1325 print '<span class="hideonsmartphone">'.$langs->trans("CompanyHasNoRelativeDiscount").'. </span>';
1326 }
1327 $absolute_discount = $soc->getAvailableDiscounts();
1328 if ($absolute_discount) {
1329 print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)).'.';
1330 } else {
1331 print '<span class="hideonsmartphone">'.$langs->trans("CompanyHasNoAbsoluteDiscount").'.</span>';
1332 }
1333 print '</td></tr>';
1334 }
1335
1336 // Commercial suivi
1337 print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").'</span></td><td>';
1338 print img_picto('', 'user', 'class="pictofixedwidth"');
1339 print $form->select_dolusers(GETPOST("commercial_suivi_id") ? GETPOST("commercial_suivi_id") : $user->id, 'commercial_suivi_id', 1, null);
1340 print '</td></tr>';
1341
1342 // Commercial signature
1343 print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").'</span></td><td>';
1344 print img_picto('', 'user', 'class="pictofixedwidth"');
1345 print $form->select_dolusers(GETPOST("commercial_signature_id") ? GETPOST("commercial_signature_id") : $user->id, 'commercial_signature_id', 1, null);
1346 print '</td></tr>';
1347
1348 print '<tr><td><span class="fieldrequired">'.$langs->trans("Date").'</span></td><td>';
1349 print img_picto('', 'action', 'class="pictofixedwidth"');
1350 print $form->selectDate($datecontrat, '', 0, 0, 0, "contrat");
1351 print "</td></tr>";
1352
1353 // Project
1354 if (isModEnabled('project')) {
1355 $langs->load('projects');
1356
1357 $formproject = new FormProjets($db);
1358
1359 print '<tr><td>'.$langs->trans("Project").'</td><td>';
1360 print img_picto('', 'project', 'class="pictofixedwidth"');
1361 $formproject->select_projects(($soc->id > 0 ? $soc->id : -1), $projectid, "projectid", 0, 0, 1, 1, 0, 0, 0, '', 0, 0, 'minwidth150 maxwidth300 widthcentpercentminusxx');
1362 print ' &nbsp; <a href="' . dolBuildUrl(DOL_URL_ROOT . '/projet/card.php', ['socid' => $soc->id, 'action' => 'create', 'status' => 1, 'backtopage' => dolBuildUrl($_SERVER["PHP_SELF"], ['action' => 'create', 'socid' => $soc->id])]) . '"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans("AddProject").'"></span></a>';
1363 print "</td></tr>";
1364 }
1365
1366 // Note public
1367 print '<tr><td>'.$langs->trans("NotePublic").'</td><td class="tdtop">';
1368 $doleditor = new DolEditor('note_public', (string) $note_public, '', 100, 'dolibarr_notes', 'In', true, true, !getDolGlobalString('FCKEDITOR_ENABLE_NOTE_PUBLIC') ? 0 : 1, ROWS_3, '90%');
1369 print $doleditor->Create(1);
1370 print '</td></tr>';
1371
1372 // Note private
1373 if (empty($user->socid)) {
1374 print '<tr><td>'.$langs->trans("NotePrivate").'</td><td class="tdtop">';
1375 $doleditor = new DolEditor('note_private', (string) $note_private, '', 100, 'dolibarr_notes', 'In', true, true, !getDolGlobalString('FCKEDITOR_ENABLE_NOTE_PRIVATE') ? 0 : 1, ROWS_3, '90%');
1376 print $doleditor->Create(1);
1377 print '</td></tr>';
1378 }
1379
1380 // Other attributes
1381 $parameters = array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"', 'cols' => '3');
1382 $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1383 print $hookmanager->resPrint;
1384
1385 // Other attributes
1386 if (empty($reshook)) {
1387 print $object->showOptionals($extrafields, 'create', $parameters);
1388 }
1389
1390 print "</table>\n";
1391
1392 print dol_get_fiche_end();
1393
1394 print $form->buttonsSaveCancel("CreateDraft");
1395
1396 if (is_object($objectsrc)) {
1397 print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
1398 print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
1399
1400 if (!getDolGlobalString('CONTRACT_SUPPORT_PRODUCTS')) {
1401 print '<br>'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed");
1402 }
1403 }
1404
1405 print "</form>\n";
1406} else {
1407 // View and edit mode
1408 $now = dol_now();
1409
1410 if ($object->id > 0) {
1411 $object->fetch_thirdparty();
1412
1413 $soc = $object->thirdparty; // $soc is used later
1414
1415 $result = $object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed
1416 if ($result < 0) {
1417 dol_print_error($db, $object->error);
1418 }
1419
1420 $nbofservices = count($object->lines);
1421
1422 $author = new User($db);
1423 $author->fetch($object->user_author_id);
1424
1425 $commercial_signature = new User($db);
1426 $commercial_signature->fetch($object->commercial_signature_id);
1427
1428 $commercial_suivi = new User($db);
1429 $commercial_suivi->fetch($object->commercial_suivi_id);
1430
1431 $head = contract_prepare_head($object);
1432
1433 $hselected = '0';
1434 $formconfirm = '';
1435
1436 print dol_get_fiche_head($head, $hselected, $langs->trans("Contract"), -1, 'contract', 0, '', '', 0, '', 1);
1437
1438
1439 if ($action == 'delete') {
1440 // Confirm contract deletion
1441 $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("DeleteAContract"), $langs->trans("ConfirmDeleteAContract"), "confirm_delete", '', 0, 1);
1442 } elseif ($action == 'valid') {
1443 // Confirm contract validation
1444 $ref = substr($object->ref, 1, 4);
1445 if ($ref == 'PROV' && !empty($modCodeContract->code_auto)) {
1446 $numref = $object->getNextNumRef($object->thirdparty);
1447 } else {
1448 $numref = (string) $object->ref;
1449 }
1450 $text = $langs->trans('ConfirmValidateContract', $numref);
1451 $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ValidateAContract"), $text, "confirm_valid", '', 0, 1);
1452 } elseif ($action == 'close') {
1453 // Confirm closing contract
1454 $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("CloseAContract"), $langs->trans("ConfirmCloseContract"), "confirm_close", '', 0, 1);
1455 } elseif ($action == 'activate') {
1456 $formquestion = array(
1457 array('type' => 'date', 'name' => 'd_start', 'label' => $langs->trans("DateServiceActivate"), 'value' => dol_now()),
1458 array('type' => 'date', 'name' => 'd_end', 'label' => $langs->trans("DateEndPlanned"), 0 => '', 1 => ''),
1459 array('type' => 'text', 'name' => 'comment', 'label' => $langs->trans("Comment"), 'value' => '', 0 => '', 1 => '', 'class' => 'minwidth300', 'moreattr' => 'autofocus')
1460 );
1461 $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ActivateAllOnContract"), $langs->trans("ConfirmActivateAllOnContract"), "confirm_activate", $formquestion, 'yes', 1, 300);
1462 } elseif ($action == 'clone') {
1463 $filter = '(s.client:IN:1,2,3) OR (s.fournisseur:=:1)';
1464 // Clone confirmation
1465 $formquestion = array(array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOSTINT('socid'), 'socid', $filter)));
1466 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneContract', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
1467 } elseif ($action == 'sign') {
1468 $text = $langs->trans('ConfirmSignContract');
1469 if (isModEnabled('notification')) {
1470 require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
1471 $notify = new Notify($db);
1472 $text .= '<br>';
1473 $text .= $notify->confirmMessage('CONTRACT_MODIFY', $object->socid, $object);
1474 }
1475 $formquestion = [];
1476 $formquestion[] = [
1477 'type' => 'select',
1478 'name' => 'signed_status',
1479 'label' => '<span class="fieldrequired">'.$langs->trans('SignStatus').'</span>',
1480 'values' => $object->getSignedStatusLocalisedArray()
1481 ];
1482 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('SignContract'), $text, 'confirm_sign', $formquestion, 0, 1);
1483 } elseif ($action == 'unsign') {
1484 $text = $langs->trans('ConfirmUnsignContract');
1485 if (isModEnabled('notification')) {
1486 require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
1487 $notify = new Notify($db);
1488 $text .= '<br>';
1489 $text .= $notify->confirmMessage('CONTRACT_MODIFY', $object->socid, $object);
1490 }
1491 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnsignContract'), $text, 'confirm_unsign', '', 0, 1);
1492 }
1493
1494
1495 // Call Hook formConfirm
1496 $parameters = array(
1497 'formConfirm' => $formconfirm,
1498 'id' => $id,
1499 //'lineid' => $lineid,
1500 );
1501 // Note that $action and $object may have been modified by hook
1502 $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action);
1503 if (empty($reshook)) {
1504 $formconfirm .= $hookmanager->resPrint;
1505 } elseif ($reshook > 0) {
1506 $formconfirm = $hookmanager->resPrint;
1507 }
1508
1509 // Print form confirm
1510 print $formconfirm;
1511
1512
1513 // Contract
1514 if ($object->status == $object::STATUS_DRAFT && $user->hasRight('contrat', 'creer')) {
1515 print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="POST">';
1516 print '<input type="hidden" name="token" value="'.newToken().'">';
1517 print '<input type="hidden" name="action" value="setremise">';
1518 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
1519 }
1520
1521 // Contract card
1522
1523 $linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
1524
1525
1526 $morehtmlref = '';
1527 if (!empty($modCodeContract->code_auto)) {
1528 $morehtmlref .= $object->ref;
1529 } else {
1530 $morehtmlref .= $form->editfieldkey("", 'ref', $object->ref, $object, $user->hasRight('contrat', 'creer'), 'string', '', 0, 3);
1531 $morehtmlref .= $form->editfieldval("", 'ref', $object->ref, $object, $user->hasRight('contrat', 'creer'), 'string', '', null, '2');
1532 }
1533
1534 $morehtmlref .= '<div class="refidno">';
1535 // Ref customer
1536 $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->hasRight('contrat', 'creer'), 'string', '', 0, 1);
1537 $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->hasRight('contrat', 'creer'), 'string'.(isset($conf->global->THIRDPARTY_REF_INPUT_SIZE) ? ':' . getDolGlobalString('THIRDPARTY_REF_INPUT_SIZE') : ''), '', null, null, '', 1, 'getFormatedCustomerRef');
1538 // Ref supplier
1539 $morehtmlref .= '<br>';
1540 $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->hasRight('contrat', 'creer'), 'string', '', 0, 1);
1541 $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->hasRight('contrat', 'creer'), 'string', '', null, null, '', 1, 'getFormatedSupplierRef');
1542 // Thirdparty
1543 $morehtmlref .= '<br>'.$object->thirdparty->getNomUrl(1);
1544 if (!getDolGlobalString('MAIN_DISABLE_OTHER_LINK') && $object->thirdparty->id > 0) {
1545 $morehtmlref .= ' <span class="otherlink valignmiddle">(<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.((int) $object->thirdparty->id).'">'.$langs->trans("OtherContracts").'</a>)</span>';
1546 }
1547 // Project
1548 if (isModEnabled('project')) {
1549 $langs->load("projects");
1550 $morehtmlref .= '<br>';
1551 if ($permissiontoadd) {
1552 $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
1553 if ($action != 'classify') {
1554 $morehtmlref .= '<a class="editfielda" href="'.dolBuildUrl($_SERVER['PHP_SELF'], ['action' => 'classify', 'id' => ((int) $object->id)], true).'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> ';
1555 }
1556 $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, (string) $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
1557 } else {
1558 if (!empty($object->fk_project)) {
1559 $proj = new Project($db);
1560 $proj->fetch($object->fk_project);
1561 $morehtmlref .= $proj->getNomUrl(1);
1562 if ($proj->title) {
1563 $morehtmlref .= '<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).'</span>';
1564 }
1565 }
1566 }
1567 }
1568 $morehtmlref .= '</div>';
1569
1570
1571 dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);
1572
1573
1574 print '<div class="fichecenter">';
1575 print '<div class="fichehalfleft">';
1576 print '<div class="underbanner clearboth"></div>';
1577
1578 print '<table class="border centpercent tableforfield">';
1579
1580 // Line info of thirdparty discounts
1581 print '<tr><td class="titlefield">'.$langs->trans('Discount').'</td><td colspan="3">';
1582 if ($object->thirdparty->remise_percent) {
1583 print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent).'. ';
1584 } else {
1585 print '<span class="hideonsmartphone opacitymedium">'.$langs->trans("CompanyHasNoRelativeDiscount").'. </span>';
1586 }
1587 $absolute_discount = $object->thirdparty->getAvailableDiscounts();
1588 if ($absolute_discount) {
1589 print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)).'.';
1590 } else {
1591 print '<span class="hideonsmartphone opacitymedium">'.$langs->trans("CompanyHasNoAbsoluteDiscount").'.</span>';
1592 }
1593 print '</td></tr>';
1594
1595 // Date
1596 print '<tr>';
1597 print '<td class="titlefield">';
1598 print $form->editfieldkey("Date", 'date_contrat', $object->date_contrat, $object, $user->hasRight('contrat', 'creer'));
1599 print '</td><td>';
1600 print $form->editfieldval("Date", 'date_contrat', $object->date_contrat, $object, $user->hasRight('contrat', 'creer'), 'datehourpicker');
1601 print '</td>';
1602 print '</tr>';
1603
1604 // Other attributes
1605 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
1606
1607 print "</table>";
1608
1609 print '</div>';
1610 print '<div class="fichehalfright">';
1611
1612 print '<!-- amounts -->'."\n";
1613 print '<div class="underbanner clearboth"></div>';
1614
1615 if (getDolGlobalString("CONTRACT_SHOW_SUMMARY_Of_AMOUNTS")) {
1616 print '<div class="div-table-responsive-no-min">';
1617 print '<table class="border tableforfield centpercent">';
1618
1619 // Qty by service status
1620 print '<tr><td class="titlefield">'."".'</td>';
1621 print '<td class=right>'.$langs->trans('Total').'</td>';
1622 print '<td class=right>'.$staticcontractline->LibStatut(0, 5, 0).'</td>';
1623 print '<td class=right>'.$staticcontractline->LibStatut(4, 5, 0).'</td>';
1624 print '<td class=right>'.$staticcontractline->LibStatut(4, 5, 1).'</td>';
1625 print '<td class=right>'.$staticcontractline->LibStatut(5, 5, 0).'</td>';
1626 print '</tr>';
1627
1628 $all= $object->getTotalizedLines(-1, 0);
1629 $draft= $object->getTotalizedLines(0, 0);
1630 $enabled= $object->getTotalizedLines(4, 0);
1631 $expired= $object->getTotalizedLines(4, 1);
1632 $close= $object->getTotalizedLines(5, 0);
1633
1634 // Note that the line with qty is a duplicate of the same summary information reported in the status banner.
1635 print '<tr><td class="titlefield">'.$langs->trans("Quantity").'</td>';
1636 print '<td class="right nowrap">'.($all['total_qty'] ? price2num($all['total_qty']) : '<span class="opacitymedium">0</span>').'</td>';
1637 print '<td class="right">'.($draft['total_qty'] ? price2num($draft['total_qty']) : '<span class="opacitymedium">0</span>').'</td>';
1638 print '<td class="right">'.($enabled['total_qty'] ? price2num($enabled['total_qty']) : '<span class="opacitymedium">0</span>').'</td>';
1639 print '<td class="right">'.($expired['total_qty'] ? price2num($expired['total_qty']) : '<span class="opacitymedium">0</span>').'</td>';
1640 print '<td class="right">'.($close['total_qty'] ? price2num($close['total_qty']) : '<span class="opacitymedium">0</span>').'</td>';
1641 print '</tr>';
1642
1643 print '<tr><td class="titlefield">'.$langs->trans("TotalHT").'</td>';
1644 print '<td class="nowraponall amountcard right">'.($all['total_ht'] ? price($all['total_ht']) : '<span class="opacitymedium">0</span>').'</td>';
1645 print '<td class="nowraponall amountcard right">'.($draft['total_ht'] ? price($draft['total_ht']) : '<span class="opacitymedium">0</span>').'</td>';
1646 print '<td class="nowraponall amountcard right">'.($enabled['total_ht'] ? price($enabled['total_ht']) : '<span class="opacitymedium">0</span>').'</td>';
1647 print '<td class="nowraponall amountcard right">'.($expired['total_ht'] ? price($expired['total_ht']) : '<span class="opacitymedium">0</span>').'</td>';
1648 print '<td class="nowraponall amountcard right">'.($close['total_ht'] ? price($close['total_ht']) : '<span class="opacitymedium">0</span>').'</td>';
1649 print '</tr>';
1650
1651 print '<tr><td class="titlefield">'.$langs->trans("TotalVAT").'</td>';
1652 print '<td class="nowraponall amountcard right nowrap">'.($all['total_tva'] ? price($all['total_tva']) : '<span class="opacitymedium">0</span>').'</td>';
1653 print '<td class="nowraponall amountcard right">'.($draft['total_tva'] ? price($draft['total_tva']) : '<span class="opacitymedium">0</span>').'</td>';
1654 print '<td class="nowraponall amountcard right">'.($enabled['total_tva'] ? price($enabled['total_tva']) : '<span class="opacitymedium">0</span>').'</td>';
1655 print '<td class="nowraponall amountcard right">'.($expired['total_tva'] ? price($expired['total_tva']) : '<span class="opacitymedium">0</span>').'</td>';
1656 print '<td class="nowraponall amountcard right">'.($close['total_tva'] ? price($close['total_tva']) : '<span class="opacitymedium">0</span>').'</td>';
1657 print '</tr>';
1658
1659 if ($mysoc->localtax1_assuj == "1" || $all['total_localtax1'] != 0) {
1660 print '<tr><td class="titlefield">' . $langs->trans("TotalLT1") . '</td>';
1661 print '<td class="nowraponall amountcard right nowrap">' . ($all['total_localtax1'] ? price($all['total_localtax1']) : '<span class="opacitymedium">0</span>') . '</td>';
1662 print '<td class="nowraponall amountcard right">' . ($draft['total_localtax1'] ? price($draft['total_localtax1']) : '<span class="opacitymedium">0</span>') . '</td>';
1663 print '<td class="nowraponall amountcard right">' . ($enabled['total_localtax1'] ? price($enabled['total_localtax1']) : '<span class="opacitymedium">0</span>') . '</td>';
1664 print '<td class="nowraponall amountcard right">' . ($expired['total_localtax1'] ? price($expired['total_localtax1']) : '<span class="opacitymedium">0</span>') . '</td>';
1665 print '<td class="nowraponall amountcard right">' . ($close['total_localtax1'] ? price($close['total_localtax1']) : '<span class="opacitymedium">0</span>') . '</td>';
1666 print '</tr>';
1667 }
1668
1669 if ($mysoc->localtax2_assuj == "1" || $all['total_localtax2'] != 0) {
1670 print '<tr><td class="titlefield">' . $langs->trans("TotalLT2") . '</td>';
1671 print '<td class="nowraponall amountcard right nowrap">' . ($all['total_localtax2'] ? price($all['total_localtax2']) : '<span class="opacitymedium">0</span>') . '</td>';
1672 print '<td class="nowraponall amountcard right">' . ($draft['total_localtax2'] ? price($draft['total_localtax2']) : '<span class="opacitymedium">0</span>') . '</td>';
1673 print '<td class="nowraponall amountcard right">' . ($enabled['total_localtax2'] ? price($enabled['total_localtax2']) : '<span class="opacitymedium">0</span>') . '</td>';
1674 print '<td class="nowraponall amountcard right">' . ($expired['total_localtax2'] ? price($expired['total_localtax2']) : '<span class="opacitymedium">0</span>') . '</td>';
1675 print '<td class="nowraponall amountcard right">' . ($close['total_localtax2'] ? price($close['total_localtax2']) : '<span class="opacitymedium">0</span>') . '</td>';
1676 print '</tr>';
1677 }
1678
1679 print '<tr><td class="titlefield">'.$langs->trans("TotalTTC").'</td>';
1680 print '<td class="nowraponall amountcard right nowrap">'.($all['total_ttc'] ? price($all['total_ttc']): '<span class="opacitymedium">0</span>').'</td>';
1681 print '<td class="nowraponall amountcard right">'.($draft['total_ttc'] ? price($draft['total_ttc']) : '<span class="opacitymedium">0</span>').'</td>';
1682 print '<td class="nowraponall amountcard right">'.($enabled['total_ttc'] ? price($enabled['total_ttc']) : '<span class="opacitymedium">0</span>').'</td>';
1683 print '<td class="nowraponall amountcard right">'.($expired['total_ttc'] ? price($expired['total_ttc']) : '<span class="opacitymedium">0</span>').'</td>';
1684 print '<td class="nowraponall amountcard right">'.($close['total_ttc'] ? price($close['total_ttc']) : '<span class="opacitymedium">0</span>').'</td>';
1685 print '</tr>';
1686
1687 print "</table>";
1688 print '</div>';
1689 }
1690
1691 print '</div>';
1692 print '</div>';
1693
1694 print '<div class="clearboth"></div><br>';
1695
1696 if ($object->status == $object::STATUS_DRAFT && $user->hasRight('contrat', 'creer')) {
1697 print '</form>';
1698 }
1699
1700 echo '<br>';
1701
1702 if (getDolGlobalString('MAIN_DISABLE_CONTACTS_TAB')) {
1703 $blocname = 'contacts';
1704 $title = $langs->trans('ContactsAddresses');
1705 include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1706 }
1707
1708 if (getDolGlobalString('MAIN_DISABLE_NOTES_TAB')) {
1709 $blocname = 'notes';
1710 $title = $langs->trans('Notes');
1711 include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1712 }
1713
1714
1715 $arrayothercontracts = $object->getListOfContracts('others'); // array or -1 if technical error
1716
1717 /*
1718 * Lines of contracts
1719 */
1720
1721 // Add products/services form
1722 //$forceall = 1;
1723 global $inputalsopricewithtax;
1724 $inputalsopricewithtax = 1;
1725
1726 $productstatic = new Product($db);
1727
1728 $usemargins = 0;
1729 if (isModEnabled('margin') && !empty($object->element) && in_array($object->element, array('facture', 'propal', 'commande'))) {
1730 $usemargins = 1;
1731 }
1732
1733 $parameters = array('nbOfLines' => &$nbofservices);
1734 $reshook = $hookmanager->executeHooks('printObjectLinesBlock', $parameters, $object, $action);
1735 if (empty($reshook)) {
1736 // Title line for service
1737 $cursorline = 1;
1738
1739 print '<div id="contrat-lines-container" id="contractlines" data-contractid="'.$object->id.'" data-element="'.$object->element.'" >';
1740 while ($cursorline <= $nbofservices) {
1741 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.'" >';
1742 print '<form name="update" id="addproduct" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="post">';
1743 print '<input type="hidden" name="token" value="'.newToken().'">';
1744 print '<input type="hidden" name="action" value="updateline">';
1745 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
1746 print '<input type="hidden" name="elrowid" value="'.$object->lines[$cursorline - 1]->id.'">';
1747 print '<input type="hidden" name="fournprice" value="'.(!empty($object->lines[$cursorline - 1]->fk_fournprice) ? $object->lines[$cursorline - 1]->fk_fournprice : 0).'">';
1748
1749 // Area with common detail of line
1750 print '<div class="div-table-responsive-no-min">';
1751 print '<table class="notopnoleftnoright allwidth tableforservicepart1 centpercent">';
1752
1753 $sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.qty,";
1754 $sql .= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,";
1755 $sql .= " cd.date_ouverture_prevue as date_start, cd.date_ouverture as date_start_real,";
1756 $sql .= " cd.date_fin_validite as date_end, cd.date_cloture as date_end_real,";
1757 $sql .= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,";
1758 $sql .= " cd.fk_unit,";
1759 $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";
1760 $sql .= " ,cd.rang";
1761 $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
1762 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
1763 $sql .= " WHERE cd.rowid = ".((int) $object->lines[$cursorline - 1]->id);
1764
1765 $result = $db->query($sql);
1766 $objp = null;
1767 if ($result) {
1768 $total = 0;
1769
1770 $objp = $db->fetch_object($result);
1771
1772 // Line title
1773 print '<tr class="liste_titre'.($cursorline ? ' liste_titre_add' : '').'">';
1774 print '<td>'.$langs->trans("ServiceNb", $cursorline).'</td>';
1775 print '<td width="80" class="center">'.$langs->trans("VAT").'</td>';
1776 print '<td width="80" class="right">'.$langs->trans("PriceUHT").'</td>';
1777 //if (isModEnabled("multicurrency")) {
1778 // print '<td width="80" class="right">'.$langs->trans("PriceUHTCurrency").'</td>';
1779 //}
1780 print '<td width="30" class="center">'.$langs->trans("Qty").'</td>';
1781 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
1782 print '<td width="30" class="left">'.$langs->trans("Unit").'</td>';
1783 }
1784 print '<td width="50" class="right">'.$langs->trans("ReductionShort").'</td>';
1785 if (isModEnabled('margin') && getDolGlobalString('MARGIN_SHOW_ON_CONTRACT')) {
1786 print '<td width="50" class="right">'.$langs->trans("BuyingPrice").'</td>';
1787 }
1788 //
1789
1790 if ($nbofservices > 1 && $conf->browser->layout != 'phone' && $user->hasRight('contrat', 'creer')) {
1791 print '<td width="30" class="linecolmove tdlineupdown center">';
1792 if ($cursorline > 1) {
1793 print '<a class="lineupdown reposition paddingrightonly paddingleftonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=up&token='.newToken().'&rowid='.$objp->rowid.'">';
1794 echo img_up('default', 0, 'imgupforline');
1795 print '</a>';
1796 }
1797 if ($cursorline < $nbofservices) {
1798 print '<a class="lineupdown reposition paddingrightonly paddingleftonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=down&token='.newToken().'&rowid='.$objp->rowid.'">';
1799 echo img_down('default', 0, 'imgdownforline');
1800 print '</a>';
1801 }
1802 print '</td>';
1803 } else {
1804 print '<td width="30">&nbsp;</td>';
1805 }
1806
1807 print "</tr>\n";
1808
1809
1810
1811 // Line in view mode
1812 if ($action != 'editline' || $idline != $objp->rowid) {
1813 $moreparam = '';
1814 if (getDolGlobalString('CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT') && $objp->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') {
1815 $moreparam = 'style="display: none;"';
1816 }
1817
1818 $line = $objp;
1819 $line->id = $objp->rowid;
1820
1821 $coldisplay = 0;
1822
1823 print '<tr class="tdtop oddeven" '.$moreparam.'>';
1824
1825 // Label
1826 print '<td class="linecoldescription minwidth300imp">';
1827 $coldisplay++;
1828 print '<div id="line_'.$line->rowid.'"></div>';
1829 if ($objp->fk_product > 0) {
1830 $productstatic->id = $objp->fk_product;
1831 $productstatic->type = $objp->ptype;
1832 $productstatic->ref = $objp->pref;
1833 $productstatic->entity = $objp->pentity;
1834 $productstatic->label = $objp->plabel;
1835 $productstatic->status = $objp->tosell;
1836 $productstatic->status_buy = $objp->tobuy;
1837 $productstatic->status_batch = $objp->tobatch;
1838
1839 $text = $productstatic->getNomUrl(1, '', 32);
1840 if ($objp->plabel) {
1841 $text .= ' - ';
1842 $text .= $objp->plabel;
1843 }
1844 $description = $objp->description;
1845
1846 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1847 print (!empty($line->fk_parent_line) ? img_picto('', 'rightarrow.png') : '') . $text;
1848 if (!getDolGlobalInt('PRODUIT_DESC_IN_FORM')) {
1849 print $form->textwithpicto('', $description);
1850 }
1851 } else {
1852 print $form->textwithtooltip($text, $description, 3, 0, '', '', 0, (!empty($line->fk_parent_line) ? img_picto('', 'rightarrow.png') : ''));
1853 }
1854
1855 // Add description in form
1856 if ($line->fk_product > 0 && getDolGlobalInt('PRODUIT_DESC_IN_FORM_ACCORDING_TO_DEVICE')) {
1857 print (!empty($line->description) && $line->description != $line->plabel) ? (($line->date_start || $line->date_end) ? '' : '<br>').'<br>'.dol_htmlentitiesbr($line->description) : '';
1858 }
1859 } else {
1860 print img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description)."\n";
1861 }
1862 print '</td>';
1863
1864 // VAT
1865 print '<td class="center">';
1866 print vatrate($objp->tva_tx.($objp->vat_src_code ? (' ('.$objp->vat_src_code.')') : ''), true, $objp->info_bits);
1867 print '</td>';
1868 // Price
1869 print '<td class="right">'.($objp->subprice != '' ? price($objp->subprice) : '')."</td>\n";
1870 // Price multicurrency
1871 /*if (isModEnabled("multicurrency")) {
1872 print '<td class="linecoluht_currency nowrap right">'.price($objp->multicurrency_subprice).'</td>';
1873 }*/
1874 // Quantity
1875 print '<td class="center">'.$objp->qty.'</td>';
1876 // Unit
1877 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
1878 print '<td class="left">'.$object->lines[$cursorline - 1]->getLabelOfUnit('long', $langs).'</td>';
1879 }
1880 // Discount
1881 if ($objp->remise_percent > 0) {
1882 print '<td class="right">'.$objp->remise_percent."%</td>\n";
1883 } else {
1884 print '<td>&nbsp;</td>';
1885 }
1886
1887 // Margin
1888 if (isModEnabled('margin') && getDolGlobalString('MARGIN_SHOW_ON_CONTRACT')) {
1889 print '<td class="right nowraponall">'.price($objp->pa_ht).'</td>';
1890 }
1891
1892 // Icon move, update et delete (status contract 0=draft,1=validated,2=closed)
1893 print '<td class="nowraponall right">';
1894 if ($user->hasRight('contrat', 'creer') && is_array($arrayothercontracts) && count($arrayothercontracts) && ($object->status >= 0)) {
1895 print '<!-- link to move service line into another contract -->';
1896 print '<a class="reposition marginrightonly" style="padding-left: 5px;" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=move&token='.newToken().'&elrowid='.$objp->rowid.'">';
1897 print img_picto($langs->trans("MoveToAnotherContract"), 'uparrow');
1898 print '</a>';
1899 }
1900 if ($user->hasRight('contrat', 'creer') && ($object->statut >= 0)) {
1901 print '<a class="reposition marginrightonly editfielda" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=editline&token='.newToken().'&elrowid='.$objp->rowid.'">';
1902 print img_edit();
1903 print '</a>';
1904 }
1905 if ($user->hasRight('contrat', 'creer') && ($object->statut >= 0)) {
1906 print '<a class="reposition marginrightonly" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=deleteline&token='.newToken().'&elrowid='.$objp->rowid.'">';
1907 print img_delete();
1908 print '</a>';
1909 }
1910 print '</td>';
1911
1912 print "</tr>\n";
1913
1914 $colspan = 6;
1915 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
1916 $colspan++;
1917 }
1918 if (isModEnabled('margin') && getDolGlobalString('MARGIN_SHOW_ON_CONTRACT')) {
1919 $colspan++;
1920 }
1921
1922 // Dates of service planned and real
1923 if ($objp->subprice >= 0) {
1924 print '<tr class="oddeven" '.$moreparam.'>';
1925 print '<td colspan="'.$colspan.'">';
1926
1927 // Date planned
1928 print $langs->trans("DateStartPlanned").': ';
1929 if ($objp->date_start) {
1930 print dol_print_date($db->jdate($objp->date_start), 'day');
1931 // Warning si date prevu passee et pas en service
1932 if ($objp->statut == 0 && $db->jdate($objp->date_start) < ($now - $conf->contrat->services->inactifs->warning_delay)) {
1933 $warning_delay = $conf->contrat->services->inactifs->warning_delay / 3600 / 24;
1934 $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
1935 print " ".img_warning($textlate);
1936 }
1937 } else {
1938 print $langs->trans("Unknown");
1939 }
1940 print ' &nbsp;-&nbsp; ';
1941 print $langs->trans("DateEndPlanned").': ';
1942 if ($objp->date_end) {
1943 print dol_print_date($db->jdate($objp->date_end), 'day');
1944 if ($objp->statut == 4 && $db->jdate($objp->date_end) < ($now - $conf->contrat->services->expires->warning_delay)) {
1945 $warning_delay = $conf->contrat->services->expires->warning_delay / 3600 / 24;
1946 $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
1947 print " ".img_warning($textlate);
1948 }
1949 } else {
1950 print $langs->trans("Unknown");
1951 }
1952
1953 print '</td>';
1954 print '</tr>';
1955 }
1956
1957 // Display lines extrafields
1958 if (is_array($extralabelslines) && count($extralabelslines) > 0) {
1959 $line = new ContratLigne($db);
1960 $line->id = $objp->rowid;
1961 $line->fetch_optionals();
1962 print $line->showOptionals($extrafields, 'view', array('class' => 'oddeven', 'style' => $moreparam, 'colspan' => $colspan, 'tdclass' => 'notitlefieldcreate'), '', '', '1');
1963 }
1964 } else {
1965 // Line in mode update
1966 // Line carac
1967 print '<tr class="oddeven">';
1968 print '<td>';
1969 $currentLineProductId = GETPOSTISSET('idprod') ? GETPOST('idprod') : (!empty($object->lines[$cursorline - 1]->fk_product) ? $object->lines[$cursorline - 1]->fk_product : 0);
1970 if ($objp->fk_product > 0) {
1971 $canchangeproduct = 1;
1972
1973 // @TODO: As $canchangeproduct is set just before, in what usecase it can be empty ?
1974 if (empty($canchangeproduct)) {
1975 $productstatic->id = $objp->fk_product;
1976 $productstatic->type = $objp->ptype;
1977 $productstatic->ref = $objp->pref;
1978 $productstatic->entity = $objp->pentity;
1979 print $productstatic->getNomUrl(1, '', 32);
1980 print $objp->label ? ' - '.dol_trunc($objp->label, 32) : '';
1981 print '<input type="hidden" name="idprod" value="'.$currentLineProductId.'">';
1982 } else {
1983 $senderissupplier = 0; // @TODO Option to allow purchased products ?
1984 if (empty($senderissupplier)) {
1985 if (getDolGlobalString('CONTRACT_SUPPORT_PRODUCTS')) {
1986 $filtertype = '';
1987 } else {
1988 $filtertype = '1';
1989 }
1990 print $form->select_produits($currentLineProductId, 'idprod', $filtertype, 0, 0, 1, 2, '', 0, array(), 0, 1, 0, 'minwidth250onall maxwidth500 widthcentpercentminusx');
1991 } else {
1992 $form->select_produits_fournisseurs($currentLineProductId, 'idprod');
1993 }
1994 }
1995 print '<br>';
1996 } else {
1997 print $objp->label ? $objp->label.'<br>' : '';
1998 print '<input type="hidden" name="idprod" value="'.$currentLineProductId.'">';
1999 }
2000
2001 // editeur wysiwyg
2002 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
2003 $nbrows = ROWS_2;
2004 if (getDolGlobalString('MAIN_INPUT_DESC_HEIGHT')) {
2005 $nbrows = getDolGlobalString('MAIN_INPUT_DESC_HEIGHT');
2006 }
2007 $doleditor = new DolEditor('product_desc', (GETPOSTISSET('product_desc') ? GETPOST('product_desc') : $objp->description), '', 92, 'dolibarr_details', '', false, true, getDolGlobalInt('FCKEDITOR_ENABLE_DETAILS'), $nbrows, '90%');
2008 $doleditor->Create();
2009
2010 print '</td>';
2011
2012 // VAT
2013 print '<td class="right">';
2014 print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code ? (' ('.$objp->vat_src_code.')') : ''), $mysoc, $object->thirdparty, $currentLineProductId, $objp->info_bits, $objp->product_type, false, 1);
2015 print '</td>';
2016
2017 // Price
2018 print '<td class="right"><input class="width50" type="text" name="elprice" value="'.(GETPOSTISSET('elprice') ? GETPOST('elprice') : price($objp->subprice)).'"></td>';
2019
2020 // Price multicurrency
2021 /*if (isModEnabled("multicurrency")) {
2022 print '<td class="linecoluht_currency nowrap right">'.price($objp->multicurrency_subprice).'</td>';
2023 }*/
2024
2025 // Quantity
2026 print '<td class="center"><input size="2" type="text" name="elqty" value="'.(GETPOSTISSET('elqty') ? GETPOST('elqty') : $objp->qty).'"></td>';
2027
2028 // Unit
2029 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
2030 print '<td class="left">';
2031 print $form->selectUnits((GETPOSTISSET('unit') ? GETPOSTINT('unit') : $objp->fk_unit), "unit");
2032 print '</td>';
2033 }
2034
2035 // Discount
2036 print '<td class="nowraponall right"><input size="1" type="text" name="elremise_percent" value="'.(GETPOSTISSET('elremise_percent') ? GETPOST('elremise_percent') : $objp->remise_percent).'">%</td>';
2037
2038 if (!empty($usemargins)) {
2039 print '<td class="right">';
2040 if ($objp->fk_product) {
2041 print '<select id="fournprice" name="fournprice"></select>';
2042 }
2043 print '<input id="buying_price" type="text" class="width50" name="buying_price" value="'.price((GETPOSTISSET('buying_price') ? GETPOST('buying_price') : $objp->pa_ht), 0, '', 0).'"></td>';
2044 }
2045 print '<td class="center">';
2046 print '<input type="submit" class="button margintoponly marginbottomonly" name="save" value="'.$langs->trans("Modify").'">';
2047 print '<br><input type="submit" class="button margintoponly marginbottomonly button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
2048 print '</td>';
2049 print '</tr>';
2050
2051 $colspan = 6;
2052 if (isModEnabled('margin') && getDolGlobalString('MARGIN_SHOW_ON_CONTRACT')) {
2053 $colspan++;
2054 }
2055 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
2056 $colspan++;
2057 }
2058
2059 // Line dates planned
2060 print '<tr class="oddeven">';
2061 print '<td colspan="'.$colspan.'">';
2062 print $langs->trans("DateStartPlanned").' ';
2063 print $form->selectDate($db->jdate($objp->date_start), "date_start_update", $usehm, $usehm, ($db->jdate($objp->date_start) > 0 ? 0 : 1), "update");
2064 print ' &nbsp;&nbsp;'.$langs->trans("DateEndPlanned").' ';
2065 print $form->selectDate($db->jdate($objp->date_end), "date_end_update", $usehm, $usehm, ($db->jdate($objp->date_end) > 0 ? 0 : 1), "update");
2066 print '</td>';
2067 print '</tr>';
2068
2069 if (is_array($extralabelslines) && count($extralabelslines) > 0) {
2070 $line = new ContratLigne($db);
2071 $line->id = $objp->rowid;
2072 $line->fetch_optionals();
2073
2074 print $line->showOptionals($extrafields, 'edit', array('style' => 'class="oddeven"', 'colspan' => $colspan, 'tdclass' => 'notitlefieldcreate'), '', '', '1');
2075 }
2076 }
2077
2078 $db->free($result);
2079 } else {
2081 }
2082
2083 if ($object->statut > 0) {
2084 $moreparam = '';
2085 if (getDolGlobalString('CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT') && $object->lines[$cursorline - 1]->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') {
2086 $moreparam = 'style="display: none;"';
2087 }
2088
2089 $colspan = 6;
2090 if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
2091 $colspan++;
2092 }
2093 if (isModEnabled('margin') && getDolGlobalString('MARGIN_SHOW_ON_CONTRACT')) {
2094 $colspan++;
2095 }
2096
2097 print '<tr class="oddeven" '.$moreparam.'>';
2098 print '<td class="tdhrthin" colspan="'.$colspan.'"><hr class="opacitymedium tdhrthin"></td>';
2099 print "</tr>\n";
2100 }
2101
2102 print "</table>";
2103 print '</div>';
2104
2105 print "</form>\n";
2106
2107
2108 /*
2109 * Confirmation to delete service line of contract
2110 */
2111 if ($action == 'deleteline' && !$cancel && $user->hasRight('contrat', 'creer') && $object->lines[$cursorline - 1]->id == $idline) {
2112 print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".((int) $object->id)."&lineid=".((int) $idline), $langs->trans("DeleteContractLine"), $langs->trans("ConfirmDeleteContractLine"), "confirm_deleteline", '', 0, 1);
2113 if ($ret == 'html') {
2114 print '<table class="notopnoleftnoright centpercent"><tr class="oddeven" height="6"><td></td></tr></table>';
2115 }
2116 }
2117
2118 /*
2119 * Confirmation to move service toward another contract
2120 */
2121 if ($action == 'move' && !$cancel && $user->hasRight('contrat', 'creer') && $object->lines[$cursorline - 1]->id == $idline) {
2122 $arraycontractid = array();
2123 foreach ($arrayothercontracts as $contractcursor) {
2124 $arraycontractid[$contractcursor->id] = $contractcursor->ref;
2125 }
2126 //var_dump($arraycontractid);
2127 // Cree un tableau formulaire
2128 $formquestion = array(
2129 'text' => $langs->trans("ConfirmMoveToAnotherContractQuestion"),
2130 0 => array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid));
2131
2132 print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".((int) $object->id)."&lineid=".((int) $idline), $langs->trans("MoveToAnotherContract"), $langs->trans("ConfirmMoveToAnotherContract"), "confirm_move", $formquestion, 'yes');
2133 print '<table class="notopnoleftnoright centpercent"><tr class="oddeven" height="6"><td></td></tr></table>';
2134 }
2135
2136 // Area with status and activation info of line
2137 if ($object->status > 0) {
2138 print '<table class="notopnoleftnoright tableforservicepart2'.($cursorline < $nbofservices ? ' boxtablenobottom' : '').' centpercent">';
2139
2140 print '<tr class="oddeven" '.$moreparam.'>';
2141 print '<td><span class="valignmiddle hideonsmartphone">'.$langs->trans("ServiceStatus").':</span> '.$object->lines[$cursorline - 1]->getLibStatut(4).'</td>';
2142 print '<td width="30" class="right">';
2143 if ($user->socid == 0) {
2144 if ($object->status > 0 && $action != 'activateline' && $action != 'unactivateline' && is_object($objp)) {
2145 $tmpaction = 'activateline';
2146 $tmpactionpicto = 'play';
2147 $tmpactiontext = $langs->trans("Activate");
2148 if ($objp->statut == 4) {
2149 $tmpaction = 'unactivateline';
2150 $tmpactionpicto = 'playstop.png';
2151 $tmpactiontext = $langs->trans("Disable");
2152 }
2153 if (($tmpaction == 'activateline' && $user->hasRight('contrat', 'activer')) || ($tmpaction == 'unactivateline' && $user->hasRight('contrat', 'desactiver'))) {
2154 print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline - 1]->id.'&amp;action='.$tmpaction.'&token='.newToken().'">';
2155 print img_picto($tmpactiontext, $tmpactionpicto);
2156 print '</a>';
2157 }
2158 }
2159 }
2160 print '</td>';
2161 print "</tr>\n";
2162
2163 print '<tr class="oddeven" '.$moreparam.'>';
2164
2165 print '<td>';
2166 // Si pas encore active
2167 if (!$objp->date_start_real) {
2168 print $langs->trans("DateStartReal").': ';
2169 if ($objp->date_start_real) {
2170 print dol_print_date($db->jdate($objp->date_start_real), 'day');
2171 } else {
2172 print $langs->trans("ContractStatusNotRunning");
2173 }
2174 }
2175 // Si active et en cours
2176 if ($objp->date_start_real && !$objp->date_end_real) {
2177 print $langs->trans("DateStartReal").': ';
2178 print dol_print_date($db->jdate($objp->date_start_real), 'day');
2179 }
2180 // Si desactive
2181 if ($objp->date_start_real && $objp->date_end_real) {
2182 print $langs->trans("DateStartReal").': ';
2183 print dol_print_date($db->jdate($objp->date_start_real), 'day');
2184 print ' &nbsp;-&nbsp; ';
2185 print $langs->trans("DateEndReal").': ';
2186 print dol_print_date($db->jdate($objp->date_end_real), 'day');
2187 }
2188 if (!empty($objp->comment)) {
2189 print " &nbsp;-&nbsp; ".$objp->comment;
2190 }
2191 print '</td>';
2192
2193 print '<td class="center">&nbsp;</td>';
2194
2195 print '</tr>';
2196 print '</table>';
2197 }
2198
2199 // Form to activate line
2200 if ($permissiontoactivate && $action == 'activateline' && $object->lines[$cursorline - 1]->id == GETPOSTINT('ligne') && is_object($objp)) {
2201 print '<form name="active" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
2202 print '<input type="hidden" name="token" value="'.newToken().'">';
2203 print '<input type="hidden" name="action" value="confirm_active">';
2204 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
2205 print '<input type="hidden" name="id" value="'.$object->id.'">';
2206 print '<input type="hidden" name="ligne" value="'.GETPOSTINT('ligne').'">';
2207 print '<input type="hidden" name="confirm" value="yes">';
2208
2209 print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ? ' boxtablenobottom' : '').' centpercent">';
2210
2211 // Definie date debut et fin par default
2212 $dateactstart = $objp->date_start;
2213 if (GETPOST('remonth')) {
2214 $dateactstart = dol_mktime(12, 0, 0, GETPOSTINT('remonth'), GETPOSTINT('reday'), GETPOSTINT('reyear'));
2215 } elseif (!$dateactstart) {
2216 $dateactstart = time();
2217 }
2218
2219 $dateactend = $objp->date_end;
2220 if (GETPOST('endmonth')) {
2221 $dateactend = dol_mktime(12, 0, 0, GETPOSTINT('endmonth'), GETPOSTINT('endday'), GETPOSTINT('endyear'));
2222 } elseif (!$dateactend) {
2223 if ($objp->fk_product > 0) {
2224 $product = new Product($db);
2225 $product->fetch($objp->fk_product);
2226 if (!empty($product->duration_value) && !empty($product->duration_unit)) {
2227 $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
2228 }
2229 }
2230 }
2231
2232 print '<tr class="oddeven">';
2233 print '<td class="nohover">'.$langs->trans("DateServiceActivate").'</td><td class="nohover">';
2234 print $form->selectDate($dateactstart, 'start', $usehm, $usehm, 0, "active", 1, 0);
2235 print '</td>';
2236 print '<td class="nohover">'.$langs->trans("DateEndPlanned").'</td><td class="nohover">';
2237 print $form->selectDate($dateactend, "end", $usehm, $usehm, 0, "active", 1, 0);
2238 print '</td>';
2239 print '<td class="center nohover">';
2240 print '</td>';
2241
2242 print '</tr>';
2243
2244 print '<tr class="oddeven">';
2245 print '<td class="nohover">'.$langs->trans("Comment").'</td><td colspan="3" class="nohover" colspan="'.(isModEnabled('margin') ? 4 : 3).'"><input type="text" class="minwidth300" name="comment" value="'.dol_escape_htmltag(GETPOST("comment", 'alphanohtml')).'"></td>';
2246 print '<td class="nohover right">';
2247 print '<input type="submit" class="button" name="activate" value="'.$langs->trans("Activate").'"> &nbsp; ';
2248 print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
2249 print '</td>';
2250 print '</tr>';
2251
2252 print '</table>';
2253
2254 print '</form>';
2255 }
2256
2257 // Form to disable a contract line
2258 if ($permissiontodisable && $action == 'unactivateline' && $object->lines[$cursorline - 1]->id == GETPOSTINT('ligne') && is_object($objp)) {
2259 print '<!-- Form to disabled a line -->'."\n";
2260 print '<form name="confirm_closeline" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline - 1]->id.'" method="post">';
2261 print '<input type="hidden" name="token" value="'.newToken().'">';
2262 print '<input type="hidden" name="confirm" value="yes">';
2263 print '<input type="hidden" name="action" value="confirm_closeline">';
2264 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
2265
2266 print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ? ' boxtablenobottom' : '').' centpercent">';
2267
2268 // Definie date debut et fin par default
2269 $dateactstart = $objp->date_start_real;
2270 if (GETPOST('remonth')) {
2271 $dateactstart = dol_mktime(12, 0, 0, GETPOSTINT('remonth'), GETPOSTINT('reday'), GETPOSTINT('reyear'));
2272 } elseif (!$dateactstart) {
2273 $dateactstart = time();
2274 }
2275
2276 $dateactend = $objp->date_end_real;
2277 if (GETPOST('endmonth')) {
2278 $dateactend = dol_mktime(12, 0, 0, GETPOSTINT('endmonth'), GETPOSTINT('endday'), GETPOSTINT('endyear'));
2279 } elseif (!$dateactend) {
2280 if ($objp->fk_product > 0) {
2281 $product = new Product($db);
2282 $product->fetch($objp->fk_product);
2283 $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
2284 }
2285 }
2286 $now = dol_now();
2287 if ($dateactend > $now) {
2288 $dateactend = $now;
2289 }
2290
2291 print '<tr class="oddeven"><td colspan="2" class="nohover">';
2292 if ($objp->statut >= 4) {
2293 if ($objp->statut == 4) {
2294 print $langs->trans("DateEndReal").' ';
2295 print $form->selectDate($dateactend, "end", $usehm, $usehm, ($objp->date_end_real > 0 ? 0 : 1), "closeline", 1, 1);
2296 }
2297 }
2298 print '</td>';
2299 print '<td class="center nohover">';
2300 print '</td></tr>';
2301
2302 print '<tr class="oddeven">';
2303 print '<td class="nohover">'.$langs->trans("Comment").'</td><td class="nohover"><input class="quatrevingtpercent" type="text" class="flat" name="comment" value="'.dol_escape_htmltag(GETPOST('comment', 'alpha')).'"></td>';
2304 print '<td class="nohover right">';
2305 print '<input type="submit" class="button" name="close" value="'.$langs->trans("Disable").'"> &nbsp; ';
2306 print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
2307 print '</td>';
2308 print '</tr>';
2309
2310 print '</table>';
2311
2312 print '</form>';
2313 }
2314 print '</div>';
2315 $cursorline++;
2316 }
2317 print '</div>';
2318 }
2319
2320 // Form to add new line
2321 if ($user->hasRight('contrat', 'creer') && ($object->status == 0)) {
2322 $dateSelector = 1;
2323
2324 print "\n";
2325 print ' <form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '' : '#line_'.GETPOSTINT('lineid')).'" method="POST">
2326 <input type="hidden" name="token" value="'.newToken().'">
2327 <input type="hidden" name="action" value="'.(($action != 'editline') ? 'addline' : 'updateline').'">
2328 <input type="hidden" name="mode" value="">
2329 <input type="hidden" name="id" value="'.$object->id.'">
2330 <input type="hidden" name="page_y" value="">
2331 <input type="hidden" name="backtopage" value="'.$backtopage.'">
2332 ';
2333
2334 print '<div class="div-table-responsive-no-min">';
2335 print '<table id="tablelines" class="noborder noshadow" width="100%">'; // Array with (n*2)+1 lines
2336
2337 // Form to add new line
2338 if ($action != 'editline') {
2339 $forcetoshowtitlelines = 1;
2340 if (empty($object->multicurrency_code)) {
2341 $object->multicurrency_code = $conf->currency; // TODO Remove this when multicurrency supported on contracts
2342 }
2343
2344 // Add free products/services
2345
2346 $parameters = array();
2347 $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2348 if ($reshook < 0) {
2349 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
2350 }
2351 if (empty($reshook)) {
2352 $object->formAddObjectLine(1, $mysoc, $soc);
2353 }
2354 }
2355
2356 print '</table>';
2357 print '</div>';
2358 print '</form>';
2359 }
2360
2361 print dol_get_fiche_end();
2362
2363 // Select mail models is same action as presend
2364 if (GETPOST('modelselected')) {
2365 $action = 'presend';
2366 }
2367
2368 /*
2369 * Buttons
2370 */
2371 if ($user->socid == 0 && $action != 'presend' && $action != 'editline') {
2372 print '<div class="tabsAction">';
2373
2374 $parameters = array();
2375 $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2376
2377 if (empty($reshook)) {
2378 $params = array(
2379 'attr' => array(
2380 'title' => '',
2381 'class' => 'classfortooltip'
2382 )
2383 );
2384
2385 // Send
2386 if (empty($user->socid)) {
2387 if ($object->status == $object::STATUS_VALIDATED) {
2388 if ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || $user->hasRight('contrat', 'creer'))) {
2389 print dolGetButtonAction('', $langs->trans('SendMail'), 'email', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&token='.newToken().'&mode=init#formmailbeforetitle', '', true, $params);
2390 } else {
2391 print dolGetButtonAction('', $langs->trans('SendMail'), 'email', '#', '', false, $params);
2392 }
2393 }
2394 }
2395
2396 if ($object->status == $object::STATUS_DRAFT && $nbofservices) {
2397 if ($user->hasRight('contrat', 'creer')) {
2398 unset($params['attr']['title']);
2399 print dolGetButtonAction($langs->trans('Validate'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=valid&token='.newToken(), '', true, $params);
2400 } else {
2401 $params['attr']['title'] = $langs->trans("NotEnoughPermissions");
2402 print dolGetButtonAction($langs->trans('Validate'), '', 'default', '#', '', false, $params);
2403 }
2404 }
2405 if ($object->status == $object::STATUS_VALIDATED) {
2406 if ($user->hasRight('contrat', 'creer')) {
2407 unset($params['attr']['title']);
2408 print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=reopen&token='.newToken(), '', true, $params);
2409 } else {
2410 $params['attr']['title'] = $langs->trans("NotEnoughPermissions");
2411 print dolGetButtonAction($langs->trans('Modify'), '', 'default', '#', '', false, $params);
2412 }
2413 }
2414
2415 // Create ... buttons
2416 $arrayofcreatebutton = array();
2417 if (isModEnabled('propal') && $object->status > 0 && $soc->client > 0) {
2418 $arrayofcreatebutton[] = array(
2419 'url' => '/comm/propal/card.php?action=create&origin='.$object->element.'&originid='.$object->id.'&socid='.$object->thirdparty->id.'&renewal=true',
2420 'label' => $langs->trans('AddProp'),
2421 'lang' => 'propal',
2422 'perm' => $user->hasRight('propale', 'creer') ? true : false,
2423 'enabled' => true,
2424 );
2425 }
2426 //if (isModEnabled('order') && $object->status > 0 && $object->nbofservicesclosed < $nbofservices) {
2427 if (isModEnabled('order') && $object->status > 0 && $soc->client > 0) {
2428 $arrayofcreatebutton[] = array(
2429 'url' => '/commande/card.php?action=create&token='.newToken().'&origin='.$object->element.'&originid='.$object->id.'&socid='.$object->thirdparty->id,
2430 'label' => $langs->trans('AddOrder'),
2431 'lang' => 'orders',
2432 'perm' => $user->hasRight('commande', 'creer') ? true : false,
2433 'enabled' => true,
2434 );
2435 }
2436 if (isModEnabled('invoice') && $object->status > 0 && $soc->client > 0) {
2437 $arrayofcreatebutton[] = array(
2438 'url' => '/compta/facture/card.php?action=create&origin='.$object->element.'&originid='.$object->id.'&socid='.$object->thirdparty->id,
2439 'label' => $langs->trans('CreateBill'),
2440 'lang' => 'bills',
2441 'perm' => $user->hasRight('facture', 'creer') ? true : false,
2442 'enabled' => true,
2443 );
2444 }
2445 if (isModEnabled('supplier_invoice') && $object->status > 0 && $soc->fournisseur == 1) {
2446 $langs->load("suppliers");
2447 $arrayofcreatebutton[] = array(
2448 'url' => '/fourn/facture/card.php?action=create&origin='.$object->element.'&originid='.$object->id.'&socid='.$object->thirdparty->id,
2449 'label' => $langs->trans('AddSupplierInvoice'),
2450 'lang' => 'bills',
2451 'perm' => $user->hasRight('fournisseur', 'facture', 'creer') ? true : false,
2452 'enabled' => true,
2453 );
2454 }
2455 if (count($arrayofcreatebutton)) {
2456 unset($params['attr']['title']);
2457 print dolGetButtonAction('', $langs->trans("Create"), 'default', $arrayofcreatebutton, '', true, $params);
2458 }
2459
2460 $arrayforbutaction = array();
2461 $arrayforbutaction[] = array(
2462 'url' => '/contrat/card.php?id='.$object->id.'&action=activate&token='.newToken(),
2463 'label' => $langs->trans('ActivateAllContracts'),
2464 'lang' => 'bills',
2465 'perm' => ($object->nbofservicesclosed > 0 || $object->nbofserviceswait > 0) ? $permissiontoactivate : -1,
2466 'enabled' => true,
2467 );
2468 $arrayforbutaction[] = array(
2469 'url' => '/contrat/card.php?id='.$object->id.'&action=close&token='.newToken(),
2470 'label' => $langs->trans('CloseAllContracts'),
2471 'lang' => 'bills',
2472 'perm' => ($object->nbofservicesclosed < $nbofservices) ? $permissiontodisable : -1,
2473 'enabled' => true,
2474 );
2475
2476 if (count($arrayforbutaction)) {
2477 unset($params['attr']['title']);
2478 print dolGetButtonAction('', $langs->trans("Enable")." / ".$langs->trans("Close"), 'default', $arrayforbutaction, '', true, $params);
2479 }
2480
2481 if (getDolGlobalString('CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT') && $object->nbofservicesclosed > 0) {
2482 if ($action == 'showclosedlines') {
2483 print '<div class="inline-block divButAction"><a class="butAction" id="btnhideclosedlines" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=hideclosedlines&amp;token='.newToken().'">'.$langs->trans("HideClosedServices").'</a></div>';
2484 } else {
2485 print '<div class="inline-block divButAction"><a class="butAction" id="btnshowclosedlines" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=showclosedlines&amp;token='.newToken().'">'.$langs->trans("ShowClosedServices").'</a></div>';
2486 }
2487 }
2488
2489 // Sign
2490 if (getDolGlobalString('CONTRACT_SHOW_SIGNATURE_STATUS_WITH_SERVICE_STATUS') && $object->status > Contrat::STATUS_DRAFT) {
2491 if ($object->signed_status != Contrat::$SIGNED_STATUSES['STATUS_SIGNED_ALL']) {
2492 print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=sign&token=' . newToken() . '">' . $langs->trans("ContractSign") . '</a></div>';
2493 } else {
2494 print '<div class="inline-block divButAction"><a class="butAction" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=unsign&token=' . newToken() . '">' . $langs->trans("ContractUnsign") . '</a></div>';
2495 }
2496 }
2497
2498 // Clone
2499 if ($user->hasRight('contrat', 'creer')) {
2500 unset($params['attr']['title']);
2501 print dolGetButtonAction($langs->trans('ToClone'), '', 'clone', $_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->socid.'&action=clone&token='.newToken(), '', true, $params);
2502 }
2503
2504 // Delete
2505 unset($params['attr']['title']);
2506 print dolGetButtonAction($langs->trans('Delete'), '', 'delete', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken(), '', $permissiontodelete, $params);
2507 }
2508
2509 print "</div>";
2510 }
2511
2512 if ($action != 'presend') {
2513 print '<div class="fichecenter"><div class="fichehalfleft">';
2514
2515 /*
2516 * Generated documents
2517 */
2518 $filename = dol_sanitizeFileName($object->ref);
2519 $filedir = $conf->contract->multidir_output[$object->entity ?? $conf->entity]."/".dol_sanitizeFileName($object->ref);
2520 $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
2521 $genallowed = $user->hasRight('contrat', 'lire');
2522 $delallowed = $user->hasRight('contrat', 'creer');
2523 $tooltipAfterComboOfModels = '';
2524 if (getDolGlobalString('MAIN_PDF_ADD_TERMSOFSALE_CONTRACT')) {
2525 $tooltipAfterComboOfModels = $langs->trans("AccordingToYourSetupTheFileWillBeConcatenated", getDolGlobalString('MAIN_INFO_CONTRACT_TERMSOFSALE'));
2526 }
2527
2528 print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, ($object->model_pdf ? $object->model_pdf : getDolGlobalString('CONTRACT_ADDON_PDF')), 1, 0, 0, 28, 0, '', '0', '', $soc->default_lang, '', $object, 0, 'remove_file', $tooltipAfterComboOfModels);
2529
2530
2531 // Show links to link elements
2532 $tmparray = $form->showLinkToObjectBlock($object, array(), array('contrat'), 1);
2533 $linktoelem = $tmparray['linktoelem'];
2534 $htmltoenteralink = $tmparray['htmltoenteralink'];
2535 print $htmltoenteralink;
2536
2537 $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
2538
2539 // Show online signature link
2540 if ($object->status != Contrat::STATUS_DRAFT && getDolGlobalString('CONTRACT_ALLOW_ONLINESIGN')) {
2541 print '<br><!-- Link to sign -->';
2542 require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
2543
2544 print showOnlineSignatureUrl('contract', $object->ref, $object).'<br>';
2545 }
2546
2547 print '</div><div class="fichehalfright">';
2548
2549 $MAXEVENT = 10;
2550
2551 $morehtmlcenter = '<div class="nowraponall">';
2552 $morehtmlcenter .= dolGetButtonTitle($langs->trans('FullConversation'), '', 'fa fa-comments imgforviewmode', DOL_URL_ROOT.'/contrat/messaging.php?id='.$object->id);
2553 $morehtmlcenter .= dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-bars imgforviewmode', DOL_URL_ROOT.'/contrat/agenda.php?id='.$object->id);
2554 $morehtmlcenter .= '</div>';
2555
2556
2557 // List of actions on element
2558 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
2559 $formactions = new FormActions($db);
2560 $somethingshown = $formactions->showactions($object, 'contract', $socid, 1, 'listactions', $MAXEVENT, '', $morehtmlcenter);
2561
2562 print '</div></div>';
2563 }
2564
2565 // Presend form
2566 $modelmail = 'contract';
2567 $defaulttopic = 'SendContractRef';
2568 $diroutput = $conf->contract->multidir_output[$object->entity ?? $conf->entity];
2569 $trackid = 'con'.$object->id;
2570
2571 include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
2572 }
2573}
2574
2575
2576llxFooter();
2577
2578$db->close();
2579
2580
2581// TODO Why this on the page when editing margin for contracts ?
2582if (isModEnabled('margin') && $action == 'editline') {
2583 print "\n".'<script type="text/javascript">'."\n";
2584 ?>
2585 $(document).ready(function() {
2586 var idprod = $("input[name='idprod']").val();
2587 var fournprice = $("input[name='fournprice']").val();
2588 var token = '<?php echo currentToken(); ?>'; // For AJAX Call we use old 'token' and not 'newtoken'
2589 if (idprod > 0) {
2590 $.post('<?php echo DOL_URL_ROOT; ?>/fourn/ajax/getSupplierPrices.php', {
2591 'idprod': idprod,
2592 'token': token
2593 }, function(data) {
2594 if (data.length > 0) {
2595 var options = '';
2596 var trouve=false;
2597 $(data).each(function() {
2598 options += '<option value="'+this.id+'" price="'+this.price+'"';
2599 if (fournprice > 0) {
2600 if (this.id == fournprice) {
2601 options += ' selected';
2602 $("#buying_price").val(pricejs(this.price, 'MU'));
2603 trouve = true;
2604 }
2605 }
2606 options += '>'+this.label+'</option>';
2607 });
2608 options += '<option value=null'+(trouve?'':' selected')+'><?php echo $langs->trans("InputPrice"); ?></option>';
2609 $("#fournprice").html(options);
2610 if (trouve) {
2611 $("#buying_price").hide();
2612 $("#fournprice").show();
2613 }
2614 else {
2615 $("#buying_price").show();
2616 }
2617 $("#fournprice").change(function() {
2618 var selval = $(this).find('option:selected').attr("price");
2619 if (selval)
2620 $("#buying_price").val(pricejs(selval, 'MU')).hide();
2621 else
2622 $('#buying_price').show();
2623 });
2624 }
2625 else {
2626 $("#fournprice").hide();
2627 $('#buying_price').show();
2628 }
2629 },
2630 'json');
2631 }
2632 else {
2633 $("#fournprice").hide();
2634 $('#buying_price').show();
2635 }
2636 });
2637 <?php
2638 print '</script>'."\n";
2639}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage lines of contracts.
Class to manage a WYSIWYG editor.
Class to manage building of HTML components.
Class to offer components to list and upload files.
Class to manage generation of HTML components Only common components must be here.
Class to manage building of HTML components.
Class to manage the table of subscription to notifications.
File of class to manage predefined price products or services by customer.
Class to manage products or services.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
global $mysoc
contract_prepare_head(Contrat $object)
Prepare array with list of tabs.
pricejs(amount, mode='MT', currency_code='', force_locale='')
Function similar to PHP price()
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:129
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_move_dir($srcdir, $destdir, $overwriteifexists=1, $indexdatabase=1, $renamedircontent=1)
Move a directory into another name.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
recordNotFound($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Displays an error page when a record is not found.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
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.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
img_down($titlealt='default', $selected=0, $moreclass='')
Show down arrow logo.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
GETPOSTISARRAY($paramname, $method=0)
Return true if the parameter $paramname is submit from a POST OR GET as an array.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dolGetButtonAction($label, $text='', $actionType='default', $url='', $id='', $userRight=1, $params=array())
Function dolGetButtonAction.
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...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
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...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
img_edit($titlealt='default', $float=0, $other='')
Show logo edit/modify fiche.
img_up($titlealt='default', $selected=0, $moreclass='')
Show top arrow logo.
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.