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