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