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