Issues (2811)

public/htdocs/contrat/card.php (1 issue)

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