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