dolibarr  17.0.2
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  $tva_tx = (GETPOSTISSET('tva_tx') ? GETPOST('tva_tx', 'alpha') : 0);
686  } else {
687  $idprod = GETPOST('idprod', 'int');
688  $tva_tx = '';
689  }
690 
691 
692  // Prepare a price equivalent for minimum price check
693  $pu_equivalent = $pu_ht;
694  $pu_equivalent_ttc = $pu_ttc;
695  $currency_tx = $object->multicurrency_tx;
696 
697  // Check if we have a foreing currency
698  // If so, we update the pu_equiv as the equivalent price in base currency
699  if ($pu_ht == '' && $pu_ht_devise != '' && $currency_tx != '') {
700  $pu_equivalent = $pu_ht_devise * $currency_tx;
701  }
702  if ($pu_ttc == '' && $pu_ttc_devise != '' && $currency_tx != '') {
703  $pu_equivalent_ttc = $pu_ttc_devise * $currency_tx;
704  }
705 
706  $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS', 2);
707 
708  $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef, 'alpha'), '', 2) : 0);
709  if (empty($remise_percent)) {
710  $remise_percent = 0;
711  }
712 
713  // Extrafields
714  $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
715  $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
716  // Unset extrafield
717  if (is_array($extralabelsline)) {
718  // Get extra fields
719  foreach ($extralabelsline as $key => $value) {
720  unset($_POST["options_".$key]);
721  }
722  }
723 
724  if ((empty($idprod) || $idprod < 0) && ($price_ht < 0) && ($qty < 0)) {
725  setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
726  $error++;
727  }
728  if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
729  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
730  $error++;
731  }
732  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.
733  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
734  $error++;
735  }
736  if ($qty == '') {
737  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
738  $error++;
739  }
740  if ($qty < 0) {
741  setEventMessages($langs->trans('FieldCannotBeNegative', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
742  $error++;
743  }
744  if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && empty($product_desc)) {
745  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
746  $error++;
747  }
748 
749  if (!$error && isModEnabled('variants') && $prod_entry_mode != 'free') {
750  if ($combinations = GETPOST('combinations', 'array')) {
751  //Check if there is a product with the given combination
752  $prodcomb = new ProductCombination($db);
753 
754  if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
755  $idprod = $res->fk_product_child;
756  } else {
757  setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
758  $error++;
759  }
760  }
761  }
762 
763  if (!$error && ($qty >= 0) && (!empty($product_desc) || (!empty($idprod) && $idprod > 0))) {
764  // Clean parameters
765  $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'));
766  $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'));
767  $price_base_type = (GETPOST('price_base_type', 'alpha') ?GETPOST('price_base_type', 'alpha') : 'HT');
768 
769  // Ecrase $pu par celui du produit
770  // Ecrase $desc par celui du produit
771  // Ecrase $tva_tx par celui du produit
772  // Ecrase $base_price_type par celui du produit
773  if (!empty($idprod) && $idprod > 0) {
774  $prod = new Product($db);
775  $prod->fetch($idprod);
776 
777  $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
778 
779  // Update if prices fields are defined
780  $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
781  $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
782  if (empty($tva_tx)) {
783  $tva_npr = 0;
784  }
785 
786  $pu_ht = $prod->price;
787  $pu_ttc = $prod->price_ttc;
788  $price_min = $prod->price_min;
789  $price_min_ttc = $prod->price_min_ttc;
790  $price_base_type = $prod->price_base_type;
791 
792  // If price per segment
793  if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) {
794  $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
795  $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
796  $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
797  $price_min_ttc = $prod->multiprices_min_ttc[$object->thirdparty->price_level];
798  $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
799  if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
800  if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) {
801  $tva_tx = $prod->multiprices_tva_tx[$object->thirdparty->price_level];
802  }
803  if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) {
804  $tva_npr = $prod->multiprices_recuperableonly[$object->thirdparty->price_level];
805  }
806  }
807  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
808  // If price per customer
809  require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
810 
811  $prodcustprice = new Productcustomerprice($db);
812 
813  $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $object->thirdparty->id);
814 
815  $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
816  if ($result >= 0) {
817  if (count($prodcustprice->lines) > 0) {
818  $pu_ht = price($prodcustprice->lines[0]->price);
819  $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
820  $price_min = price($prodcustprice->lines[0]->price_min);
821  $price_min_ttc = price($prodcustprice->lines[0]->price_min_ttc);
822  $price_base_type = $prodcustprice->lines[0]->price_base_type;
823  $tva_tx = $prodcustprice->lines[0]->tva_tx;
824  if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
825  $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
826  }
827  $tva_npr = $prodcustprice->lines[0]->recuperableonly;
828  if (empty($tva_tx)) {
829  $tva_npr = 0;
830  }
831  }
832  } else {
833  setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
834  }
835  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
836  // If price per quantity
837  if ($prod->prices_by_qty[0]) { // yes, this product has some prices per quantity
838  // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
839  $pqp = GETPOST('pbq', 'int');
840 
841  // Search price into product_price_by_qty from $prod->id
842  foreach ($prod->prices_by_qty_list[0] as $priceforthequantityarray) {
843  if ($priceforthequantityarray['rowid'] != $pqp) {
844  continue;
845  }
846  // We found the price
847  if ($priceforthequantityarray['price_base_type'] == 'HT') {
848  $pu_ht = $priceforthequantityarray['unitprice'];
849  } else {
850  $pu_ttc = $priceforthequantityarray['unitprice'];
851  }
852  // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST.
853  break;
854  }
855  }
856  } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
857  // If price per quantity and customer
858  if ($prod->prices_by_qty[$object->thirdparty->price_level]) { // yes, this product has some prices per quantity
859  // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
860  $pqp = GETPOST('pbq', 'int');
861  // Search price into product_price_by_qty from $prod->id
862  foreach ($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) {
863  if ($priceforthequantityarray['rowid'] != $pqp) {
864  continue;
865  }
866  // We found the price
867  if ($priceforthequantityarray['price_base_type'] == 'HT') {
868  $pu_ht = $priceforthequantityarray['unitprice'];
869  } else {
870  $pu_ttc = $priceforthequantityarray['unitprice'];
871  }
872  // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST.
873  break;
874  }
875  }
876  }
877 
878  $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
879  $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
880 
881  // Set unit price to use
882  if (!empty($price_ht) || $price_ht === '0') {
883  $pu_ht = price2num($price_ht, 'MU');
884  $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
885  } elseif (!empty($price_ttc) || $price_ttc === '0') {
886  $pu_ttc = price2num($price_ttc, 'MU');
887  $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
888  } elseif ($tmpvat != $tmpprodvat) {
889  // Is this still used ?
890  if ($price_base_type != 'HT') {
891  $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
892  } else {
893  $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
894  }
895  }
896 
897  $desc = '';
898 
899  // Define output language
900  if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
901  $outputlangs = $langs;
902  $newlang = '';
903  if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
904  $newlang = GETPOST('lang_id', 'aZ09');
905  }
906  if (empty($newlang)) {
907  $newlang = $object->thirdparty->default_lang;
908  }
909  if (!empty($newlang)) {
910  $outputlangs = new Translate("", $conf);
911  $outputlangs->setDefaultLang($newlang);
912  }
913 
914  $desc = (!empty($prod->multilangs[$outputlangs->defaultlang]["description"])) ? $prod->multilangs[$outputlangs->defaultlang]["description"] : $prod->description;
915  } else {
916  $desc = $prod->description;
917  }
918 
919  //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time
920  if ($product_desc==$desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) {
921  $product_desc='';
922  }
923 
924  if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) {
925  $desc = $product_desc;
926  } else {
927  $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
928  }
929 
930  // Add custom code and origin country into description
931  if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) {
932  $tmptxt = '(';
933  // Define output language
934  if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
935  $outputlangs = $langs;
936  $newlang = '';
937  if (empty($newlang) && GETPOST('lang_id', 'alpha')) {
938  $newlang = GETPOST('lang_id', 'alpha');
939  }
940  if (empty($newlang)) {
941  $newlang = $object->thirdparty->default_lang;
942  }
943  if (!empty($newlang)) {
944  $outputlangs = new Translate("", $conf);
945  $outputlangs->setDefaultLang($newlang);
946  $outputlangs->load('products');
947  }
948  if (!empty($prod->customcode)) {
949  $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
950  }
951  if (!empty($prod->customcode) && !empty($prod->country_code)) {
952  $tmptxt .= ' - ';
953  }
954  if (!empty($prod->country_code)) {
955  $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0);
956  }
957  } else {
958  if (!empty($prod->customcode)) {
959  $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
960  }
961  if (!empty($prod->customcode) && !empty($prod->country_code)) {
962  $tmptxt .= ' - ';
963  }
964  if (!empty($prod->country_code)) {
965  $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0);
966  }
967  }
968  $tmptxt .= ')';
969  $desc = dol_concatdesc($desc, $tmptxt);
970  }
971 
972  $type = $prod->type;
973  $fk_unit = $prod->fk_unit;
974  } else {
975  $pu_ht = price2num($price_ht, 'MU');
976  $pu_ttc = price2num($price_ttc, 'MU');
977  $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
978  $tva_tx = str_replace('*', '', $tva_tx);
979  if (empty($tva_tx)) {
980  $tva_npr = 0;
981  }
982  $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
983  $desc = $product_desc;
984  $type = GETPOST('type');
985  $fk_unit = GETPOST('units', 'alpha');
986  $pu_ht_devise = price2num($price_ht_devise, 'MU');
987  $pu_ttc_devise = price2num($price_ttc_devise, 'MU');
988 
989  if ($pu_ttc && !$pu_ht) {
990  $price_base_type = 'TTC';
991  }
992  }
993 
994  // Margin
995  $fournprice = price2num(GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : '');
996  $buyingprice = price2num(GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''); // If buying_price is '0', we muste keep this value
997 
998  // Local Taxes
999  $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty);
1000  $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty);
1001 
1002  $info_bits = 0;
1003  if ($tva_npr) {
1004  $info_bits |= 0x01;
1005  }
1006 
1007  $desc = dol_htmlcleanlastbr($desc);
1008 
1009  if ($usermustrespectpricemin) {
1010  if ($pu_equivalent && $price_min && ((price2num($pu_equivalent) * (1 - $remise_percent / 100)) < price2num($price_min))) {
1011  $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
1012  setEventMessages($mesg, null, 'errors');
1013  $error++;
1014  } elseif ($pu_equivalent_ttc && $price_min_ttc && ((price2num($pu_equivalent_ttc) * (1 - $remise_percent / 100)) < price2num($price_min_ttc))) {
1015  $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
1016  setEventMessages($mesg, null, 'errors');
1017  $error++;
1018  }
1019  }
1020 
1021  if (!$error) {
1022  // Insert line
1023  $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);
1024 
1025  if ($result > 0) {
1026  $ret = $object->fetch($object->id); // Reload to get new records
1027  $object->fetch_thirdparty();
1028 
1029  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
1030  // Define output language
1031  $outputlangs = $langs;
1032  $newlang = GETPOST('lang_id', 'alpha');
1033  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1034  $newlang = $object->thirdparty->default_lang;
1035  }
1036  if (!empty($newlang)) {
1037  $outputlangs = new Translate("", $conf);
1038  $outputlangs->setDefaultLang($newlang);
1039  }
1040 
1041  $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1042  }
1043 
1044  unset($_POST['prod_entry_mode']);
1045 
1046  unset($_POST['qty']);
1047  unset($_POST['type']);
1048  unset($_POST['remise_percent']);
1049  unset($_POST['price_ht']);
1050  unset($_POST['multicurrency_price_ht']);
1051  unset($_POST['price_ttc']);
1052  unset($_POST['tva_tx']);
1053  unset($_POST['product_ref']);
1054  unset($_POST['product_label']);
1055  unset($_POST['product_desc']);
1056  unset($_POST['fournprice']);
1057  unset($_POST['buying_price']);
1058  unset($_POST['np_marginRate']);
1059  unset($_POST['np_markRate']);
1060  unset($_POST['dp_desc']);
1061  unset($_POST['idprod']);
1062  unset($_POST['units']);
1063 
1064  unset($_POST['date_starthour']);
1065  unset($_POST['date_startmin']);
1066  unset($_POST['date_startsec']);
1067  unset($_POST['date_startday']);
1068  unset($_POST['date_startmonth']);
1069  unset($_POST['date_startyear']);
1070  unset($_POST['date_endhour']);
1071  unset($_POST['date_endmin']);
1072  unset($_POST['date_endsec']);
1073  unset($_POST['date_endday']);
1074  unset($_POST['date_endmonth']);
1075  unset($_POST['date_endyear']);
1076  } else {
1077  setEventMessages($object->error, $object->errors, 'errors');
1078  }
1079  }
1080  }
1081  } elseif ($action == 'updateline' && $usercancreate && GETPOST('save')) {
1082  // Update a line
1083  // Clean parameters
1084  $date_start = '';
1085  $date_end = '';
1086  $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
1087  $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
1088  $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml'));
1089  $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx', 'alpha') : 0);
1090  $vat_rate = str_replace('*', '', $vat_rate);
1091 
1092  $pu_ht = price2num(GETPOST('price_ht'), '', 2);
1093  $pu_ttc = price2num(GETPOST('price_ttc'), '', 2);
1094 
1095  $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2);
1096  $pu_ttc_devise = price2num(GETPOST('multicurrency_subprice_ttc'), '', 2);
1097 
1098  $qty = price2num(GETPOST('qty', 'alpha'), 'MS');
1099 
1100  // Prepare a price equivalent for minimum price check
1101  $pu_equivalent = $pu_ht;
1102  $pu_equivalent_ttc = $pu_ttc;
1103  $currency_tx = $object->multicurrency_tx;
1104 
1105  // Check if we have a foreing currency
1106  // If so, we update the pu_equiv as the equivalent price in base currency
1107  if ($pu_ht == '' && $pu_ht_devise != '' && $currency_tx != '') {
1108  $pu_equivalent = $pu_ht_devise * $currency_tx;
1109  }
1110  if ($pu_ttc == '' && $pu_ttc_devise != '' && $currency_tx != '') {
1111  $pu_equivalent_ttc = $pu_ttc_devise * $currency_tx;
1112  }
1113 
1114  // Define info_bits
1115  $info_bits = 0;
1116  if (preg_match('/\*/', $vat_rate)) {
1117  $info_bits |= 0x01;
1118  }
1119 
1120  // Define vat_rate
1121  $vat_rate = str_replace('*', '', $vat_rate);
1122  $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
1123  $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
1124 
1125  // Add buying price
1126  $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
1127  $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
1128 
1129  // Extrafields Lines
1130  $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
1131  $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
1132  // Unset extrafield POST Data
1133  if (is_array($extralabelsline)) {
1134  foreach ($extralabelsline as $key => $value) {
1135  unset($_POST["options_".$key]);
1136  }
1137  }
1138 
1139  // Define special_code for special lines
1140  $special_code = GETPOST('special_code');
1141  if (!GETPOST('qty')) {
1142  $special_code = 3;
1143  }
1144 
1145  $remise_percent = GETPOST('remise_percent') != '' ? price2num(GETPOST('remise_percent'), '', 2) : 0;
1146 
1147  // Check minimum price
1148  $productid = GETPOST('productid', 'int');
1149  if (!empty($productid)) {
1150  $product = new Product($db);
1151  $product->fetch($productid);
1152 
1153  $type = $product->type;
1154 
1155  $price_min = $product->price_min;
1156  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) {
1157  $price_min = $product->multiprices_min[$object->thirdparty->price_level];
1158  }
1159  $price_min_ttc = $product->price_min_ttc;
1160  if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) {
1161  $price_min_ttc = $product->multiprices_min_ttc[$object->thirdparty->price_level];
1162  }
1163 
1164  $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
1165 
1166  if ($usermustrespectpricemin) {
1167  if ($pu_equivalent && $price_min && ((price2num($pu_equivalent) * (1 - $remise_percent / 100)) < price2num($price_min))) {
1168  $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
1169  setEventMessages($mesg, null, 'errors');
1170  $error++;
1171  $action = 'editline';
1172  } elseif ($pu_equivalent_ttc && $price_min_ttc && ((price2num($pu_equivalent_ttc) * (1 - $remise_percent / 100)) < price2num($price_min_ttc))) {
1173  $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
1174  setEventMessages($mesg, null, 'errors');
1175  $error++;
1176  $action = 'editline';
1177  }
1178  }
1179  } else {
1180  $type = GETPOST('type');
1181  $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
1182 
1183  // Check parameters
1184  if (GETPOST('type') < 0) {
1185  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
1186  $error++;
1187  $action = 'editline';
1188  }
1189  }
1190 
1191  if ($qty < 0) {
1192  setEventMessages($langs->trans('FieldCannotBeNegative', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
1193  $error++;
1194  $action = 'editline';
1195  }
1196 
1197  if (!$error) {
1198  if (empty($user->rights->margins->creer)) {
1199  foreach ($object->lines as &$line) {
1200  if ($line->id == GETPOST('lineid', 'int')) {
1201  $fournprice = $line->fk_fournprice;
1202  $buyingprice = $line->pa_ht;
1203  break;
1204  }
1205  }
1206  }
1207 
1208  $price_base_type = 'HT';
1209  $pu = $pu_ht;
1210  if (empty($pu) && !empty($pu_ttc)) {
1211  $pu = $pu_ttc;
1212  $price_base_type = 'TTC';
1213  }
1214 
1215  $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);
1216 
1217  if ($result >= 0) {
1218  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
1219  // Define output language
1220  $outputlangs = $langs;
1221  $newlang = '';
1222  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
1223  $newlang = GETPOST('lang_id', 'aZ09');
1224  }
1225  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1226  $newlang = $object->thirdparty->default_lang;
1227  }
1228  if (!empty($newlang)) {
1229  $outputlangs = new Translate("", $conf);
1230  $outputlangs->setDefaultLang($newlang);
1231  }
1232 
1233  $ret = $object->fetch($object->id); // Reload to get new records
1234  $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1235  }
1236 
1237  unset($_POST['qty']);
1238  unset($_POST['type']);
1239  unset($_POST['productid']);
1240  unset($_POST['remise_percent']);
1241  unset($_POST['price_ht']);
1242  unset($_POST['multicurrency_price_ht']);
1243  unset($_POST['price_ttc']);
1244  unset($_POST['tva_tx']);
1245  unset($_POST['product_ref']);
1246  unset($_POST['product_label']);
1247  unset($_POST['product_desc']);
1248  unset($_POST['fournprice']);
1249  unset($_POST['buying_price']);
1250 
1251  unset($_POST['date_starthour']);
1252  unset($_POST['date_startmin']);
1253  unset($_POST['date_startsec']);
1254  unset($_POST['date_startday']);
1255  unset($_POST['date_startmonth']);
1256  unset($_POST['date_startyear']);
1257  unset($_POST['date_endhour']);
1258  unset($_POST['date_endmin']);
1259  unset($_POST['date_endsec']);
1260  unset($_POST['date_endday']);
1261  unset($_POST['date_endmonth']);
1262  unset($_POST['date_endyear']);
1263  } else {
1264  setEventMessages($object->error, $object->errors, 'errors');
1265  }
1266  }
1267  } elseif ($action == 'updateline' && $usercancreate && GETPOST('cancel', 'alpha')) {
1268  header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); // Pour reaffichage de la fiche en cours d'edition
1269  exit();
1270  } elseif ($action == 'confirm_validate' && $confirm == 'yes' && $usercanvalidate) {
1271  $idwarehouse = GETPOST('idwarehouse', 'int');
1272 
1273  $qualified_for_stock_change = 0;
1274  if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
1275  $qualified_for_stock_change = $object->hasProductsOrServices(2);
1276  } else {
1277  $qualified_for_stock_change = $object->hasProductsOrServices(1);
1278  }
1279 
1280  // Check parameters
1281  if (isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) {
1282  if (!$idwarehouse || $idwarehouse == -1) {
1283  $error++;
1284  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
1285  $action = '';
1286  }
1287  }
1288 
1289  if (!$error) {
1290  $locationTarget = '';
1291  $db->begin();
1292  $result = $object->valid($user, $idwarehouse);
1293  if ($result >= 0) {
1294  $error = 0;
1295  $deposit = null;
1296 
1297  $deposit_percent_from_payment_terms = getDictionaryValue('c_payment_term', 'deposit_percent', $object->cond_reglement_id);
1298 
1299  if (
1300  GETPOST('generate_deposit', 'alpha') == 'on' && !empty($deposit_percent_from_payment_terms)
1301  && isModEnabled('facture') && !empty($user->rights->facture->creer)
1302  ) {
1303  require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
1304 
1305  $date = dol_mktime(0, 0, 0, GETPOST('datefmonth', 'int'), GETPOST('datefday', 'int'), GETPOST('datefyear', 'int'));
1306  $forceFields = array();
1307 
1308  if (GETPOSTISSET('date_pointoftax')) {
1309  $forceFields['date_pointoftax'] = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'));
1310  }
1311 
1312  $deposit = Facture::createDepositFromOrigin($object, $date, GETPOST('cond_reglement_id', 'int'), $user, 0, GETPOST('validate_generated_deposit', 'alpha') == 'on', $forceFields);
1313 
1314  if ($deposit) {
1315  setEventMessage('DepositGenerated');
1316  $locationTarget = DOL_URL_ROOT . '/compta/facture/card.php?id=' . $deposit->id;
1317  } else {
1318  $error++;
1319  setEventMessages($object->error, $object->errors, 'errors');
1320  }
1321  }
1322 
1323  // Define output language
1324  if (! $error) {
1325  $db->commit();
1326 
1327  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
1328  $outputlangs = $langs;
1329  $newlang = '';
1330  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
1331  $newlang = GETPOST('lang_id', 'aZ09');
1332  }
1333  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1334  $newlang = $object->thirdparty->default_lang;
1335  }
1336  if (!empty($newlang)) {
1337  $outputlangs = new Translate("", $conf);
1338  $outputlangs->setDefaultLang($newlang);
1339  }
1340  $model = $object->model_pdf;
1341  $ret = $object->fetch($id); // Reload to get new records
1342 
1343  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1344 
1345  if ($deposit) {
1346  $deposit->fetch($deposit->id); // Reload to get new records
1347  $deposit->generateDocument($deposit->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1348  }
1349  }
1350 
1351  if ($locationTarget) {
1352  header('Location: ' . $locationTarget);
1353  exit;
1354  }
1355  } else {
1356  $db->rollback();
1357  }
1358  } else {
1359  $db->rollback();
1360  setEventMessages($object->error, $object->errors, 'errors');
1361  }
1362  }
1363  } elseif ($action == 'confirm_modif' && $usercancreate) {
1364  // Go back to draft status
1365  $idwarehouse = GETPOST('idwarehouse');
1366 
1367  $qualified_for_stock_change = 0;
1368  if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
1369  $qualified_for_stock_change = $object->hasProductsOrServices(2);
1370  } else {
1371  $qualified_for_stock_change = $object->hasProductsOrServices(1);
1372  }
1373 
1374  // Check parameters
1375  if (isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) {
1376  if (!$idwarehouse || $idwarehouse == -1) {
1377  $error++;
1378  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
1379  $action = '';
1380  }
1381  }
1382 
1383  if (!$error) {
1384  $result = $object->setDraft($user, $idwarehouse);
1385  if ($result >= 0) {
1386  // Define output language
1387  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
1388  $outputlangs = $langs;
1389  $newlang = '';
1390  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
1391  $newlang = GETPOST('lang_id', 'aZ09');
1392  }
1393  if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1394  $newlang = $object->thirdparty->default_lang;
1395  }
1396  if (!empty($newlang)) {
1397  $outputlangs = new Translate("", $conf);
1398  $outputlangs->setDefaultLang($newlang);
1399  }
1400  $model = $object->model_pdf;
1401  $ret = $object->fetch($id); // Reload to get new records
1402 
1403  $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1404  }
1405  }
1406  }
1407  } elseif ($action == 'confirm_shipped' && $confirm == 'yes' && $usercanclose) {
1408  $result = $object->cloture($user);
1409  if ($result < 0) {
1410  setEventMessages($object->error, $object->errors, 'errors');
1411  }
1412  } elseif ($action == 'confirm_cancel' && $confirm == 'yes' && $usercanvalidate) {
1413  $idwarehouse = GETPOST('idwarehouse', 'int');
1414 
1415  $qualified_for_stock_change = 0;
1416  if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
1417  $qualified_for_stock_change = $object->hasProductsOrServices(2);
1418  } else {
1419  $qualified_for_stock_change = $object->hasProductsOrServices(1);
1420  }
1421 
1422  // Check parameters
1423  if (isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) {
1424  if (!$idwarehouse || $idwarehouse == -1) {
1425  $error++;
1426  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
1427  $action = '';
1428  }
1429  }
1430 
1431  if (!$error) {
1432  $result = $object->cancel($idwarehouse);
1433 
1434  if ($result < 0) {
1435  setEventMessages($object->error, $object->errors, 'errors');
1436  }
1437  }
1438  }
1439 
1440  if ($action == 'update_extras') {
1441  $object->oldcopy = dol_clone($object);
1442 
1443  // Fill array 'array_options' with data from update form
1444  $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
1445  if ($ret < 0) {
1446  $error++;
1447  }
1448 
1449  if (!$error) {
1450  // Actions on extra fields
1451  $result = $object->insertExtraFields('ORDER_MODIFY');
1452  if ($result < 0) {
1453  setEventMessages($object->error, $object->errors, 'errors');
1454  $error++;
1455  }
1456  }
1457 
1458  if ($error) {
1459  $action = 'edit_extras';
1460  }
1461  }
1462 
1463  // add lines from objectlinked
1464  if ($action == 'import_lines_from_object'
1465  && $usercancreate
1466  && $object->statut == Commande::STATUS_DRAFT
1467  ) {
1468  $fromElement = GETPOST('fromelement');
1469  $fromElementid = GETPOST('fromelementid');
1470  $importLines = GETPOST('line_checkbox');
1471 
1472  if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) {
1473  if ($fromElement == 'commande') {
1474  dol_include_once('/'.$fromElement.'/class/'.$fromElement.'.class.php');
1475  $lineClassName = 'OrderLine';
1476  } elseif ($fromElement == 'propal') {
1477  dol_include_once('/comm/'.$fromElement.'/class/'.$fromElement.'.class.php');
1478  $lineClassName = 'PropaleLigne';
1479  }
1480  $nextRang = count($object->lines) + 1;
1481  $importCount = 0;
1482  $error = 0;
1483  foreach ($importLines as $lineId) {
1484  $lineId = intval($lineId);
1485  $originLine = new $lineClassName($db);
1486  if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) {
1487  $originLine->fetch_optionals();
1488  $desc = $originLine->desc;
1489  $pu_ht = $originLine->subprice;
1490  $qty = $originLine->qty;
1491  $txtva = $originLine->tva_tx;
1492  $txlocaltax1 = $originLine->localtax1_tx;
1493  $txlocaltax2 = $originLine->localtax2_tx;
1494  $fk_product = $originLine->fk_product;
1495  $remise_percent = $originLine->remise_percent;
1496  $date_start = $originLine->date_start;
1497  $date_end = $originLine->date_end;
1498  $ventil = 0;
1499  $info_bits = $originLine->info_bits;
1500  $fk_remise_except = $originLine->fk_remise_except;
1501  $price_base_type = 'HT';
1502  $pu_ttc = 0;
1503  $type = $originLine->product_type;
1504  $rang = $nextRang++;
1505  $special_code = $originLine->special_code;
1506  $origin = $originLine->element;
1507  $origin_id = $originLine->id;
1508  $fk_parent_line = 0;
1509  $fk_fournprice = $originLine->fk_fournprice;
1510  $pa_ht = $originLine->pa_ht;
1511  $label = $originLine->label;
1512  $array_options = $originLine->array_options;
1513  $situation_percent = 100;
1514  $fk_prev_id = '';
1515  $fk_unit = $originLine->fk_unit;
1516  $pu_ht_devise = $originLine->multicurrency_subprice;
1517 
1518  $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);
1519 
1520  if ($res > 0) {
1521  $importCount++;
1522  } else {
1523  $error++;
1524  }
1525  } else {
1526  $error++;
1527  }
1528  }
1529 
1530  if ($error) {
1531  setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors');
1532  }
1533  }
1534  }
1535 
1536  // Actions when printing a doc from card
1537  include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
1538 
1539  // Actions to build doc
1540  $upload_dir = !empty($conf->commande->multidir_output[$object->entity])?$conf->commande->multidir_output[$object->entity]:$conf->commande->dir_output;
1541  $permissiontoadd = $usercancreate;
1542  include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
1543 
1544  // Actions to send emails
1545  $triggersendname = 'ORDER_SENTBYMAIL';
1546  $paramname = 'id';
1547  $autocopy = 'MAIN_MAIL_AUTOCOPY_ORDER_TO'; // used to know the automatic BCC to add
1548  $trackid = 'ord'.$object->id;
1549  include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
1550 
1551 
1552  if (!$error && !empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) {
1553  if ($action == 'addcontact') {
1554  if ($object->id > 0) {
1555  $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
1556  $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
1557  $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
1558  }
1559 
1560  if ($result >= 0) {
1561  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1562  exit();
1563  } else {
1564  if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
1565  $langs->load("errors");
1566  setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
1567  } else {
1568  setEventMessages($object->error, $object->errors, 'errors');
1569  }
1570  }
1571  } elseif ($action == 'swapstatut') {
1572  // bascule du statut d'un contact
1573  if ($object->id > 0) {
1574  $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
1575  } else {
1576  dol_print_error($db);
1577  }
1578  } elseif ($action == 'deletecontact') {
1579  // Efface un contact
1580  $result = $object->delete_contact($lineid);
1581 
1582  if ($result >= 0) {
1583  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1584  exit();
1585  } else {
1586  dol_print_error($db);
1587  }
1588  }
1589  }
1590 }
1591 
1592 
1593 /*
1594  * View
1595  */
1596 
1597 $title = $object->ref." - ".$langs->trans('Card');
1598 if ($action == 'create') {
1599  $title = $langs->trans("NewOrder");
1600 }
1601 $help_url = 'EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes|DE:Modul_Kundenaufträge';
1602 
1603 llxHeader('', $title, $help_url);
1604 
1605 $form = new Form($db);
1606 $formfile = new FormFile($db);
1607 $formorder = new FormOrder($db);
1608 $formmargin = new FormMargin($db);
1609 if (isModEnabled('project')) {
1610  $formproject = new FormProjets($db);
1611 }
1612 
1613 // Mode creation
1614 if ($action == 'create' && $usercancreate) {
1615  print load_fiche_titre($langs->trans('CreateOrder'), '', 'order');
1616 
1617  $soc = new Societe($db);
1618  if ($socid > 0) {
1619  $res = $soc->fetch($socid);
1620  }
1621 
1622  $remise_absolue = 0;
1623 
1624  $currency_code = $conf->currency;
1625 
1626  $cond_reglement_id = GETPOST('cond_reglement_id', 'int');
1627  $deposit_percent = GETPOST('cond_reglement_id_deposit_percent', 'alpha');
1628  $mode_reglement_id = GETPOST('mode_reglement_id', 'int');
1629 
1630  if (!empty($origin) && !empty($originid)) {
1631  // Parse element/subelement (ex: project_task)
1632  $element = $subelement = $origin;
1633  $regs = array();
1634  if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
1635  $element = $regs[1];
1636  $subelement = $regs[2];
1637  }
1638 
1639  if ($element == 'project') {
1640  $projectid = $originid;
1641 
1642  if (!$cond_reglement_id) {
1643  $cond_reglement_id = $soc->cond_reglement_id;
1644  }
1645  if (!$deposit_percent) {
1646  $deposit_percent = $soc->deposit_percent;
1647  }
1648  if (!$mode_reglement_id) {
1649  $mode_reglement_id = $soc->mode_reglement_id;
1650  }
1651  if (!$remise_percent) {
1652  $remise_percent = $soc->remise_percent;
1653  }
1654  if (!$dateorder) {
1655  // Do not set 0 here (0 for a date is 1970)
1656  $dateorder = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE_ODER) ?-1 : '') : $dateorder);
1657  }
1658  } else {
1659  // For compatibility
1660  if ($element == 'order' || $element == 'commande') {
1661  $element = $subelement = 'commande';
1662  } elseif ($element == 'propal') {
1663  $element = 'comm/propal';
1664  $subelement = 'propal';
1665  } elseif ($element == 'contract') {
1666  $element = $subelement = 'contrat';
1667  }
1668 
1669  dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
1670 
1671  $classname = ucfirst($subelement);
1672  $objectsrc = new $classname($db);
1673  $objectsrc->fetch($originid);
1674  if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
1675  $objectsrc->fetch_lines();
1676  }
1677  $objectsrc->fetch_thirdparty();
1678 
1679  // Replicate extrafields
1680  $objectsrc->fetch_optionals();
1681  $object->array_options = $objectsrc->array_options;
1682 
1683  $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : '');
1684  $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : '');
1685 
1686  $soc = $objectsrc->thirdparty;
1687  $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
1688  $deposit_percent = (!empty($objectsrc->deposit_percent) ? $objectsrc->deposit_percent : (!empty($soc->deposit_percent) ? $soc->deposit_percent : null));
1689  $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
1690  $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
1691  $availability_id = (!empty($objectsrc->availability_id) ? $objectsrc->availability_id : 0);
1692  $shipping_method_id = (!empty($objectsrc->shipping_method_id) ? $objectsrc->shipping_method_id : (!empty($soc->shipping_method_id) ? $soc->shipping_method_id : 0));
1693  $warehouse_id = (!empty($objectsrc->warehouse_id) ? $objectsrc->warehouse_id : (!empty($soc->warehouse_id) ? $soc->warehouse_id : 0));
1694  $demand_reason_id = (!empty($objectsrc->demand_reason_id) ? $objectsrc->demand_reason_id : (!empty($soc->demand_reason_id) ? $soc->demand_reason_id : 0));
1695  $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0));
1696  $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
1697  $dateorder = empty($conf->global->MAIN_AUTOFILL_DATE_ORDER) ? -1 : '';
1698 
1699  $date_delivery = (!empty($objectsrc->delivery_date) ? $objectsrc->delivery_date : '');
1700  if (empty($date_delivery)) {
1701  $date_delivery = (!empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : '');
1702  }
1703 
1704  if (isModEnabled("multicurrency")) {
1705  if (!empty($objectsrc->multicurrency_code)) {
1706  $currency_code = $objectsrc->multicurrency_code;
1707  }
1708  if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) {
1709  $currency_tx = $objectsrc->multicurrency_tx;
1710  }
1711  }
1712 
1713  $note_private = $object->getDefaultCreateValueFor('note_private', (!empty($objectsrc->note_private) ? $objectsrc->note_private : null));
1714  $note_public = $object->getDefaultCreateValueFor('note_public', (!empty($objectsrc->note_public) ? $objectsrc->note_public : null));
1715 
1716  // Object source contacts list
1717  $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1);
1718  }
1719  } else {
1720  $cond_reglement_id = $soc->cond_reglement_id;
1721  $deposit_percent = $soc->deposit_percent;
1722  $mode_reglement_id = $soc->mode_reglement_id;
1723  $fk_account = $soc->fk_account;
1724  $availability_id = 0;
1725  $shipping_method_id = $soc->shipping_method_id;
1726  $warehouse_id = $soc->fk_warehouse;
1727  $demand_reason_id = $soc->demand_reason_id;
1728  $remise_percent = $soc->remise_percent;
1729  $remise_absolue = 0;
1730  $dateorder = empty($conf->global->MAIN_AUTOFILL_DATE_ORDER) ?-1 : '';
1731 
1732  if (isModEnabled("multicurrency") && !empty($soc->multicurrency_code)) {
1733  $currency_code = $soc->multicurrency_code;
1734  }
1735 
1736  $note_private = $object->getDefaultCreateValueFor('note_private');
1737  $note_public = $object->getDefaultCreateValueFor('note_public');
1738  }
1739 
1740  //Warehouse default if null
1741  if ($soc->fk_warehouse > 0) {
1742  $warehouse_id = $soc->fk_warehouse;
1743  }
1744  if (isModEnabled('stock') && empty($warehouse_id) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) {
1745  if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) {
1746  $warehouse_id = $conf->global->MAIN_DEFAULT_WAREHOUSE;
1747  }
1748  if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) {
1749  $warehouse_id = $user->fk_warehouse;
1750  }
1751  }
1752 
1753  print '<form name="crea_commande" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
1754  print '<input type="hidden" name="token" value="'.newToken().'">';
1755  print '<input type="hidden" name="action" value="add">';
1756  print '<input type="hidden" name="socid" value="'.$soc->id.'">'."\n";
1757  print '<input type="hidden" name="remise_percent" value="'.$soc->remise_percent.'">';
1758  print '<input type="hidden" name="origin" value="'.$origin.'">';
1759  print '<input type="hidden" name="originid" value="'.$originid.'">';
1760  if (!empty($currency_tx)) {
1761  print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">';
1762  }
1763 
1764  print dol_get_fiche_head('');
1765 
1766  print '<table class="border centpercent">';
1767 
1768  // Reference
1769  print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td>'.$langs->trans("Draft").'</td></tr>';
1770 
1771  // Reference client
1772  print '<tr><td>'.$langs->trans('RefCustomer').'</td><td>';
1773  if (!empty($conf->global->MAIN_USE_PROPAL_REFCLIENT_FOR_ORDER) && !empty($origin) && !empty($originid)) {
1774  print '<input type="text" name="ref_client" value="'.$ref_client.'"></td>';
1775  } else {
1776  print '<input type="text" name="ref_client" value="'.GETPOST('ref_client').'"></td>';
1777  }
1778  print '</tr>';
1779 
1780  // Thirdparty
1781  print '<tr>';
1782  print '<td class="fieldrequired">'.$langs->trans('Customer').'</td>';
1783  if ($socid > 0) {
1784  print '<td>';
1785  print $soc->getNomUrl(1, 'customer');
1786  print '<input type="hidden" name="socid" value="'.$soc->id.'">';
1787  print '</td>';
1788  } else {
1789  print '<td>';
1790  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');
1791  // reload page to retrieve customer informations
1792  if (empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED)) {
1793  print '<script type="text/javascript">
1794  $(document).ready(function() {
1795  $("#socid").change(function() {
1796  console.log("We have changed the company - Reload page");
1797  var socid = $(this).val();
1798  // reload page
1799  $("input[name=action]").val("create");
1800  $("form[name=crea_commande]").submit();
1801  });
1802  });
1803  </script>';
1804  }
1805  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>';
1806  print '</td>';
1807  }
1808  print '</tr>'."\n";
1809 
1810  // Contact of order
1811  if ($socid > 0) {
1812  // Contacts (ask contact only if thirdparty already defined).
1813  print "<tr><td>".$langs->trans("DefaultContact").'</td><td>';
1814  print img_picto('', 'contact', 'class="pictofixedwidth"');
1815  print $form->selectcontacts($soc->id, $contactid, 'contactid', 1, !empty($srccontactslist)?$srccontactslist:"", '', 1, 'maxwidth200 widthcentpercentminusx');
1816  print '</td></tr>';
1817 
1818  // Ligne info remises tiers
1819  print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
1820 
1821  $absolute_discount = $soc->getAvailableDiscounts();
1822 
1823  $thirdparty = $soc;
1824  $discount_type = 0;
1825  $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$thirdparty->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid'));
1826  include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
1827 
1828  print '</td></tr>';
1829  }
1830 
1831  // Date
1832  print '<tr><td class="fieldrequired">'.$langs->trans('Date').'</td><td>';
1833  print $form->selectDate('', 're', '', '', '', "crea_commande", 1, 1); // Always autofill date with current date
1834  print '</td></tr>';
1835 
1836  // Date delivery planned
1837  print '<tr><td>'.$langs->trans("DateDeliveryPlanned").'</td>';
1838  print '<td colspan="3">';
1839  $date_delivery = ($date_delivery ? $date_delivery : $object->delivery_date);
1840  print $form->selectDate($date_delivery ? $date_delivery : -1, 'liv_', 1, 1, 1);
1841  print "</td>\n";
1842  print '</tr>';
1843 
1844  // Delivery delay
1845  print '<tr class="fielddeliverydelay"><td>'.$langs->trans('AvailabilityPeriod').'</td><td>';
1846  print img_picto('', 'clock', 'class="pictofixedwidth"');
1847  $form->selectAvailabilityDelay((GETPOSTISSET('availability_id')?GETPOST('availability_id'):$availability_id), 'availability_id', '', 1, 'maxwidth200 widthcentpercentminusx');
1848  print '</td></tr>';
1849 
1850  // Terms of payment
1851  print '<tr><td class="nowrap">'.$langs->trans('PaymentConditionsShort').'</td><td>';
1852  print img_picto('', 'payment', 'class="pictofixedwidth"');
1853  print $form->getSelectConditionsPaiements((GETPOSTISSET('cond_reglement_id')?GETPOST('cond_reglement_id'):$cond_reglement_id), 'cond_reglement_id', 1, 1, 0, 'maxwidth200 widthcentpercentminusx', $deposit_percent);
1854  print '</td></tr>';
1855 
1856  // Payment mode
1857  print '<tr><td>'.$langs->trans('PaymentMode').'</td><td>';
1858  print img_picto('', 'bank', 'class="pictofixedwidth"');
1859  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);
1860  print '</td></tr>';
1861 
1862  // Bank Account
1863  if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && isModEnabled("banque")) {
1864  print '<tr><td>'.$langs->trans('BankAccount').'</td><td>';
1865  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);
1866  print '</td></tr>';
1867  }
1868 
1869  // Shipping Method
1870  if (isModEnabled('expedition')) {
1871  print '<tr><td>'.$langs->trans('SendingMethod').'</td><td>';
1872  print img_picto('', 'object_dolly', 'class="pictofixedwidth"');
1873  $form->selectShippingMethod((GETPOSTISSET('shipping_method_id')?GETPOST('shipping_method_id'):$shipping_method_id), 'shipping_method_id', '', 1, '', 0, 'maxwidth200 widthcentpercentminusx');
1874  print '</td></tr>';
1875  }
1876 
1877  // Warehouse
1878  if (isModEnabled('stock') && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) {
1879  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
1880  $formproduct = new FormProduct($db);
1881  print '<tr><td>'.$langs->trans('Warehouse').'</td><td>';
1882  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');
1883  print '</td></tr>';
1884  }
1885 
1886  // Source / Channel - What trigger creation
1887  print '<tr><td>'.$langs->trans('Channel').'</td><td>';
1888  print img_picto('', 'question', 'class="pictofixedwidth"');
1889  $form->selectInputReason((GETPOSTISSET('demand_reason_id')?GETPOST('demand_reason_id'):$demand_reason_id), 'demand_reason_id', '', 1, 'maxwidth200 widthcentpercentminusx');
1890  print '</td></tr>';
1891 
1892  // TODO How record was recorded OrderMode (llx_c_input_method)
1893 
1894  // Project
1895  if (isModEnabled('project')) {
1896  $langs->load("projects");
1897  print '<tr>';
1898  print '<td>'.$langs->trans("Project").'</td><td>';
1899  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');
1900  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>';
1901  print '</td>';
1902  print '</tr>';
1903  }
1904 
1905  // Incoterms
1906  if (isModEnabled('incoterm')) {
1907  print '<tr>';
1908  print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), !empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms, 1).'</label></td>';
1909  print '<td class="maxwidthonsmartphone">';
1910  $incoterm_id = GETPOST('incoterm_id');
1911  $incoterm_location = GETPOST('location_incoterms');
1912  if (empty($incoterm_id)) {
1913  $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms);
1914  $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms);
1915  }
1916  print $form->select_incoterms($incoterm_id, $incoterm_location);
1917  print '</td></tr>';
1918  }
1919 
1920  // Other attributes
1921  $parameters = array();
1922  if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
1923  $parameters['objectsrc'] = $objectsrc;
1924  }
1925  $parameters['socid'] = $socid;
1926 
1927  // Note that $action and $object may be modified by hook
1928  $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);
1929  print $hookmanager->resPrint;
1930  if (empty($reshook)) {
1931  if (!empty($conf->global->THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER) && !empty($soc->id)) {
1932  // copy from thirdparty
1933  $tpExtrafields = new Extrafields($db);
1934  $tpExtrafieldLabels = $tpExtrafields->fetch_name_optionals_label($soc->table_element);
1935  if ($soc->fetch_optionals() > 0) {
1936  $object->array_options = array_merge($object->array_options, $soc->array_options);
1937  }
1938  };
1939 
1940  print $object->showOptionals($extrafields, 'create', $parameters);
1941  }
1942 
1943  // Template to use by default
1944  print '<tr><td>'.$langs->trans('DefaultModel').'</td>';
1945  print '<td>';
1946  include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
1947  $liste = ModelePDFCommandes::liste_modeles($db);
1948  $preselected = $conf->global->COMMANDE_ADDON_PDF;
1949  print img_picto('', 'pdf', 'class="pictofixedwidth"');
1950  print $form->selectarray('model', $liste, $preselected, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth200 widthcentpercentminusx', 1);
1951  print "</td></tr>";
1952 
1953  // Multicurrency
1954  if (isModEnabled("multicurrency")) {
1955  print '<tr>';
1956  print '<td>'.$form->editfieldkey("Currency", 'multicurrency_code', '', $object, 0).'</td>';
1957  print '<td class="maxwidthonsmartphone">';
1958  print img_picto('', 'currency', 'class="pictofixedwidth"').$form->selectMultiCurrency((GETPOSTISSET('multicurrency_code')?GETPOST('multicurrency_code'):$currency_code), 'multicurrency_code', 0, '', false, 'maxwidth200 widthcentpercentminusx');
1959  print '</td></tr>';
1960  }
1961 
1962  // Note public
1963  print '<tr>';
1964  print '<td class="tdtop">'.$langs->trans('NotePublic').'</td>';
1965  print '<td>';
1966 
1967  $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%');
1968  print $doleditor->Create(1);
1969  // print '<textarea name="note_public" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_public.'</textarea>';
1970  print '</td></tr>';
1971 
1972  // Note private
1973  if (empty($user->socid)) {
1974  print '<tr>';
1975  print '<td class="tdtop">'.$langs->trans('NotePrivate').'</td>';
1976  print '<td>';
1977 
1978  $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%');
1979  print $doleditor->Create(1);
1980  // print '<textarea name="note" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'</textarea>';
1981  print '</td></tr>';
1982  }
1983 
1984  if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
1985  // TODO for compatibility
1986  if ($origin == 'contrat') {
1987  // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
1988  $objectsrc->remise_absolue = $remise_absolue;
1989  $objectsrc->remise_percent = $remise_percent;
1990  $objectsrc->update_price(1);
1991  }
1992 
1993  print "\n<!-- ".$classname." info -->";
1994  print "\n";
1995  print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n";
1996  print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n";
1997  print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n";
1998  print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
1999  print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
2000 
2001  switch ($classname) {
2002  case 'Propal':
2003  $newclassname = 'CommercialProposal';
2004  break;
2005  case 'Commande':
2006  $newclassname = 'Order';
2007  break;
2008  case 'Expedition':
2009  $newclassname = 'Sending';
2010  break;
2011  case 'Contrat':
2012  $newclassname = 'Contract';
2013  break;
2014  default:
2015  $newclassname = $classname;
2016  }
2017 
2018  print '<tr><td>'.$langs->trans($newclassname).'</td><td>'.$objectsrc->getNomUrl(1).'</td></tr>';
2019 
2020  // Amount
2021  print '<tr><td>'.$langs->trans('AmountHT').'</td><td>'.price($objectsrc->total_ht).'</td></tr>';
2022  print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($objectsrc->total_tva)."</td></tr>";
2023  if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1 RE
2024  print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1)."</td></tr>";
2025  }
2026 
2027  if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2 IRPF
2028  print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2)."</td></tr>";
2029  }
2030 
2031  print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($objectsrc->total_ttc)."</td></tr>";
2032 
2033  if (isModEnabled("multicurrency")) {
2034  print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht).'</td></tr>';
2035  print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva)."</td></tr>";
2036  print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc)."</td></tr>";
2037  }
2038  }
2039 
2040  print '</table>';
2041 
2042  print dol_get_fiche_end();
2043 
2044  print $form->buttonsSaveCancel("CreateDraft");
2045 
2046  // Show origin lines
2047  if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
2048  $title = $langs->trans('ProductsAndServices');
2049  print load_fiche_titre($title);
2050 
2051  print '<div class="div-table-responsive-no-min">';
2052  print '<table class="noborder centpercent">';
2053 
2054  $objectsrc->printOriginLinesList('', $selectedLines);
2055 
2056  print '</table>';
2057  print '</div>';
2058  }
2059 
2060  print '</form>';
2061 } else {
2062  // Mode view
2063  $now = dol_now();
2064 
2065  if ($object->id > 0) {
2066  $product_static = new Product($db);
2067 
2068  $soc = new Societe($db);
2069  $soc->fetch($object->socid);
2070 
2071  $author = new User($db);
2072  $author->fetch($object->user_author_id);
2073 
2074  $object->fetch_thirdparty();
2075  $res = $object->fetch_optionals();
2076 
2077  $head = commande_prepare_head($object);
2078  print dol_get_fiche_head($head, 'order', $langs->trans("CustomerOrder"), -1, 'order');
2079 
2080  $formconfirm = '';
2081 
2082  // Confirmation to delete
2083  if ($action == 'delete') {
2084  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteOrder'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1);
2085  }
2086 
2087  // Confirmation of validation
2088  if ($action == 'validate') {
2089  // We check that object has a temporary ref
2090  $ref = substr($object->ref, 1, 4);
2091  if ($ref == 'PROV' || $ref == '') {
2092  $numref = $object->getNextNumRef($soc);
2093  if (empty($numref)) {
2094  $error++;
2095  setEventMessages($object->error, $object->errors, 'errors');
2096  }
2097  } else {
2098  $numref = $object->ref;
2099  }
2100 
2101  $text = $langs->trans('ConfirmValidateOrder', $numref);
2102  if (isModEnabled('notification')) {
2103  require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
2104  $notify = new Notify($db);
2105  $text .= '<br>';
2106  $text .= $notify->confirmMessage('ORDER_VALIDATE', $object->socid, $object);
2107  }
2108 
2109  $qualified_for_stock_change = 0;
2110  if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
2111  $qualified_for_stock_change = $object->hasProductsOrServices(2);
2112  } else {
2113  $qualified_for_stock_change = $object->hasProductsOrServices(1);
2114  }
2115 
2116  $formquestion = array();
2117  if (isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) {
2118  $langs->load("stocks");
2119  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
2120  $formproduct = new FormProduct($db);
2121  $forcecombo = 0;
2122  if ($conf->browser->name == 'ie') {
2123  $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
2124  }
2125  $formquestion = array(
2126  // 'text' => $langs->trans("ConfirmClone"),
2127  // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
2128  // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
2129  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))
2130  );
2131  }
2132 
2133  // mandatoryPeriod
2134  $nbMandated = 0;
2135  foreach ($object->lines as $line) {
2136  $res = $line->fetch_product();
2137  if ($res > 0 ) {
2138  if ($line->product->isService() && $line->product->isMandatoryPeriod() && (empty($line->date_start) || empty($line->date_end) )) {
2139  $nbMandated++;
2140  break;
2141  }
2142  }
2143  }
2144  if ($nbMandated > 0 ) $text .= '<div><span class="clearboth nowraponall warning">'.$langs->trans("mandatoryPeriodNeedTobeSetMsgValidate").'</span></div>';
2145 
2146  if (getDolGlobalInt('SALE_ORDER_SUGGEST_DOWN_PAYMENT_INVOICE_CREATION')) {
2147  // This is a hidden option:
2148  // Suggestion to create invoice during order validation is not enabled by default.
2149  // Such choice should be managed by the workflow module and trigger. This option generates conflicts with some setup.
2150  // It may also break step of creating an order when invoicing must be done from proposals and not from orders
2151  $deposit_percent_from_payment_terms = getDictionaryValue('c_payment_term', 'deposit_percent', $object->cond_reglement_id);
2152 
2153  if (!empty($deposit_percent_from_payment_terms) && isModEnabled('facture') && !empty($user->rights->facture->creer)) {
2154  require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
2155 
2156  $object->fetchObjectLinked();
2157 
2158  $eligibleForDepositGeneration = true;
2159 
2160  if (array_key_exists('facture', $object->linkedObjects)) {
2161  foreach ($object->linkedObjects['facture'] as $invoice) {
2162  if ($invoice->type == Facture::TYPE_DEPOSIT) {
2163  $eligibleForDepositGeneration = false;
2164  break;
2165  }
2166  }
2167  }
2168 
2169  if ($eligibleForDepositGeneration && array_key_exists('propal', $object->linkedObjects)) {
2170  foreach ($object->linkedObjects['propal'] as $proposal) {
2171  $proposal->fetchObjectLinked();
2172 
2173  if (array_key_exists('facture', $proposal->linkedObjects)) {
2174  foreach ($proposal->linkedObjects['facture'] as $invoice) {
2175  if ($invoice->type == Facture::TYPE_DEPOSIT) {
2176  $eligibleForDepositGeneration = false;
2177  break 2;
2178  }
2179  }
2180  }
2181  }
2182  }
2183 
2184  if ($eligibleForDepositGeneration) {
2185  $formquestion[] = array(
2186  'type' => 'checkbox',
2187  'tdclass' => '',
2188  'name' => 'generate_deposit',
2189  'label' => $form->textwithpicto($langs->trans('GenerateDeposit', $object->deposit_percent), $langs->trans('DepositGenerationPermittedByThePaymentTermsSelected'))
2190  );
2191 
2192  $formquestion[] = array(
2193  'type' => 'date',
2194  'tdclass' => 'fieldrequired showonlyifgeneratedeposit',
2195  'name' => 'datef',
2196  'label' => $langs->trans('DateInvoice'),
2197  'value' => dol_now(),
2198  'datenow' => true
2199  );
2200 
2201  if (!empty($conf->global->INVOICE_POINTOFTAX_DATE)) {
2202  $formquestion[] = array(
2203  'type' => 'date',
2204  'tdclass' => 'fieldrequired showonlyifgeneratedeposit',
2205  'name' => 'date_pointoftax',
2206  'label' => $langs->trans('DatePointOfTax'),
2207  'value' => dol_now(),
2208  'datenow' => true
2209  );
2210  }
2211 
2212 
2213  $paymentTermsSelect = $form->getSelectConditionsPaiements(0, 'cond_reglement_id', -1, 0, 0, 'minwidth200');
2214 
2215  $formquestion[] = array(
2216  'type' => 'other',
2217  'tdclass' => 'fieldrequired showonlyifgeneratedeposit',
2218  'name' => 'cond_reglement_id',
2219  'label' => $langs->trans('PaymentTerm'),
2220  'value' => $paymentTermsSelect
2221  );
2222 
2223  $formquestion[] = array(
2224  'type' => 'checkbox',
2225  'tdclass' => 'showonlyifgeneratedeposit',
2226  'name' => 'validate_generated_deposit',
2227  'label' => $langs->trans('ValidateGeneratedDeposit')
2228  );
2229 
2230  $formquestion[] = array(
2231  'type' => 'onecolumn',
2232  'value' => '
2233  <script>
2234  $(document).ready(function() {
2235  $("[name=generate_deposit]").change(function () {
2236  let $self = $(this);
2237  let $target = $(".showonlyifgeneratedeposit").parent(".tagtr");
2238 
2239  if (! $self.parents(".tagtr").is(":hidden") && $self.is(":checked")) {
2240  $target.show();
2241  } else {
2242  $target.hide();
2243  }
2244 
2245  return true;
2246  });
2247  });
2248  </script>
2249  '
2250  );
2251  }
2252  }
2253  }
2254 
2255  if (!$error) {
2256  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateOrder'), $text, 'confirm_validate', $formquestion, 0, 1, 220);
2257  }
2258  }
2259 
2260  // Confirm back to draft status
2261  if ($action == 'modif') {
2262  $qualified_for_stock_change = 0;
2263  if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
2264  $qualified_for_stock_change = $object->hasProductsOrServices(2);
2265  } else {
2266  $qualified_for_stock_change = $object->hasProductsOrServices(1);
2267  }
2268 
2269  $text = $langs->trans('ConfirmUnvalidateOrder', $object->ref);
2270  $formquestion = array();
2271  if (isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) {
2272  $langs->load("stocks");
2273  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
2274  $formproduct = new FormProduct($db);
2275  $forcecombo = 0;
2276  if ($conf->browser->name == 'ie') {
2277  $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
2278  }
2279  $formquestion = array(
2280  // 'text' => $langs->trans("ConfirmClone"),
2281  // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
2282  // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
2283  array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
2284  );
2285  }
2286 
2287  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateOrder'), $text, 'confirm_modif', $formquestion, "yes", 1, 220);
2288  }
2289 
2290  /*
2291  * Confirmation de la cloture
2292  */
2293  if ($action == 'shipped') {
2294  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('CloseOrder'), $langs->trans('ConfirmCloseOrder'), 'confirm_shipped', '', 0, 1);
2295  }
2296 
2297  /*
2298  * Confirmation de l'annulation
2299  */
2300  if ($action == 'cancel') {
2301  $qualified_for_stock_change = 0;
2302  if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
2303  $qualified_for_stock_change = $object->hasProductsOrServices(2);
2304  } else {
2305  $qualified_for_stock_change = $object->hasProductsOrServices(1);
2306  }
2307 
2308  $text = $langs->trans('ConfirmCancelOrder', $object->ref);
2309  $formquestion = array();
2310  if (isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) {
2311  $langs->load("stocks");
2312  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
2313  $formproduct = new FormProduct($db);
2314  $forcecombo = 0;
2315  if ($conf->browser->name == 'ie') {
2316  $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
2317  }
2318  $formquestion = array(
2319  // 'text' => $langs->trans("ConfirmClone"),
2320  // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
2321  // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
2322  array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
2323  );
2324  }
2325 
2326  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans("Cancel"), $text, 'confirm_cancel', $formquestion, 0, 1);
2327  }
2328 
2329  // Confirmation to delete line
2330  if ($action == 'ask_deleteline') {
2331  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1);
2332  }
2333 
2334  // Clone confirmation
2335  if ($action == 'clone') {
2336  // Create an array for form
2337  $formquestion = array(
2338  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'))
2339  );
2340  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneOrder', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
2341  }
2342 
2343  // Call Hook formConfirm
2344  $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
2345  // Note that $action and $object may be modified by hook
2346  $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action);
2347  if (empty($reshook)) {
2348  $formconfirm .= $hookmanager->resPrint;
2349  } elseif ($reshook > 0) {
2350  $formconfirm = $hookmanager->resPrint;
2351  }
2352 
2353  // Print form confirm
2354  print $formconfirm;
2355 
2356 
2357  // Order card
2358 
2359  $linkback = '<a href="'.DOL_URL_ROOT.'/commande/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
2360 
2361  $morehtmlref = '<div class="refidno">';
2362  // Ref customer
2363  $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1);
2364  $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);
2365  // Thirdparty
2366  $morehtmlref .= '<br>'.$soc->getNomUrl(1, 'customer');
2367  if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
2368  $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/commande/list.php?socid='.$object->thirdparty->id.'&search_societe='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherOrders").'</a>)';
2369  }
2370  // Project
2371  if (isModEnabled('project')) {
2372  $langs->load("projects");
2373  $morehtmlref .= '<br>';
2374  if ($usercancreate) {
2375  $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
2376  if ($action != 'classify') {
2377  $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> ';
2378  }
2379  $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
2380  } else {
2381  if (!empty($object->fk_project)) {
2382  $proj = new Project($db);
2383  $proj->fetch($object->fk_project);
2384  $morehtmlref .= $proj->getNomUrl(1);
2385  if ($proj->title) {
2386  $morehtmlref .= '<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).'</span>';
2387  }
2388  }
2389  }
2390  }
2391  $morehtmlref .= '</div>';
2392 
2393 
2394  dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
2395 
2396 
2397  print '<div class="fichecenter">';
2398  print '<div class="fichehalfleft">';
2399  print '<div class="underbanner clearboth"></div>';
2400 
2401  print '<table class="border tableforfield centpercent">';
2402 
2403  if ($soc->outstanding_limit) {
2404  // Outstanding Bill
2405  print '<tr><td class="titlefield">';
2406  print $langs->trans('OutstandingBill');
2407  print '</td><td class="valuefield">';
2408  $arrayoutstandingbills = $soc->getOutstandingBills();
2409  print price($arrayoutstandingbills['opened']).' / ';
2410  print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency);
2411  print '</td>';
2412  print '</tr>';
2413  }
2414 
2415  // Relative and absolute discounts
2416  if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
2417  $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
2418  $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
2419  } else {
2420  $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
2421  $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
2422  }
2423 
2424  $addrelativediscount = '<a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("EditRelativeDiscounts").'</a>';
2425  $addabsolutediscount = '<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("EditGlobalDiscounts").'</a>';
2426  $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>';
2427 
2428  print '<tr><td class="titlefield">'.$langs->trans('Discounts').'</td><td class="valuefield">';
2429 
2430  $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount);
2431  $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote);
2432  $absolute_discount = price2num($absolute_discount, 'MT');
2433  $absolute_creditnote = price2num($absolute_creditnote, 'MT');
2434 
2435  $thirdparty = $soc;
2436  $discount_type = 0;
2437  $backtopage = urlencode($_SERVER["PHP_SELF"].'?id='.$object->id);
2438  include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
2439 
2440  print '</td></tr>';
2441 
2442  // Date
2443  print '<tr><td>';
2444  $editenable = $usercancreate && $object->statut == Commande::STATUS_DRAFT;
2445  print $form->editfieldkey("Date", 'date', '', $object, $editenable);
2446  print '</td><td class="valuefield">';
2447  if ($action == 'editdate') {
2448  print '<form name="setdate" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
2449  print '<input type="hidden" name="token" value="'.newToken().'">';
2450  print '<input type="hidden" name="action" value="setdate">';
2451  print $form->selectDate($object->date, 'order_', '', '', '', "setdate");
2452  print '<input type="submit" class="button button-edit" value="'.$langs->trans('Modify').'">';
2453  print '</form>';
2454  } else {
2455  print $object->date ? dol_print_date($object->date, 'day') : '&nbsp;';
2456  if ($object->hasDelay() && empty($object->delivery_date)) { // If there is a delivery date planned, warning should be on this date
2457  print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning");
2458  }
2459  }
2460  print '</td>';
2461  print '</tr>';
2462 
2463  // Delivery date planed
2464  print '<tr><td>';
2465  $editenable = $usercancreate;
2466  print $form->editfieldkey("DateDeliveryPlanned", 'date_livraison', '', $object, $editenable);
2467  print '</td><td class="valuefield">';
2468  if ($action == 'editdate_livraison') {
2469  print '<form name="setdate_livraison" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
2470  print '<input type="hidden" name="token" value="'.newToken().'">';
2471  print '<input type="hidden" name="action" value="setdate_livraison">';
2472  print $form->selectDate($object->delivery_date ? $object->delivery_date : -1, 'liv_', 1, 1, '', "setdate_livraison", 1, 0);
2473  print '<input type="submit" class="button button-edit" value="'.$langs->trans('Modify').'">';
2474  print '</form>';
2475  } else {
2476  print $object->delivery_date ? dol_print_date($object->delivery_date, 'dayhour') : '&nbsp;';
2477  if ($object->hasDelay() && !empty($object->delivery_date)) {
2478  print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning");
2479  }
2480  }
2481  print '</td>';
2482  print '</tr>';
2483 
2484  // Delivery delay
2485  print '<tr class="fielddeliverydelay"><td>';
2486  $editenable = $usercancreate;
2487  print $form->editfieldkey("AvailabilityPeriod", 'availability', '', $object, $editenable);
2488  print '</td><td class="valuefield">';
2489  if ($action == 'editavailability') {
2490  $form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'availability_id', 1);
2491  } else {
2492  $form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'none', 1);
2493  }
2494  print '</td></tr>';
2495 
2496  // Shipping Method
2497  if (isModEnabled('expedition')) {
2498  print '<tr><td>';
2499  $editenable = $usercancreate;
2500  print $form->editfieldkey("SendingMethod", 'shippingmethod', '', $object, $editenable);
2501  print '</td><td class="valuefield">';
2502  if ($action == 'editshippingmethod') {
2503  $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1);
2504  } else {
2505  $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none');
2506  }
2507  print '</td>';
2508  print '</tr>';
2509  }
2510 
2511  // Warehouse
2512  if (isModEnabled('stock') && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) {
2513  $langs->load('stocks');
2514  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
2515  $formproduct = new FormProduct($db);
2516  print '<tr><td>';
2517  $editenable = $usercancreate;
2518  print $form->editfieldkey("Warehouse", 'warehouse', '', $object, $editenable);
2519  print '</td><td class="valuefield">';
2520  if ($action == 'editwarehouse') {
2521  $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1);
2522  } else {
2523  $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'none');
2524  }
2525  print '</td>';
2526  print '</tr>';
2527  }
2528 
2529  // Source reason (why we have an order)
2530  print '<tr><td>';
2531  $editenable = $usercancreate;
2532  print $form->editfieldkey("Source", 'demandreason', '', $object, $editenable);
2533  print '</td><td class="valuefield">';
2534  if ($action == 'editdemandreason') {
2535  $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'demand_reason_id', 1);
2536  } else {
2537  $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'none');
2538  }
2539  print '</td></tr>';
2540 
2541  // Terms of payment
2542  print '<tr><td>';
2543  $editenable = $usercancreate;
2544  print $form->editfieldkey("PaymentConditionsShort", 'conditions', '', $object, $editenable);
2545  print '</td><td class="valuefield">';
2546  if ($action == 'editconditions') {
2547  $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id', 1, '', 1, $object->deposit_percent);
2548  } else {
2549  $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none', 1, '', 1, $object->deposit_percent);
2550  }
2551  print '</td>';
2552 
2553  print '</tr>';
2554 
2555  // Mode of payment
2556  print '<tr><td>';
2557  $editenable = $usercancreate;
2558  print $form->editfieldkey("PaymentMode", 'mode', '', $object, $editenable);
2559  print '</td><td class="valuefield">';
2560  if ($action == 'editmode') {
2561  $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1);
2562  } else {
2563  $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none');
2564  }
2565  print '</td></tr>';
2566 
2567  // Multicurrency
2568  if (isModEnabled("multicurrency")) {
2569  // Multicurrency code
2570  print '<tr>';
2571  print '<td>';
2572  $editenable = $usercancreate && $object->statut == Commande::STATUS_DRAFT;
2573  print $form->editfieldkey("Currency", 'multicurrencycode', '', $object, $editenable);
2574  print '</td><td class="valuefield">';
2575  if ($action == 'editmulticurrencycode') {
2576  $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code');
2577  } else {
2578  $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'none');
2579  }
2580  print '</td></tr>';
2581 
2582  // Multicurrency rate
2583  if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
2584  print '<tr>';
2585  print '<td>';
2586  $editenable = $usercancreate && $object->multicurrency_code && $object->multicurrency_code != $conf->currency && $object->statut == $object::STATUS_DRAFT;
2587  print $form->editfieldkey("CurrencyRate", 'multicurrencyrate', '', $object, $editenable);
2588  print '</td><td class="valuefield">';
2589  if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
2590  if ($action == 'actualizemulticurrencyrate') {
2591  list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
2592  }
2593  $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
2594  } else {
2595  $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
2596  if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
2597  print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
2598  print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
2599  print '</div>';
2600  }
2601  }
2602  print '</td></tr>';
2603  }
2604  }
2605 
2606  // TODO Order mode (how we receive order). Not yet implemented
2607  /*
2608  print '<tr><td>';
2609  $editenable = $usercancreate;
2610  print $form->editfieldkey("SourceMode", 'inputmode', '', $object, $editenable);
2611  print '</td><td>';
2612  if ($action == 'editinputmode') {
2613  $form->formInputMode($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->source, 'input_mode_id', 1);
2614  } else {
2615  $form->formInputMode($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->source, 'none');
2616  }
2617  print '</td></tr>';
2618  */
2619 
2620  $tmparray = $object->getTotalWeightVolume();
2621  $totalWeight = $tmparray['weight'];
2622  $totalVolume = $tmparray['volume'];
2623  if ($totalWeight) {
2624  print '<tr><td>'.$langs->trans("CalculatedWeight").'</td>';
2625  print '<td class="valuefield">';
2626  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');
2627  print '</td></tr>';
2628  }
2629  if ($totalVolume) {
2630  print '<tr><td>'.$langs->trans("CalculatedVolume").'</td>';
2631  print '<td class="valuefield">';
2632  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');
2633  print '</td></tr>';
2634  }
2635 
2636  // TODO How record was recorded OrderMode (llx_c_input_method)
2637 
2638  // Incoterms
2639  if (isModEnabled('incoterm')) {
2640  print '<tr><td>';
2641  $editenable = $usercancreate;
2642  print $form->editfieldkey("IncotermLabel", 'incoterm', '', $object, $editenable);
2643  print '</td>';
2644  print '<td class="valuefield">';
2645  if ($action != 'editincoterm') {
2646  print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
2647  } else {
2648  print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
2649  }
2650  print '</td></tr>';
2651  }
2652 
2653  // Bank Account
2654  if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && isModEnabled("banque")) {
2655  print '<tr><td>';
2656  $editenable = $usercancreate;
2657  print $form->editfieldkey("BankAccount", 'bankaccount', '', $object, $editenable);
2658  print '</td><td class="valuefield">';
2659  if ($action == 'editbankaccount') {
2660  $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
2661  } else {
2662  $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
2663  }
2664  print '</td>';
2665  print '</tr>';
2666  }
2667 
2668  // Other attributes
2669  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
2670 
2671  print '</table>';
2672 
2673  print '</div>';
2674  print '<div class="fichehalfright">';
2675  print '<div class="underbanner clearboth"></div>';
2676 
2677  print '<table class="border tableforfield centpercent">';
2678 
2679  if (isModEnabled("multicurrency") && ($object->multicurrency_code != $conf->currency)) {
2680  // Multicurrency Amount HT
2681  print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>';
2682  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>';
2683  print '</tr>';
2684 
2685  // Multicurrency Amount VAT
2686  print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).'</td>';
2687  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>';
2688  print '</tr>';
2689 
2690  // Multicurrency Amount TTC
2691  print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).'</td>';
2692  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>';
2693  print '</tr>';
2694  }
2695 
2696  // Total HT
2697  $alert = '';
2698  if (!empty($conf->global->ORDER_MANAGE_MIN_AMOUNT) && $object->total_ht < $object->thirdparty->order_min_amount) {
2699  $alert = ' '.img_warning($langs->trans('OrderMinAmount').': '.price($object->thirdparty->order_min_amount));
2700  }
2701  print '<tr><td class="titlefieldmiddle">'.$langs->trans('AmountHT').'</td>';
2702  print '<td class="valuefield nowrap right amountcard">'.price($object->total_ht, 1, '', 1, -1, -1, $conf->currency).$alert.'</td>';
2703 
2704  // Total VAT
2705  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>';
2706 
2707  // Amount Local Taxes
2708  if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { // Localtax1
2709  print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>';
2710  print '<td class="valuefield nowrap right amountcard">'.price($object->total_localtax1, 1, '', 1, -1, -1, $conf->currency).'</td></tr>';
2711  }
2712  if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { // Localtax2 IRPF
2713  print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>';
2714  print '<td class="valuefield nowrap right amountcard">'.price($object->total_localtax2, 1, '', 1, -1, -1, $conf->currency).'</td></tr>';
2715  }
2716 
2717  // Total TTC
2718  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>';
2719 
2720  // Statut
2721  //print '<tr><td>' . $langs->trans('Status') . '</td><td>' . $object->getLibStatut(4) . '</td></tr>';
2722 
2723  print '</table>';
2724 
2725  // Margin Infos
2726  if (isModEnabled('margin')) {
2727  $formmargin->displayMarginInfos($object);
2728  }
2729 
2730 
2731  print '</div>';
2732  print '</div>'; // Close fichecenter
2733 
2734  print '<div class="clearboth"></div><br>';
2735 
2736  if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
2737  $blocname = 'contacts';
2738  $title = $langs->trans('ContactsAddresses');
2739  include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
2740  }
2741 
2742  if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
2743  $blocname = 'notes';
2744  $title = $langs->trans('Notes');
2745  include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
2746  }
2747 
2748  /*
2749  * Lines
2750  */
2751 
2752  // Get object lines
2753  $result = $object->getLinesArray();
2754 
2755  // Add products/services form
2756  //$forceall = 1;
2757  global $inputalsopricewithtax;
2758  $inputalsopricewithtax = 1;
2759 
2760  print '<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">
2761  <input type="hidden" name="token" value="' . newToken().'">
2762  <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">
2763  <input type="hidden" name="mode" value="">
2764  <input type="hidden" name="page_y" value="">
2765  <input type="hidden" name="id" value="' . $object->id.'">';
2766 
2767  if (!empty($conf->use_javascript_ajax) && $object->statut == Commande::STATUS_DRAFT) {
2768  include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
2769  }
2770 
2771  print '<div class="div-table-responsive-no-min">';
2772  print '<table id="tablelines" class="noborder noshadow" width="100%">';
2773 
2774  // Show object lines
2775  if (!empty($object->lines)) {
2776  $object->printObjectLines($action, $mysoc, $soc, $lineid, 1);
2777  }
2778 
2779  $numlines = count($object->lines);
2780 
2781  /*
2782  * Form to add new line
2783  */
2784  if ($object->statut == Commande::STATUS_DRAFT && $usercancreate && $action != 'selectlines') {
2785  if ($action != 'editline') {
2786  // Add free products/services
2787 
2788  $parameters = array();
2789  // Note that $action and $object may be modified by hook
2790  $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action);
2791  if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
2792  if (empty($reshook))
2793  $object->formAddObjectLine(1, $mysoc, $soc);
2794  }
2795  }
2796  print '</table>';
2797  print '</div>';
2798 
2799  print "</form>\n";
2800 
2801  print dol_get_fiche_end();
2802 
2803  /*
2804  * Buttons for actions
2805  */
2806  if ($action != 'presend' && $action != 'editline') {
2807  print '<div class="tabsAction">';
2808 
2809  $parameters = array();
2810  // Note that $action and $object may be modified by hook
2811  $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action);
2812  if (empty($reshook)) {
2813  // Reopen a closed order
2814  if (($object->statut == Commande::STATUS_CLOSED || $object->statut == Commande::STATUS_CANCELED) && $usercancreate) {
2815  print dolGetButtonAction('', $langs->trans('ReOpen'), 'default', $_SERVER["PHP_SELF"].'?action=reopen&amp;token='.newToken().'&amp;id='.$object->id, '');
2816  }
2817 
2818  // Send
2819  if (empty($user->socid)) {
2820  if ($object->statut > Commande::STATUS_DRAFT || !empty($conf->global->COMMANDE_SENDBYEMAIL_FOR_ALL_STATUS)) {
2821  if ($usercansend) {
2822  print dolGetButtonAction('', $langs->trans('SendMail'), 'default', $_SERVER["PHP_SELF"].'?action=presend&token='.newToken().'&id='.$object->id.'&mode=init#formmailbeforetitle', '');
2823  } else {
2824  print dolGetButtonAction('', $langs->trans('SendMail'), 'default', $_SERVER['PHP_SELF']. '#', '', false);
2825  }
2826  }
2827  }
2828 
2829  // Valid
2830  if ($object->statut == Commande::STATUS_DRAFT && ($object->total_ttc >= 0 || !empty($conf->global->ORDER_ENABLE_NEGATIVE)) && $numlines > 0 && $usercanvalidate) {
2831  print dolGetButtonAction('', $langs->trans('Validate'), 'default', $_SERVER["PHP_SELF"].'?action=validate&amp;token='.newToken().'&amp;id='.$object->id, '');
2832  }
2833  // Edit
2834  if ($object->statut == Commande::STATUS_VALIDATED && $usercancreate) {
2835  print dolGetButtonAction('', $langs->trans('Modify'), 'default', $_SERVER["PHP_SELF"].'?action=modif&amp;token='.newToken().'&amp;id='.$object->id, '');
2836  }
2837  // Create event
2838  /*if (isModEnabled('agenda') && !empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD))
2839  {
2840  // Add hidden condition because this is not a
2841  // "workflow" action so should appears somewhere else on
2842  // page.
2843  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>';
2844  }*/
2845 
2846  // Create a purchase order
2847  if (!empty($conf->global->WORKFLOW_CAN_CREATE_PURCHASE_ORDER_FROM_SALE_ORDER)) {
2848  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) {
2849  if ($usercancreatepurchaseorder) {
2850  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, '');
2851  }
2852  }
2853  }
2854 
2855  // Create intervention
2856  if (isModEnabled('ficheinter')) {
2857  $langs->load("interventions");
2858 
2859  if ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED && $object->getNbOfServicesLines() > 0) {
2860  if ($user->hasRight('ficheinter', 'creer')) {
2861  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, '');
2862  } else {
2863  print dolGetButtonAction($langs->trans('NotAllowed'), $langs->trans('AddIntervention'), 'default', $_SERVER['PHP_SELF']. '#', '', false);
2864  }
2865  }
2866  }
2867 
2868  // Create contract
2869  if (isModEnabled('contrat') && ($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_SHIPMENTONPROCESS || $object->statut == Commande::STATUS_CLOSED)) {
2870  $langs->load("contracts");
2871 
2872  if ($user->hasRight('contrat', 'creer')) {
2873  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, '');
2874  }
2875  }
2876 
2877  // Ship
2878  $numshipping = 0;
2879  if (isModEnabled('expedition')) {
2880  $numshipping = $object->nb_expedition();
2881 
2882  if ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED && ($object->getNbOfProductsLines() > 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
2883  if ((isModEnabled('expedition_bon') && $user->rights->expedition->creer) || ($conf->delivery_note->enabled && $user->rights->expedition->delivery->creer)) {
2884  if ($user->hasRight('expedition', 'creer')) {
2885  print dolGetButtonAction('', $langs->trans('CreateShipment'), 'default', DOL_URL_ROOT.'/expedition/shipment.php?id='.$object->id, '');
2886  } else {
2887  print dolGetButtonAction($langs->trans('NotAllowed'), $langs->trans('CreateShipment'), 'default', $_SERVER['PHP_SELF']. '#', '', false);
2888  }
2889  } else {
2890  $langs->load("errors");
2891  print dolGetButtonAction($langs->trans('ErrorModuleSetupNotComplete'), $langs->trans('CreateShipment'), 'default', $_SERVER['PHP_SELF']. '#', '', false);
2892  }
2893  }
2894  }
2895 
2896  // Set to shipped
2897  if (($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_SHIPMENTONPROCESS) && $usercanclose) {
2898  print dolGetButtonAction('', $langs->trans('ClassifyShipped'), 'default', $_SERVER["PHP_SELF"].'?action=shipped&amp;token='.newToken().'&amp;id='.$object->id, '');
2899  }
2900  // Create bill and Classify billed
2901  // Note: Even if module invoice is not enabled, we should be able to use button "Classified billed"
2902  if ($object->statut > Commande::STATUS_DRAFT && !$object->billed && $object->total_ttc >= 0) {
2903  if (isModEnabled('facture') && $user->hasRight('facture', 'creer') && empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) {
2904  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, '');
2905  }
2906  if ($usercancreate && $object->statut >= Commande::STATUS_VALIDATED && empty($conf->global->WORKFLOW_DISABLE_CLASSIFY_BILLED_FROM_ORDER) && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) {
2907  print dolGetButtonAction('', $langs->trans('ClassifyBilled'), 'default', $_SERVER["PHP_SELF"].'?action=classifybilled&amp;token='.newToken().'&amp;id='.$object->id, '');
2908  }
2909  }
2910  if ($object->statut > Commande::STATUS_DRAFT && $object->billed) {
2911  if ($usercancreate && $object->statut >= Commande::STATUS_VALIDATED && empty($conf->global->WORKFLOW_DISABLE_CLASSIFY_BILLED_FROM_ORDER) && empty($conf->global->WORKFLOW_BILL_ON_SHIPMENT)) {
2912  print dolGetButtonAction('', $langs->trans('ClassifyUnBilled'), 'default', $_SERVER["PHP_SELF"].'?action=classifyunbilled&amp;token='.newToken().'&amp;id='.$object->id, '');
2913  }
2914  }
2915  // Clone
2916  if ($usercancreate) {
2917  print dolGetButtonAction('', $langs->trans('ToClone'), 'default', $_SERVER["PHP_SELF"].'?action=clone&amp;token='.newToken().'&amp;id='.$object->id.'&amp;socid='.$object->socid, '');
2918  }
2919 
2920  // Cancel order
2921  if ($object->statut == Commande::STATUS_VALIDATED && !empty($usercancancel)) {
2922  print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=cancel&token='.newToken().'">'.$langs->trans("Cancel").'</a>';
2923  }
2924 
2925  // Delete order
2926  if ($usercandelete) {
2927  if ($numshipping == 0) {
2928  print dolGetButtonAction('', $langs->trans('Delete'), 'delete', $_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&id='.$object->id, '');
2929  } else {
2930  print dolGetButtonAction($langs->trans('ShippingExist'), $langs->trans('Delete'), 'default', $_SERVER['PHP_SELF']. '#', '', false);
2931  }
2932  }
2933  }
2934  print '</div>';
2935  }
2936 
2937  // Select mail models is same action as presend
2938  if (GETPOST('modelselected')) {
2939  $action = 'presend';
2940  }
2941 
2942  if ($action != 'presend') {
2943  print '<div class="fichecenter"><div class="fichehalfleft">';
2944  print '<a name="builddoc"></a>'; // ancre
2945  // Documents
2946  $objref = dol_sanitizeFileName($object->ref);
2947  $relativepath = $objref.'/'.$objref.'.pdf';
2948  $filedir = $conf->commande->multidir_output[$object->entity].'/'.$objref;
2949  $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
2950  $genallowed = $usercanread;
2951  $delallowed = $usercancreate;
2952  print $formfile->showdocuments('commande', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang, '', $object);
2953 
2954 
2955  // Show links to link elements
2956  $linktoelem = $form->showLinkToObjectBlock($object, null, array('order'));
2957 
2958  $compatibleImportElementsList = false;
2959  if ($usercancreate
2960  && $object->statut == Commande::STATUS_DRAFT) {
2961  $compatibleImportElementsList = array('commande', 'propal'); // import from linked elements
2962  }
2963  $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList);
2964 
2965  // Show online payment link
2966  $useonlinepayment = (isModEnabled('paypal') || isModEnabled('stripe') || isModEnabled('paybox'));
2967  if (!empty($conf->global->ORDER_HIDE_ONLINE_PAYMENT_ON_ORDER)) {
2968  $useonlinepayment = 0;
2969  }
2970  if ($object->statut != Commande::STATUS_DRAFT && $useonlinepayment) {
2971  print '<br><!-- Link to pay -->';
2972  require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
2973  print showOnlinePaymentUrl('order', $object->ref).'<br>';
2974  }
2975 
2976  print '</div><div class="fichehalfright">';
2977 
2978  // List of actions on element
2979  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
2980  $formactions = new FormActions($db);
2981  $somethingshown = $formactions->showactions($object, 'order', $socid, 1);
2982 
2983  print '</div></div>';
2984  }
2985 
2986  // Presend form
2987  $modelmail = 'order_send';
2988  $defaulttopic = 'SendOrderRef';
2989  $diroutput = $conf->commande->multidir_output[$object->entity];
2990  $trackid = 'ord'.$object->id;
2991 
2992  include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
2993  }
2994 }
2995 
2996 // End of page
2997 llxFooter();
2998 $db->close();
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:49
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1225
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:5360
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:520
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:4993
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:388
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:1032
Translate
Class to manage translations.
Definition: translate.class.php:30
Commande\STATUS_SHIPMENTONPROCESS
const STATUS_SHIPMENTONPROCESS
Shipment on process.
Definition: commande.class.php:382
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:1157
Notify
Class to manage notifications.
Definition: notify.class.php:33
Commande\STATUS_CANCELED
const STATUS_CANCELED
Canceled status.
Definition: commande.class.php:370
img_edit
img_edit($titlealt='default', $float=0, $other='')
Show logo editer/modifier fiche.
Definition: functions.lib.php:4538
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:2082
$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:5823
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:2550
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:7542
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:4024
Commande\STATUS_VALIDATED
const STATUS_VALIDATED
Validated status.
Definition: commande.class.php:378
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:1494
$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:179
$formconfirm
$formconfirm
if ($action == 'delbookkeepingyear') {
Definition: listbyaccount.php:614
get_default_npr
get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Fonction qui renvoie si tva doit etre tva percue recuperable.
Definition: functions.lib.php:6591
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:6004
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:10519
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1628
setEventMessage
setEventMessage($mesgs, $style='mesgs')
Set event message in dol_events session object.
Definition: functions.lib.php:8431
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:1858
dol_htmlcleanlastbr
dol_htmlcleanlastbr($stringtodecode)
This function remove all ending and br at end.
Definition: functions.lib.php:7326
get_default_tva
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
Definition: functions.lib.php:6490
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:346
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:11269
dol_get_fiche_end
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition: functions.lib.php:2054
Commande\STATUS_DRAFT
const STATUS_DRAFT
Draft status.
Definition: commande.class.php:374
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:137
User
Class to manage Dolibarr users.
Definition: user.class.php:46
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:421
dolGetButtonAction
dolGetButtonAction($label, $text='', $actionType='default', $url='', $id='', $userRight=1, $params=array())
Function dolGetButtonAction.
Definition: functions.lib.php:10832
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:53
$parameters
$parameters
Actions.
Definition: card.php:79
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2951
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:5697
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:8460
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:2863
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:5955
DolEditor
Class to manage a WYSIWYG editor.
Definition: doleditor.class.php:30