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