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