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