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