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