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