dolibarr  16.0.5
card.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2001-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2014 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
5  * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
6  * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
7  * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
8  * Copyright (C) 2010-2023 Juanjo Menent <jmenent@2byte.es>
9  * Copyright (C) 2010-2021 Philippe Grand <philippe.grand@atoo-net.com>
10  * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
11  * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
12  * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
13  * Copyright (C) 2014 Ferran Marcet <fmarcet@2byte.es>
14  * Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
15  * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
16  * Copyright (C) 2020 Nicolas ZABOURI <info@inovea-conseil.com>
17  * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
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 
40 require '../../main.inc.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
42 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
43 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formpropal.class.php';
44 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
45 require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
46 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
47 require_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php';
48 require_once DOL_DOCUMENT_ROOT.'/core/lib/propal.lib.php';
49 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
50 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
51 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
52 if (!empty($conf->project->enabled)) {
53  require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
54  require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
55 }
56 
57 if (!empty($conf->variants->enabled)) {
58  require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
59 }
60 
61 // Load translation files required by the page
62 $langs->loadLangs(array('companies', 'propal', 'compta', 'bills', 'orders', 'products', 'deliveries', 'sendings', 'other'));
63 if (!empty($conf->incoterm->enabled)) {
64  $langs->load('incoterm');
65 }
66 if (!empty($conf->margin->enabled)) {
67  $langs->load('margins');
68 }
69 
70 $error = 0;
71 
72 $id = GETPOST('id', 'int');
73 $ref = GETPOST('ref', 'alpha');
74 $socid = GETPOST('socid', 'int');
75 $action = GETPOST('action', 'aZ09');
76 $cancel = GETPOST('cancel', 'alpha');
77 $origin = GETPOST('origin', 'alpha');
78 $originid = GETPOST('originid', 'int');
79 $confirm = GETPOST('confirm', 'alpha');
80 $lineid = GETPOST('lineid', 'int');
81 $contactid = GETPOST('contactid', 'int');
82 $projectid = GETPOST('projectid', 'int');
83 $rank = (GETPOST('rank', 'int') > 0) ? GETPOST('rank', 'int') : -1;
84 
85 // PDF
86 $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
87 $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
88 $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
89 
90 // Nombre de ligne pour choix de produit/service predefinis
91 $NBLINES = 4;
92 
93 $object = new Propal($db);
94 $extrafields = new ExtraFields($db);
95 
96 // fetch optionals attributes and labels
97 $extrafields->fetch_name_optionals_label($object->table_element);
98 
99 // Load object
100 if ($id > 0 || !empty($ref)) {
101  $ret = $object->fetch($id, $ref);
102  if ($ret > 0) {
103  $ret = $object->fetch_thirdparty();
104  }
105  if ($ret <= 0) {
106  setEventMessages($object->error, $object->errors, 'errors');
107  $action = '';
108  }
109 }
110 
111 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
112 $hookmanager->initHooks(array('propalcard', 'globalcard'));
113 
114 $usercanread = $user->hasRight("propal", "lire");
115 $usercancreate = $user->hasRight("propal", "creer");
116 $usercandelete = $user->hasRight("propal", "supprimer");
117 
118 $usercanclose = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->propal_advance->close)));
119 $usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->propal_advance->validate)));
120 $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->propal->propal_advance->send)));
121 
122 $usercancreateorder = $user->hasRight("commande", "creer");
123 $usercancreateinvoice = $user->hasRight("facture", "creer");
124 $usercancreatecontract = $user->hasRight("contrat", "creer");
125 $usercancreateintervention = $user->hasRight('ficheinter', 'creer');
126 $usercancreatepurchaseorder = ($user->hasRight('fournisseur', 'commande', 'creer') || $user->hasRight('supplier_order', 'creer'));
127 
128 $permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
129 $permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
130 $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdown.inc.php
131 
132 // Security check
133 if (!empty($user->socid)) {
134  $socid = $user->socid;
135 }
136 restrictedArea($user, 'propal', $object->id);
137 
138 
139 /*
140  * Actions
141  */
142 
143 $parameters = array('socid' => $socid);
144 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
145 if ($reshook < 0) {
146  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
147 }
148 
149 if (empty($reshook)) {
150  $backurlforlist = DOL_URL_ROOT.'/comm/propal/list.php';
151 
152  if (empty($backtopage) || ($cancel && empty($id))) {
153  if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
154  if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
155  $backtopage = $backurlforlist;
156  } else {
157  $backtopage = DOL_URL_ROOT.'/comm/propal/card.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
158  }
159  }
160  }
161 
162  if ($cancel) {
163  if (!empty($backtopageforcancel)) {
164  header("Location: ".$backtopageforcancel);
165  exit;
166  } elseif (!empty($backtopage)) {
167  header("Location: ".$backtopage);
168  exit;
169  }
170  $action = '';
171  }
172 
173  include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once
174 
175  include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
176 
177  include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
178 
179  // Action clone object
180  if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) {
181  if (!GETPOST('socid', 3)) {
182  setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
183  } else {
184  if ($object->id > 0) {
185  if (!empty($conf->global->PROPAL_CLONE_DATE_DELIVERY)) {
186  //Get difference between old and new delivery date and change lines according to difference
187  $date_delivery = dol_mktime(
188  12,
189  0,
190  0,
191  GETPOST('date_deliverymonth', 'int'),
192  GETPOST('date_deliveryday', 'int'),
193  GETPOST('date_deliveryyear', 'int')
194  );
195  $date_delivery_old = (empty($object->delivery_date) ? $object->date_livraison : $object->delivery_date);
196  if (!empty($date_delivery_old) && !empty($date_delivery)) {
197  //Attempt to get the date without possible hour rounding errors
198  $old_date_delivery = dol_mktime(
199  12,
200  0,
201  0,
202  dol_print_date($date_delivery_old, '%m'),
203  dol_print_date($date_delivery_old, '%d'),
204  dol_print_date($date_delivery_old, '%Y')
205  );
206  //Calculate the difference and apply if necessary
207  $difference = $date_delivery - $old_date_delivery;
208  if ($difference != 0) {
209  $object->date_livraison = $date_delivery;
210  $object->delivery_date = $date_delivery;
211  foreach ($object->lines as $line) {
212  if (isset($line->date_start)) {
213  $line->date_start = $line->date_start + $difference;
214  }
215  if (isset($line->date_end)) {
216  $line->date_end = $line->date_end + $difference;
217  }
218  }
219  }
220  }
221  }
222 
223  $result = $object->createFromClone($user, $socid, (GETPOSTISSET('entity') ? GETPOST('entity', 'int') : null), (GETPOST('update_prices', 'aZ') ? true : false));
224  if ($result > 0) {
225  header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
226  exit();
227  } else {
228  if (count($object->errors) > 0) {
229  setEventMessages($object->error, $object->errors, 'errors');
230  }
231  $action = '';
232  }
233  }
234  }
235  } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) {
236  // Delete proposal
237  $result = $object->delete($user);
238  if ($result > 0) {
239  header('Location: '.DOL_URL_ROOT.'/comm/propal/list.php?restore_lastsearch_values=1');
240  exit();
241  } else {
242  $langs->load("errors");
243  setEventMessages($object->error, $object->errors, 'errors');
244  }
245  } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
246  // Remove line
247  $result = $object->deleteline($lineid);
248  // reorder lines
249  if ($result > 0) {
250  $object->line_order(true);
251  } else {
252  $langs->load("errors");
253  setEventMessages($object->error, $object->errors, 'errors');
254  }
255 
256  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
257  // Define output language
258  $outputlangs = $langs;
259  if (!empty($conf->global->MAIN_MULTILANGS)) {
260  $outputlangs = new Translate("", $conf);
261  $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $object->thirdparty->default_lang);
262  $outputlangs->setDefaultLang($newlang);
263  }
264  $ret = $object->fetch($id); // Reload to get new records
265  if ($ret > 0) {
266  $object->fetch_thirdparty();
267  }
268  $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
269  }
270 
271  header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
272  exit();
273  } elseif ($action == 'confirm_validate' && $confirm == 'yes' && $usercanvalidate) {
274  // Validation
275  $idwarehouse = GETPOST('idwarehouse', 'int');
276  $result = $object->valid($user);
277  if ($result >= 0) {
278  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
279  $outputlangs = $langs;
280  $newlang = '';
281  if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
282  $newlang = GETPOST('lang_id', 'aZ09');
283  }
284  if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) {
285  $newlang = $object->thirdparty->default_lang;
286  }
287  if (!empty($newlang)) {
288  $outputlangs = new Translate("", $conf);
289  $outputlangs->setDefaultLang($newlang);
290  }
291  $model = $object->model_pdf;
292  $ret = $object->fetch($id); // Reload to get new records
293  if ($ret > 0) {
294  $object->fetch_thirdparty();
295  }
296 
297  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
298  }
299  } else {
300  $langs->load("errors");
301  if (count($object->errors) > 0) {
302  setEventMessages($object->error, $object->errors, 'errors');
303  } else {
304  setEventMessages($langs->trans($object->error), null, 'errors');
305  }
306  }
307  } elseif ($action == 'setdate' && $usercancreate) {
308  $datep = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
309 
310  if (empty($datep)) {
311  $error++;
312  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
313  }
314 
315  if (!$error) {
316  $result = $object->set_date($user, $datep);
317  if ($result > 0 && !empty($object->duree_validite) && !empty($object->fin_validite)) {
318  $datev = $datep + ($object->duree_validite * 24 * 3600);
319  $result = $object->set_echeance($user, $datev, 1);
320  }
321  if ($result < 0) {
322  dol_print_error($db, $object->error);
323  } elseif (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
324  $outputlangs = $langs;
325  $newlang = '';
326  if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
327  if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) $newlang = $object->thirdparty->default_lang;
328  if (!empty($newlang)) {
329  $outputlangs = new Translate("", $conf);
330  $outputlangs->setDefaultLang($newlang);
331  }
332  $model = $object->model_pdf;
333  $ret = $object->fetch($id); // Reload to get new records
334  if ($ret > 0) {
335  $object->fetch_thirdparty();
336  }
337 
338  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
339  }
340  }
341  } elseif ($action == 'setecheance' && $usercancreate) {
342  $result = $object->set_echeance($user, dol_mktime(12, 0, 0, GETPOST('echmonth', 'int'), GETPOST('echday', 'int'), GETPOST('echyear', 'int')));
343  if ($result >= 0) {
344  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
345  $outputlangs = $langs;
346  $newlang = '';
347  if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
348  if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) $newlang = $object->thirdparty->default_lang;
349  if (!empty($newlang)) {
350  $outputlangs = new Translate("", $conf);
351  $outputlangs->setDefaultLang($newlang);
352  }
353  $model = $object->model_pdf;
354  $ret = $object->fetch($id); // Reload to get new records
355  if ($ret > 0) {
356  $object->fetch_thirdparty();
357  }
358 
359  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
360  }
361  } else {
362  setEventMessages($object->error, $object->errors, 'errors');
363  }
364  } elseif ($action == 'setdate_livraison' && $usercancreate) {
365  $result = $object->setDeliveryDate($user, dol_mktime(12, 0, 0, GETPOST('date_livraisonmonth', 'int'), GETPOST('date_livraisonday', 'int'), GETPOST('date_livraisonyear', 'int')));
366  if ($result < 0) {
367  dol_print_error($db, $object->error);
368  }
369  } elseif ($action == 'setref_client' && $usercancreate) {
370  // Positionne ref client
371  $result = $object->set_ref_client($user, GETPOST('ref_client'));
372  if ($result < 0) {
373  setEventMessages($object->error, $object->errors, 'errors');
374  }
375  } elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled) && $usercancreate) {
376  // Set incoterm
377  $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
378  } elseif ($action == 'add' && $usercancreate) {
379  // Create proposal
380  $object->socid = $socid;
381  $object->fetch_thirdparty();
382 
383  $datep = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
384  $date_delivery = dol_mktime(12, 0, 0, GETPOST('date_livraisonmonth'), GETPOST('date_livraisonday'), GETPOST('date_livraisonyear'));
385  $duration = GETPOST('duree_validite', 'int');
386 
387  if (empty($datep)) {
388  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DatePropal")), null, 'errors');
389  $action = 'create';
390  $error++;
391  }
392  if (empty($duration)) {
393  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ValidityDuration")), null, 'errors');
394  $action = 'create';
395  $error++;
396  }
397 
398  if ($socid < 1) {
399  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors');
400 
401  $action = 'create';
402  $error++;
403  }
404 
405  if (!$error) {
406  $db->begin();
407 
408  // If we select proposal to clone during creation (when option PROPAL_CLONE_ON_CREATE_PAGE is on)
409  if (GETPOST('createmode') == 'copy' && GETPOST('copie_propal')) {
410  if ($object->fetch(GETPOST('copie_propal', 'int')) > 0) {
411  $object->ref = GETPOST('ref');
412  $object->datep = $datep;
413  $object->date = $datep;
414  $object->date_livraison = $date_delivery; // deprecated
415  $object->delivery_date = $date_delivery;
416  $object->availability_id = GETPOST('availability_id');
417  $object->demand_reason_id = GETPOST('demand_reason_id');
418  $object->fk_delivery_address = GETPOST('fk_address', 'int');
419  $object->shipping_method_id = GETPOST('shipping_method_id', 'int');
420  $object->warehouse_id = GETPOST('warehouse_id', 'int');
421  $object->duree_validite = $duration;
422  $object->cond_reglement_id = GETPOST('cond_reglement_id');
423  $object->deposit_percent = GETPOST('cond_reglement_id_deposit_percent', 'alpha');
424  $object->mode_reglement_id = GETPOST('mode_reglement_id');
425  $object->fk_account = GETPOST('fk_account', 'int');
426  $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU', 2); // deprecated
427  $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
428  $object->socid = GETPOST('socid', 'int');
429  $object->contact_id = GETPOST('contactid', 'int');
430  $object->fk_project = GETPOST('projectid', 'int');
431  $object->model_pdf = GETPOST('model', 'alphanohtml');
432  $object->author = $user->id; // deprecated
433  $object->user_author_id = $user->id;
434  $object->note_private = GETPOST('note_private', 'restricthtml');
435  $object->note_public = GETPOST('note_public', 'restricthtml');
436  $object->statut = Propal::STATUS_DRAFT;
437  $object->fk_incoterms = GETPOST('incoterm_id', 'int');
438  $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
439  } else {
440  setEventMessages($langs->trans("ErrorFailedToCopyProposal", GETPOST('copie_propal')), null, 'errors');
441  }
442  } else {
443  $object->ref = GETPOST('ref');
444  $object->ref_client = GETPOST('ref_client');
445  $object->datep = $datep;
446  $object->date = $datep;
447  $object->date_livraison = $date_delivery;
448  $object->delivery_date = $date_delivery;
449  $object->availability_id = GETPOST('availability_id', 'int');
450  $object->demand_reason_id = GETPOST('demand_reason_id', 'int');
451  $object->fk_delivery_address = GETPOST('fk_address', 'int');
452  $object->shipping_method_id = GETPOST('shipping_method_id', 'int');
453  $object->warehouse_id = GETPOST('warehouse_id', 'int');
454  $object->duree_validite = price2num(GETPOST('duree_validite', 'alpha'));
455  $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
456  $object->deposit_percent = GETPOST('cond_reglement_id_deposit_percent', 'alpha');
457  $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
458  $object->fk_account = GETPOST('fk_account', 'int');
459  $object->contact_id = GETPOST('contactid', 'int');
460  $object->fk_project = GETPOST('projectid', 'int');
461  $object->model_pdf = GETPOST('model');
462  $object->author = $user->id; // deprecated
463  $object->note_private = GETPOST('note_private', 'restricthtml');
464  $object->note_public = GETPOST('note_public', 'restricthtml');
465  $object->fk_incoterms = GETPOST('incoterm_id', 'int');
466  $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
467 
468  $object->origin = GETPOST('origin');
469  $object->origin_id = GETPOST('originid');
470 
471  // Multicurrency
472  if (!empty($conf->multicurrency->enabled)) {
473  $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
474  }
475 
476  // Fill array 'array_options' with data from add form
477  $ret = $extrafields->setOptionalsFromPost(null, $object);
478  if ($ret < 0) {
479  $error++;
480  $action = 'create';
481  }
482  }
483 
484  if (!$error) {
485  if ($origin && $originid) {
486  // Parse element/subelement (ex: project_task)
487  $element = $subelement = $origin;
488  if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
489  $element = $regs [1];
490  $subelement = $regs [2];
491  }
492 
493  // For compatibility
494  if ($element == 'order') {
495  $element = $subelement = 'commande';
496  }
497  if ($element == 'propal') {
498  $element = 'comm/propal';
499  $subelement = 'propal';
500  }
501  if ($element == 'contract') {
502  $element = $subelement = 'contrat';
503  }
504  if ($element == 'inter') {
505  $element = $subelement = 'ficheinter';
506  }
507  if ($element == 'shipping') {
508  $element = $subelement = 'expedition';
509  }
510 
511  $object->origin = $origin;
512  $object->origin_id = $originid;
513 
514  // Possibility to add external linked objects with hooks
515  $object->linked_objects [$object->origin] = $object->origin_id;
516  if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) {
517  $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
518  }
519 
520  $id = $object->create($user);
521  if ($id > 0) {
522  dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
523 
524  $classname = ucfirst($subelement);
525  $srcobject = new $classname($db);
526 
527  dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
528  $result = $srcobject->fetch($object->origin_id);
529 
530  if ($result > 0) {
531  $lines = $srcobject->lines;
532  if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
533  $srcobject->fetch_lines();
534  $lines = $srcobject->lines;
535  }
536 
537  $fk_parent_line = 0;
538  $num = count($lines);
539  for ($i = 0; $i < $num; $i++) {
540  $label = (!empty($lines[$i]->label) ? $lines[$i]->label : '');
541  $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->libelle);
542 
543  // Positive line
544  $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
545 
546  // Date start
547  $date_start = false;
548  if ($lines[$i]->date_debut_prevue) {
549  $date_start = $lines[$i]->date_debut_prevue;
550  }
551  if ($lines[$i]->date_debut_reel) {
552  $date_start = $lines[$i]->date_debut_reel;
553  }
554  if ($lines[$i]->date_start) {
555  $date_start = $lines[$i]->date_start;
556  }
557 
558  // Date end
559  $date_end = false;
560  if ($lines[$i]->date_fin_prevue) {
561  $date_end = $lines[$i]->date_fin_prevue;
562  }
563  if ($lines[$i]->date_fin_reel) {
564  $date_end = $lines[$i]->date_fin_reel;
565  }
566  if ($lines[$i]->date_end) {
567  $date_end = $lines[$i]->date_end;
568  }
569 
570  // Reset fk_parent_line for no child products and special product
571  if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
572  $fk_parent_line = 0;
573  }
574 
575  // Extrafields
576  if (method_exists($lines[$i], 'fetch_optionals')) {
577  $lines[$i]->fetch_optionals();
578  $array_options = $lines[$i]->array_options;
579  }
580 
581  $tva_tx = $lines[$i]->tva_tx;
582  if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) {
583  $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
584  }
585 
586  $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, 'HT', 0, $lines[$i]->info_bits, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $date_start, $date_end, $array_options, $lines[$i]->fk_unit);
587 
588  if ($result > 0) {
589  $lineid = $result;
590  } else {
591  $lineid = 0;
592  $error++;
593  break;
594  }
595 
596  // Defined the new fk_parent_line
597  if ($result > 0 && $lines[$i]->product_type == 9) {
598  $fk_parent_line = $result;
599  }
600  }
601 
602  // Hooks
603  $parameters = array('objFrom' => $srcobject);
604  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
605  // modified by hook
606  if ($reshook < 0) {
607  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
608  $error++;
609  }
610  } else {
611  setEventMessages($srcobject->error, $srcobject->errors, 'errors');
612  $error++;
613  }
614  } else {
615  setEventMessages($object->error, $object->errors, 'errors');
616  $error++;
617  }
618  } else {
619  // Standard creation
620  $id = $object->create($user);
621  }
622 
623  if ($id > 0) {
624  // Insert default contacts if defined
625  if (GETPOST('contactid') > 0) {
626  $result = $object->add_contact(GETPOST('contactid'), 'CUSTOMER', 'external');
627  if ($result < 0) {
628  $error++;
629  setEventMessages($langs->trans("ErrorFailedToAddContact"), null, 'errors');
630  }
631  }
632 
633  if (!empty($conf->global->PROPOSAL_AUTO_ADD_AUTHOR_AS_CONTACT)) {
634  $result = $object->add_contact($user->id, 'SALESREPFOLL', 'internal');
635  if ($result < 0) {
636  $error++;
637  setEventMessages($langs->trans("ErrorFailedToAddUserAsContact"), null, 'errors');
638  }
639  }
640 
641  if (!$error) {
642  $db->commit();
643 
644  // Define output language
645  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
646  $outputlangs = $langs;
647  $newlang = '';
648  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
649  $newlang = GETPOST('lang_id', 'aZ09');
650  }
651  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
652  $newlang = $object->thirdparty->default_lang;
653  }
654  if (!empty($newlang)) {
655  $outputlangs = new Translate("", $conf);
656  $outputlangs->setDefaultLang($newlang);
657  }
658  $model = $object->model_pdf;
659 
660  $ret = $object->fetch($id); // Reload to get new records
661  $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
662  if ($result < 0) {
663  dol_print_error($db, $result);
664  }
665  }
666 
667  header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id);
668  exit();
669  } else {
670  $db->rollback();
671  $action = 'create';
672  }
673  } else {
674  setEventMessages($object->error, $object->errors, 'errors');
675  $db->rollback();
676  $action = 'create';
677  }
678  }
679  }
680  } elseif ($action == 'classifybilled' && $usercanclose) {
681  // Classify billed
682  $db->begin();
683 
684  $result = $object->classifyBilled($user, 0, '');
685  if ($result < 0) {
686  setEventMessages($object->error, $object->errors, 'errors');
687  $error++;
688  }
689 
690  if (!$error) {
691  $db->commit();
692  } else {
693  $db->rollback();
694  }
695  } elseif ($action == 'confirm_closeas' && $usercanclose && !GETPOST('cancel', 'alpha')) {
696  // Close proposal
697  if (!(GETPOST('statut', 'int') > 0)) {
698  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CloseAs")), null, 'errors');
699  $action = 'closeas';
700  } elseif (GETPOST('statut', 'int') == $object::STATUS_SIGNED || GETPOST('statut', 'int') == $object::STATUS_NOTSIGNED) {
701  // prevent browser refresh from closing proposal several times
702  if ($object->statut == $object::STATUS_VALIDATED) {
703  $db->begin();
704 
705  $result = $object->closeProposal($user, GETPOST('statut', 'int'), GETPOST('note_private', 'restricthtml'));
706  if ($result < 0) {
707  setEventMessages($object->error, $object->errors, 'errors');
708  $error++;
709  }
710 
711  $deposit = null;
712  $locationTarget = '';
713 
714  $deposit_percent_from_payment_terms = getDictionaryValue('c_payment_term', 'deposit_percent', $object->cond_reglement_id);
715 
716  if (
717  !$error && GETPOST('statut', 'int') == $object::STATUS_SIGNED && GETPOST('generate_deposit', 'alpha') == 'on'
718  && ! empty($deposit_percent_from_payment_terms) && isModEnabled('facture') && !empty($user->rights->facture->creer)
719  ) {
720  require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
721 
722  $date = dol_mktime(0, 0, 0, GETPOST('datefmonth', 'int'), GETPOST('datefday', 'int'), GETPOST('datefyear', 'int'));
723  $forceFields = array();
724 
725  if (GETPOSTISSET('date_pointoftax')) {
726  $forceFields['date_pointoftax'] = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'));
727  }
728 
729  $deposit = Facture::createDepositFromOrigin($object, $date, GETPOST('cond_reglement_id', 'int'), $user, 0, GETPOST('validate_generated_deposit', 'alpha') == 'on', $forceFields);
730 
731  if ($deposit) {
732  setEventMessage('DepositGenerated');
733  $locationTarget = DOL_URL_ROOT . '/compta/facture/card.php?id=' . $deposit->id;
734  } else {
735  $error++;
736  setEventMessages($object->error, $object->errors, 'errors');
737  }
738  }
739 
740  if (!$error) {
741  $db->commit();
742 
743  if ($deposit && empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
744  $ret = $deposit->fetch($deposit->id); // Reload to get new records
745  $outputlangs = $langs;
746 
747  if ($conf->global->MAIN_MULTILANGS) {
748  $outputlangs = new Translate('', $conf);
749  $outputlangs->setDefaultLang($deposit->thirdparty->default_lang);
750  $outputlangs->load('products');
751  }
752 
753  $result = $deposit->generateDocument($deposit->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
754 
755  if ($result < 0) {
756  setEventMessages($deposit->error, $deposit->errors, 'errors');
757  }
758  }
759 
760  if ($locationTarget) {
761  header('Location: ' . $locationTarget);
762  exit;
763  }
764  } else {
765  $db->rollback();
766  $action = '';
767  }
768  }
769  }
770  } elseif ($action == 'confirm_reopen' && $usercanclose && !GETPOST('cancel', 'alpha')) {
771  // Reopen proposal
772  // prevent browser refresh from reopening proposal several times
773  if ($object->statut == Propal::STATUS_SIGNED || $object->statut == Propal::STATUS_NOTSIGNED || $object->statut == Propal::STATUS_BILLED) {
774  $db->begin();
775 
776  $result = $object->reopen($user, 1);
777  if ($result < 0) {
778  setEventMessages($object->error, $object->errors, 'errors');
779  $error++;
780  }
781 
782  if (!$error) {
783  $db->commit();
784  } else {
785  $db->rollback();
786  }
787  }
788  } elseif ($action == 'import_lines_from_object'
789  && $user->rights->propal->creer
790  && $object->statut == Propal::STATUS_DRAFT
791  ) {
792  // add lines from objectlinked
793  $fromElement = GETPOST('fromelement');
794  $fromElementid = GETPOST('fromelementid');
795  $importLines = GETPOST('line_checkbox');
796 
797  if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) {
798  if ($fromElement == 'commande') {
799  dol_include_once('/'.$fromElement.'/class/'.$fromElement.'.class.php');
800  $lineClassName = 'OrderLine';
801  } elseif ($fromElement == 'propal') {
802  dol_include_once('/comm/'.$fromElement.'/class/'.$fromElement.'.class.php');
803  $lineClassName = 'PropaleLigne';
804  }
805  $nextRang = count($object->lines) + 1;
806  $importCount = 0;
807  $error = 0;
808  foreach ($importLines as $lineId) {
809  $lineId = intval($lineId);
810  $originLine = new $lineClassName($db);
811  if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) {
812  $originLine->fetch_optionals();
813  $desc = $originLine->desc;
814  $pu_ht = $originLine->subprice;
815  $qty = $originLine->qty;
816  $txtva = $originLine->tva_tx;
817  $txlocaltax1 = $originLine->localtax1_tx;
818  $txlocaltax2 = $originLine->localtax2_tx;
819  $fk_product = $originLine->fk_product;
820  $remise_percent = $originLine->remise_percent;
821  $date_start = $originLine->date_start;
822  $date_end = $originLine->date_end;
823  $ventil = 0;
824  $info_bits = $originLine->info_bits;
825  $fk_remise_except = $originLine->fk_remise_except;
826  $price_base_type = 'HT';
827  $pu_ttc = 0;
828  $type = $originLine->product_type;
829  $rang = $nextRang++;
830  $special_code = $originLine->special_code;
831  $origin = $originLine->element;
832  $origin_id = $originLine->id;
833  $fk_parent_line = 0;
834  $fk_fournprice = $originLine->fk_fournprice;
835  $pa_ht = $originLine->pa_ht;
836  $label = $originLine->label;
837  $array_options = $originLine->array_options;
838  $situation_percent = 100;
839  $fk_prev_id = '';
840  $fk_unit = $originLine->fk_unit;
841  $pu_ht_devise = $originLine->multicurrency_subprice;
842 
843  $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $price_base_type, $pu_ttc, $info_bits, $type, $rang, $special_code, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $date_start, $date_end, $array_options, $fk_unit, $origin, $origin_id, $pu_ht_devise, $fk_remise_except);
844 
845  if ($res > 0) {
846  $importCount++;
847  } else {
848  $error++;
849  }
850  } else {
851  $error++;
852  }
853  }
854 
855  if ($error) {
856  setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors');
857  }
858  }
859  }
860 
861  include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
862 
863  // Actions to send emails
864  $actiontypecode = 'AC_OTH_AUTO';
865  $triggersendname = 'PROPAL_SENTBYMAIL';
866  $autocopy = 'MAIN_MAIL_AUTOCOPY_PROPOSAL_TO';
867  $trackid = 'pro'.$object->id;
868  include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
869 
870 
871  // Go back to draft
872  if ($action == 'modif' && $usercancreate) {
873  $object->setDraft($user);
874 
875  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
876  // Define output language
877  $outputlangs = $langs;
878  if (!empty($conf->global->MAIN_MULTILANGS)) {
879  $outputlangs = new Translate("", $conf);
880  $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $object->thirdparty->default_lang);
881  $outputlangs->setDefaultLang($newlang);
882  }
883  $ret = $object->fetch($id); // Reload to get new records
884  if ($ret > 0) {
885  $object->fetch_thirdparty();
886  }
887  $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
888  }
889  } elseif ($action == "setabsolutediscount" && $usercancreate) {
890  if (GETPOST("remise_id", "int")) {
891  if ($object->id > 0) {
892  $result = $object->insert_discount(GETPOST("remise_id", "int"));
893  if ($result < 0) {
894  setEventMessages($object->error, $object->errors, 'errors');
895  }
896  }
897  }
898  } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('vatforalllines', 'alpha') !== '' && $usercancreate) {
899  // Define vat_rate
900  $vat_rate = (GETPOST('vatforalllines') ? GETPOST('vatforalllines') : 0);
901  $vat_rate = str_replace('*', '', $vat_rate);
902  $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
903  $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
904  foreach ($object->lines as $line) {
905  $result = $object->updateline($line->id, $line->subprice, $line->qty, $line->remise_percent, $vat_rate, $localtax1_rate, $localtax2_rate, $line->desc, 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice);
906  }
907  } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('remiseforalllines', 'alpha') !== '' && $usercancreate) {
908  // Define vat_rate
909  $remise_percent = (GETPOST('remiseforalllines') ? GETPOST('remiseforalllines') : 0);
910  $remise_percent = str_replace('*', '', $remise_percent);
911  foreach ($object->lines as $line) {
912  $result = $object->updateline($line->id, $line->subprice, $line->qty, $remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->desc, 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice);
913  }
914  } elseif ($action == 'addline' && $usercancreate) { // Add line
915  // Set if we used free entry or predefined product
916  $predef = '';
917  $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
918  $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
919  $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
920  $prod_entry_mode = GETPOST('prod_entry_mode');
921  if ($prod_entry_mode == 'free') {
922  $idprod = 0;
923  $tva_tx = (GETPOST('tva_tx') ? price2num(preg_replace('/\s*\(.*\)/', '', GETPOST('tva_tx'))) : 0);
924  } else {
925  $idprod = GETPOST('idprod', 'int');
926  $tva_tx = '';
927  }
928 
929  $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS', 2);
930  $remise_percent = price2num(GETPOST('remise_percent'.$predef), '', 2);
931  if (empty($remise_percent)) {
932  $remise_percent = 0;
933  }
934 
935  // Extrafields
936  $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
937  $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
938  // Unset extrafield
939  if (is_array($extralabelsline)) {
940  // Get extra fields
941  foreach ($extralabelsline as $key => $value) {
942  unset($_POST["options_".$key]);
943  }
944  }
945 
946  if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
947  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
948  $error++;
949  }
950 
951  if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && $price_ht === '' && $price_ht_devise === '') { // Unit price can be 0 but not ''. Also price can be negative for proposal.
952  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
953  $error++;
954  }
955  if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && empty($product_desc)) {
956  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors');
957  $error++;
958  }
959 
960  if (!$error && !empty($conf->variants->enabled) && $prod_entry_mode != 'free') {
961  if ($combinations = GETPOST('combinations', 'array')) {
962  //Check if there is a product with the given combination
963  $prodcomb = new ProductCombination($db);
964 
965  if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
966  $idprod = $res->fk_product_child;
967  } else {
968  setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
969  $error++;
970  }
971  }
972  }
973 
974  $propal_qty_requirement = (!empty($conf->global->PROPAL_ENABLE_NEGATIVE_QTY) ? ($qty >= 0 || $qty <= 0) : $qty >= 0);
975  if (!$error && $propal_qty_requirement && (!empty($product_desc) || (!empty($idprod) && $idprod > 0))) {
976  $pu_ht = 0;
977  $pu_ttc = 0;
978  $price_min = 0;
979  $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
980 
981  $db->begin();
982 
983  // $tva_tx can be 'x.x (XXX)'
984 
985  // Ecrase $pu par celui du produit
986  // Ecrase $desc par celui du produit
987  // Ecrase $tva_tx par celui du produit
988  // Replaces $fk_unit with the product unit
989  if (!empty($idprod) && $idprod > 0) {
990  $prod = new Product($db);
991  $prod->fetch($idprod);
992 
993  $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
994 
995  // Update if prices fields are defined
996  $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
997  $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
998  if (empty($tva_tx)) {
999  $tva_npr = 0;
1000  }
1001 
1002  // Price unique per product
1003  $pu_ht = $prod->price;
1004  $pu_ttc = $prod->price_ttc;
1005  $price_min = $prod->price_min;
1006  $price_base_type = $prod->price_base_type;
1007 
1008  // If price per segment
1009  if (!empty($conf->global->PRODUIT_MULTIPRICES) && $object->thirdparty->price_level) {
1010  $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
1011  $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
1012  $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
1013  $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
1014  if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
1015  if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) {
1016  $tva_tx = $prod->multiprices_tva_tx[$object->thirdparty->price_level];
1017  }
1018  if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) {
1019  $tva_npr = $prod->multiprices_recuperableonly[$object->thirdparty->price_level];
1020  }
1021  }
1022  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
1023  // If price per customer
1024  require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
1025 
1026  $prodcustprice = new Productcustomerprice($db);
1027 
1028  $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $object->thirdparty->id);
1029 
1030  $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
1031  if ($result) {
1032  // If there is some prices specific to the customer
1033  if (count($prodcustprice->lines) > 0) {
1034  $pu_ht = price($prodcustprice->lines[0]->price);
1035  $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
1036  $price_min = price($prodcustprice->lines[0]->price_min);
1037  $price_base_type = $prodcustprice->lines[0]->price_base_type;
1038  $tva_tx = ($prodcustprice->lines[0]->default_vat_code ? $prodcustprice->lines[0]->tva_tx.' ('.$prodcustprice->lines[0]->default_vat_code.' )' : $prodcustprice->lines[0]->tva_tx);
1039  if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
1040  $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
1041  }
1042  $tva_npr = $prodcustprice->lines[0]->recuperableonly;
1043  if (empty($tva_tx)) {
1044  $tva_npr = 0;
1045  }
1046  }
1047  }
1048  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
1049  // If price per quantity
1050  if ($prod->prices_by_qty[0]) { // yes, this product has some prices per quantity
1051  // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
1052  $pqp = GETPOST('pbq', 'int');
1053 
1054  // Search price into product_price_by_qty from $prod->id
1055  foreach ($prod->prices_by_qty_list[0] as $priceforthequantityarray) {
1056  if ($priceforthequantityarray['rowid'] != $pqp) {
1057  continue;
1058  }
1059  // We found the price
1060  if ($priceforthequantityarray['price_base_type'] == 'HT') {
1061  $pu_ht = $priceforthequantityarray['unitprice'];
1062  } else {
1063  $pu_ttc = $priceforthequantityarray['unitprice'];
1064  }
1065  // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST.
1066  break;
1067  }
1068  }
1069  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
1070  // If price per quantity and customer
1071  if ($prod->prices_by_qty[$object->thirdparty->price_level]) { // yes, this product has some prices per quantity
1072  // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
1073  $pqp = GETPOST('pbq', 'int');
1074 
1075  // Search price into product_price_by_qty from $prod->id
1076  foreach ($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) {
1077  if ($priceforthequantityarray['rowid'] != $pqp) {
1078  continue;
1079  }
1080  // We found the price
1081  if ($priceforthequantityarray['price_base_type'] == 'HT') {
1082  $pu_ht = $priceforthequantityarray['unitprice'];
1083  } else {
1084  $pu_ttc = $priceforthequantityarray['unitprice'];
1085  }
1086  // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST.
1087  break;
1088  }
1089  }
1090  }
1091 
1092  $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
1093  $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
1094 
1095  // if price ht is forced (ie: calculated by margin rate and cost price). TODO Why this ?
1096  if (!empty($price_ht) || $price_ht === '0') {
1097  $pu_ht = price2num($price_ht, 'MU');
1098  $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
1099  } elseif ($tmpvat != $tmpprodvat) {
1100  // On reevalue prix selon taux tva car taux tva transaction peut etre different
1101  // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
1102  if ($price_base_type != 'HT') {
1103  $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
1104  } else {
1105  $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
1106  }
1107  }
1108 
1109  $desc = '';
1110 
1111  // Define output language
1112  if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
1113  $outputlangs = $langs;
1114  $newlang = '';
1115  if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
1116  $newlang = GETPOST('lang_id', 'aZ09');
1117  }
1118  if (empty($newlang)) {
1119  $newlang = $object->thirdparty->default_lang;
1120  }
1121  if (!empty($newlang)) {
1122  $outputlangs = new Translate("", $conf);
1123  $outputlangs->setDefaultLang($newlang);
1124  }
1125 
1126  $desc = (!empty($prod->multilangs[$outputlangs->defaultlang]["description"])) ? $prod->multilangs[$outputlangs->defaultlang]["description"] : $prod->description;
1127  } else {
1128  $desc = $prod->description;
1129  }
1130 
1131  //If text set in desc is the same as product description (as now it's preloaded) whe add it only one time
1132  if ($product_desc==$desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) {
1133  $product_desc='';
1134  }
1135 
1136  if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) {
1137  $desc = $product_desc;
1138  } else {
1139  $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
1140  }
1141 
1142  // Add dimensions into product description
1143  /*if (empty($conf->global->MAIN_PRODUCT_DISABLE_AUTOADD_DIM))
1144  {
1145  $text='';
1146  if ($prod->weight) $text.=($text?"\n":"").$outputlangs->trans("Weight").': '.$prod->weight.' '.$prod->weight_units;
1147  if ($prod->length) $text.=($text?"\n":"").$outputlangs->trans("Length").': '.$prod->length.' '.$prod->length_units;
1148  if ($prod->surface) $text.=($text?"\n":"").$outputlangs->trans("Surface").': '.$prod->surface.' '.$prod->surface_units;
1149  if ($prod->volume) $text.=($text?"\n":"").$outputlangs->trans("Volume").': '.$prod->volume.' '.$prod->volume_units;
1150 
1151  $desc = dol_concatdesc($desc, $text);
1152  }*/
1153 
1154  // Add custom code and origin country into description
1155  if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) {
1156  $tmptxt = '(';
1157  // Define output language
1158  if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
1159  $outputlangs = $langs;
1160  $newlang = '';
1161  if (empty($newlang) && GETPOST('lang_id', 'alpha')) {
1162  $newlang = GETPOST('lang_id', 'alpha');
1163  }
1164  if (empty($newlang)) {
1165  $newlang = $object->thirdparty->default_lang;
1166  }
1167  if (!empty($newlang)) {
1168  $outputlangs = new Translate("", $conf);
1169  $outputlangs->setDefaultLang($newlang);
1170  $outputlangs->load('products');
1171  }
1172  if (!empty($prod->customcode)) {
1173  $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
1174  }
1175  if (!empty($prod->customcode) && !empty($prod->country_code)) {
1176  $tmptxt .= ' - ';
1177  }
1178  if (!empty($prod->country_code)) {
1179  $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0);
1180  }
1181  } else {
1182  if (!empty($prod->customcode)) {
1183  $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
1184  }
1185  if (!empty($prod->customcode) && !empty($prod->country_code)) {
1186  $tmptxt .= ' - ';
1187  }
1188  if (!empty($prod->country_code)) {
1189  $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0);
1190  }
1191  }
1192  $tmptxt .= ')';
1193  $desc = dol_concatdesc($desc, $tmptxt);
1194  }
1195 
1196  $type = $prod->type;
1197  $fk_unit = $prod->fk_unit;
1198  } else {
1199  $pu_ht = price2num($price_ht, 'MU');
1200  $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
1201  $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
1202  $tva_tx = str_replace('*', '', $tva_tx);
1203  $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
1204  $desc = $product_desc;
1205  $type = GETPOST('type');
1206 
1207  $fk_unit = GETPOST('units', 'alpha');
1208  $pu_ht_devise = price2num($price_ht_devise, 'MU');
1209  }
1210 
1211  // Margin
1212  $fournprice = price2num(GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : '');
1213  $buyingprice = price2num(GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''); // If buying_price is '0', we muste keep this value
1214 
1215  $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'));
1216  $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'));
1217 
1218  // Local Taxes
1219  $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $tva_npr);
1220  $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $tva_npr);
1221 
1222  $info_bits = 0;
1223  if ($tva_npr) {
1224  $info_bits |= 0x01;
1225  }
1226 
1227  if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && (!empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) {
1228  $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency));
1229  setEventMessages($mesg, null, 'errors');
1230  } else {
1231  // Insert line
1232  $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $price_base_type, $pu_ttc, $info_bits, $type, min($rank, count($object->lines) + 1), 0, GETPOST('fk_parent_line'), $fournprice, $buyingprice, $label, $date_start, $date_end, $array_options, $fk_unit, '', 0, $pu_ht_devise);
1233 
1234  if ($result > 0) {
1235  $db->commit();
1236 
1237  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
1238  // Define output language
1239  $outputlangs = $langs;
1240  if (!empty($conf->global->MAIN_MULTILANGS)) {
1241  $outputlangs = new Translate("", $conf);
1242  $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $object->thirdparty->default_lang);
1243  $outputlangs->setDefaultLang($newlang);
1244  }
1245  $ret = $object->fetch($id); // Reload to get new records
1246  if ($ret > 0) {
1247  $object->fetch_thirdparty();
1248  }
1249  $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1250  }
1251 
1252  unset($_POST['prod_entry_mode']);
1253 
1254  unset($_POST['qty']);
1255  unset($_POST['type']);
1256  unset($_POST['remise_percent']);
1257  unset($_POST['price_ht']);
1258  unset($_POST['multicurrency_price_ht']);
1259  unset($_POST['price_ttc']);
1260  unset($_POST['tva_tx']);
1261  unset($_POST['product_ref']);
1262  unset($_POST['product_label']);
1263  unset($_POST['product_desc']);
1264  unset($_POST['fournprice']);
1265  unset($_POST['buying_price']);
1266  unset($_POST['np_marginRate']);
1267  unset($_POST['np_markRate']);
1268  unset($_POST['dp_desc']);
1269  unset($_POST['idprod']);
1270  unset($_POST['units']);
1271 
1272  unset($_POST['date_starthour']);
1273  unset($_POST['date_startmin']);
1274  unset($_POST['date_startsec']);
1275  unset($_POST['date_startday']);
1276  unset($_POST['date_startmonth']);
1277  unset($_POST['date_startyear']);
1278  unset($_POST['date_endhour']);
1279  unset($_POST['date_endmin']);
1280  unset($_POST['date_endsec']);
1281  unset($_POST['date_endday']);
1282  unset($_POST['date_endmonth']);
1283  unset($_POST['date_endyear']);
1284  } else {
1285  $db->rollback();
1286 
1287  setEventMessages($object->error, $object->errors, 'errors');
1288  }
1289  }
1290  }
1291  } elseif ($action == 'updateline' && $usercancreate && GETPOST('save')) {
1292  // Update a line within proposal
1293  // Define info_bits
1294  $info_bits = 0;
1295  if (preg_match('/\*/', GETPOST('tva_tx'))) {
1296  $info_bits |= 0x01;
1297  }
1298 
1299  // Clean parameters
1300  $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml'));
1301 
1302  // Define vat_rate
1303  $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
1304  $vat_rate = str_replace('*', '', $vat_rate);
1305  $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
1306  $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
1307  $pu_ht = price2num(GETPOST('price_ht'), '', 2);
1308 
1309  // Add buying price
1310  $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
1311  $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
1312 
1313  $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2);
1314 
1315  $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
1316  $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
1317 
1318  $remise_percent = price2num(GETPOST('remise_percent'), '', 2);
1319 
1320  // Extrafields
1321  $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
1322  $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
1323  // Unset extrafield
1324  if (is_array($extralabelsline)) {
1325  // Get extra fields
1326  foreach ($extralabelsline as $key => $value) {
1327  unset($_POST["options_".$key]);
1328  }
1329  }
1330 
1331  // Define special_code for special lines
1332  $special_code = GETPOST('special_code', 'int');
1333  if (!GETPOST('qty')) {
1334  $special_code = 3;
1335  }
1336 
1337  // Check minimum price
1338  $productid = GETPOST('productid', 'int');
1339  if (!empty($productid)) {
1340  $product = new Product($db);
1341  $res = $product->fetch($productid);
1342 
1343  $type = $product->type;
1344 
1345  $price_min = $product->price_min;
1346  if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) {
1347  $price_min = $product->multiprices_min [$object->thirdparty->price_level];
1348  }
1349 
1350  $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
1351  if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && ($price_min && (price2num($pu_ht) * (1 - $remise_percent / 100) < price2num($price_min)))) {
1352  setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors');
1353  $error++;
1354  }
1355  } else {
1356  $type = GETPOST('type');
1357  $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
1358 
1359  // Check parameters
1360  if (GETPOST('type') < 0) {
1361  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
1362  $error++;
1363  }
1364  }
1365 
1366  if (!$error) {
1367  $db->begin();
1368 
1369  if (empty($user->rights->margins->creer)) {
1370  foreach ($object->lines as &$line) {
1371  if ($line->id == GETPOST('lineid', 'int')) {
1372  $fournprice = $line->fk_fournprice;
1373  $buyingprice = $line->pa_ht;
1374  break;
1375  }
1376  }
1377  }
1378 
1379  $qty = price2num(GETPOST('qty', 'alpha'), 'MS');
1380 
1381  $result = $object->updateline(GETPOST('lineid', 'int'), $pu_ht, $qty, $remise_percent, $vat_rate, $localtax1_rate, $localtax2_rate, $description, 'HT', $info_bits, $special_code, GETPOST('fk_parent_line'), 0, $fournprice, $buyingprice, $label, $type, $date_start, $date_end, $array_options, GETPOST("units"), $pu_ht_devise);
1382 
1383  if ($result >= 0) {
1384  $db->commit();
1385 
1386  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
1387  // Define output language
1388  $outputlangs = $langs;
1389  if (!empty($conf->global->MAIN_MULTILANGS)) {
1390  $outputlangs = new Translate("", $conf);
1391  $newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $object->thirdparty->default_lang);
1392  $outputlangs->setDefaultLang($newlang);
1393  }
1394  $ret = $object->fetch($id); // Reload to get new records
1395  if ($ret > 0) {
1396  $object->fetch_thirdparty();
1397  }
1398  $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1399  }
1400 
1401  unset($_POST['qty']);
1402  unset($_POST['type']);
1403  unset($_POST['productid']);
1404  unset($_POST['remise_percent']);
1405  unset($_POST['price_ht']);
1406  unset($_POST['multicurrency_price_ht']);
1407  unset($_POST['price_ttc']);
1408  unset($_POST['tva_tx']);
1409  unset($_POST['product_ref']);
1410  unset($_POST['product_label']);
1411  unset($_POST['product_desc']);
1412  unset($_POST['fournprice']);
1413  unset($_POST['buying_price']);
1414 
1415  unset($_POST['date_starthour']);
1416  unset($_POST['date_startmin']);
1417  unset($_POST['date_startsec']);
1418  unset($_POST['date_startday']);
1419  unset($_POST['date_startmonth']);
1420  unset($_POST['date_startyear']);
1421  unset($_POST['date_endhour']);
1422  unset($_POST['date_endmin']);
1423  unset($_POST['date_endsec']);
1424  unset($_POST['date_endday']);
1425  unset($_POST['date_endmonth']);
1426  unset($_POST['date_endyear']);
1427  } else {
1428  $db->rollback();
1429 
1430  setEventMessages($object->error, $object->errors, 'errors');
1431  }
1432  }
1433  } elseif ($action == 'updateline' && $usercancreate && GETPOST('cancel', 'alpha')) {
1434  header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); // Pour reaffichage de la fiche en cours d'edition
1435  exit();
1436  } elseif ($action == 'classin' && $usercancreate) {
1437  // Set project
1438  $object->setProject(GETPOST('projectid', 'int'));
1439  } elseif ($action == 'setavailability' && $usercancreate) {
1440  // Delivery time
1441  $result = $object->set_availability($user, GETPOST('availability_id', 'int'));
1442  } elseif ($action == 'setdemandreason' && $usercancreate) {
1443  // Origin of the commercial proposal
1444  $result = $object->set_demand_reason($user, GETPOST('demand_reason_id', 'int'));
1445  } elseif ($action == 'setconditions' && $usercancreate) {
1446  // Terms of payment
1447  $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'), GETPOST('cond_reglement_id_deposit_percent', 'alpha'));
1448  } elseif ($action == 'setremisepercent' && $usercancreate) {
1449  $result = $object->set_remise_percent($user, price2num(GETPOST('remise_percent'), '', 2));
1450  } elseif ($action == 'setremiseabsolue' && $usercancreate) {
1451  $result = $object->set_remise_absolue($user, price2num(GETPOST('remise_absolue'), 'MU', 2));
1452  } elseif ($action == 'setmode' && $usercancreate) {
1453  // Payment choice
1454  $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
1455  } elseif ($action == 'setmulticurrencycode' && $usercancreate) {
1456  // Multicurrency Code
1457  $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
1458  } elseif ($action == 'setmulticurrencyrate' && $usercancreate) {
1459  // Multicurrency rate
1460  $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int'));
1461  } elseif ($action == 'setbankaccount' && $usercancreate) {
1462  // bank account
1463  $result = $object->setBankAccount(GETPOST('fk_account', 'int'));
1464  } elseif ($action == 'setshippingmethod' && $usercancreate) {
1465  // shipping method
1466  $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int'));
1467  } elseif ($action == 'setwarehouse' && $usercancreate) {
1468  // warehouse
1469  $result = $object->setWarehouse(GETPOST('warehouse_id', 'int'));
1470  } elseif ($action == 'update_extras') {
1471  $object->oldcopy = dol_clone($object, 2);
1472 
1473  // Fill array 'array_options' with data from update form
1474  $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
1475  if ($ret < 0) {
1476  $error++;
1477  }
1478  if (!$error) {
1479  $result = $object->insertExtraFields('PROPAL_MODIFY');
1480  if ($result < 0) {
1481  setEventMessages($object->error, $object->errors, 'errors');
1482  $error++;
1483  }
1484  }
1485  if ($error) {
1486  $action = 'edit_extras';
1487  }
1488  }
1489 
1490  if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) {
1491  if ($action == 'addcontact') {
1492  if ($object->id > 0) {
1493  $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
1494  $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
1495  $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
1496  }
1497 
1498  if ($result >= 0) {
1499  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1500  exit();
1501  } else {
1502  if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1503  $langs->load("errors");
1504  setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
1505  } else {
1506  setEventMessages($object->error, $object->errors, 'errors');
1507  }
1508  }
1509  } elseif ($action == 'swapstatut') {
1510  // Toggle the status of a contact
1511  if ($object->fetch($id) > 0) {
1512  $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
1513  } else {
1514  dol_print_error($db);
1515  }
1516  } elseif ($action == 'deletecontact') {
1517  // Delete a contact
1518  $object->fetch($id);
1519  $result = $object->delete_contact($lineid);
1520 
1521  if ($result >= 0) {
1522  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1523  exit();
1524  } else {
1525  dol_print_error($db);
1526  }
1527  }
1528  }
1529 
1530  // Actions to build doc
1531  $upload_dir = !empty($conf->propal->multidir_output[$object->entity])?$conf->propal->multidir_output[$object->entity]:$conf->propal->dir_output;
1532  $permissiontoadd = $usercancreate;
1533  include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
1534 }
1535 
1536 
1537 /*
1538  * View
1539  */
1540 
1541 $form = new Form($db);
1542 $formfile = new FormFile($db);
1543 $formpropal = new FormPropal($db);
1544 $formmargin = new FormMargin($db);
1545 if (!empty($conf->project->enabled)) {
1546  $formproject = new FormProjets($db);
1547 }
1548 
1549 $title = $langs->trans('Proposal')." - ".$langs->trans('Card');
1550 $help_url = 'EN:Commercial_Proposals|FR:Proposition_commerciale|ES:Presupuestos|DE:Modul_Angebote';
1551 llxHeader('', $title, $help_url);
1552 
1553 $now = dol_now();
1554 
1555 // Add new proposal
1556 if ($action == 'create') {
1557  $currency_code = $conf->currency;
1558 
1559  print load_fiche_titre($langs->trans("NewProp"), '', 'propal');
1560 
1561  $soc = new Societe($db);
1562  if ($socid > 0) {
1563  $res = $soc->fetch($socid);
1564  }
1565 
1566  // Load objectsrc
1567  if (!empty($origin) && !empty($originid)) {
1568  // Parse element/subelement (ex: project_task)
1569  $element = $subelement = $origin;
1570  $regs = array();
1571  if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
1572  $element = $regs[1];
1573  $subelement = $regs[2];
1574  }
1575 
1576  if ($element == 'project') {
1577  $projectid = $originid;
1578  } else {
1579  // For compatibility
1580  if ($element == 'order' || $element == 'commande') {
1581  $element = $subelement = 'commande';
1582  }
1583  if ($element == 'propal') {
1584  $element = 'comm/propal';
1585  $subelement = 'propal';
1586  }
1587  if ($element == 'contract') {
1588  $element = $subelement = 'contrat';
1589  }
1590  if ($element == 'shipping') {
1591  $element = $subelement = 'expedition';
1592  }
1593 
1594  dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
1595 
1596  $classname = ucfirst($subelement);
1597  $objectsrc = new $classname($db);
1598  $objectsrc->fetch($originid);
1599  if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
1600  $objectsrc->fetch_lines();
1601  }
1602  $objectsrc->fetch_thirdparty();
1603 
1604  $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : 0);
1605  $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : '');
1606 
1607  $soc = $objectsrc->thirdparty;
1608 
1609  $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0)); // TODO maybe add default value option
1610  $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
1611  $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0)); // deprecated
1612  $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0));
1613  $warehouse_id = (!empty($objectsrc->warehouse_id) ? $objectsrc->warehouse_id : (!empty($soc->warehouse_id) ? $soc->warehouse_id : 0));
1614  $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice);
1615 
1616  // Replicate extrafields
1617  $objectsrc->fetch_optionals();
1618  $object->array_options = $objectsrc->array_options;
1619 
1620  if (!empty($conf->multicurrency->enabled)) {
1621  if (!empty($objectsrc->multicurrency_code)) {
1622  $currency_code = $objectsrc->multicurrency_code;
1623  }
1624  if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) {
1625  $currency_tx = $objectsrc->multicurrency_tx;
1626  }
1627  }
1628  }
1629  } else {
1630  if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) {
1631  $currency_code = $soc->multicurrency_code;
1632  }
1633  }
1634 
1635  //Warehouse default if null
1636  if ($soc->fk_warehouse > 0) {
1637  $warehouse_id = $soc->fk_warehouse;
1638  }
1639  if (!empty($conf->stock->enabled) && empty($warehouse_id) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) {
1640  if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) {
1641  $warehouse_id = $conf->global->MAIN_DEFAULT_WAREHOUSE;
1642  }
1643  if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) {
1644  $warehouse_id = $user->fk_warehouse;
1645  }
1646  }
1647 
1648  print '<form name="addprop" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
1649  print '<input type="hidden" name="token" value="'.newToken().'">';
1650  print '<input type="hidden" name="action" value="add">';
1651  if ($origin != 'project' && $originid) {
1652  print '<input type="hidden" name="origin" value="'.$origin.'">';
1653  print '<input type="hidden" name="originid" value="'.$originid.'">';
1654  } elseif ($origin == 'project' && !empty($projectid)) {
1655  print '<input type="hidden" name="projectid" value="'.$projectid.'">';
1656  }
1657 
1658  print dol_get_fiche_head();
1659 
1660  print '<table class="border centpercent">';
1661 
1662  // Reference
1663  print '<tr class="field_ref"><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td class="valuefieldcreate">'.$langs->trans("Draft").'</td></tr>';
1664 
1665  // Ref customer
1666  print '<tr class="field_ref_client"><td class="titlefieldcreate">'.$langs->trans('RefCustomer').'</td><td class="valuefieldcreate">';
1667  print '<input type="text" name="ref_client" value="'.(!empty($ref_client)?$ref_client:GETPOST('ref_client')).'"></td>';
1668  print '</tr>';
1669 
1670  // Third party
1671  print '<tr class="field_socid">';
1672  print '<td class="titlefieldcreate fieldrequired">'.$langs->trans('Customer').'</td>';
1673  $shipping_method_id = 0;
1674  if ($socid > 0) {
1675  print '<td class="valuefieldcreate">';
1676  print $soc->getNomUrl(1, 'customer');
1677  print '<input type="hidden" name="socid" value="'.$soc->id.'">';
1678  print '</td>';
1679  if (!empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD) && !empty($soc->shipping_method_id)) {
1680  $shipping_method_id = $soc->shipping_method_id;
1681  }
1682  //$warehouse_id = $soc->warehouse_id;
1683  } else {
1684  print '<td class="valuefieldcreate">';
1685  print img_picto('', 'company').$form->select_company('', 'socid', '((s.client = 1 OR s.client = 2 OR s.client = 3) AND status=1)', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300 maxwidth500 widthcentpercentminusxx');
1686  // reload page to retrieve customer informations
1687  if (empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED)) {
1688  print '<script type="text/javascript">
1689  $(document).ready(function() {
1690  $("#socid").change(function() {
1691  console.log("We have changed the company - Reload page");
1692  var socid = $(this).val();
1693  // reload page
1694  $("input[name=action]").val("create");
1695  $("form[name=addprop]").submit();
1696  });
1697  });
1698  </script>';
1699  }
1700  print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&client=3&fournisseur=0&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
1701  print '</td>';
1702  }
1703  print '</tr>'."\n";
1704 
1705  if ($socid > 0) {
1706  // Contacts (ask contact only if thirdparty already defined).
1707  print '<tr class="field_contactid"><td class="titlefieldcreate">'.$langs->trans("DefaultContact").'</td><td class="valuefieldcreate">';
1708  print img_picto('', 'contact');
1709  print $form->selectcontacts($soc->id, $contactid, 'contactid', 1, '', '', 0, 'minwidth300');
1710  print '</td></tr>';
1711 
1712  // Third party discounts info line
1713  print '<tr class="field_discount_info"><td class="titlefieldcreate">'.$langs->trans('Discounts').'</td><td class="valuefieldcreate">';
1714 
1715  $absolute_discount = $soc->getAvailableDiscounts();
1716 
1717  $thirdparty = $soc;
1718  $discount_type = 0;
1719  $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$thirdparty->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid'));
1720  include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
1721  print '</td></tr>';
1722  }
1723 
1724  // Date
1725  print '<tr class="field_addprop"><td class="titlefieldcreate fieldrequired">'.$langs->trans('DatePropal').'</td><td class="valuefieldcreate">';
1726  print $form->selectDate('', '', '', '', '', "addprop", 1, 1);
1727  print '</td></tr>';
1728 
1729  // Validaty duration
1730  print '<tr class="field_duree_validitee"><td class="titlefieldcreate fieldrequired">'.$langs->trans("ValidityDuration").'</td><td class="valuefieldcreate">'.img_picto('', 'clock', 'class="paddingright"').'<input name="duree_validite" class="width50" value="'.(GETPOSTISSET('duree_validite') ? GETPOST('duree_validite', 'alphanohtml') : $conf->global->PROPALE_VALIDITY_DURATION).'"> '.$langs->trans("days").'</td></tr>';
1731 
1732  // Terms of payment
1733  print '<tr class="field_cond_reglement_id"><td class="nowrap">'.$langs->trans('PaymentConditionsShort').'</td><td>';
1734  print img_picto('', 'paiment');
1735  $form->select_conditions_paiements((GETPOSTISSET('cond_reglement_id') && GETPOST('cond_reglement_id', 'int') != 0) ? GETPOST('cond_reglement_id', 'int') : $soc->cond_reglement_id, 'cond_reglement_id', 1, 1, 0, '', (GETPOSTISSET('cond_reglement_id_deposit_percent') ? GETPOST('cond_reglement_id_deposit_percent', 'alpha') : $soc->deposit_percent));
1736  print '</td></tr>';
1737 
1738  // Mode of payment
1739  print '<tr class="field_mode_reglement_id"><td class="titlefieldcreate">'.$langs->trans('PaymentMode').'</td><td class="valuefieldcreate">';
1740  print img_picto('', 'bank', 'class="pictofixedwidth"');
1741  $form->select_types_paiements((GETPOSTISSET('mode_reglement_id') && GETPOST('mode_reglement_id', 'int') != 0) ? GETPOST('mode_reglement_id', 'int') : $soc->mode_reglement_id, 'mode_reglement_id', 'CRDT', 0, 1, 0, 0, 1, 'maxwidth200 widthcentpercentminusx');
1742  print '</td></tr>';
1743 
1744  // Bank Account
1745  if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && !empty($conf->banque->enabled)) {
1746  print '<tr class="field_fk_account"><td class="titlefieldcreate">'.$langs->trans('BankAccount').'</td><td class="valuefieldcreate">';
1747  print img_picto('', 'bank_account', 'class="pictofixedwidth"').$form->select_comptes($soc->fk_account, 'fk_account', 0, '', 1, '', 0, 'maxwidth200 widthcentpercentminusx', 1);
1748  print '</td></tr>';
1749  }
1750 
1751  // Source / Channel - What trigger creation
1752  print '<tr class="field_demand_reason_id"><td class="titlefieldcreate">'.$langs->trans('Source').'</td><td class="valuefieldcreate">';
1753  print img_picto('', 'question', 'class="pictofixedwidth"');
1754  $form->selectInputReason('', 'demand_reason_id', "SRC_PROP", 1, 'maxwidth200 widthcentpercentminusx');
1755  print '</td></tr>';
1756 
1757  // Delivery delay
1758  print '<tr class="field_availability_id"><td class="titlefieldcreate">'.$langs->trans('AvailabilityPeriod');
1759  if (!empty($conf->commande->enabled)) {
1760  print ' ('.$langs->trans('AfterOrder').')';
1761  }
1762  print '</td><td class="valuefieldcreate">';
1763  print img_picto('', 'clock', 'class="pictofixedwidth"');
1764  $form->selectAvailabilityDelay('', 'availability_id', '', 1, 'maxwidth200 widthcentpercentminusx');
1765  print '</td></tr>';
1766 
1767  // Shipping Method
1768  if (!empty($conf->expedition->enabled)) {
1769  if (!empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD) && !empty($soc->shipping_method_id)) {
1770  $shipping_method_id = $soc->shipping_method_id;
1771  }
1772  print '<tr class="field_shipping_method_id"><td class="titlefieldcreate">'.$langs->trans('SendingMethod').'</td><td class="valuefieldcreate">';
1773  print img_picto('', 'object_dollyrevert', 'class="pictofixedwidth"');
1774  print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1, '', 0, 'maxwidth200 widthcentpercentminusx');
1775  print '</td></tr>';
1776  }
1777 
1778  // Warehouse
1779  if (!empty($conf->stock->enabled) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_PROPAL)) {
1780  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
1781  $formproduct = new FormProduct($db);
1782  print '<tr class="field_warehouse_id"><td class="titlefieldcreate">'.$langs->trans('Warehouse').'</td><td class="valuefieldcreate">';
1783  print img_picto('', 'stock', 'class="pictofixedwidth"').$formproduct->selectWarehouses($warehouse_id, 'warehouse_id', '', 1, 0, 0, '', 0, 0, array(), 'maxwidth500 widthcentpercentminusxx');
1784  print '</td></tr>';
1785  }
1786 
1787  // Delivery date (or manufacturing)
1788  print '<tr class="field_date_livraison"><td class="titlefieldcreate">'.$langs->trans("DeliveryDate").'</td>';
1789  print '<td class="valuefieldcreate">';
1790  if (isset($conf->global->DATE_LIVRAISON_WEEK_DELAY) && is_numeric($conf->global->DATE_LIVRAISON_WEEK_DELAY)) {
1791  $tmpdte = time() + ((7 * $conf->global->DATE_LIVRAISON_WEEK_DELAY) * 24 * 60 * 60);
1792  $syear = date("Y", $tmpdte);
1793  $smonth = date("m", $tmpdte);
1794  $sday = date("d", $tmpdte);
1795  print $form->selectDate($syear."-".$smonth."-".$sday, 'date_livraison', '', '', '', "addprop");
1796  } else {
1797  print $form->selectDate(-1, 'date_livraison', '', '', '', "addprop", 1, 1);
1798  }
1799  print '</td></tr>';
1800 
1801  // Project
1802  if (!empty($conf->project->enabled)) {
1803  $langs->load("projects");
1804  print '<tr class="field_projectid">';
1805  print '<td class="titlefieldcreate">'.$langs->trans("Project").'</td><td class="valuefieldcreate">';
1806  print img_picto('', 'project', 'class="pictofixedwidth"').$formproject->select_projects(($soc->id > 0 ? $soc->id : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx');
1807  print ' <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$soc->id.'&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id).'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddProject").'"></span></a>';
1808  print '</td>';
1809  print '</tr>';
1810  }
1811 
1812  // Incoterms
1813  if (!empty($conf->incoterm->enabled)) {
1814  print '<tr class="field_incoterm_id">';
1815  print '<td class="titlefieldcreate"><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), $soc->label_incoterms, 1).'</label></td>';
1816  print '<td class="valuefieldcreate maxwidthonsmartphone">';
1817  print $form->select_incoterms((!empty($soc->fk_incoterms) ? $soc->fk_incoterms : ''), (!empty($soc->location_incoterms) ? $soc->location_incoterms : ''));
1818  print '</td></tr>';
1819  }
1820 
1821  // Template to use by default
1822  print '<tr class="field_model">';
1823  print '<td class="titlefieldcreate">'.$langs->trans("DefaultModel").'</td>';
1824  print '<td class="valuefieldcreate">';
1825  print img_picto('', 'pdf', 'class="pictofixedwidth"');
1826  $liste = ModelePDFPropales::liste_modeles($db);
1827  $preselected = (!empty($conf->global->PROPALE_ADDON_PDF_ODT_DEFAULT) ? $conf->global->PROPALE_ADDON_PDF_ODT_DEFAULT : getDolGlobalString("PROPALE_ADDON_PDF"));
1828  print $form->selectarray('model', $liste, $preselected, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth200 widthcentpercentminusx', 1);
1829  print "</td></tr>";
1830 
1831  // Multicurrency
1832  if (!empty($conf->multicurrency->enabled)) {
1833  print '<tr class="field_currency">';
1834  print '<td class="titlefieldcreate">'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
1835  print '<td class="valuefieldcreate maxwidthonsmartphone">';
1836  print img_picto('', 'currency', 'class="pictofixedwidth"').$form->selectMultiCurrency($currency_code, 'multicurrency_code', 0);
1837  print '</td></tr>';
1838  }
1839 
1840  // Public note
1841  print '<tr class="field_note_public">';
1842  print '<td class="titlefieldcreate tdtop">'.$langs->trans('NotePublic').'</td>';
1843  print '<td class="valuefieldcreate">';
1844  $note_public = $object->getDefaultCreateValueFor('note_public', (!empty($objectsrc) ? $objectsrc->note_public : null));
1845  $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%');
1846  print $doleditor->Create(1);
1847 
1848  // Private note
1849  if (empty($user->socid)) {
1850  print '<tr class="field_note_private">';
1851  print '<td class="titlefieldcreate tdtop">'.$langs->trans('NotePrivate').'</td>';
1852  print '<td class="valuefieldcreate">';
1853  $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc)) ? $objectsrc->note_private : null));
1854  $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%');
1855  print $doleditor->Create(1);
1856  // print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
1857  print '</td></tr>';
1858  }
1859 
1860  // Other attributes
1861  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';
1862 
1863  // Lines from source
1864  if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
1865  // TODO for compatibility
1866  if ($origin == 'contrat') {
1867  // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
1868  $objectsrc->remise_absolue = $remise_absolue; // deprecated
1869  $objectsrc->remise_percent = $remise_percent;
1870  $objectsrc->update_price(1, - 1, 1);
1871  }
1872 
1873  print "\n<!-- ".$classname." info -->";
1874  print "\n";
1875  print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n";
1876  print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n";
1877  print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n";
1878  print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
1879  print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
1880 
1881  $newclassname = $classname;
1882  if ($newclassname == 'Propal') {
1883  $newclassname = 'CommercialProposal';
1884  } elseif ($newclassname == 'Commande') {
1885  $newclassname = 'Order';
1886  } elseif ($newclassname == 'Expedition') {
1887  $newclassname = 'Sending';
1888  } elseif ($newclassname == 'Fichinter') {
1889  $newclassname = 'Intervention';
1890  }
1891 
1892  print '<tr><td>'.$langs->trans($newclassname).'</td><td>'.$objectsrc->getNomUrl(1).'</td></tr>';
1893  print '<tr><td>'.$langs->trans('AmountHT').'</td><td>'.price($objectsrc->total_ht, 0, $langs, 1, -1, -1, $conf->currency).'</td></tr>';
1894  print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($objectsrc->total_tva, 0, $langs, 1, -1, -1, $conf->currency)."</td></tr>";
1895  if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1
1896  print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1, 0, $langs, 1, -1, -1, $conf->currency)."</td></tr>";
1897  }
1898 
1899  if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2
1900  print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2, 0, $langs, 1, -1, -1, $conf->currency)."</td></tr>";
1901  }
1902  print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($objectsrc->total_ttc, 0, $langs, 1, -1, -1, $conf->currency)."</td></tr>";
1903 
1904  if (!empty($conf->multicurrency->enabled)) {
1905  print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht).'</td></tr>';
1906  print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva)."</td></tr>";
1907  print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc)."</td></tr>";
1908  }
1909  }
1910 
1911  print "</table>\n";
1912 
1913 
1914  /*
1915  * Combobox for copy function
1916  */
1917 
1918  if (empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) {
1919  print '<input type="hidden" name="createmode" value="empty">';
1920  }
1921 
1922  if (!empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) {
1923  print '<br><table>';
1924 
1925  // For backward compatibility
1926  print '<tr>';
1927  print '<td><input type="radio" name="createmode" value="copy"></td>';
1928  print '<td>'.$langs->trans("CopyPropalFrom").' </td>';
1929  print '<td>';
1930  $liste_propal = array();
1931  $liste_propal [0] = '';
1932 
1933  $sql = "SELECT p.rowid as id, p.ref, s.nom";
1934  $sql .= " FROM ".MAIN_DB_PREFIX."propal p";
1935  $sql .= ", ".MAIN_DB_PREFIX."societe s";
1936  $sql .= " WHERE s.rowid = p.fk_soc";
1937  $sql .= " AND p.entity IN (".getEntity('propal').")";
1938  $sql .= " AND p.fk_statut <> 0";
1939  $sql .= " ORDER BY Id";
1940 
1941  $resql = $db->query($sql);
1942  if ($resql) {
1943  $num = $db->num_rows($resql);
1944  $i = 0;
1945  while ($i < $num) {
1946  $row = $db->fetch_row($resql);
1947  $propalRefAndSocName = $row [1]." - ".$row [2];
1948  $liste_propal [$row [0]] = $propalRefAndSocName;
1949  $i++;
1950  }
1951  print $form->selectarray("copie_propal", $liste_propal, 0);
1952  } else {
1953  dol_print_error($db);
1954  }
1955  print '</td></tr>';
1956 
1957  print '<tr><td class="tdtop"><input type="radio" name="createmode" value="empty" checked></td>';
1958  print '<td valign="top" colspan="2">'.$langs->trans("CreateEmptyPropal").'</td></tr>';
1959  print '</table>';
1960  }
1961 
1962  print dol_get_fiche_end();
1963 
1964  $langs->load("bills");
1965 
1966  print $form->buttonsSaveCancel("CreateDraft");
1967 
1968  print "</form>";
1969 
1970 
1971  // Show origin lines
1972  if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
1973  print '<br>';
1974 
1975  $title = $langs->trans('ProductsAndServices');
1976  print load_fiche_titre($title);
1977 
1978  print '<div class="div-table-responsive-no-min">';
1979  print '<table class="noborder centpercent">';
1980 
1981  $objectsrc->printOriginLinesList();
1982 
1983  print '</table>';
1984  print '</div>';
1985  }
1986 } elseif ($object->id > 0) {
1987  /*
1988  * Show object in view mode
1989  */
1990  $object->fetch_thirdparty();
1991  if ($object->thirdparty) {
1992  $soc = $object->thirdparty;
1993  } else {
1994  $soc = new Societe($db);
1995  }
1996 
1997  $head = propal_prepare_head($object);
1998  print dol_get_fiche_head($head, 'comm', $langs->trans('Proposal'), -1, 'propal');
1999 
2000  $formconfirm = '';
2001 
2002  // Clone confirmation
2003  if ($action == 'clone') {
2004  // Create an array for form
2005  $formquestion = array(
2006  // 'text' => $langs->trans("ConfirmClone"),
2007  // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
2008  array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)', '', 0, 0, null, 0, 'maxwidth300')),
2009  array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans('PuttingPricesUpToDate'), 'value' => (!empty($conf->global->PROPOSAL_CLONE_UPDATE_PRICES) ? 1 : 0)),
2010  );
2011  if (!empty($conf->global->PROPAL_CLONE_DATE_DELIVERY) && !empty($object->delivery_date)) {
2012  $formquestion[] = array('type' => 'date', 'name' => 'date_delivery', 'label' => $langs->trans("DeliveryDate"), 'value' => $object->delivery_date);
2013  }
2014  // Incomplete payment. We ask if reason = discount or other
2015  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmClonePropal', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
2016  }
2017 
2018  if ($action == 'closeas') {
2019  //Form to close proposal (signed or not)
2020  $formquestion = array(
2021  array('type' => 'select', 'name' => 'statut', 'label' => '<span class="fieldrequired">'.$langs->trans("CloseAs").'</span>', 'values' => array($object::STATUS_SIGNED => $object->LibStatut($object::STATUS_SIGNED), $object::STATUS_NOTSIGNED => $object->LibStatut($object::STATUS_NOTSIGNED))),
2022  array('type' => 'text', 'name' => 'note_private', 'label' => $langs->trans("Note"), 'value' => '') // Field to complete private note (not replace)
2023  );
2024 
2025  $deposit_percent_from_payment_terms = getDictionaryValue('c_payment_term', 'deposit_percent', $object->cond_reglement_id);
2026 
2027  if (!empty($deposit_percent_from_payment_terms) && isModEnabled('facture') && ! empty($user->rights->facture->creer)) {
2028  require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
2029 
2030  $object->fetchObjectLinked();
2031 
2032  $eligibleForDepositGeneration = true;
2033 
2034  if (array_key_exists('facture', $object->linkedObjects)) {
2035  foreach ($object->linkedObjects['facture'] as $invoice) {
2036  if ($invoice->type == Facture::TYPE_DEPOSIT) {
2037  $eligibleForDepositGeneration = false;
2038  break;
2039  }
2040  }
2041  }
2042 
2043  if ($eligibleForDepositGeneration && array_key_exists('commande', $object->linkedObjects)) {
2044  foreach ($object->linkedObjects['commande'] as $order) {
2045  $order->fetchObjectLinked();
2046 
2047  if (array_key_exists('facture', $order->linkedObjects)) {
2048  foreach ($order->linkedObjects['facture'] as $invoice) {
2049  if ($invoice->type == Facture::TYPE_DEPOSIT) {
2050  $eligibleForDepositGeneration = false;
2051  break 2;
2052  }
2053  }
2054  }
2055  }
2056  }
2057 
2058 
2059  if ($eligibleForDepositGeneration) {
2060  $formquestion[] = array(
2061  'type' => 'checkbox',
2062  'tdclass' => 'showonlyifsigned',
2063  'name' => 'generate_deposit',
2064  'label' => $form->textwithpicto($langs->trans('GenerateDeposit', $object->deposit_percent), $langs->trans('DepositGenerationPermittedByThePaymentTermsSelected'))
2065  );
2066 
2067  $formquestion[] = array(
2068  'type' => 'date',
2069  'tdclass' => 'fieldrequired showonlyifgeneratedeposit',
2070  'name' => 'datef',
2071  'label' => $langs->trans('DateInvoice'),
2072  'value' => dol_now(),
2073  'datenow' => true
2074  );
2075 
2076  if (! empty($conf->global->INVOICE_POINTOFTAX_DATE)) {
2077  $formquestion[] = array(
2078  'type' => 'date',
2079  'tdclass' => 'fieldrequired showonlyifgeneratedeposit',
2080  'name' => 'date_pointoftax',
2081  'label' => $langs->trans('DatePointOfTax'),
2082  'value' => dol_now(),
2083  'datenow' => true
2084  );
2085  }
2086 
2087  ob_start();
2088  $form->select_conditions_paiements(0, 'cond_reglement_id', -1, 0, 0, 'minwidth200');
2089  $paymentTermsSelect = ob_get_clean();
2090 
2091  $formquestion[] = array(
2092  'type' => 'other',
2093  'tdclass' => 'fieldrequired showonlyifgeneratedeposit',
2094  'name' => 'cond_reglement_id',
2095  'label' => $langs->trans('PaymentTerm'),
2096  'value' => $paymentTermsSelect
2097  );
2098 
2099  $formquestion[] = array(
2100  'type' => 'checkbox',
2101  'tdclass' => 'showonlyifgeneratedeposit',
2102  'name' => 'validate_generated_deposit',
2103  'label' => $langs->trans('ValidateGeneratedDeposit')
2104  );
2105 
2106  $formquestion[] = array(
2107  'type' => 'onecolumn',
2108  'value' => '
2109  <script>
2110  let signedValue = ' . $object::STATUS_SIGNED . ';
2111 
2112  $(document).ready(function() {
2113  $("[name=generate_deposit]").change(function () {
2114  let $self = $(this);
2115  let $target = $(".showonlyifgeneratedeposit").parent(".tagtr");
2116 
2117  if (! $self.parents(".tagtr").is(":hidden") && $self.is(":checked")) {
2118  $target.show();
2119  } else {
2120  $target.hide();
2121  }
2122 
2123  return true;
2124  });
2125 
2126  $("#statut").change(function() {
2127  let $target = $(".showonlyifsigned").parent(".tagtr");
2128 
2129  if ($(this).val() == signedValue) {
2130  $target.show();
2131  } else {
2132  $target.hide();
2133  }
2134 
2135  $("[name=generate_deposit]").trigger("change");
2136 
2137  return true;
2138  });
2139 
2140  $("#statut").trigger("change");
2141  });
2142  </script>
2143  '
2144  );
2145  }
2146  }
2147 
2148  if (!empty($conf->notification->enabled)) {
2149  require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
2150  $notify = new Notify($db);
2151  $formquestion = array_merge($formquestion, array(
2152  array('type' => 'onecolumn', 'value' => $notify->confirmMessage('PROPAL_CLOSE_SIGNED', $object->socid, $object)),
2153  ));
2154  }
2155 
2156  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('SetAcceptedRefused'), $text, 'confirm_closeas', $formquestion, '', 1, 250);
2157  } elseif ($action == 'delete') {
2158  // Confirm delete
2159  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteProp'), $langs->trans('ConfirmDeleteProp', $object->ref), 'confirm_delete', '', 0, 1);
2160  } elseif ($action == 'reopen') {
2161  // Confirm reopen
2162  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ReOpen'), $langs->trans('ConfirmReOpenProp', $object->ref), 'confirm_reopen', '', 0, 1);
2163  } elseif ($action == 'ask_deleteline') {
2164  // Confirmation delete product/service line
2165  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1);
2166  } elseif ($action == 'validate') {
2167  // Confirm validate proposal
2168  $error = 0;
2169 
2170  // We verify whether the object is provisionally numbering
2171  $ref = substr($object->ref, 1, 4);
2172  if ($ref == 'PROV' || $ref == '') {
2173  $numref = $object->getNextNumRef($soc);
2174  if (empty($numref)) {
2175  $error++;
2176  setEventMessages($object->error, $object->errors, 'errors');
2177  }
2178  } else {
2179  $numref = $object->ref;
2180  }
2181 
2182  $text = $langs->trans('ConfirmValidateProp', $numref);
2183  if (!empty($conf->notification->enabled)) {
2184  require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
2185  $notify = new Notify($db);
2186  $text .= '<br>';
2187  $text .= $notify->confirmMessage('PROPAL_VALIDATE', $object->socid, $object);
2188  }
2189 
2190  // mandatoryPeriod
2191  $nbMandated = 0;
2192  foreach ($object->lines as $line) {
2193  $res = $line->fetch_product();
2194  if ($res > 0 ) {
2195  if ($line->product->isService() && $line->product->isMandatoryPeriod() && (empty($line->date_start) || empty($line->date_end) )) {
2196  $nbMandated++;
2197  break;
2198  }
2199  }
2200  }
2201  if ($nbMandated > 0) {
2202  $text .= '<div><span class="clearboth nowraponall warning">'.$langs->trans("mandatoryPeriodNeedTobeSetMsgValidate").'</span></div>';
2203  }
2204 
2205  if (!$error) {
2206  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateProp'), $text, 'confirm_validate', '', 0, 1);
2207  }
2208  }
2209 
2210  // Call Hook formConfirm
2211  $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
2212  $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2213  if (empty($reshook)) {
2214  $formconfirm .= $hookmanager->resPrint;
2215  } elseif ($reshook > 0) {
2216  $formconfirm = $hookmanager->resPrint;
2217  }
2218 
2219  // Print form confirm
2220  print $formconfirm;
2221 
2222 
2223  // Proposal card
2224 
2225  $linkback = '<a href="'.DOL_URL_ROOT.'/comm/propal/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
2226 
2227  $morehtmlref = '<div class="refidno">';
2228  // Ref customer
2229  $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1);
2230  $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', null, null, '', 1);
2231  // Thirdparty
2232  $morehtmlref .= '<br><span class="hideonsmartphone">'.$langs->trans('ThirdParty').' : </span>'.$soc->getNomUrl(1, 'customer');
2233  if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $soc->id > 0) {
2234  $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/comm/propal/list.php?socid='.$soc->id.'&search_societe='.urlencode($soc->name).'">'.$langs->trans("OtherProposals").'</a>)';
2235  }
2236  // Project
2237  if (!empty($conf->project->enabled)) {
2238  $langs->load("projects");
2239  $morehtmlref .= '<br><span class="paddingrightonly">'.$langs->trans('Project').'</span>';
2240  if ($usercancreate) {
2241  if ($action != 'classify') {
2242  $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
2243  }
2244  if ($action == 'classify') {
2245  //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
2246  $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
2247  $morehtmlref .= '<input type="hidden" name="action" value="classin">';
2248  $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
2249  $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
2250  $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
2251  $morehtmlref .= '</form>';
2252  } else {
2253  $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
2254  }
2255  } else {
2256  if (!empty($object->fk_project)) {
2257  $proj = new Project($db);
2258  $proj->fetch($object->fk_project);
2259  $morehtmlref .= ': '.$proj->getNomUrl(1);
2260  if ($proj->title) {
2261  $morehtmlref .= ' - '.$proj->title;
2262  }
2263  } else {
2264  $morehtmlref .= '';
2265  }
2266  }
2267  }
2268  $morehtmlref .= '</div>';
2269 
2270 
2271  dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
2272 
2273 
2274  print '<div class="fichecenter">';
2275  print '<div class="fichehalfleft">';
2276  print '<div class="underbanner clearboth"></div>';
2277 
2278  print '<table class="border tableforfield" width="100%">';
2279 
2280  // Link for thirdparty discounts
2281  if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
2282  $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
2283  $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
2284  } else {
2285  $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
2286  $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
2287  }
2288 
2289  print '<tr><td class="titlefield">'.$langs->trans('Discounts').'</td><td>';
2290 
2291  $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount);
2292  $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote);
2293  $absolute_discount = price2num($absolute_discount, 'MT');
2294  $absolute_creditnote = price2num($absolute_creditnote, 'MT');
2295 
2296  $caneditfield = ($object->statut != Propal::STATUS_SIGNED && $object->statut != Propal::STATUS_BILLED);
2297 
2298  $thirdparty = $soc;
2299  $discount_type = 0;
2300  $backtopage = urlencode($_SERVER["PHP_SELF"].'?id='.$object->id);
2301  include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
2302 
2303  print '</td></tr>';
2304 
2305  // Date of proposal
2306  print '<tr>';
2307  print '<td>';
2308  // print '<table class="nobordernopadding" width="100%"><tr><td>';
2309  // print $langs->trans('DatePropal');
2310  // print '</td>';
2311  // if ($action != 'editdate' && $usercancreate && $caneditfield) {
2312  // print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
2313  // }
2314 
2315  // print '</tr></table>';
2316  $editenable = $usercancreate && $caneditfield && $object->statut == Propal::STATUS_DRAFT;
2317  print $form->editfieldkey("DatePropal", 'date', '', $object, $editenable);
2318  print '</td><td class="valuefield">';
2319  if ($action == 'editdate' && $usercancreate && $caneditfield) {
2320  print '<form name="editdate" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
2321  print '<input type="hidden" name="token" value="'.newToken().'">';
2322  print '<input type="hidden" name="action" value="setdate">';
2323  print $form->selectDate($object->date, 're', '', '', 0, "editdate");
2324  print '<input type="submit" class="button button-edit" value="'.$langs->trans('Modify').'">';
2325  print '</form>';
2326  } else {
2327  if ($object->date) {
2328  print dol_print_date($object->date, 'day');
2329  } else {
2330  print '&nbsp;';
2331  }
2332  }
2333  print '</td>';
2334 
2335  // Date end proposal
2336  print '<tr>';
2337  print '<td>';
2338  print '<table class="nobordernopadding" width="100%"><tr><td>';
2339  print $langs->trans('DateEndPropal');
2340  print '</td>';
2341  if ($action != 'editecheance' && $usercancreate && $caneditfield) {
2342  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editecheance&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>';
2343  }
2344  print '</tr></table>';
2345  print '</td><td class="valuefield">';
2346  if ($action == 'editecheance' && $usercancreate && $caneditfield) {
2347  print '<form name="editecheance" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
2348  print '<input type="hidden" name="token" value="'.newToken().'">';
2349  print '<input type="hidden" name="action" value="setecheance">';
2350  print $form->selectDate($object->fin_validite, 'ech', '', '', '', "editecheance");
2351  print '<input type="submit" class="button button-edit" value="'.$langs->trans('Modify').'">';
2352  print '</form>';
2353  } else {
2354  if (!empty($object->fin_validite)) {
2355  print dol_print_date($object->fin_validite, 'day');
2356  if ($object->statut == Propal::STATUS_VALIDATED && $object->fin_validite < ($now - $conf->propal->cloture->warning_delay)) {
2357  print img_warning($langs->trans("Late"));
2358  }
2359  } else {
2360  print '&nbsp;';
2361  }
2362  }
2363  print '</td>';
2364  print '</tr>';
2365 
2366  // Payment term
2367  print '<tr><td>';
2368  print '<table class="nobordernopadding" width="100%"><tr><td>';
2369  print $langs->trans('PaymentConditionsShort');
2370  print '</td>';
2371  if ($action != 'editconditions' && $usercancreate && $caneditfield) {
2372  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetConditions'), 1).'</a></td>';
2373  }
2374  print '</tr></table>';
2375  print '</td><td class="valuefield">';
2376  if ($action == 'editconditions' && $usercancreate && $caneditfield) {
2377  $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id', 0, '', 1, $object->deposit_percent);
2378  } else {
2379  $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none', 0, '', 1, $object->deposit_percent);
2380  }
2381  print '</td>';
2382  print '</tr>';
2383 
2384  // Payment mode
2385  print '<tr class="field_mode_reglement_id">';
2386  print '<td class="titlefieldcreate">';
2387  print '<table class="nobordernopadding centpercent"><tr><td>';
2388  print $langs->trans('PaymentMode');
2389  print '</td>';
2390  if ($action != 'editmode' && $usercancreate && $caneditfield) {
2391  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMode'), 1).'</a></td>';
2392  }
2393  print '</tr></table>';
2394  print '</td><td class="valuefieldcreate">';
2395  if ($action == 'editmode' && $usercancreate && $caneditfield) {
2396  $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1);
2397  } else {
2398  $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none');
2399  }
2400  print '</td></tr>';
2401 
2402  // Delivery date
2403  $langs->load('deliveries');
2404  print '<tr><td>';
2405  print $form->editfieldkey($langs->trans('DeliveryDate'), 'date_livraison', $object->delivery_date, $object, $usercancreate && $caneditfield, 'datepicker');
2406  print '</td><td class="valuefieldedit">';
2407  print $form->editfieldval($langs->trans('DeliveryDate'), 'date_livraison', $object->delivery_date, $object, $usercancreate && $caneditfield, 'datepicker');
2408  print '</td>';
2409  print '</tr>';
2410 
2411  // Delivery delay
2412  print '<tr class="fielddeliverydelay"><td>';
2413  print '<table class="nobordernopadding" width="100%"><tr><td>';
2414  if (!empty($conf->commande->enabled)) {
2415  print $form->textwithpicto($langs->trans('AvailabilityPeriod'), $langs->trans('AvailabilityPeriod').' ('.$langs->trans('AfterOrder').')');
2416  } else {
2417  print $langs->trans('AvailabilityPeriod');
2418  }
2419  print '</td>';
2420  if ($action != 'editavailability' && $usercancreate && $caneditfield) {
2421  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editavailability&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetAvailability'), 1).'</a></td>';
2422  }
2423  print '</tr></table>';
2424  print '</td><td class="valuefield">';
2425  if ($action == 'editavailability' && $usercancreate && $caneditfield) {
2426  $form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'availability_id', 1);
2427  } else {
2428  $form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'none', 1);
2429  }
2430 
2431  print '</td>';
2432  print '</tr>';
2433 
2434  // Shipping Method
2435  if (!empty($conf->expedition->enabled)) {
2436  print '<tr><td>';
2437  print '<table class="nobordernopadding centpercent"><tr><td>';
2438  print $langs->trans('SendingMethod');
2439  print '</td>';
2440  if ($action != 'editshippingmethod' && $usercancreate && $caneditfield) {
2441  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editshippingmethod&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetShippingMode'), 1).'</a></td>';
2442  }
2443  print '</tr></table>';
2444  print '</td><td class="valuefield">';
2445  if ($action == 'editshippingmethod' && $usercancreate && $caneditfield) {
2446  $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1);
2447  } else {
2448  $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none');
2449  }
2450  print '</td>';
2451  print '</tr>';
2452  }
2453 
2454  // Warehouse
2455  if (!empty($conf->stock->enabled) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_PROPAL)) {
2456  $langs->load('stocks');
2457  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
2458  $formproduct = new FormProduct($db);
2459  print '<tr class="field_warehouse_id"><td class="titlefieldcreate">';
2460  $editenable = $usercancreate;
2461  print $form->editfieldkey("Warehouse", 'warehouse', '', $object, $editenable);
2462  print '</td><td class="valuefieldcreate">';
2463  if ($action == 'editwarehouse') {
2464  $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1);
2465  } else {
2466  $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'none');
2467  }
2468  print '</td>';
2469  print '</tr>';
2470  }
2471 
2472  // Origin of demand
2473  print '<tr><td>';
2474  print '<table class="nobordernopadding centpercent"><tr><td>';
2475  print $langs->trans('Source');
2476  print '</td>';
2477  if ($action != 'editdemandreason' && $usercancreate) {
2478  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdemandreason&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetDemandReason'), 1).'</a></td>';
2479  }
2480  print '</tr></table>';
2481  print '</td><td class="valuefield">';
2482  if ($action == 'editdemandreason' && $usercancreate) {
2483  $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'demand_reason_id', 1);
2484  } else {
2485  $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'none');
2486  }
2487  print '</td>';
2488  print '</tr>';
2489 
2490  // Multicurrency
2491  if (!empty($conf->multicurrency->enabled)) {
2492  // Multicurrency code
2493  print '<tr>';
2494  print '<td>';
2495  print '<table class="nobordernopadding" width="100%"><tr><td>';
2496  print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0);
2497  print '</td>';
2498  if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT && $usercancreate) {
2499  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencycode&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>';
2500  }
2501  print '</tr></table>';
2502  print '</td><td class="valuefield">';
2503  if ($object->statut == $object::STATUS_DRAFT && $action == 'editmulticurrencycode' && $usercancreate) {
2504  $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code');
2505  } else {
2506  $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'none');
2507  }
2508  print '</td></tr>';
2509 
2510  // Multicurrency rate
2511  if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
2512  print '<tr>';
2513  print '<td>';
2514  print '<table class="nobordernopadding" width="100%"><tr>';
2515  print '<td>';
2516  print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0);
2517  print '</td>';
2518  if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency && $usercancreate) {
2519  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencyrate&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>';
2520  }
2521  print '</tr></table>';
2522  print '</td><td class="valuefield">';
2523  if ($object->statut == $object::STATUS_DRAFT && ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') && $usercancreate) {
2524  if ($action == 'actualizemulticurrencyrate') {
2525  list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
2526  }
2527  $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
2528  } else {
2529  $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
2530  if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
2531  print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
2532  print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
2533  print '</div>';
2534  }
2535  }
2536  print '</td></tr>';
2537  }
2538  }
2539 
2540  if ($soc->outstanding_limit) {
2541  // Outstanding Bill
2542  print '<tr><td>';
2543  print $langs->trans('OutstandingBill');
2544  print '</td><td class="valuefield">';
2545  $arrayoutstandingbills = $soc->getOutstandingBills();
2546  print ($arrayoutstandingbills['opened'] > $soc->outstanding_limit ? img_warning() : '');
2547  print price($arrayoutstandingbills['opened']).' / ';
2548  print price($soc->outstanding_limit, 0, $langs, 1, - 1, - 1, $conf->currency);
2549  print '</td>';
2550  print '</tr>';
2551  }
2552 
2553  if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && !empty($conf->banque->enabled)) {
2554  // Bank Account
2555  print '<tr><td>';
2556  print '<table width="100%" class="nobordernopadding"><tr><td>';
2557  print $langs->trans('BankAccount');
2558  print '</td>';
2559  if ($action != 'editbankaccount' && $usercancreate) {
2560  print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'</a></td>';
2561  }
2562  print '</tr></table>';
2563  print '</td><td class="valuefield">';
2564  if ($action == 'editbankaccount') {
2565  $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
2566  } else {
2567  $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
2568  }
2569  print '</td>';
2570  print '</tr>';
2571  }
2572 
2573  $tmparray = $object->getTotalWeightVolume();
2574  $totalWeight = $tmparray['weight'];
2575  $totalVolume = $tmparray['volume'];
2576  if ($totalWeight) {
2577  print '<tr><td>'.$langs->trans("CalculatedWeight").'</td>';
2578  print '<td class="valuefield">';
2579  print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND) ? $conf->global->MAIN_WEIGHT_DEFAULT_ROUND : -1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? $conf->global->MAIN_WEIGHT_DEFAULT_UNIT : 'no', 0);
2580  print '</td></tr>';
2581  }
2582  if ($totalVolume) {
2583  print '<tr><td>'.$langs->trans("CalculatedVolume").'</td>';
2584  print '<td class="valuefield">';
2585  print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND) ? $conf->global->MAIN_VOLUME_DEFAULT_ROUND : -1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT) ? $conf->global->MAIN_VOLUME_DEFAULT_UNIT : 'no', 0);
2586  print '</td></tr>';
2587  }
2588 
2589  // Incoterms
2590  if (!empty($conf->incoterm->enabled)) {
2591  print '<tr><td>';
2592  print '<table width="100%" class="nobordernopadding"><tr><td>';
2593  print $langs->trans('IncotermLabel');
2594  print '<td><td class="right">';
2595  if ($action != 'editincoterm' && $usercancreate && $caneditfield) {
2596  print '<a class="editfielda" href="'.DOL_URL_ROOT.'/comm/propal/card.php?id='.$object->id.'&action=editincoterm&token='.newToken().'">'.img_edit().'</a>';
2597  } else {
2598  print '&nbsp;';
2599  }
2600  print '</td></tr></table>';
2601  print '</td>';
2602  print '<td class="valuefield">';
2603  if ($action == 'editincoterm' && $usercancreate && $caneditfield) {
2604  print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
2605  } else {
2606  print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
2607  }
2608  print '</td></tr>';
2609  }
2610 
2611  // Other attributes
2612  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
2613 
2614  print '</table>';
2615 
2616  print '</div>';
2617  print '<div class="fichehalfright">';
2618  print '<div class="underbanner clearboth"></div>';
2619 
2620  print '<table class="border tableforfield centpercent">';
2621 
2622  if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
2623  // Multicurrency Amount HT
2624  print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>';
2625  print '<td class="nowrap right amountcard">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
2626  print '</tr>';
2627 
2628  // Multicurrency Amount VAT
2629  print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).'</td>';
2630  print '<td class="nowrap right amountcard">'.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
2631  print '</tr>';
2632 
2633  // Multicurrency Amount TTC
2634  print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).'</td>';
2635  print '<td class="nowrap right amountcard">'.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
2636  print '</tr>';
2637  }
2638 
2639  // Amount HT
2640  print '<tr><td class="titlefieldmiddle">'.$langs->trans('AmountHT').'</td>';
2641  print '<td class="nowrap right amountcard">'.price($object->total_ht, '', $langs, 0, - 1, - 1, $conf->currency).'</td>';
2642  print '</tr>';
2643 
2644  // Amount VAT
2645  print '<tr><td>'.$langs->trans('AmountVAT').'</td>';
2646  print '<td class="nowrap right amountcard">'.price($object->total_tva, '', $langs, 0, - 1, - 1, $conf->currency).'</td>';
2647  print '</tr>';
2648 
2649  // Amount Local Taxes
2650  if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { // Localtax1
2651  print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>';
2652  print '<td class="nowrap right amountcard">'.price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency).'</td>';
2653  print '</tr>';
2654  }
2655  if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { // Localtax2
2656  print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>';
2657  print '<td class="nowrap right amountcard">'.price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency).'</td>';
2658  print '</tr>';
2659  }
2660 
2661  // Amount TTC
2662  print '<tr><td>'.$langs->trans('AmountTTC').'</td>';
2663  print '<td class="nowrap right amountcard">'.price($object->total_ttc, '', $langs, 0, - 1, - 1, $conf->currency).'</td>';
2664  print '</tr>';
2665 
2666  // Statut
2667  //print '<tr><td height="10">' . $langs->trans('Status') . '</td><td class="left" colspan="2">' . $object->getLibStatut(4) . '</td></tr>';
2668 
2669  print '</table>';
2670 
2671  // Margin Infos
2672  if (!empty($conf->margin->enabled)) {
2673  $formmargin->displayMarginInfos($object);
2674  }
2675 
2676  print '</div>';
2677  print '</div>';
2678 
2679  print '<div class="clearboth"></div><br>';
2680 
2681  if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
2682  $blocname = 'contacts';
2683  $title = $langs->trans('ContactsAddresses');
2684  include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
2685  }
2686 
2687  if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
2688  $blocname = 'notes';
2689  $title = $langs->trans('Notes');
2690  include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
2691  }
2692 
2693  /*
2694  * Lines
2695  */
2696 
2697  // Show object lines
2698  $result = $object->getLinesArray();
2699 
2700  print ' <form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">
2701  <input type="hidden" name="token" value="' . newToken().'">
2702  <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">
2703  <input type="hidden" name="mode" value="">
2704  <input type="hidden" name="page_y" value="">
2705  <input type="hidden" name="id" value="' . $object->id.'">
2706  ';
2707 
2708  if (!empty($conf->use_javascript_ajax) && $object->statut == Propal::STATUS_DRAFT) {
2709  include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
2710  }
2711 
2712  print '<div class="div-table-responsive-no-min">';
2713  if (!empty($object->lines) || ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines' && $action != 'editline')) {
2714  print '<table id="tablelines" class="noborder noshadow" width="100%">';
2715  }
2716 
2717  if (!empty($object->lines)) {
2718  $ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 1);
2719  }
2720 
2721  // Form to add new line
2722  if ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines') {
2723  if ($action != 'editline') {
2724  // Add products/services form
2725 
2726  $parameters = array();
2727  $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2728  if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
2729  if (empty($reshook))
2730  $object->formAddObjectLine(1, $mysoc, $soc);
2731  } else {
2732  $parameters = array();
2733  $reshook = $hookmanager->executeHooks('formEditObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2734  }
2735  }
2736 
2737  if (!empty($object->lines) || ($object->statut == Propal::STATUS_DRAFT && $usercancreate && $action != 'selectlines' && $action != 'editline')) {
2738  print '</table>';
2739  }
2740  print '</div>';
2741 
2742  print "</form>\n";
2743 
2744  print dol_get_fiche_end();
2745 
2746 
2747  /*
2748  * Button Actions
2749  */
2750 
2751  if ($action != 'presend') {
2752  print '<div class="tabsAction">';
2753 
2754  $parameters = array();
2755  $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
2756  // modified by hook
2757  if (empty($reshook)) {
2758  if ($action != 'editline') {
2759  // Validate
2760  if (($object->statut == Propal::STATUS_DRAFT && $object->total_ttc >= 0 && count($object->lines) > 0)
2761  || ($object->statut == Propal::STATUS_DRAFT && !empty($conf->global->PROPAL_ENABLE_NEGATIVE) && count($object->lines) > 0)) {
2762  if ($usercanvalidate) {
2763  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=validate&token='.newToken().'">'.$langs->trans('Validate').'</a>';
2764  } else {
2765  print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans('Validate').'</a>';
2766  }
2767  }
2768  // Create event
2769  /*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page.
2770  {
2771  print '<a class="butAction" href="' . DOL_URL_ROOT . '/comm/action/card.php?action=create&amp;origin=' . $object->element . '&amp;originid=' . $object->id . '&amp;socid=' . $object->socid . '">' . $langs->trans("AddAction") . '</a></div>';
2772  }*/
2773  // Edit
2774  if ($object->statut == Propal::STATUS_VALIDATED && $usercancreate) {
2775  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=modif&token='.newToken().'">'.$langs->trans('Modify').'</a>';
2776  }
2777 
2778  // ReOpen
2779  if ( (( ! empty($conf->global->PROPAL_REOPEN_UNSIGNED_ONLY) && $object->statut == Propal::STATUS_NOTSIGNED) || (empty($conf->global->PROPAL_REOPEN_UNSIGNED_ONLY) && ($object->statut == Propal::STATUS_SIGNED || $object->statut == Propal::STATUS_NOTSIGNED || $object->statut == Propal::STATUS_BILLED))) && $usercanclose) {
2780  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=reopen&token='.newToken().(empty($conf->global->MAIN_JUMP_TAG) ? '' : '#reopen').'"';
2781  print '>'.$langs->trans('ReOpen').'</a>';
2782  }
2783 
2784  // Send
2785  if (empty($user->socid)) {
2786  if ($object->statut == Propal::STATUS_VALIDATED || $object->statut == Propal::STATUS_SIGNED || !empty($conf->global->PROPOSAL_SENDBYEMAIL_FOR_ALL_STATUS)) {
2787  if ($usercansend) {
2788  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&token='.newToken().'&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>';
2789  } else {
2790  print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('SendMail').'</a>';
2791  }
2792  }
2793  }
2794 
2795  // Create a sale order
2796  if (!empty($conf->commande->enabled) && $object->statut == Propal::STATUS_SIGNED) {
2797  if ($usercancreateorder) {
2798  print '<a class="butAction" href="'.DOL_URL_ROOT.'/commande/card.php?action=create&origin='.$object->element.'&originid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("AddOrder").'</a>';
2799  }
2800  }
2801 
2802  // Create a purchase order
2803  if (!empty($conf->global->WORKFLOW_CAN_CREATE_PURCHASE_ORDER_FROM_PROPOSAL)) {
2804  if ($object->statut == Propal::STATUS_SIGNED && ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled))) {
2805  if ($usercancreatepurchaseorder) {
2806  print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/commande/card.php?action=create&origin='.$object->element.'&originid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("AddPurchaseOrder").'</a>';
2807  }
2808  }
2809  }
2810 
2811  // Create an intervention
2812  if (!empty($conf->service->enabled) && !empty($conf->ficheinter->enabled) && $object->statut == Propal::STATUS_SIGNED) {
2813  if ($usercancreateintervention) {
2814  $langs->load("interventions");
2815  print '<a class="butAction" href="'.DOL_URL_ROOT.'/fichinter/card.php?action=create&origin='.$object->element.'&originid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("AddIntervention").'</a>';
2816  }
2817  }
2818 
2819  // Create contract
2820  if (!empty($conf->contrat->enabled) && $object->statut == Propal::STATUS_SIGNED) {
2821  $langs->load("contracts");
2822 
2823  if ($usercancreatecontract) {
2824  print '<a class="butAction" href="'.DOL_URL_ROOT.'/contrat/card.php?action=create&origin='.$object->element.'&originid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans('AddContract').'</a>';
2825  }
2826  }
2827 
2828  // Create an invoice and classify billed
2829  if ($object->statut == Propal::STATUS_SIGNED && empty($conf->global->PROPOSAL_ARE_NOT_BILLABLE)) {
2830  if (isModEnabled('facture') && $usercancreateinvoice) {
2831  print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&origin='.$object->element.'&originid='.$object->id.'&socid='.$object->socid.'">'.$langs->trans("CreateBill").'</a>';
2832  }
2833 
2834  $arrayofinvoiceforpropal = $object->getInvoiceArrayList();
2835  if ((is_array($arrayofinvoiceforpropal) && count($arrayofinvoiceforpropal) > 0) || empty($conf->global->WORKFLOW_PROPAL_NEED_INVOICE_TO_BE_CLASSIFIED_BILLED)) {
2836  if ($usercanclose) {
2837  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=classifybilled&token='.newToken().'&socid='.$object->socid.'">'.$langs->trans("ClassifyBilled").'</a>';
2838  } else {
2839  print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("ClassifyBilled").'</a>';
2840  }
2841  }
2842  }
2843 
2844  // Close as accepted/refused
2845  if ($object->statut == Propal::STATUS_VALIDATED) {
2846  if ($usercanclose) {
2847  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=closeas&token='.newToken().(empty($conf->global->MAIN_JUMP_TAG) ? '' : '#close').'"';
2848  print '>'.$langs->trans('SetAcceptedRefused').'</a>';
2849  } else {
2850  print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'"';
2851  print '>'.$langs->trans('SetAcceptedRefused').'</a>';
2852  }
2853  }
2854 
2855  // Clone
2856  if ($usercancreate) {
2857  print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&socid='.$object->socid.'&action=clone&token='.newToken().'&object='.$object->element.'">'.$langs->trans("ToClone").'</a>';
2858  }
2859 
2860  // Delete
2861  if ($usercandelete) {
2862  print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'"';
2863  print '>'.$langs->trans('Delete').'</a>';
2864  }
2865  }
2866  }
2867 
2868  print '</div>';
2869  }
2870 
2871  //Select mail models is same action as presend
2872  if (GETPOST('modelselected')) {
2873  $action = 'presend';
2874  }
2875 
2876  if ($action != 'presend') {
2877  print '<div class="fichecenter"><div class="fichehalfleft">';
2878  print '<a name="builddoc"></a>'; // ancre
2879  /*
2880  * Generated documents
2881  */
2882  $objref = dol_sanitizeFileName($object->ref);
2883  $filedir = $conf->propal->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref);
2884  $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
2885  $genallowed = $usercanread;
2886  $delallowed = $usercancreate;
2887 
2888  print $formfile->showdocuments('propal', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang, '', $object);
2889 
2890  // Show links to link elements
2891  $linktoelem = $form->showLinkToObjectBlock($object, null, array('propal'));
2892 
2893  $compatibleImportElementsList = false;
2894  if ($user->rights->propal->creer && $object->statut == Propal::STATUS_DRAFT) {
2895  $compatibleImportElementsList = array('commande', 'propal'); // import from linked elements
2896  }
2897  $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList);
2898 
2899  // Show online signature link
2900  $useonlinesignature = 1;
2901 
2902  if ($object->statut != Propal::STATUS_DRAFT && $useonlinesignature) {
2903  print '<br><!-- Link to sign -->';
2904  require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
2905  print showOnlineSignatureUrl('proposal', $object->ref).'<br>';
2906  }
2907 
2908  print '</div><div class="fichehalfright">';
2909 
2910  // List of actions on element
2911  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
2912  $formactions = new FormActions($db);
2913  $somethingshown = $formactions->showactions($object, 'propal', $socid, 1);
2914 
2915  print '</div></div>';
2916  }
2917 
2918  // Presend form
2919  $modelmail = 'propal_send';
2920  $defaulttopic = 'SendPropalRef';
2921  $diroutput = $conf->propal->multidir_output[$object->entity];
2922  $trackid = 'pro'.$object->id;
2923 
2924  include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
2925 }
2926 
2927 // End of page
2928 llxFooter();
2929 $db->close();
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:48
Propal\STATUS_SIGNED
const STATUS_SIGNED
Signed quote.
Definition: propal.class.php:360
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1226
restrictedArea
restrictedArea($user, $features, $objectid=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $mode=0)
Check permissions of a user to show a page and an object.
Definition: security.lib.php:234
llxFooter
llxFooter()
Empty footer.
Definition: wrapper.php:73
Project
Class to manage projects.
Definition: project.class.php:35
ProductCombination
Class ProductCombination Used to represent a product combination.
Definition: ProductCombination.class.php:25
Productcustomerprice
File of class to manage predefined price products or services by customer.
Definition: productcustomerprice.class.php:29
load_fiche_titre
load_fiche_titre($titre, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
Definition: functions.lib.php:5204
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:484
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
FormActions
Class to manage building of HTML components.
Definition: html.formactions.class.php:30
dol_include_once
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
Definition: functions.lib.php:1033
Translate
Class to manage translations.
Definition: translate.class.php:30
img_warning
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
Definition: functions.lib.php:4521
FormProjets
Class to manage building of HTML components.
Definition: html.formprojet.class.php:30
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:142
FormMargin
Classe permettant la generation de composants html autre Only common components are here.
Definition: html.formmargin.class.php:29
FormPropal
Class to manage generation of HTML components for proposal management.
Definition: html.formpropal.class.php:28
dol_clone
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
Definition: functions.lib.php:1158
Notify
Class to manage notifications.
Definition: notify.class.php:33
img_edit
img_edit($titlealt='default', $float=0, $other='')
Show logo editer/modifier fiche.
Definition: functions.lib.php:4389
dol_banner_tab
dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='rowid', $fieldref='ref', $morehtmlref='', $moreparam='', $nodbprefix=0, $morehtmlleft='', $morehtmlstatus='', $onlybanner=0, $morehtmlright='')
Show tab footer of a card.
Definition: functions.lib.php:2046
$help_url
if(GETPOST('button_removefilter_x', 'alpha')||GETPOST('button_removefilter.x', 'alpha')||GETPOST('button_removefilter', 'alpha')) if(GETPOST('button_search_x', 'alpha')||GETPOST('button_search.x', 'alpha')||GETPOST('button_search', 'alpha')) if($action=="save" &&empty($cancel)) $help_url
View.
Definition: agenda.php:116
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5661
Facture\TYPE_DEPOSIT
const TYPE_DEPOSIT
Deposit invoice.
Definition: facture.class.php:397
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2514
Propal\STATUS_DRAFT
const STATUS_DRAFT
Draft status.
Definition: propal.class.php:352
dol_concatdesc
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
Definition: functions.lib.php:7248
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
Facture\createDepositFromOrigin
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
Definition: facture.class.php:1502
$formactions
if(preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) if(preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) if($action=='set') elseif($action=='specimen') elseif($action=='setmodel') elseif($action=='del') elseif($action=='setdoc') $formactions
View.
Definition: agenda_other.php:178
$formconfirm
$formconfirm
if ($action == 'delbookkeepingyear') {
Definition: listbyaccount.php:576
Propal\STATUS_BILLED
const STATUS_BILLED
Billed or processed quote.
Definition: propal.class.php:368
get_default_npr
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Fonction qui renvoie si tva doit etre tva percue recuperable.
Definition: functions.lib.php:6405
FormFile
Class to offer components to list and upload files.
Definition: html.formfile.class.php:36
get_localtax
get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller="", $vatnpr=0)
Return localtax rate for a particular vat, when selling a product with vat $vatrate,...
Definition: functions.lib.php:5837
propal_prepare_head
propal_prepare_head($object)
Prepare array with list of tabs.
Definition: propal.lib.php:32
getDictionaryValue
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
Definition: functions.lib.php:10138
Propal\STATUS_VALIDATED
const STATUS_VALIDATED
Validated status.
Definition: propal.class.php:356
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
setEventMessage
setEventMessage($mesgs, $style='mesgs')
Set event message in dol_events session object.
Definition: functions.lib.php:8108
MultiCurrency\getIdAndTxFromCode
static getIdAndTxFromCode($dbs, $code, $date_document='')
Get id and rate of currency from code.
Definition: multicurrency.class.php:526
dol_get_fiche_head
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='')
Show tabs of a record.
Definition: functions.lib.php:1822
getDolGlobalString
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
Definition: functions.lib.php:80
dol_htmlcleanlastbr
dol_htmlcleanlastbr($stringtodecode)
This function remove all ending and br at end.
Definition: functions.lib.php:7036
get_default_tva
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
Definition: functions.lib.php:6304
FormProduct
Class with static methods for building HTML components related to products Only components common to ...
Definition: html.formproduct.class.php:30
newToken
newToken()
Return the value of token currently saved into session with name 'newtoken'.
Definition: functions.lib.php:10878
dol_get_fiche_end
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition: functions.lib.php:2018
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:105
GETPOSTISSET
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
Definition: functions.lib.php:386
ExtraFields
Class to manage standard extra fields.
Definition: extrafields.class.php:39
Product
Class to manage products or services.
Definition: product.class.php:46
Form
Class to manage generation of HTML components Only common components must be here.
Definition: html.form.class.php:52
$parameters
$parameters
Actions.
Definition: card.php:78
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
price
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
Definition: functions.lib.php:5541
getCountry
getCountry($searchkey, $withcode='', $dbtouse=0, $outputlangs='', $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
Definition: company.lib.php:489
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8137
ModelePDFPropales\liste_modeles
static liste_modeles($db, $maxfilenamelength=0)
Return list of active generation modules.
Definition: modules_propale.php:53
Propal
Class to manage proposals.
Definition: propal.class.php:52
dol_mktime
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
Definition: functions.lib.php:2757
showDimensionInBestUnit
showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round=-1, $forceunitoutput='no', $use_short_label=0)
Output a dimension with best unit.
Definition: functions.lib.php:5788
llxHeader
if(!defined('NOREQUIRESOC')) if(!defined('NOREQUIRETRAN')) if(!defined('NOCSRFCHECK')) if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) llxHeader()
Empty header.
Definition: wrapper.php:59
DolEditor
Class to manage a WYSIWYG editor.
Definition: doleditor.class.php:30
Propal\STATUS_NOTSIGNED
const STATUS_NOTSIGNED
Not signed quote.
Definition: propal.class.php:364