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