dolibarr  9.0.0
card.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2004-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2004-2015 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2005 Eric Seigne <eric.seigne@ryxeo.com>
5  * Copyright (C) 2005-2016 Regis Houssin <regis.houssin@inodbox.com>
6  * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
7  * Copyright (C) 2011-2018 Philippe Grand <philippe.grand@atoo-net.com>
8  * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
9  * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
10  * Copyright (C) 2014 Ion Agorria <ion@agorria.com>
11  * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program. If not, see <http://www.gnu.org/licenses/>.
25  * or see http://www.gnu.org/
26  */
27 
34 require '../../main.inc.php';
35 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
36 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formorder.class.php';
37 require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
38 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
39 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
40 require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
41 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
42 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
43 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
44 if (! empty($conf->supplier_proposal->enabled))
45  require_once DOL_DOCUMENT_ROOT . '/supplier_proposal/class/supplier_proposal.class.php';
46 if (!empty($conf->produit->enabled))
47  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
48 if (!empty($conf->projet->enabled)) {
49  require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
50  require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
51 }
52 require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP
53 
54 if (!empty($conf->variants->enabled)) {
55  require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
56 }
57 
58 $langs->loadLangs(array('admin','orders','sendings','companies','bills','propal','supplier_proposal','deliveries','products','stocks','productbatch'));
59 if (!empty($conf->incoterm->enabled)) $langs->load('incoterm');
60 
61 $id = GETPOST('id','int');
62 $ref = GETPOST('ref','alpha');
63 $action = GETPOST('action','alpha');
64 $confirm = GETPOST('confirm','alpha');
65 $comclientid = GETPOST('comid','int');
66 $socid = GETPOST('socid','int');
67 $projectid = GETPOST('projectid','int');
68 $cancel = GETPOST('cancel','alpha');
69 $lineid = GETPOST('lineid', 'int');
70 
71 $lineid = GETPOST('lineid', 'int');
72 $origin = GETPOST('origin', 'alpha');
73 $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility
74 
75 //PDF
76 $hidedetails = (GETPOST('hidedetails','int') ? GETPOST('hidedetails','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
77 $hidedesc = (GETPOST('hidedesc','int') ? GETPOST('hidedesc','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
78 $hideref = (GETPOST('hideref','int') ? GETPOST('hideref','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
79 
80 $datelivraison=dol_mktime(GETPOST('liv_hour','int'), GETPOST('liv_min','int'), GETPOST('liv_sec','int'), GETPOST('liv_month','int'), GETPOST('liv_day','int'),GETPOST('liv_year','int'));
81 
82 
83 // Security check
84 if ($user->societe_id) $socid=$user->societe_id;
85 $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande');
86 
87 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
88 $hookmanager->initHooks(array('ordersuppliercard','globalcard'));
89 
90 $object = new CommandeFournisseur($db);
91 $extrafields = new ExtraFields($db);
92 
93 // fetch optionals attributes and labels
94 $extralabels=$extrafields->fetch_name_optionals_label($object->table_element);
95 
96 // Load object
97 if ($id > 0 || ! empty($ref))
98 {
99  $ret = $object->fetch($id, $ref);
100  if ($ret < 0) dol_print_error($db,$object->error);
101  $ret = $object->fetch_thirdparty();
102  if ($ret < 0) dol_print_error($db,$object->error);
103 }
104 else if (! empty($socid) && $socid > 0)
105 {
106  $fourn = new Fournisseur($db);
107  $ret=$fourn->fetch($socid);
108  if ($ret < 0) dol_print_error($db,$object->error);
109  $object->socid = $fourn->id;
110  $ret = $object->fetch_thirdparty();
111  if ($ret < 0) dol_print_error($db,$object->error);
112 }
113 
114 $permissionnote=$user->rights->fournisseur->commande->creer; // Used by the include of actions_setnotes.inc.php
115 $permissiondellink=$user->rights->fournisseur->commande->creer; // Used by the include of actions_dellink.inc.php
116 $permissiontoedit=$user->rights->fournisseur->commande->creer; // Used by the include of actions_lineupdown.inc.php
117 
118 
119 /*
120  * Actions
121  */
122 
123 $parameters=array('socid'=>$socid);
124 $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
125 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
126 
127 if (empty($reshook))
128 {
129  if ($cancel)
130  {
131  if (! empty($backtopage))
132  {
133  header("Location: ".$backtopage);
134  exit;
135  }
136  $action='';
137  }
138 
139  include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
140 
141  include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
142 
143  include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
144 
145  if ($action == 'setref_supplier' && $user->rights->fournisseur->commande->creer)
146  {
147  $result=$object->setValueFrom('ref_supplier', GETPOST('ref_supplier','alpha'), '', null, 'text', '', $user, 'ORDER_SUPPLIER_MODIFY');
148  if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
149  }
150 
151  // Set incoterm
152  if ($action == 'set_incoterms' && $user->rights->fournisseur->commande->creer)
153  {
154  $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
155  if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
156  }
157 
158  // payment conditions
159  if ($action == 'setconditions' && $user->rights->fournisseur->commande->creer)
160  {
161  $result=$object->setPaymentTerms(GETPOST('cond_reglement_id','int'));
162  if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
163  }
164 
165  // payment mode
166  if ($action == 'setmode' && $user->rights->fournisseur->commande->creer)
167  {
168  $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int'));
169  if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
170  }
171 
172  // Multicurrency Code
173  else if ($action == 'setmulticurrencycode' && $user->rights->fournisseur->commande->creer) {
174  $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
175  }
176 
177  // Multicurrency rate
178  else if ($action == 'setmulticurrencyrate' && $user->rights->fournisseur->commande->creer) {
179  $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')));
180  }
181 
182  // bank account
183  if ($action == 'setbankaccount' && $user->rights->fournisseur->commande->creer)
184  {
185  $result=$object->setBankAccount(GETPOST('fk_account', 'int'));
186  if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
187  }
188 
189  // date of delivery
190  if ($action == 'setdate_livraison' && $user->rights->fournisseur->commande->creer)
191  {
192  $result=$object->set_date_livraison($user,$datelivraison);
193  if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
194  }
195 
196  // Set project
197  if ($action == 'classin' && $user->rights->fournisseur->commande->creer)
198  {
199  $result=$object->setProject($projectid);
200  if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
201  }
202 
203  if ($action == 'setremisepercent' && $user->rights->fournisseur->commande->creer)
204  {
205  $result = $object->set_remise($user, $_POST['remise_percent']);
206  if ($result < 0) setEventMessages($object->error, $object->errors, 'errors');
207  }
208 
209  if ($action == 'reopen') // no test on permission here, permission to use will depends on status
210  {
211  if (in_array($object->statut, array(1, 2, 3, 4, 5, 6, 7, 9)))
212  {
213  if ($object->statut == 1) $newstatus=0; // Validated->Draft
214  else if ($object->statut == 2) $newstatus=0; // Approved->Draft
215  else if ($object->statut == 3) $newstatus=2; // Ordered->Approved
216  else if ($object->statut == 4) $newstatus=3;
217  else if ($object->statut == 5)
218  {
219  //$newstatus=2; // Ordered
220  // TODO Can we set it to submited ?
221  //$newstatus=3; // Submited
222  // TODO If there is at least one reception, we can set to Received->Received partially
223  $newstatus=4; // Received partially
224  }
225  else if ($object->statut == 6) $newstatus=2; // Canceled->Approved
226  else if ($object->statut == 7) $newstatus=3; // Canceled->Process running
227  else if ($object->statut == 9) $newstatus=1; // Refused->Validated
228  else $newstatus = 2;
229 
230  //print "old status = ".$object->statut.' new status = '.$newstatus;
231  $db->begin();
232 
233  $result = $object->setStatus($user, $newstatus);
234  if ($result > 0)
235  {
236  // Currently the "Re-open" also remove the billed flag because there is no button "Set unpaid" yet.
237  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur';
238  $sql.= ' SET billed = 0';
239  $sql.= ' WHERE rowid = '.$object->id;
240 
241  $resql=$db->query($sql);
242 
243  if ($newstatus == 0)
244  {
245  $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur';
246  $sql.= ' SET fk_user_approve = null, fk_user_approve2 = null, date_approve = null, date_approve2 = null';
247  $sql.= ' WHERE rowid = '.$object->id;
248 
249  $resql=$db->query($sql);
250  }
251 
252  $db->commit();
253 
254  header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
255  exit;
256  }
257  else
258  {
259  $db->rollback();
260 
261  setEventMessages($object->error, $object->errors, 'errors');
262  }
263  }
264  }
265 
266  /*
267  * Classify supplier order as billed
268  */
269  if ($action == 'classifybilled' && $user->rights->fournisseur->commande->creer)
270  {
271  $ret=$object->classifyBilled($user);
272  if ($ret < 0) {
273  setEventMessages($object->error, $object->errors, 'errors');
274  }
275  }
276 
277  // Add a product line
278  if ($action == 'addline' && $user->rights->fournisseur->commande->creer)
279  {
280  $db->begin();
281 
282  $langs->load('errors');
283  $error = 0;
284 
285  // Set if we used free entry or predefined product
286  $predef='';
287  $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
288  $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'));
289  $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'));
290  $prod_entry_mode = GETPOST('prod_entry_mode');
291  if ($prod_entry_mode == 'free')
292  {
293  $idprod=0;
294  $price_ht = GETPOST('price_ht');
295  $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
296  }
297  else
298  {
299  $idprod=GETPOST('idprod', 'int');
300  $price_ht = '';
301  $tva_tx = '';
302  }
303 
304  $qty = GETPOST('qty'.$predef);
305  $remise_percent=GETPOST('remise_percent'.$predef);
306  $price_ht_devise = GETPOST('multicurrency_price_ht');
307 
308  // Extrafields
309  $extrafieldsline = new ExtraFields($db);
310  $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
311  $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef);
312  // Unset extrafield
313  if (is_array($extralabelsline)) {
314  // Get extra fields
315  foreach ($extralabelsline as $key => $value) {
316  unset($_POST["options_" . $key]);
317  }
318  }
319 
320  if ($prod_entry_mode =='free' && GETPOST('price_ht') < 0 && $qty < 0)
321  {
322  setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
323  $error++;
324  }
325  if ($prod_entry_mode =='free' && ! GETPOST('idprodfournprice') && GETPOST('type') < 0)
326  {
327  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
328  $error++;
329  }
330  if ($prod_entry_mode =='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='' && $price_ht_devise === '') // Unit price can be 0 but not ''
331  {
332  setEventMessages($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), null, 'errors');
333  $error++;
334  }
335  if ($prod_entry_mode =='free' && ! GETPOST('dp_desc'))
336  {
337  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
338  $error++;
339  }
340  if (! GETPOST('qty'))
341  {
342  setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
343  $error++;
344  }
345 
346  if (!$error && !empty($conf->variants->enabled) && $prod_entry_mode != 'free') {
347  if ($combinations = GETPOST('combinations', 'array')) {
348  //Check if there is a product with the given combination
349  $prodcomb = new ProductCombination($db);
350 
351  if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
352  $idprod = $res->fk_product_child;
353  } else {
354  setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
355  $error ++;
356  }
357  }
358  }
359 
360  // Ecrase $pu par celui du produit
361  // Ecrase $desc par celui du produit
362  // Ecrase $txtva par celui du produit
363  if (($prod_entry_mode != 'free') && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or ''
364  {
365  $productsupplier = new ProductFournisseur($db);
366 
367  $idprod=0;
368  if (GETPOST('idprodfournprice','alpha') == -1 || GETPOST('idprodfournprice','alpha') == '') $idprod=-99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...)
369  if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice','alpha'), $reg))
370  {
371  $idprod=$reg[1];
372  $res=$productsupplier->fetch($idprod); // Load product from its ID
373  // Call to init some price properties of $productsupplier
374  // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price
375  if (! empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER))
376  {
377  $fksoctosearch = 0;
378  $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
379  if ($productsupplier->fourn_socid != $socid) // The price we found is for another supplier, so we clear supplier price
380  {
381  $productsupplier->ref_supplier = '';
382  }
383  }
384  else
385  {
386  $fksoctosearch = $object->thirdparty->id;
387  $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
388  }
389  }
390  elseif (GETPOST('idprodfournprice','alpha') > 0)
391  {
392  $qtytosearch=$qty; // Just to see if a price exists for the quantity. Not used to found vat.
393  //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist
394  $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice','alpha'), $qtytosearch);
395  $res=$productsupplier->fetch($idprod);
396  }
397 
398  if ($idprod > 0)
399  {
400  $label = $productsupplier->label;
401 
402  // if we use supplier description of the products
403  if(!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) {
404  $desc = $productsupplier->desc_supplier;
405  } else $desc = $productsupplier->description;
406 
407  if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc);
408 
409  $type = $productsupplier->type;
410  $price_base_type = ($productsupplier->fourn_price_base_type?$productsupplier->fourn_price_base_type:'HT');
411 
412  $ref_supplier = $productsupplier->ref_supplier;
413 
414  $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice','alpha'));
415  $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice','alpha'));
416  if (empty($tva_tx)) $tva_npr=0;
417  $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr);
418  $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr);
419 
420  $pu = $productsupplier->fourn_pu;
421  if (empty($pu)) $pu = 0; // If pu is '' or null, we force to have a numeric value
422 
423  $result=$object->addline(
424  $desc,
425  $pu,
426  $qty,
427  $tva_tx,
428  $localtax1_tx,
429  $localtax2_tx,
430  $idprod,
431  0, // We already have the $idprod always defined
432  $ref_supplier,
433  $remise_percent,
434  'HT',
435  $pu_ttc,
436  $type,
437  $tva_npr,
438  '',
439  $date_start,
440  $date_end,
441  $array_options,
442  $productsupplier->fk_unit,
443  $productsupplier->fourn_multicurrency_unitprice
444  );
445  }
446  if ($idprod == -99 || $idprod == 0)
447  {
448  // Product not selected
449  $error++;
450  $langs->load("errors");
451  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")).' '.$langs->trans("or").' '.$langs->trans("NoPriceDefinedForThisSupplier"), null, 'errors');
452  }
453  if ($idprod == -1)
454  {
455  // Quantity too low
456  $error++;
457  $langs->load("errors");
458  setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors');
459  }
460  }
461  else if (empty($error)) // $price_ht is already set
462  {
463  $pu_ht = price2num($price_ht, 'MU');
464  $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
465  $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
466  $tva_tx = str_replace('*', '', $tva_tx);
467  $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
468  $desc = $product_desc;
469  $type = GETPOST('type');
470  $ref_supplier = GETPOST('fourn_ref','alpha');
471 
472  $fk_unit= GETPOST('units', 'alpha');
473 
474  $tva_tx = price2num($tva_tx); // When vat is text input field
475 
476  // Local Taxes
477  $localtax1_tx= get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
478  $localtax2_tx= get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
479 
480  if ($price_ht !== '')
481  {
482  $pu_ht = price2num($price_ht, 'MU'); // $pu_ht must be rounded according to settings
483  }
484  else
485  {
486  $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
487  $pu_ht = price2num($pu_ttc / (1 + ($tva_tx / 100)), 'MU'); // $pu_ht must be rounded according to settings
488  }
489  $price_base_type = 'HT';
490  $pu_ht_devise = price2num($price_ht_devise, 'MU');
491 
492  $result=$object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, $ref_supplier, $remise_percent, $price_base_type, $pu_ttc, $type,'','', $date_start, $date_end, $array_options, $fk_unit, $pu_ht_devise);
493  }
494 
495  //print "xx".$tva_tx; exit;
496  if (! $error && $result > 0)
497  {
498  $db->commit();
499 
500  $ret=$object->fetch($object->id); // Reload to get new records
501 
502  // Define output language
503  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
504  {
505  $outputlangs = $langs;
506  $newlang = '';
507  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
508  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
509  if (! empty($newlang)) {
510  $outputlangs = new Translate("", $conf);
511  $outputlangs->setDefaultLang($newlang);
512  }
513  $model=$object->modelpdf;
514  $ret = $object->fetch($id); // Reload to get new records
515 
516  $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
517  if ($result < 0) dol_print_error($db,$result);
518  }
519 
520  unset($_POST ['prod_entry_mode']);
521 
522  unset($_POST['qty']);
523  unset($_POST['type']);
524  unset($_POST['remise_percent']);
525  unset($_POST['pu']);
526  unset($_POST['price_ht']);
527  unset($_POST['multicurrency_price_ht']);
528  unset($_POST['price_ttc']);
529  unset($_POST['fourn_ref']);
530  unset($_POST['tva_tx']);
531  unset($_POST['label']);
532  unset($localtax1_tx);
533  unset($localtax2_tx);
534  unset($_POST['np_marginRate']);
535  unset($_POST['np_markRate']);
536  unset($_POST['dp_desc']);
537  unset($_POST['idprodfournprice']);
538 
539  unset($_POST['date_starthour']);
540  unset($_POST['date_startmin']);
541  unset($_POST['date_startsec']);
542  unset($_POST['date_startday']);
543  unset($_POST['date_startmonth']);
544  unset($_POST['date_startyear']);
545  unset($_POST['date_endhour']);
546  unset($_POST['date_endmin']);
547  unset($_POST['date_endsec']);
548  unset($_POST['date_endday']);
549  unset($_POST['date_endmonth']);
550  unset($_POST['date_endyear']);
551  }
552  else
553  {
554  $db->rollback();
555  setEventMessages($object->error, $object->errors, 'errors');
556  }
557 
558  $action = '';
559  }
560 
561  /*
562  * Updating a line in the order
563  */
564  if ($action == 'updateline' && $user->rights->fournisseur->commande->creer && ! GETPOST('cancel','alpha'))
565  {
566  $vat_rate=(GETPOST('tva_tx')?GETPOST('tva_tx'):0);
567 
568  if ($lineid)
569  {
570  $line = new CommandeFournisseurLigne($db);
571  $res = $line->fetch($lineid);
572  if (!$res) dol_print_error($db);
573  }
574 
575  $productsupplier = new ProductFournisseur($db);
576  if (! empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY))
577  {
578  if ($line->fk_product > 0 && $productsupplier->get_buyprice(0, price2num($_POST['qty']), $line->fk_product, 'none', GETPOST('socid','int')) < 0 )
579  {
580  setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings');
581  }
582  }
583 
584  $date_start=dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
585  $date_end=dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
586 
587  // Define info_bits
588  $info_bits = 0;
589  if (preg_match('/\*/', $vat_rate))
590  $info_bits |= 0x01;
591 
592  // Define vat_rate
593  $vat_rate = str_replace('*', '', $vat_rate);
594  $localtax1_rate = get_localtax($vat_rate, 1, $mysoc, $object->thirdparty);
595  $localtax2_rate = get_localtax($vat_rate, 2, $mysoc, $object->thirdparty);
596 
597  if (GETPOST('price_ht') != '')
598  {
599  $price_base_type = 'HT';
600  $ht = price2num(GETPOST('price_ht'));
601  }
602  else
603  {
604  $vatratecleaned = $vat_rate;
605  if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) // If vat is "xx (yy)"
606  {
607  $vatratecleaned = trim($reg[1]);
608  $vatratecode = $reg[2];
609  }
610 
611  $ttc = price2num(GETPOST('price_ttc'));
612  $ht = $ttc / (1 + ($vatratecleaned / 100));
613  $price_base_type = 'HT';
614  }
615 
616  $pu_ht_devise = GETPOST('multicurrency_subprice');
617 
618  // Extrafields Lines
619  $extrafieldsline = new ExtraFields($db);
620  $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line);
621  $array_options = $extrafieldsline->getOptionalsFromPost($extralabelsline);
622  // Unset extrafield POST Data
623  if (is_array($extralabelsline)) {
624  foreach ($extralabelsline as $key => $value) {
625  unset($_POST["options_" . $key]);
626  }
627  }
628 
629  $result = $object->updateline(
630  $lineid,
631  $_POST['product_desc'],
632  $ht,
633  $_POST['qty'],
634  $_POST['remise_percent'],
635  $vat_rate,
636  $localtax1_rate,
637  $localtax2_rate,
638  $price_base_type,
639  0,
640  isset($_POST["type"])?$_POST["type"]:$line->product_type,
641  false,
642  $date_start,
643  $date_end,
644  $array_options,
645  $_POST['units'],
646  $pu_ht_devise,
647  GETPOST('fourn_ref','alpha')
648  );
649  unset($_POST['qty']);
650  unset($_POST['type']);
651  unset($_POST['idprodfournprice']);
652  unset($_POST['remmise_percent']);
653  unset($_POST['dp_desc']);
654  unset($_POST['np_desc']);
655  unset($_POST['pu']);
656  unset($_POST['fourn_ref']);
657  unset($_POST['tva_tx']);
658  unset($_POST['date_start']);
659  unset($_POST['date_end']);
660  unset($_POST['units']);
661  unset($localtax1_tx);
662  unset($localtax2_tx);
663 
664  unset($_POST['date_starthour']);
665  unset($_POST['date_startmin']);
666  unset($_POST['date_startsec']);
667  unset($_POST['date_startday']);
668  unset($_POST['date_startmonth']);
669  unset($_POST['date_startyear']);
670  unset($_POST['date_endhour']);
671  unset($_POST['date_endmin']);
672  unset($_POST['date_endsec']);
673  unset($_POST['date_endday']);
674  unset($_POST['date_endmonth']);
675  unset($_POST['date_endyear']);
676 
677  if ($result >= 0)
678  {
679  // Define output language
680  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
681  {
682  $outputlangs = $langs;
683  $newlang = '';
684  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
685  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
686  if (! empty($newlang)) {
687  $outputlangs = new Translate("", $conf);
688  $outputlangs->setDefaultLang($newlang);
689  }
690  $model=$object->modelpdf;
691  $ret = $object->fetch($id); // Reload to get new records
692 
693  $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
694  if ($result < 0) dol_print_error($db,$result);
695  }
696  }
697  else
698  {
699  dol_print_error($db,$object->error);
700  exit;
701  }
702  }
703 
704  // Remove a product line
705  if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->fournisseur->commande->creer)
706  {
707  $result = $object->deleteline($lineid);
708  if ($result > 0)
709  {
710  // Define output language
711  $outputlangs = $langs;
712  $newlang = '';
713  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09'))
714  $newlang = GETPOST('lang_id','aZ09');
715  if ($conf->global->MAIN_MULTILANGS && empty($newlang))
716  $newlang = $object->thirdparty->default_lang;
717  if (! empty($newlang)) {
718  $outputlangs = new Translate("", $conf);
719  $outputlangs->setDefaultLang($newlang);
720  }
721  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
722  $ret = $object->fetch($object->id); // Reload to get new records
723  $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
724  }
725 
726  header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
727  exit;
728  }
729  else
730  {
731  setEventMessages($object->error, $object->errors, 'errors');
732  /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */
733  $action='';
734  }
735  }
736 
737  // Validate
738  if ($action == 'confirm_valid' && $confirm == 'yes' &&
739  ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->commande->creer))
740  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_order_advance->validate)))
741  )
742  {
743  $object->date_commande=dol_now();
744  $result = $object->valid($user);
745  if ($result >= 0)
746  {
747  // Define output language
748  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
749  {
750  $outputlangs = $langs;
751  $newlang = '';
752  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
753  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
754  if (! empty($newlang)) {
755  $outputlangs = new Translate("", $conf);
756  $outputlangs->setDefaultLang($newlang);
757  }
758  $model=$object->modelpdf;
759  $ret = $object->fetch($id); // Reload to get new records
760 
761  $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
762  if ($result < 0) dol_print_error($db,$result);
763  }
764  }
765  else
766  {
767  setEventMessages($object->error, $object->errors, 'errors');
768  }
769 
770  // If we have permission, and if we don't need to provide the idwarehouse, we go directly on approved step
771  if (empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE) && $user->rights->fournisseur->commande->approuver && ! (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1)))
772  {
773  $action='confirm_approve'; // can make standard or first level approval also if permission is set
774  }
775  }
776 
777  if (($action == 'confirm_approve' || $action == 'confirm_approve2') && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver)
778  {
779  $idwarehouse=GETPOST('idwarehouse', 'int');
780 
781  $qualified_for_stock_change=0;
782  if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
783  {
784  $qualified_for_stock_change=$object->hasProductsOrServices(2);
785  }
786  else
787  {
788  $qualified_for_stock_change=$object->hasProductsOrServices(1);
789  }
790 
791  // Check parameters
792  if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) // warning name of option should be STOCK_CALCULATE_ON_SUPPLIER_APPROVE_ORDER
793  {
794  if (! $idwarehouse || $idwarehouse == -1)
795  {
796  $error++;
797  setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
798  $action='';
799  }
800  }
801 
802  if (! $error)
803  {
804  $result = $object->approve($user, $idwarehouse, ($action=='confirm_approve2'?1:0));
805  if ($result > 0)
806  {
807  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
808  $outputlangs = $langs;
809  $newlang = '';
810  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
811  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
812  if (! empty($newlang)) {
813  $outputlangs = new Translate("", $conf);
814  $outputlangs->setDefaultLang($newlang);
815  }
816  $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
817  }
818  header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id);
819  exit;
820  }
821  else
822  {
823  setEventMessages($object->error, $object->errors, 'errors');
824  }
825  }
826  }
827 
828  if ($action == 'confirm_refuse' && $confirm == 'yes' && $user->rights->fournisseur->commande->approuver)
829  {
830  $result = $object->refuse($user);
831  if ($result > 0)
832  {
833  header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id);
834  exit;
835  }
836  else
837  {
838  setEventMessages($object->error, $object->errors, 'errors');
839  }
840  }
841 
842  if ($action == 'confirm_commande' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander)
843  {
844  $result = $object->commande($user, $_REQUEST["datecommande"], $_REQUEST["methode"], $_REQUEST['comment']);
845  if ($result > 0)
846  {
847  if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE))
848  {
849  $outputlangs = $langs;
850  $newlang = '';
851  if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang = GETPOST('lang_id','aZ09');
852  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang;
853  if (! empty($newlang)) {
854  $outputlangs = new Translate("", $conf);
855  $outputlangs->setDefaultLang($newlang);
856  }
857  $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
858  }
859  $action = '';
860  header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id);
861  exit;
862  }
863  else
864  {
865  setEventMessages($object->error, $object->errors, 'errors');
866  }
867  }
868 
869 
870  if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->commande->supprimer)
871  {
872  $result=$object->delete($user);
873  if ($result > 0)
874  {
875  header("Location: ".DOL_URL_ROOT.'/fourn/commande/list.php?restore_lastsearch_values=1');
876  exit;
877  }
878  else
879  {
880  setEventMessages($object->error, $object->errors, 'errors');
881  }
882  }
883 
884  // Action clone object
885  if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->fournisseur->commande->creer)
886  {
887  if (1==0 && ! GETPOST('clone_content') && ! GETPOST('clone_receivers'))
888  {
889  setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
890  }
891  else
892  {
893  if ($object->id > 0)
894  {
895  $result=$object->createFromClone();
896  if ($result > 0)
897  {
898  header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
899  exit;
900  }
901  else
902  {
903  setEventMessages($object->error, $object->errors, 'errors');
904  $action='';
905  }
906  }
907  }
908  }
909 
910  // Set status of reception (complete, partial, ...)
911  if ($action == 'livraison' && $user->rights->fournisseur->commande->receptionner)
912  {
913  if (GETPOST("type") != '')
914  {
915  $date_liv = dol_mktime(GETPOST('rehour'),GETPOST('remin'),GETPOST('resec'),GETPOST("remonth"),GETPOST("reday"),GETPOST("reyear"));
916 
917  $result = $object->Livraison($user, $date_liv, GETPOST("type"), GETPOST("comment")); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
918  if ($result > 0)
919  {
920  $langs->load("deliveries");
921  setEventMessages($langs->trans("DeliveryStateSaved"), null);
922  $action = '';
923  }
924  else if($result == -3)
925  {
926  setEventMessages($object->error, $object->errors, 'errors');
927  }
928  else
929  {
930  setEventMessages($object->error, $object->errors, 'errors');
931  }
932  }
933  else
934  {
935  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Delivery")), null, 'errors');
936  }
937  }
938 
939  if ($action == 'confirm_cancel' && $confirm == 'yes' && $user->rights->fournisseur->commande->commander)
940  {
941  $result = $object->cancel($user);
942  if ($result > 0)
943  {
944  header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id);
945  exit;
946  }
947  else
948  {
949  setEventMessages($object->error, $object->errors, 'errors');
950  }
951  }
952 
953  // Actions when printing a doc from card
954  include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
955 
956  // Actions to send emails
957  $trigger_name='ORDER_SUPPLIER_SENTBYMAIL';
958  $autocopy='MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO';
959  $trackid='sor'.$object->id;
960  include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
961 
962  // Actions to build doc
963  $upload_dir = $conf->fournisseur->commande->dir_output;
964  $permissioncreate = $user->rights->fournisseur->commande->creer;
965  include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
966 
967 
968  if ($action == 'update_extras')
969  {
970  $object->oldcopy = dol_clone($object);
971 
972  // Fill array 'array_options' with data from add form
973  $extralabels=$extrafields->fetch_name_optionals_label($object->table_element);
974  $ret = $extrafields->setOptionalsFromPost($extralabels,$object,GETPOST('attribute', 'none'));
975  if ($ret < 0) $error++;
976 
977  if (! $error)
978  {
979  // Actions on extra fields
980  if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
981  {
982  $result=$object->insertExtraFields('ORDER_SUPPLIER_MODIFY');
983  if ($result < 0)
984  {
985  $error++;
986  setEventMessages($object->error,$object->errors,'errors');
987  }
988  }
989  }
990 
991  if ($error)
992  $action = 'edit_extras';
993  }
994 
995  /*
996  * Create an order
997  */
998  if ($action == 'add' && $user->rights->fournisseur->commande->creer)
999  {
1000  $error=0;
1001 
1002  if ($socid <1)
1003  {
1004  setEventMessages($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), null, 'errors');
1005  $action='create';
1006  $error++;
1007  }
1008 
1009  if (! $error)
1010  {
1011  $db->begin();
1012 
1013  // Creation commande
1014  $object->ref_supplier = GETPOST('refsupplier');
1015  $object->socid = $socid;
1016  $object->cond_reglement_id = GETPOST('cond_reglement_id');
1017  $object->mode_reglement_id = GETPOST('mode_reglement_id');
1018  $object->fk_account = GETPOST('fk_account', 'int');
1019  $object->note_private = GETPOST('note_private','none');
1020  $object->note_public = GETPOST('note_public','none');
1021  $object->date_livraison = $datelivraison;
1022  $object->fk_incoterms = GETPOST('incoterm_id', 'int');
1023  $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
1024  $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
1025  $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
1026  $object->fk_project = GETPOST('projectid');
1027 
1028  // Fill array 'array_options' with data from add form
1029  if (! $error)
1030  {
1031  $ret = $extrafields->setOptionalsFromPost($extralabels,$object);
1032  if ($ret < 0) $error++;
1033  }
1034 
1035  if (! $error)
1036  {
1037  // If creation from another object of another module (Example: origin=propal, originid=1)
1038  if (! empty($origin) && ! empty($originid))
1039  {
1040  if ($origin == 'order' || $origin == 'commande')
1041  {
1042  $element = $subelement = 'commande';
1043  }
1044  else
1045  {
1046  $element = 'supplier_proposal';
1047  $subelement = 'supplier_proposal';
1048  }
1049 
1050  $object->origin = $origin;
1051  $object->origin_id = $originid;
1052 
1053  // Possibility to add external linked objects with hooks
1054  $object->linked_objects [$object->origin] = $object->origin_id;
1055  $other_linked_objects = GETPOST('other_linked_objects', 'array');
1056  if (! empty($other_linked_objects)) {
1057  $object->linked_objects = array_merge($object->linked_objects, $other_linked_objects);
1058  }
1059 
1060  $id = $object->create($user);
1061  if ($id > 0)
1062  {
1063  dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
1064 
1065  $classname = 'SupplierProposal';
1066  $srcobject = new $classname($db);
1067 
1068  dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines");
1069  $result = $srcobject->fetch($object->origin_id);
1070  if ($result > 0)
1071  {
1072  $object->set_date_livraison($user, $srcobject->date_livraison);
1073  $object->set_id_projet($user, $srcobject->fk_project);
1074 
1075  $lines = $srcobject->lines;
1076  if (empty($lines) && method_exists($srcobject, 'fetch_lines'))
1077  {
1078  $srcobject->fetch_lines();
1079  $lines = $srcobject->lines;
1080  }
1081 
1082  $fk_parent_line = 0;
1083  $num = count($lines);
1084 
1085  for($i = 0; $i < $num; $i ++)
1086  {
1087 
1088  if (empty($lines[$i]->subprice) || $lines[$i]->qty <= 0)
1089  continue;
1090 
1091  $label = (! empty($lines[$i]->label) ? $lines[$i]->label : '');
1092  $desc = (! empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->product_desc);
1093  $product_type = (! empty($lines[$i]->product_type) ? $lines[$i]->product_type : 0);
1094 
1095  // Reset fk_parent_line for no child products and special product
1096  if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
1097  $fk_parent_line = 0;
1098  }
1099 
1100  // Extrafields
1101  if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if
1102  // trigger used
1103  {
1104  $lines[$i]->fetch_optionals($lines[$i]->rowid);
1105  $array_option = $lines[$i]->array_options;
1106  }
1107 
1108  $ref_supplier = '';
1109  $product_fourn_price_id = 0;
1110  if ($origin == "commande")
1111  {
1112  $productsupplier = new ProductFournisseur($db);
1113  $result = $productsupplier->find_min_price_product_fournisseur($lines[$i]->fk_product, $lines[$i]->qty, $srcobject->socid);
1114  if ($result > 0)
1115  {
1116  $ref_supplier = $productsupplier->ref_supplier;
1117  $product_fourn_price_id = $productsupplier->product_fourn_price_id;
1118  }
1119  }
1120  else
1121  {
1122  $ref_supplier = $lines[$i]->ref_fourn;
1123  $product_fourn_price_id = 0;
1124  }
1125 
1126  $tva_tx = $lines[$i]->tva_tx;
1127 
1128  if ($origin=="commande")
1129  {
1130  $soc=new societe($db);
1131  $soc->fetch($socid);
1132  $tva_tx=get_default_tva($soc, $mysoc, $lines[$i]->fk_product, $product_fourn_price_id);
1133  }
1134 
1135  $result = $object->addline(
1136  $desc,
1137  $lines[$i]->subprice,
1138  $lines[$i]->qty,
1139  $tva_tx,
1140  $lines[$i]->localtax1_tx,
1141  $lines[$i]->localtax2_tx,
1142  $lines[$i]->fk_product > 0 ? $lines[$i]->fk_product : 0,
1143  $product_fourn_price_id,
1144  $ref_supplier,
1145  $lines[$i]->remise_percent,
1146  'HT',
1147  0,
1148  $lines[$i]->product_type,
1149  '',
1150  '',
1151  null,
1152  null,
1153  array(),
1154  $lines[$i]->fk_unit,
1155  0,
1156  $element,
1157  !empty($lines[$i]->id) ? $lines[$i]->id : $lines[$i]->rowid
1158  );
1159 
1160  if ($result < 0) {
1161  $error++;
1162  break;
1163  }
1164 
1165  // Defined the new fk_parent_line
1166  if ($result > 0 && $lines[$i]->product_type == 9) {
1167  $fk_parent_line = $result;
1168  }
1169  }
1170 
1171  // Add link between elements
1172 
1173 
1174  // Hooks
1175  $parameters = array('objFrom' => $srcobject);
1176  $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
1177 
1178  if ($reshook < 0)
1179  $error ++;
1180  } else {
1181  setEventMessages($srcobject->error, $srcobject->errors, 'errors');
1182  $error ++;
1183  }
1184  } else {
1185  setEventMessages($object->error, $object->errors, 'errors');
1186  $error ++;
1187  }
1188  }
1189  else
1190  {
1191  $id = $object->create($user);
1192  if ($id < 0)
1193  {
1194  $error++;
1195  setEventMessages($object->error, $object->errors, 'errors');
1196  }
1197  }
1198  }
1199 
1200  if ($error)
1201  {
1202  $langs->load("errors");
1203  $db->rollback();
1204  $action='create';
1205  $_GET['socid']=$_POST['socid'];
1206  }
1207  else
1208  {
1209  $db->commit();
1210  header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
1211  exit;
1212  }
1213  }
1214  }
1215 
1216  if ($action == 'webservice' && GETPOST('mode', 'alpha') == "send" && ! GETPOST('cancel','alpha'))
1217  {
1218  $ws_url = $object->thirdparty->webservices_url;
1219  $ws_key = $object->thirdparty->webservices_key;
1220  $ws_user = GETPOST('ws_user','alpha');
1221  $ws_password = GETPOST('ws_password','alpha');
1222  $ws_entity = GETPOST('ws_entity','int');
1223  $ws_thirdparty = GETPOST('ws_thirdparty','int');
1224 
1225  // NS and Authentication parameters
1226  $ws_ns='http://www.dolibarr.org/ns/';
1227  $ws_authentication=array(
1228  'dolibarrkey'=>$ws_key,
1229  'sourceapplication'=>'DolibarrWebServiceClient',
1230  'login'=>$ws_user,
1231  'password'=>$ws_password,
1232  'entity'=>$ws_entity
1233  );
1234 
1235  //Is sync supplier web services module activated? and everything filled?
1236  if (empty($conf->syncsupplierwebservices->enabled)) {
1237  setEventMessages($langs->trans("WarningModuleNotActive",$langs->transnoentities("Module2650Name")), null, 'mesgs');
1238  } else if (empty($ws_url) || empty($ws_key)) {
1239  setEventMessages($langs->trans("ErrorWebServicesFieldsRequired"), null, 'errors');
1240  } else if (empty($ws_user) || empty($ws_password) || empty($ws_thirdparty)) {
1241  setEventMessages($langs->trans("ErrorFieldsRequired"),null, 'errors');
1242  }
1243  else
1244  {
1245  //Create SOAP client and connect it to order
1246  $soapclient_order = new nusoap_client($ws_url."/webservices/server_order.php");
1247  $soapclient_order->soap_defencoding='UTF-8';
1248  $soapclient_order->decodeUTF8(false);
1249 
1250  //Create SOAP client and connect it to product/service
1251  $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php");
1252  $soapclient_product->soap_defencoding='UTF-8';
1253  $soapclient_product->decodeUTF8(false);
1254 
1255  //Prepare the order lines from order
1256  $order_lines = array();
1257  foreach ($object->lines as $line)
1258  {
1259  $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $line->ref_supplier);
1260  $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, '');
1261 
1262  if ($result_product["result"]["result_code"] == "OK")
1263  {
1264  $order_lines[] = array(
1265  'desc' => $line->product_desc,
1266  'type' => $line->product_type,
1267  'product_id' => $result_product["product"]["id"],
1268  'vat_rate' => $line->tva_tx,
1269  'qty' => $line->qty,
1270  'price' => $line->price,
1271  'unitprice' => $line->subprice,
1272  'total_net' => $line->total_ht,
1273  'total_vat' => $line->total_tva,
1274  'total' => $line->total_ttc,
1275  'date_start' => $line->date_start,
1276  'date_end' => $line->date_end,
1277  );
1278  }
1279  }
1280 
1281  //Prepare the order header
1282  $order = array(
1283  'thirdparty_id' => $ws_thirdparty,
1284  'date' => dol_print_date(dol_now(),'dayrfc'),
1285  'total_net' => $object->total_ht,
1286  'total_var' => $object->total_tva,
1287  'total' => $object->total_ttc,
1288  'lines' => $order_lines
1289  );
1290 
1291  $ws_parameters = array('authentication'=>$ws_authentication, 'order' => $order);
1292  $result_order = $soapclient_order->call("createOrder", $ws_parameters, $ws_ns, '');
1293 
1294  if (empty($result_order["result"]["result_code"])) //No result, check error str
1295  {
1296  setEventMessages($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", null, 'errors');
1297  }
1298  else if ($result_order["result"]["result_code"] != "OK") //Something went wrong
1299  {
1300  setEventMessages($langs->trans("SOAPError")." '".$result_order["result"]["result_code"]."' - '".$result_order["result"]["result_label"]."'", null, 'errors');
1301  }
1302  else
1303  {
1304  setEventMessages($langs->trans("RemoteOrderRef")." ".$result_order["ref"], null, 'mesgs');
1305  }
1306  }
1307  }
1308 
1309  if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->commande->creer)
1310  {
1311  if ($action == 'addcontact')
1312  {
1313  if ($object->id > 0)
1314  {
1315  $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
1316  $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]);
1317  }
1318 
1319  if ($result >= 0)
1320  {
1321  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1322  exit;
1323  }
1324  else
1325  {
1326  if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
1327  {
1328  $langs->load("errors");
1329  setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
1330  }
1331  else
1332  {
1333  setEventMessages($object->error, $object->errors, 'errors');
1334  }
1335  }
1336  }
1337 
1338  // bascule du statut d'un contact
1339  else if ($action == 'swapstatut' && $object->id > 0)
1340  {
1341  $result=$object->swapContactStatus(GETPOST('ligne'));
1342  }
1343 
1344  // Efface un contact
1345  else if ($action == 'deletecontact' && $object->id > 0)
1346  {
1347  $result = $object->delete_contact($_GET["lineid"]);
1348 
1349  if ($result >= 0)
1350  {
1351  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
1352  exit;
1353  }
1354  else {
1355  dol_print_error($db);
1356  }
1357  }
1358  }
1359 }
1360 
1361 
1362 /*
1363  * View
1364  */
1365 
1366 $form = new Form($db);
1367 $formfile = new FormFile($db);
1368 $formorder = new FormOrder($db);
1369 $productstatic = new Product($db);
1370 if (! empty($conf->projet->enabled)) { $formproject = new FormProjets($db); }
1371 
1372 $help_url='EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores';
1373 llxHeader('',$langs->trans("Order"),$help_url);
1374 
1375 
1376 $now=dol_now();
1377 if ($action=='create')
1378 {
1379  print load_fiche_titre($langs->trans('NewOrder'));
1380 
1382 
1383  $currency_code = $conf->currency;
1384 
1385  $societe='';
1386  if ($socid>0)
1387  {
1388  $societe=new Societe($db);
1389  $societe->fetch($socid);
1390  }
1391 
1392  if (! empty($origin) && ! empty($originid))
1393  {
1394  // Parse element/subelement (ex: project_task)
1395  $element = $subelement = $origin;
1396  if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
1397  $element = $regs [1];
1398  $subelement = $regs [2];
1399  }
1400 
1401  $element = 'supplier_proposal';
1402  $subelement = 'supplier_proposal';
1403 
1404  dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
1405 
1406  $classname = 'SupplierProposal';
1407  $objectsrc = new $classname($db);
1408  $objectsrc->fetch($originid);
1409  if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines'))
1410  $objectsrc->fetch_lines();
1411  $objectsrc->fetch_thirdparty();
1412 
1413  // Replicate extrafields
1414  $objectsrc->fetch_optionals($originid);
1415  $object->array_options = $objectsrc->array_options;
1416 
1417  $projectid = (! empty($objectsrc->fk_project) ? $objectsrc->fk_project : '');
1418  $ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : '');
1419 
1420  $soc = $objectsrc->client;
1421  $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:0));
1422  $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0));
1423  $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0));
1424  $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0));
1425  $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0));
1426  $demand_reason_id = (!empty($objectsrc->demand_reason_id)?$objectsrc->demand_reason_id:(!empty($soc->demand_reason_id)?$soc->demand_reason_id:0));
1427  $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_supplier_percent)?$soc->remise_supplier_percent:0));
1428  $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0));
1429  $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:'';
1430 
1431  $datedelivery = (! empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : '');
1432 
1433  if (!empty($conf->multicurrency->enabled))
1434  {
1435  if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code;
1436  if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx;
1437  }
1438 
1439  $note_private = $object->getDefaultCreateValueFor('note_private', (! empty($objectsrc->note_private) ? $objectsrc->note_private : null));
1440  $note_public = $object->getDefaultCreateValueFor('note_public', (! empty($objectsrc->note_public) ? $objectsrc->note_public : null));
1441 
1442  // Object source contacts list
1443  $srccontactslist = $objectsrc->liste_contact(- 1, 'external', 1);
1444  }
1445  else
1446  {
1447  $cond_reglement_id = $societe->cond_reglement_supplier_id;
1448  $mode_reglement_id = $societe->mode_reglement_supplier_id;
1449 
1450  if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) $currency_code = $societe->multicurrency_code;
1451 
1452  $note_private = $object->getDefaultCreateValueFor('note_private');
1453  $note_public = $object->getDefaultCreateValueFor('note_public');
1454  }
1455 
1456  // If not defined, set default value from constant
1457  if (empty($cond_reglement_id) && ! empty($conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_TERM_ID)) $cond_reglement_id=$conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_TERM_ID;
1458  if (empty($mode_reglement_id) && ! empty($conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_MODE_ID)) $mode_reglement_id=$conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_MODE_ID;
1459 
1460  print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">';
1461  print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1462  print '<input type="hidden" name="action" value="add">';
1463  print '<input type="hidden" name="socid" value="' . $soc->id . '">' . "\n";
1464  print '<input type="hidden" name="remise_percent" value="' . $soc->remise_supplier_percent . '">';
1465  print '<input type="hidden" name="origin" value="' . $origin . '">';
1466  print '<input type="hidden" name="originid" value="' . $originid . '">';
1467  if (!empty($currency_tx)) print '<input type="hidden" name="originmulticurrency_tx" value="' . $currency_tx . '">';
1468 
1469  dol_fiche_head('');
1470 
1471  print '<table class="border" width="100%">';
1472 
1473  // Ref
1474  print '<tr><td class="titlefieldcreate">'.$langs->trans('Ref').'</td><td>'.$langs->trans('Draft').'</td></tr>';
1475 
1476  // Third party
1477  print '<tr><td class="fieldrequired">'.$langs->trans('Supplier').'</td>';
1478  print '<td>';
1479 
1480  if ($socid > 0)
1481  {
1482  print $societe->getNomUrl(1);
1483  print '<input type="hidden" name="socid" value="'.$socid.'">';
1484  }
1485  else
1486  {
1487  print $form->select_company((empty($socid)?'':$socid), 'socid', 's.fournisseur = 1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300');
1488  // reload page to retrieve customer informations
1489  if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE))
1490  {
1491  print '<script type="text/javascript">
1492  $(document).ready(function() {
1493  $("#socid").change(function() {
1494  var socid = $(this).val();
1495  // reload page
1496  window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid;
1497  });
1498  });
1499  </script>';
1500  }
1501  print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&client=0&fournisseur=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'">'.$langs->trans("AddThirdParty").'</a>';
1502  }
1503  print '</td>';
1504 
1505  if ($societe->id > 0)
1506  {
1507  // Discounts for third party
1508  print '<tr><td>' . $langs->trans('Discounts') . '</td><td>';
1509 
1510  $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1);
1511 
1512  $thirdparty = $societe;
1513  $discount_type = 1;
1514  $backtopage = urlencode($_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . GETPOST('origin') . '&originid=' . GETPOST('originid'));
1515  include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
1516 
1517  print '</td></tr>';
1518  }
1519 
1520  // Ref supplier
1521  print '<tr><td>'.$langs->trans('RefSupplier').'</td><td><input name="refsupplier" type="text"></td>';
1522  print '</tr>';
1523 
1524  print '</td></tr>';
1525 
1526  // Payment term
1527  print '<tr><td class="nowrap">'.$langs->trans('PaymentConditionsShort').'</td><td colspan="2">';
1528  $form->select_conditions_paiements(isset($_POST['cond_reglement_id'])?$_POST['cond_reglement_id']:$cond_reglement_id,'cond_reglement_id');
1529  print '</td></tr>';
1530 
1531  // Payment mode
1532  print '<tr><td>'.$langs->trans('PaymentMode').'</td><td colspan="2">';
1533  $form->select_types_paiements(isset($_POST['mode_reglement_id'])?$_POST['mode_reglement_id']:$mode_reglement_id,'mode_reglement_id');
1534  print '</td></tr>';
1535 
1536  // Planned delivery date
1537  print '<tr><td>';
1538  print $langs->trans('DateDeliveryPlanned');
1539  print '</td>';
1540  print '<td>';
1541  $usehourmin=0;
1542  if (! empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin=1;
1543  print $form->selectDate($datelivraison?$datelivraison:-1, 'liv_', $usehourmin, $usehourmin, '', "set");
1544  print '</td></tr>';
1545 
1546  // Bank Account
1547  if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && ! empty($conf->banque->enabled))
1548  {
1549  $langs->load("bank");
1550  print '<tr><td>' . $langs->trans('BankAccount') . '</td><td colspan="2">';
1551  $form->select_comptes($fk_account, 'fk_account', 0, '', 1);
1552  print '</td></tr>';
1553  }
1554 
1555  // Project
1556  if (! empty($conf->projet->enabled))
1557  {
1558  $formproject = new FormProjets($db);
1559 
1560  $langs->load('projects');
1561  print '<tr><td>' . $langs->trans('Project') . '</td><td colspan="2">';
1562  $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$societe->id:-1), $projectid, 'projectid', 0, 0, 1, 1);
1563  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='.$societe->id).'">' . $langs->trans("AddProject") . '</a>';
1564 
1565  print '</td></tr>';
1566  }
1567 
1568  // Incoterms
1569  if (!empty($conf->incoterm->enabled))
1570  {
1571  print '<tr>';
1572  print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), $object->libelle_incoterms, 1).'</label></td>';
1573  print '<td colspan="3" class="maxwidthonsmartphone">';
1574  print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''));
1575  print '</td></tr>';
1576  }
1577 
1578  // Multicurrency
1579  if (! empty($conf->multicurrency->enabled))
1580  {
1581  print '<tr>';
1582  print '<td>'.fieldLabel('Currency','multicurrency_code').'</td>';
1583  print '<td colspan="3" class="maxwidthonsmartphone">';
1584  print $form->selectMultiCurrency($currency_code, 'multicurrency_code');
1585  print '</td></tr>';
1586  }
1587 
1588  print '<tr><td>'.$langs->trans('NotePublic').'</td>';
1589  print '<td>';
1590  $doleditor = new DolEditor('note_public', isset($note_public) ? $note_public : GETPOST('note_public','none'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
1591  print $doleditor->Create(1);
1592  print '</td>';
1593  //print '<textarea name="note_public" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea>';
1594  print '</tr>';
1595 
1596  print '<tr><td>'.$langs->trans('NotePrivate').'</td>';
1597  print '<td>';
1598  $doleditor = new DolEditor('note_private', isset($note_private) ? $note_private : GETPOST('note_private','none'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%');
1599  print $doleditor->Create(1);
1600  print '</td>';
1601  //print '<td><textarea name="note_private" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
1602  print '</tr>';
1603 
1604  if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) {
1605 
1606  print "\n<!-- " . $classname . " info -->";
1607  print "\n";
1608  print '<input type="hidden" name="amount" value="' . $objectsrc->total_ht . '">' . "\n";
1609  print '<input type="hidden" name="total" value="' . $objectsrc->total_ttc . '">' . "\n";
1610  print '<input type="hidden" name="tva" value="' . $objectsrc->total_tva . '">' . "\n";
1611  print '<input type="hidden" name="origin" value="' . $objectsrc->element . '">';
1612  print '<input type="hidden" name="originid" value="' . $objectsrc->id . '">';
1613 
1614  $newclassname = $classname;
1615  print '<tr><td>' . $langs->trans($newclassname) . '</td><td colspan="2">' . $objectsrc->getNomUrl(1) . '</td></tr>';
1616  print '<tr><td>' . $langs->trans('TotalHT') . '</td><td colspan="2">' . price($objectsrc->total_ht) . '</td></tr>';
1617  print '<tr><td>' . $langs->trans('TotalVAT') . '</td><td colspan="2">' . price($objectsrc->total_tva) . "</td></tr>";
1618  if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE
1619  {
1620  print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td><td colspan="2">' . price($objectsrc->total_localtax1) . "</td></tr>";
1621  }
1622 
1623  if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF
1624  {
1625  print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td><td colspan="2">' . price($objectsrc->total_localtax2) . "</td></tr>";
1626  }
1627 
1628  print '<tr><td>' . $langs->trans('TotalTTC') . '</td><td colspan="2">' . price($objectsrc->total_ttc) . "</td></tr>";
1629 
1630  if (!empty($conf->multicurrency->enabled))
1631  {
1632  print '<tr><td>' . $langs->trans('MulticurrencyTotalHT') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_ht) . '</td></tr>';
1633  print '<tr><td>' . $langs->trans('MulticurrencyTotalVAT') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_tva) . '</td></tr>';
1634  print '<tr><td>' . $langs->trans('MulticurrencyTotalTTC') . '</td><td colspan="2">' . price($objectsrc->multicurrency_total_ttc) . '</td></tr>';
1635  }
1636  }
1637 
1638  // Other options
1639  $parameters=array();
1640  $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
1641  print $hookmanager->resPrint;
1642 
1643  if (empty($reshook))
1644  {
1645  print $object->showOptionals($extrafields,'edit');
1646  }
1647 
1648  // Bouton "Create Draft"
1649  print "</table>\n";
1650 
1651  dol_fiche_end();
1652 
1653  print '<div class="center">';
1654  print '<input type="submit" class="button" name="bouton" value="'.$langs->trans('CreateDraft').'">';
1655  print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1656  print '<input type="button" class="button" value="' . $langs->trans("Cancel") . '" onClick="javascript:history.go(-1)">';
1657  print '</div>';
1658 
1659  print "</form>\n";
1660 
1661  // Show origin lines
1662  if (! empty($origin) && ! empty($originid) && is_object($objectsrc))
1663  {
1664  $title = $langs->trans('ProductsAndServices');
1665  print load_fiche_titre($title);
1666 
1667  print '<table class="noborder" width="100%">';
1668 
1669  $objectsrc->printOriginLinesList();
1670 
1671  print '</table>';
1672  }
1673 }
1674 elseif (! empty($object->id))
1675 {
1676  $result = $object->fetch($id, $ref);
1677 
1678  $societe = new Fournisseur($db);
1679  $result=$societe->fetch($object->socid);
1680  if ($result < 0) dol_print_error($db);
1681 
1682  $author = new User($db);
1683  $author->fetch($object->user_author_id);
1684 
1685  $res=$object->fetch_optionals();
1686 
1687 
1688  $head = ordersupplier_prepare_head($object);
1689 
1690  $title=$langs->trans("SupplierOrder");
1691  dol_fiche_head($head, 'card', $title, -1, 'order');
1692 
1693 
1694  $formconfirm='';
1695 
1696  // Confirmation de la suppression de la commande
1697  if ($action == 'delete')
1698  {
1699  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteOrder'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 2);
1700  }
1701 
1702  // Clone confirmation
1703  if ($action == 'clone')
1704  {
1705  // Create an array for form
1706  $formquestion=array(
1707  //array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1)
1708  );
1709  // Paiement incomplet. On demande si motif = escompte ou autre
1710  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneOrder'),$langs->trans('ConfirmCloneOrder',$object->ref),'confirm_clone',$formquestion,'yes',1);
1711  }
1712 
1713  // Confirmation de la validation
1714  if ($action == 'valid')
1715  {
1716  $object->date_commande=dol_now();
1717 
1718  // We check if number is temporary number
1719  if (preg_match('/^[\(]?PROV/i',$object->ref) || empty($object->ref)) // empty should not happened, but when it occurs, the test save life
1720  {
1721  $newref = $object->getNextNumRef($object->thirdparty);
1722  }
1723  else $newref = $object->ref;
1724 
1725  if ($newref < 0)
1726  {
1727  setEventMessages($object->error, $object->errors, 'errors');
1728  $action='';
1729  }
1730  else
1731  {
1732  $text=$langs->trans('ConfirmValidateOrder',$newref);
1733  if (! empty($conf->notification->enabled))
1734  {
1735  require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php';
1736  $notify=new Notify($db);
1737  $text.='<br>';
1738  $text.=$notify->confirmMessage('ORDER_SUPPLIER_VALIDATE', $object->socid, $object);
1739  }
1740 
1741  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateOrder'), $text, 'confirm_valid', '', 0, 1);
1742  }
1743  }
1744 
1745  // Confirm approval
1746  if ($action == 'approve' || $action == 'approve2')
1747  {
1748  $qualified_for_stock_change=0;
1749  if (empty($conf->global->STOCK_SUPPORTS_SERVICES))
1750  {
1751  $qualified_for_stock_change=$object->hasProductsOrServices(2);
1752  }
1753  else
1754  {
1755  $qualified_for_stock_change=$object->hasProductsOrServices(1);
1756  }
1757 
1758  $formquestion=array();
1759  if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change)
1760  {
1761  $langs->load("stocks");
1762  require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
1763  $formproduct=new FormProduct($db);
1764  $forcecombo=0;
1765  if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
1766  $formquestion=array(
1767  //'text' => $langs->trans("ConfirmClone"),
1768  //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
1769  //array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
1770  array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse','int'), 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
1771  );
1772  }
1773  $text=$langs->trans("ConfirmApproveThisOrder",$object->ref);
1774  if (! empty($conf->notification->enabled))
1775  {
1776  require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php';
1777  $notify=new Notify($db);
1778  $text.='<br>';
1779  $text.=$notify->confirmMessage('ORDER_SUPPLIER_APPROVE', $object->socid, $object);
1780  }
1781 
1782  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ApproveThisOrder"), $text, "confirm_".$action, $formquestion, 1, 1, 240);
1783  }
1784 
1785  // Confirmation de la desapprobation
1786  if ($action == 'refuse')
1787  {
1788  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id",$langs->trans("DenyingThisOrder"),$langs->trans("ConfirmDenyingThisOrder",$object->ref),"confirm_refuse", '', 0, 1);
1789  }
1790 
1791  // Confirmation de l'annulation
1792  if ($action == 'cancel')
1793  {
1794  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id",$langs->trans("Cancel"),$langs->trans("ConfirmCancelThisOrder",$object->ref),"confirm_cancel", '', 0, 1);
1795  }
1796 
1797  // Confirmation de l'envoi de la commande
1798  if ($action == 'commande')
1799  {
1800  $date_com = dol_mktime(GETPOST('rehour'),GETPOST('remin'),GETPOST('resec'),GETPOST("remonth"),GETPOST("reday"),GETPOST("reyear"));
1801  $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id."&datecommande=".$date_com."&methode=".$_POST["methodecommande"]."&comment=".urlencode($_POST["comment"]), $langs->trans("MakeOrder"),$langs->trans("ConfirmMakeOrder",dol_print_date($date_com,'day')),"confirm_commande",'',0,2);
1802  }
1803 
1804  // Confirmation to delete line
1805  if ($action == 'ask_deleteline')
1806  {
1807  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1);
1808  }
1809 
1810  if (!$formconfirm)
1811  {
1812  $parameters=array('lineid'=>$lineid);
1813  $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1814  if (empty($reshook)) $formconfirm.=$hookmanager->resPrint;
1815  elseif ($reshook > 0) $formconfirm=$hookmanager->resPrint;
1816  }
1817 
1818  // Print form confirm
1819  print $formconfirm;
1820 
1821 
1822  // Supplier order card
1823 
1824  $linkback = '<a href="'.DOL_URL_ROOT.'/fourn/commande/list.php?restore_lastsearch_values=1'.(! empty($socid)?'&socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
1825 
1826  $morehtmlref='<div class="refidno">';
1827  // Ref supplier
1828  $morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->commande->creer, 'string', '', 0, 1);
1829  $morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->fournisseur->commande->creer, 'string', '', null, null, '', 1);
1830  // Thirdparty
1831  $morehtmlref.='<br>'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1);
1832  if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref.=' (<a href="'.DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherOrders").'</a>)';
1833  // Project
1834  if (! empty($conf->projet->enabled))
1835  {
1836  $langs->load("projects");
1837  $morehtmlref.='<br>'.$langs->trans('Project') . ' ';
1838  if ($user->rights->fournisseur->commande->creer)
1839  {
1840  if ($action != 'classify')
1841  $morehtmlref.='<a href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : ';
1842  if ($action == 'classify') {
1843  //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
1844  $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
1845  $morehtmlref.='<input type="hidden" name="action" value="classin">';
1846  $morehtmlref.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1847  $morehtmlref.=$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS)?$object->socid:-1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
1848  $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
1849  $morehtmlref.='</form>';
1850  } else {
1851  $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
1852  }
1853  } else {
1854  if (! empty($object->fk_project)) {
1855  $proj = new Project($db);
1856  $proj->fetch($object->fk_project);
1857  $morehtmlref.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">';
1858  $morehtmlref.=$proj->ref;
1859  $morehtmlref.='</a>';
1860  } else {
1861  $morehtmlref.='';
1862  }
1863  }
1864  }
1865  $morehtmlref.='</div>';
1866 
1867 
1868  dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
1869 
1870 
1871  print '<div class="fichecenter">';
1872  print '<div class="fichehalfleft">';
1873  print '<div class="underbanner clearboth"></div>';
1874 
1875  print '<table class="border" width="100%">';
1876 
1877  // Date
1878  if ($object->methode_commande_id > 0)
1879  {
1880  print '<tr><td class="titlefield">'.$langs->trans("Date").'</td><td>';
1881  if ($object->date_commande)
1882  {
1883  print dol_print_date($object->date_commande,"dayhourtext")."\n";
1884  }
1885  print "</td></tr>";
1886 
1887  if ($object->methode_commande)
1888  {
1889  print '<tr><td>'.$langs->trans("Method").'</td><td>'.$object->getInputMethod().'</td></tr>';
1890  }
1891  }
1892 
1893  // Author
1894  print '<tr><td class="titlefield">'.$langs->trans("AuthorRequest").'</td>';
1895  print '<td>'.$author->getNomUrl(1, '', 0, 0, 0).'</td>';
1896  print '</tr>';
1897 
1898  // Relative and absolute discounts
1899  if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
1900  $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
1901  $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
1902  } else {
1903  $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')";
1904  $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')";
1905  }
1906 
1907  $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1);
1908  $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1);
1909  $absolute_discount = price2num($absolute_discount, 'MT');
1910  $absolute_creditnote = price2num($absolute_creditnote, 'MT');
1911 
1912  print '<tr><td class="titlefield">' . $langs->trans('Discounts') . '</td><td>';
1913 
1914  $thirdparty = $societe;
1915  $discount_type = 1;
1916  $backtopage = urlencode($_SERVER["PHP_SELF"] . '?id=' . $object->id);
1917  include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
1918 
1919  print '</td></tr>';
1920 
1921  // Conditions de reglement par defaut
1922  $langs->load('bills');
1923  print '<tr><td class="nowrap">';
1924  print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
1925  print $langs->trans('PaymentConditions');
1926  print '<td>';
1927  if ($action != 'editconditions') print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;id='.$object->id.'">'.img_edit($langs->trans('SetConditions'),1).'</a></td>';
1928  print '</tr></table>';
1929  print '</td><td>';
1930  if ($action == 'editconditions')
1931  {
1932  $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id,'cond_reglement_id');
1933  }
1934  else
1935  {
1936  $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id,'none');
1937  }
1938  print "</td>";
1939  print '</tr>';
1940 
1941  // Mode of payment
1942  $langs->load('bills');
1943  print '<tr><td class="nowrap">';
1944  print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
1945  print $langs->trans('PaymentMode');
1946  print '</td>';
1947  if ($action != 'editmode') print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->trans('SetMode'),1).'</a></td>';
1948  print '</tr></table>';
1949  print '</td><td>';
1950  if ($action == 'editmode')
1951  {
1952  $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->mode_reglement_id,'mode_reglement_id','DBIT', 1, 1);
1953  }
1954  else
1955  {
1956  $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->mode_reglement_id,'none');
1957  }
1958  print '</td></tr>';
1959 
1960  // Multicurrency
1961  if (! empty($conf->multicurrency->enabled))
1962  {
1963  // Multicurrency code
1964  print '<tr>';
1965  print '<td>';
1966  print '<table class="nobordernopadding" width="100%"><tr><td>';
1967  print fieldLabel('Currency','multicurrency_code');
1968  print '</td>';
1969  if ($action != 'editmulticurrencycode' && ! empty($object->brouillon))
1970  print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencycode&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
1971  print '</tr></table>';
1972  print '</td><td>';
1973  if ($action == 'editmulticurrencycode') {
1974  $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'multicurrency_code');
1975  } else {
1976  $form->form_multicurrency_code($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_code, 'none');
1977  }
1978  print '</td></tr>';
1979 
1980  // Multicurrency rate
1981  print '<tr>';
1982  print '<td>';
1983  print '<table class="nobordernopadding" width="100%"><tr><td>';
1984  print fieldLabel('CurrencyRate','multicurrency_tx');
1985  print '</td>';
1986  if ($action != 'editmulticurrencyrate' && ! empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency)
1987  print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editmulticurrencyrate&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1) . '</a></td>';
1988  print '</tr></table>';
1989  print '</td><td>';
1990  if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
1991  if($action == 'actualizemulticurrencyrate') {
1992  list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
1993  }
1994  $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
1995  } else {
1996  $form->form_multicurrency_rate($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
1997  if($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
1998  print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
1999  print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
2000  print '</div>';
2001  }
2002  }
2003  print '</td></tr>';
2004  }
2005 
2006  // Bank Account
2007  if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && ! empty($conf->banque->enabled))
2008  {
2009  print '<tr><td class="nowrap">';
2010  print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
2011  print $langs->trans('BankAccount');
2012  print '<td>';
2013  if ($action != 'editbankaccount' && $user->rights->fournisseur->commande->creer)
2014  print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'),1).'</a></td>';
2015  print '</tr></table>';
2016  print '</td><td>';
2017  if ($action == 'editbankaccount') {
2018  $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
2019  } else {
2020  $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
2021  }
2022  print '</td>';
2023  print '</tr>';
2024  }
2025 
2026  // Delivery date planed
2027  print '<tr><td>';
2028  print '<table class="nobordernopadding" width="100%"><tr><td>';
2029  print $langs->trans('DateDeliveryPlanned');
2030  print '</td>';
2031  if ($action != 'editdate_livraison') print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editdate_livraison&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDeliveryDate'),1).'</a></td>';
2032  print '</tr></table>';
2033  print '</td><td>';
2034  if ($action == 'editdate_livraison')
2035  {
2036  print '<form name="setdate_livraison" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
2037  print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2038  print '<input type="hidden" name="action" value="setdate_livraison">';
2039  $usehourmin=0;
2040  if (! empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin=1;
2041  print $form->selectDate($object->date_livraison?$object->date_livraison:-1, 'liv_', $usehourmin, $usehourmin, '', "setdate_livraison");
2042  print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">';
2043  print '</form>';
2044  }
2045  else
2046  {
2047  $usehourmin='day';
2048  if (! empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin='dayhour';
2049  print $object->date_livraison ? dol_print_date($object->date_livraison, $usehourmin) : '&nbsp;';
2050  if ($object->hasDelay() && ! empty($object->date_livraison)) {
2051  print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning");
2052  }
2053  }
2054  print '</td></tr>';
2055 
2056  // Delivery delay (in days)
2057  print '<tr>';
2058  print '<td>'.$langs->trans('NbDaysToDelivery').'&nbsp;'.img_picto($langs->trans('DescNbDaysToDelivery'), 'info', 'style="cursor:help"').'</td>';
2059  print '<td>'.$object->getMaxDeliveryTimeDay($langs).'</td>';
2060  print '</tr>';
2061 
2062  // Incoterms
2063  if (!empty($conf->incoterm->enabled))
2064  {
2065  print '<tr><td>';
2066  print '<table width="100%" class="nobordernopadding"><tr><td>';
2067  print $langs->trans('IncotermLabel');
2068  print '<td><td align="right">';
2069  if ($user->rights->fournisseur->commande->creer) print '<a href="'.DOL_URL_ROOT.'/fourn/commande/card.php?id='.$object->id.'&action=editincoterm">'.img_edit().'</a>';
2070  else print '&nbsp;';
2071  print '</td></tr></table>';
2072  print '</td>';
2073  print '<td>';
2074  if ($action != 'editincoterm')
2075  {
2076  print $form->textwithpicto($object->display_incoterms(), $object->libelle_incoterms, 1);
2077  }
2078  else
2079  {
2080  print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms)?$object->location_incoterms:''), $_SERVER['PHP_SELF'].'?id='.$object->id);
2081  }
2082  print '</td></tr>';
2083  }
2084 
2085  // Other attributes
2086  include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
2087 
2088  print '</table>';
2089 
2090  print '</div>';
2091  print '<div class="fichehalfright">';
2092  print '<div class="ficheaddleft">';
2093  print '<div class="underbanner clearboth"></div>';
2094 
2095  print '<table class="border centpercent">';
2096 
2097  if (!empty($conf->multicurrency->enabled))
2098  {
2099  // Multicurrency Amount HT
2100  print '<tr><td class="titlefieldmiddle">' . fieldLabel('MulticurrencyAmountHT','multicurrency_total_ht') . '</td>';
2101  print '<td class="nowrap">' . price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
2102  print '</tr>';
2103 
2104  // Multicurrency Amount VAT
2105  print '<tr><td>' . fieldLabel('MulticurrencyAmountVAT','multicurrency_total_tva') . '</td>';
2106  print '<td class="nowrap">' . price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
2107  print '</tr>';
2108 
2109  // Multicurrency Amount TTC
2110  print '<tr><td>' . fieldLabel('MulticurrencyAmountTTC','multicurrency_total_ttc') . '</td>';
2111  print '<td class="nowrap">' . price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td>';
2112  print '</tr>';
2113  }
2114 
2115  // Total
2116  $alert = '';
2117  if (! empty($conf->global->ORDER_MANAGE_MIN_AMOUNT) && $object->total_ht < $object->thirdparty->supplier_order_min_amount) {
2118  $alert = ' ' . img_warning($langs->trans('OrderMinAmount').': '.price($object->thirdparty->supplier_order_min_amount));
2119  }
2120  print '<tr><td class="titlefieldmiddle">'.$langs->trans("AmountHT").'</td>';
2121  print '<td>'.price($object->total_ht,'',$langs,1,-1,-1,$conf->currency).$alert.'</td>';
2122  print '</tr>';
2123 
2124  // Total VAT
2125  print '<tr><td>'.$langs->trans("AmountVAT").'</td><td>'.price($object->total_tva,'',$langs,1,-1,-1,$conf->currency).'</td>';
2126  print '</tr>';
2127 
2128  // Amount Local Taxes
2129  if ($mysoc->localtax1_assuj=="1" || $object->total_localtax1 != 0) //Localtax1
2130  {
2131  print '<tr><td>'.$langs->transcountry("AmountLT1",$mysoc->country_code).'</td>';
2132  print '<td>'.price($object->total_localtax1,'',$langs,1,-1,-1,$conf->currency).'</td>';
2133  print '</tr>';
2134  }
2135  if ($mysoc->localtax2_assuj=="1" || $object->total_localtax2 != 0) //Localtax2
2136  {
2137  print '<tr><td>'.$langs->transcountry("AmountLT2",$mysoc->country_code).'</td>';
2138  print '<td>'.price($object->total_localtax2,'',$langs,1,-1,-1,$conf->currency).'</td>';
2139  print '</tr>';
2140  }
2141 
2142  // Total TTC
2143  print '<tr><td>'.$langs->trans("AmountTTC").'</td><td>'.price($object->total_ttc,'',$langs,1,-1,-1,$conf->currency).'</td>';
2144  print '</tr>';
2145 
2146  print '</table>';
2147 
2148  // Margin Infos
2149  /*if (! empty($conf->margin->enabled)) {
2150  $formmargin->displayMarginInfos($object);
2151  }*/
2152 
2153 
2154  print '</div>';
2155  print '</div>';
2156  print '</div>';
2157 
2158  print '<div class="clearboth"></div><br>';
2159 
2160  if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
2161  {
2162  $blocname = 'contacts';
2163  $title = $langs->trans('ContactsAddresses');
2164  include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
2165  }
2166 
2167  if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
2168  {
2169  $blocname = 'notes';
2170  $title = $langs->trans('Notes');
2171  include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
2172  }
2173 
2174  /*
2175  * Lines
2176  */
2177  //$result = $object->getLinesArray();
2178 
2179 
2180  print ' <form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline')?'#addline':'#line_'.GETPOST('lineid')).'" method="POST">
2181  <input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">
2182  <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline') . '">
2183  <input type="hidden" name="mode" value="">
2184  <input type="hidden" name="id" value="'.$object->id.'">
2185  <input type="hidden" name="socid" value="'.$societe->id.'">
2186  ';
2187 
2188  if (! empty($conf->use_javascript_ajax) && $object->statut == 0) {
2189  include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
2190  }
2191 
2192  print '<div class="div-table-responsive-no-min">';
2193  print '<table id="tablelines" class="noborder noshadow" width="100%">';
2194 
2195  // Add free products/services form
2196  global $forceall, $senderissupplier, $dateSelector;
2197  $forceall=1; $dateSelector=0;
2198  $senderissupplier=2; // $senderissupplier=2 is same than 1 but disable test on minimum qty and disable autofill qty with minimum.
2199  //if (! empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED)) $senderissupplier=2;
2200  if (! empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) $senderissupplier=1;
2201 
2202  // Show object lines
2203  $inputalsopricewithtax=0;
2204  if (! empty($object->lines))
2205  $ret = $object->printObjectLines($action, $societe, $mysoc, $lineid, 1);
2206 
2207  $num = count($object->lines);
2208 
2209  // Form to add new line
2210  if ($object->statut == CommandeFournisseur::STATUS_DRAFT && $user->rights->fournisseur->commande->creer)
2211  {
2212  if ($action != 'editline')
2213  {
2214  // Add free products/services
2215  $object->formAddObjectLine(1, $societe, $mysoc);
2216 
2217  $parameters = array();
2218  $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2219  }
2220  }
2221  print '</table>';
2222  print '</div>';
2223  print '</form>';
2224 
2225  dol_fiche_end();
2226 
2231  if ($user->societe_id == 0 && $action != 'editline' && $action != 'delete')
2232  {
2233  print '<div class="tabsAction">';
2234 
2235  $parameters = array();
2236  $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
2237  // modified by hook
2238  if (empty($reshook))
2239  {
2240  $object->fetchObjectLinked(); // Links are used to show or not button, so we load them now.
2241 
2242  // Validate
2243  if ($object->statut == 0 && $num > 0)
2244  {
2245  if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->commande->creer))
2246  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->fournisseur->supplier_order_advance->validate)))
2247  {
2248  $tmpbuttonlabel=$langs->trans('Validate');
2249  if ($user->rights->fournisseur->commande->approuver && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE)) $tmpbuttonlabel = $langs->trans("ValidateAndApprove");
2250 
2251  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid">';
2252  print $tmpbuttonlabel;
2253  print '</a>';
2254  }
2255  }
2256  // Create event
2257  /*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page.
2258  {
2259  print '<div class="inline-block divButAction"><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></div>';
2260  }*/
2261 
2262  // Modify
2263  if ($object->statut == 1)
2264  {
2265  if ($user->rights->fournisseur->commande->commander)
2266  {
2267  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Modify").'</a>';
2268  }
2269  }
2270 
2271  // Approve
2272  if ($object->statut == 1)
2273  {
2274  if ($user->rights->fournisseur->commande->approuver)
2275  {
2276  if (! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED && ! empty($object->user_approve_id))
2277  {
2278  print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("FirstApprovalAlreadyDone")).'">'.$langs->trans("ApproveOrder").'</a>';
2279  }
2280  else
2281  {
2282  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=approve">'.$langs->trans("ApproveOrder").'</a>';
2283  }
2284  }
2285  else
2286  {
2287  print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("ApproveOrder").'</a>';
2288  }
2289  }
2290 
2291  // Second approval (if option SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set)
2292  if (! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)
2293  {
2294  if ($object->statut == 1)
2295  {
2296  if ($user->rights->fournisseur->commande->approve2)
2297  {
2298  if (! empty($object->user_approve_id2))
2299  {
2300  print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("SecondApprovalAlreadyDone")).'">'.$langs->trans("Approve2Order").'</a>';
2301  }
2302  else
2303  {
2304  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=approve2">'.$langs->trans("Approve2Order").'</a>';
2305  }
2306  }
2307  else
2308  {
2309  print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("Approve2Order").'</a>';
2310  }
2311  }
2312  }
2313 
2314  // Refuse
2315  if ($object->statut == 1)
2316  {
2317  if ($user->rights->fournisseur->commande->approuver || $user->rights->fournisseur->commande->approve2)
2318  {
2319  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=refuse">'.$langs->trans("RefuseOrder").'</a>';
2320  }
2321  else
2322  {
2323  print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("RefuseOrder").'</a>';
2324  }
2325  }
2326 
2327  // Send
2328  if (in_array($object->statut, array(2, 3, 4, 5)))
2329  {
2330  if ($user->rights->fournisseur->commande->commander)
2331  {
2332  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>';
2333  }
2334  }
2335 
2336  // Reopen
2337  if (in_array($object->statut, array(2)))
2338  {
2339  $buttonshown=0;
2340  if (! $buttonshown && $user->rights->fournisseur->commande->approuver)
2341  {
2342  if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY)
2343  || (! empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) && $user->id == $object->user_approve_id))
2344  {
2345  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Disapprove").'</a>';
2346  $buttonshown++;
2347  }
2348  }
2349  if (! $buttonshown && $user->rights->fournisseur->commande->approve2 && ! empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED))
2350  {
2351  if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY)
2352  || (! empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) && $user->id == $object->user_approve_id2))
2353  {
2354  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Disapprove").'</a>';
2355  }
2356  }
2357  }
2358  if (in_array($object->statut, array(3, 4, 5, 6, 7, 9)))
2359  {
2360  if ($user->rights->fournisseur->commande->commander)
2361  {
2362  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("ReOpen").'</a>';
2363  }
2364  }
2365 
2366  // Ship
2367  if (! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER))
2368  {
2369  if (in_array($object->statut, array(3,4,5))) {
2370  if ($conf->fournisseur->enabled && $user->rights->fournisseur->commande->receptionner) {
2371  print '<div class="inline-block divButAction"><a class="butAction" href="' . DOL_URL_ROOT . '/fourn/commande/dispatch.php?id=' . $object->id . '">' . $langs->trans('ReceiveProducts') . '</a></div>';
2372  } else {
2373  print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="' . dol_escape_htmltag($langs->trans("NotAllowed")) . '">' . $langs->trans('ReceiveProducts') . '</a></div>';
2374  }
2375  }
2376  }
2377 
2378  if ($object->statut == 2)
2379  {
2380  if ($user->rights->fournisseur->commande->commander)
2381  {
2382  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=makeorder#makeorder">'.$langs->trans("MakeOrder").'</a></div>';
2383  }
2384  else
2385  {
2386  print '<div class="inline-block divButAction"><a class="butActionRefused" href="#">'.$langs->trans("MakeOrder").'</a></div>';
2387  }
2388  }
2389 
2390  // Create bill
2391  if (! empty($conf->facture->enabled))
2392  {
2393  if (! empty($conf->fournisseur->enabled) && ($object->statut >= 2 && $object->statut != 7 && $object->billed != 1)) // statut 2 means approved, 7 means canceled
2394  {
2395  if ($user->rights->fournisseur->facture->creer)
2396  {
2397  print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("CreateBill").'</a>';
2398  }
2399  }
2400  }
2401 
2402  // Classify billed manually (need one invoice if module invoice is on, no condition on invoice if not)
2403  if ($user->rights->fournisseur->commande->creer && $object->statut >= 2 && $object->statut != 7 && $object->billed != 1) // statut 2 means approved
2404  {
2405  if (empty($conf->facture->enabled))
2406  {
2407  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifybilled">'.$langs->trans("ClassifyBilled").'</a>';
2408  }
2409  else if (!empty($object->linkedObjectsIds['invoice_supplier']))
2410  {
2411  if ($user->rights->fournisseur->facture->creer)
2412  {
2413  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifybilled">'.$langs->trans("ClassifyBilled").'</a>';
2414  }
2415  }
2416  }
2417 
2418  // Create a remote order using WebService only if module is activated
2419  if (! empty($conf->syncsupplierwebservices->enabled) && $object->statut >= 2) // 2 means accepted
2420  {
2421  print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=webservice&amp;mode=init">'.$langs->trans('CreateRemoteOrder').'</a>';
2422  }
2423 
2424  // Clone
2425  if ($user->rights->fournisseur->commande->creer)
2426  {
2427  print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$object->socid.'&amp;action=clone&amp;object=order">'.$langs->trans("ToClone").'</a>';
2428  }
2429 
2430  // Cancel
2431  if ($object->statut == 2)
2432  {
2433  if ($user->rights->fournisseur->commande->commander)
2434  {
2435  print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=cancel">'.$langs->trans("CancelOrder").'</a>';
2436  }
2437  }
2438 
2439  // Delete
2440  if ($user->rights->fournisseur->commande->supprimer)
2441  {
2442  print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete">'.$langs->trans("Delete").'</a>';
2443  }
2444  }
2445 
2446  print "</div>";
2447 
2448 
2449 
2450  if ($user->rights->fournisseur->commande->commander && $object->statut == 2 && $action == 'makeorder')
2451  {
2452  // Set status to ordered (action=commande)
2453  print '<!-- form to record supplier order -->'."\n";
2454  print '<form name="commande" id="makeorder" action="card.php?id='.$object->id.'&amp;action=commande" method="post">';
2455 
2456  print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2457  print '<input type="hidden" name="action" value="commande">';
2458  print load_fiche_titre($langs->trans("ToOrder"),'','');
2459  print '<table class="noborder" width="100%">';
2460  //print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("ToOrder").'</td></tr>';
2461  print '<tr><td>'.$langs->trans("OrderDate").'</td><td>';
2462  $date_com = dol_mktime(GETPOST('rehour','int'), GETPOST('remin','int'), GETPOST('resec','int'), GETPOST('remonth','int'), GETPOST('reday','int'), GETPOST('reyear','int'));
2463  if (empty($date_com)) $date_com=dol_now();
2464  print $form->selectDate($date_com, '', 1, 1, '', "commande", 1, 1);
2465  print '</td></tr>';
2466 
2467  print '<tr><td>'.$langs->trans("OrderMode").'</td><td>';
2468  $formorder->selectInputMethod(GETPOST('methodecommande'), "methodecommande", 1);
2469  print '</td></tr>';
2470 
2471  print '<tr><td>'.$langs->trans("Comment").'</td><td><input size="40" type="text" name="comment" value="'.GETPOST('comment').'"></td></tr>';
2472  print '<tr><td align="center" colspan="2">';
2473  print '<input type="submit" name="makeorder" class="button" value="'.$langs->trans("ToOrder").'">';
2474  print ' &nbsp; &nbsp; ';
2475  print '<input type="submit" name="cancel" class="button" value="'.$langs->trans("Cancel").'">';
2476  print '</td></tr>';
2477  print '</table>';
2478 
2479  print '</form>';
2480  print "<br>";
2481  }
2482 
2483  if ($action != 'makeorder')
2484  {
2485  print '<div class="fichecenter"><div class="fichehalfleft">';
2486 
2487  /*
2488  * Documents generes
2489  */
2490  $comfournref = dol_sanitizeFileName($object->ref);
2491  $file = $conf->fournisseur->dir_output . '/commande/' . $comfournref . '/' . $comfournref . '.pdf';
2492  $relativepath = $comfournref.'/'.$comfournref.'.pdf';
2493  $filedir = $conf->fournisseur->dir_output . '/commande/' . $comfournref;
2494  $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id;
2495  $genallowed=$user->rights->fournisseur->commande->lire;
2496  $delallowed=$user->rights->fournisseur->commande->creer;
2497 
2498  print $formfile->showdocuments('commande_fournisseur',$comfournref,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,0,0,'','','',$object->thirdparty->default_lang);
2499  $somethingshown=$formfile->numoffiles;
2500 
2501  // Show links to link elements
2502  $linktoelem = $form->showLinkToObjectBlock($object, null, array('supplier_order','order_supplier'));
2503  $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
2504 
2505  print '</div><div class="fichehalfright"><div class="ficheaddleft">';
2506 
2507  if ($user->rights->fournisseur->commande->receptionner && ($object->statut == 3 || $object->statut == 4))
2508  {
2509  // Set status to received (action=livraison)
2510  print '<!-- form to record supplier order received -->'."\n";
2511  print '<form action="card.php?id='.$object->id.'" method="post">';
2512  print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2513  print '<input type="hidden" name="action" value="livraison">';
2514  print load_fiche_titre($langs->trans("Receive"),'','');
2515 
2516  print '<table class="noborder" width="100%">';
2517  //print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Receive").'</td></tr>';
2518  print '<tr><td>'.$langs->trans("DeliveryDate").'</td><td>';
2519  $datepreselected = dol_now();
2520  print $form->selectDate($datepreselected, '', 1, 1, '', "commande", 1, 1);
2521  print "</td></tr>\n";
2522 
2523  print "<tr><td class=\"fieldrequired\">".$langs->trans("Delivery")."</td><td>\n";
2524  $liv = array();
2525  $liv[''] = '&nbsp;';
2526  $liv['tot'] = $langs->trans("CompleteOrNoMoreReceptionExpected");
2527  $liv['par'] = $langs->trans("PartialWoman");
2528  $liv['nev'] = $langs->trans("NeverReceived");
2529  $liv['can'] = $langs->trans("Canceled");
2530 
2531  print $form->selectarray("type",$liv);
2532 
2533  print '</td></tr>';
2534  print '<tr><td>'.$langs->trans("Comment").'</td><td><input size="40" type="text" name="comment"></td></tr>';
2535  print '<tr><td align="center" colspan="2"><input type="submit" class="button" value="'.$langs->trans("Receive").'"></td></tr>';
2536  print "</table>\n";
2537  print "</form>\n";
2538  print "<br>";
2539  }
2540 
2541  // List of actions on element
2542  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
2543  $formactions=new FormActions($db);
2544  $somethingshown = $formactions->showactions($object,'order_supplier',$socid,1,'listaction'.($genallowed?'largetitle':''));
2545 
2546  print '</div></div></div>';
2547  }
2548 
2549  /*
2550  * Action webservice
2551  */
2552  if ($action == 'webservice' && GETPOST('mode', 'alpha') != "send" && ! GETPOST('cancel','alpha'))
2553  {
2554  $mode = GETPOST('mode', 'alpha');
2555  $ws_url = $object->thirdparty->webservices_url;
2556  $ws_key = $object->thirdparty->webservices_key;
2557  $ws_user = GETPOST('ws_user','alpha');
2558  $ws_password = GETPOST('ws_password','alpha');
2559 
2560  // NS and Authentication parameters
2561  $ws_ns = 'http://www.dolibarr.org/ns/';
2562  $ws_authentication = array(
2563  'dolibarrkey'=>$ws_key,
2564  'sourceapplication'=>'DolibarrWebServiceClient',
2565  'login'=>$ws_user,
2566  'password'=>$ws_password,
2567  'entity'=>''
2568  );
2569 
2570  print load_fiche_titre($langs->trans('CreateRemoteOrder'),'');
2571 
2572  //Is everything filled?
2573  if (empty($ws_url) || empty($ws_key)) {
2574  setEventMessages($langs->trans("ErrorWebServicesFieldsRequired"), null, 'errors');
2575  $mode = "init";
2576  $error_occurred = true; //Don't allow to set the user/pass if thirdparty fields are not filled
2577  } else if ($mode != "init" && (empty($ws_user) || empty($ws_password))) {
2578  setEventMessages($langs->trans("ErrorFieldsRequired"), null, 'errors');
2579  $mode = "init";
2580  }
2581 
2582  if ($mode == "init")
2583  {
2584  //Table/form header
2585  print '<table class="border" width="100%">';
2586  print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
2587  print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2588  print '<input type="hidden" name="action" value="webservice">';
2589  print '<input type="hidden" name="mode" value="check">';
2590 
2591  if ($error_occurred)
2592  {
2593  print "<br>".$langs->trans("ErrorOccurredReviseAndRetry")."<br>";
2594  print '<input class="button" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
2595  }
2596  else
2597  {
2598  $textinput_size = "50";
2599  // Webservice url
2600  print '<tr><td>'.$langs->trans("WebServiceURL").'</td><td colspan="3">'.dol_print_url($ws_url).'</td></tr>';
2601  //Remote User
2602  print '<tr><td>'.$langs->trans("User").'</td><td><input size="'.$textinput_size.'" type="text" name="ws_user"></td></tr>';
2603  //Remote Password
2604  print '<tr><td>'.$langs->trans("Password").'</td><td><input size="'.$textinput_size.'" type="text" name="ws_password"></td></tr>';
2605  //Submit button
2606  print '<tr><td align="center" colspan="2">';
2607  print '<input class="button" type="submit" id="ws_submit" name="ws_submit" value="'.$langs->trans("CreateRemoteOrder").'">';
2608  print ' &nbsp; &nbsp; ';
2609  //Cancel button
2610  print '<input class="button" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
2611  print '</td></tr>';
2612  }
2613 
2614  //End table/form
2615  print '</form>';
2616  print '</table>';
2617  }
2618  elseif ($mode == "check")
2619  {
2620  $ws_entity = '';
2621  $ws_thirdparty = '';
2622  $error_occurred = false;
2623 
2624  //Create SOAP client and connect it to user
2625  $soapclient_user = new nusoap_client($ws_url."/webservices/server_user.php");
2626  $soapclient_user->soap_defencoding='UTF-8';
2627  $soapclient_user->decodeUTF8(false);
2628 
2629  //Get the thirdparty associated to user
2630  $ws_parameters = array('authentication'=>$ws_authentication, 'id' => '', 'ref'=>$ws_user);
2631  $result_user = $soapclient_user->call("getUser", $ws_parameters, $ws_ns, '');
2632  $user_status_code = $result_user["result"]["result_code"];
2633 
2634  if ($user_status_code == "OK")
2635  {
2636  //Fill the variables
2637  $ws_entity = $result_user["user"]["entity"];
2638  $ws_authentication['entity'] = $ws_entity;
2639  $ws_thirdparty = $result_user["user"]["fk_thirdparty"];
2640  if (empty($ws_thirdparty))
2641  {
2642  setEventMessages($langs->trans("RemoteUserMissingAssociatedSoc"), null, 'errors');
2643  $error_occurred = true;
2644  }
2645  else
2646  {
2647  //Create SOAP client and connect it to product/service
2648  $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php");
2649  $soapclient_product->soap_defencoding='UTF-8';
2650  $soapclient_product->decodeUTF8(false);
2651 
2652  // Iterate each line and get the reference that uses the supplier of that product/service
2653  $i = 0;
2654  foreach ($object->lines as $line) {
2655  $i = $i + 1;
2656  $ref_supplier = $line->ref_supplier;
2657  $line_id = $i."º) ".$line->product_ref.": ";
2658  if (empty($ref_supplier)) {
2659  continue;
2660  }
2661  $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $ref_supplier);
2662  $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, '');
2663  if (!$result_product)
2664  {
2665  setEventMessages($line_id.$langs->trans("SOAPError")." ".$soapclient_product->error_str." - ".$soapclient_product->response, null, 'errors');
2666  $error_occurred = true;
2667  break;
2668  }
2669 
2670  // Check the result code
2671  $status_code = $result_product["result"]["result_code"];
2672  if (empty($status_code)) //No result, check error str
2673  {
2674  setEventMessages($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", null, 'errors');
2675  }
2676  else if ($status_code != "OK") //Something went wrong
2677  {
2678  if ($status_code == "NOT_FOUND")
2679  {
2680  setEventMessages($line_id.$langs->trans("SupplierMissingRef")." '".$ref_supplier."'", null, 'warnings');
2681  }
2682  else
2683  {
2684  setEventMessages($line_id.$langs->trans("ResponseNonOK")." '".$status_code."' - '".$result_product["result"]["result_label"]."'", null, 'errors');
2685  $error_occurred = true;
2686  break;
2687  }
2688  }
2689 
2690 
2691  // Ensure that price is equal and warn user if it's not
2692  $supplier_price = price($result_product["product"]["price_net"]); //Price of client tab in supplier dolibarr
2693  $local_price = null; //Price of supplier as stated in product suppliers tab on this dolibarr, NULL if not found
2694 
2695  $product_fourn = new ProductFournisseur($db);
2696  $product_fourn_list = $product_fourn->list_product_fournisseur_price($line->fk_product);
2697  if (count($product_fourn_list)>0)
2698  {
2699  foreach($product_fourn_list as $product_fourn_line)
2700  {
2701  //Only accept the line where the supplier is the same at this order and has the same ref
2702  if ($product_fourn_line->fourn_id == $object->socid && $product_fourn_line->fourn_ref == $ref_supplier) {
2703  $local_price = price($product_fourn_line->fourn_price);
2704  }
2705  }
2706  }
2707 
2708  if ($local_price != null && $local_price != $supplier_price) {
2709  setEventMessages($line_id.$langs->trans("RemotePriceMismatch")." ".$supplier_price." - ".$local_price, null, 'warnings');
2710  }
2711 
2712  // Check if is in sale
2713  if (empty($result_product["product"]["status_tosell"])) {
2714  setEventMessages($line_id.$langs->trans("ProductStatusNotOnSellShort")." '".$ref_supplier."'", null, 'warnings');
2715  }
2716  }
2717  }
2718  }
2719  elseif ($user_status_code == "PERMISSION_DENIED")
2720  {
2721  setEventMessages($langs->trans("RemoteUserNotPermission"), null, 'errors');
2722  $error_occurred = true;
2723  }
2724  elseif ($user_status_code == "BAD_CREDENTIALS")
2725  {
2726  setEventMessages($langs->trans("RemoteUserBadCredentials"), null, 'errors');
2727  $error_occurred = true;
2728  }
2729  else
2730  {
2731  setEventMessages($langs->trans("ResponseNonOK")." '".$user_status_code."'", null, 'errors');
2732  $error_occurred = true;
2733  }
2734 
2735  //Form
2736  print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
2737  print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
2738  print '<input type="hidden" name="action" value="webservice">';
2739  print '<input type="hidden" name="mode" value="send">';
2740  print '<input type="hidden" name="ws_user" value="'.$ws_user.'">';
2741  print '<input type="hidden" name="ws_password" value="'.$ws_password.'">';
2742  print '<input type="hidden" name="ws_entity" value="'.$ws_entity.'">';
2743  print '<input type="hidden" name="ws_thirdparty" value="'.$ws_thirdparty.'">';
2744  if ($error_occurred)
2745  {
2746  print "<br>".$langs->trans("ErrorOccurredReviseAndRetry")."<br>";
2747  }
2748  else
2749  {
2750  print '<input class="button" type="submit" id="ws_submit" name="ws_submit" value="'.$langs->trans("Confirm").'">';
2751  print ' &nbsp; &nbsp; ';
2752  }
2753  print '<input class="button" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
2754  print '</form>';
2755  }
2756  }
2757 
2758  // Select mail models is same action as presend
2759  if (GETPOST('modelselected')) {
2760  $action = 'presend';
2761  }
2762 
2763  // Presend form
2764  $modelmail='order_supplier_send';
2765  $defaulttopic='SendOrderRef';
2766  $diroutput = $conf->fournisseur->commande->dir_output;
2767  $trackid = 'sor'.$object->id;
2768 
2769  include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
2770  }
2771 }
2772 
2773 // End of page
2774 llxFooter();
2775 $db->close();
print $object label
hash of file content (md5_file(dol_osencode($destfull))
Definition: edit.php:153
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.
dol_htmloutput_events($disabledoutputofmessages=0)
Print formated messages to output (Used to show messages on html output).
print
Draft customers invoices.
Definition: index.php:91
const STATUS_DRAFT
Draft status.
setEventMessages($mesg, $mesgs, $style='mesgs')
Set event messages in dol_events session object.
if(! empty($conf->facture->enabled) && $user->rights->facture->lire) if(! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) if(! empty($conf->don->enabled) && $user->rights->societe->lire) if(! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) if(! empty($conf->facture->enabled) &&! empty($conf->commande->enabled) && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(! empty($conf->facture->enabled) && $user->rights->facture->lire) if(! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1053
Class to manage building of HTML components.
ordersupplier_prepare_head($object)
Prepare array with list of tabs.
Definition: fourn.lib.php:102
dol_print_url($url, $target='_blank', $max=32, $withpicto=0)
Show Url link.
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...
dol_concatdesc($text1, $text2, $forxml=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
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 to manage suppliers.
Class with static methods for building HTML components related to products Only components common to ...
Class to manage standard extra fields.
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...
Class to manage building of HTML components.
dol_fiche_end($notab=0)
Show tab footer of a card.
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 manage predefined suppliers products.
Class to offer components to list and upload files.
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).
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 ...
Class to manage a WYSIWYG editor.
fieldLabel($langkey, $fieldkey, $fieldrequired=0)
Show a string with the label tag dedicated to the HTML edit field.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='')
Show picto whatever it&#39;s its name (generic function)
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.
Class to manage predefined suppliers products.
$parameters
Actions.
Definition: card.php:114
Class to manage line orders.
static getIdAndTxFromCode(&$db, $code, $date_document='')
Get id and rate of currency from code.