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