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