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