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