dolibarr 23.0.4
card.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2003-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2015 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
5 * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@inodbox.com>
6 * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
7 * Copyright (C) 2010-2013 Juanjo Menent <jmenent@2byte.es>
8 * Copyright (C) 2011-2023 Philippe Grand <philippe.grand@atoo-net.com>
9 * Copyright (C) 2012-2023 Christophe Battarel <christophe.battarel@altairis.fr>
10 * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
11 * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
12 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
13 * Copyright (C) 2014 Ferran Marcet <fmarcet@2byte.es>
14 * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
15 * Copyright (C) 2018-2025 Frédéric France <frederic.france@free.fr>
16 * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
17 * Copyright (C) 2023-2024 Benjamin Falière <benjamin.faliere@altairis.fr>
18 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
19 * Copyright (C) 2025 Lenin Rivas <lenin.rivas777@gmail.com>
20 *
21 * This program is free software; you can redistribute it and/or modify
22 * it under the terms of the GNU General Public License as published by
23 * the Free Software Foundation; either version 3 of the License, or
24 * (at your option) any later version.
25 *
26 * This program is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * GNU General Public License for more details.
30 *
31 * You should have received a copy of the GNU General Public License
32 * along with this program. If not, see <https://www.gnu.org/licenses/>.
33 */
34
41// Load Dolibarr environment
42require '../main.inc.php';
43require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
44require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
45require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
46require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php';
47require_once DOL_DOCUMENT_ROOT . '/core/class/html.formorder.class.php';
48require_once DOL_DOCUMENT_ROOT . '/core/class/html.formmargin.class.php';
49require_once DOL_DOCUMENT_ROOT . '/core/modules/commande/modules_commande.php';
50require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
51require_once DOL_DOCUMENT_ROOT . '/core/lib/order.lib.php';
52
53require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php';
54require_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
55
56if (isModEnabled("propal")) {
57 require_once DOL_DOCUMENT_ROOT . '/comm/propal/class/propal.class.php';
58}
59
60if (isModEnabled('project')) {
61 require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
62 require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
63}
64
65if (isModEnabled('variants')) {
66 require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductCombination.class.php';
67}
68
69
79// Load translation files required by the page
80$langs->loadLangs(array('orders', 'sendings', 'companies', 'bills', 'propal', 'products', 'other'));
81
82if (isModEnabled('incoterm')) {
83 $langs->load('incoterm');
84}
85if (isModEnabled('margin')) {
86 $langs->load('margins');
87}
88if (isModEnabled('productbatch')) {
89 $langs->load('productbatch');
90}
91
92
93$id = (GETPOSTINT('id') ? GETPOSTINT('id') : GETPOSTINT('orderid'));
94$ref = GETPOST('ref', 'alpha');
95$socid = GETPOSTINT('socid');
96$action = GETPOST('action', 'aZ09');
97$cancel = GETPOST('cancel', 'alpha');
98$confirm = GETPOST('confirm', 'alpha');
99$backtopage = GETPOST('backtopage', 'alpha');
100
101$lineid = GETPOSTINT('lineid');
102$contactid = GETPOSTINT('contactid');
103$projectid = GETPOSTINT('projectid');
104$origin = GETPOST('origin', 'alpha');
105$originid = (GETPOSTINT('originid') ? GETPOSTINT('originid') : GETPOSTINT('origin_id')); // For backward compatibility
106$rank = (GETPOSTINT('rank') > 0) ? GETPOSTINT('rank') : -1;
107
108// Type Contact default
109$type_contact_code = (getDolGlobalString('ORDER_TYPE_CONTACT_DEFAULT') ? getDolGlobalString('ORDER_TYPE_CONTACT_DEFAULT') : 'CUSTOMER');
110
111// PDF
112$hidedetails = (GETPOSTINT('hidedetails') ? GETPOSTINT('hidedetails') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0));
113$hidedesc = (GETPOSTINT('hidedesc') ? GETPOSTINT('hidedesc') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0));
114$hideref = (GETPOSTINT('hideref') ? GETPOSTINT('hideref') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0));
115
116// Security check
117if (!empty($user->socid)) {
118 $socid = $user->socid;
119}
120
121$array_options = 0;
122$object_id = 0;
123$price_base_type = null;
124$lineClassName = null;
125$remise_percent = null;
126$ref_client = null;
127$availability_id = null;
128$shipping_method_id = null;
129$warehouse_id = null;
130$demand_reason_id = null;
131$formproject = null;
132$objectsrc = null;
133$note_public = null;
134$note_private = null;
135
136
137// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
138$hookmanager->initHooks(array('ordercard', 'globalcard'));
139
140$object = new Commande($db);
141$extrafields = new ExtraFields($db);
142
143
144// fetch optionals attributes and labels
145$extrafields->fetch_name_optionals_label($object->table_element);
146
147// Load object
148include DOL_DOCUMENT_ROOT . '/core/actions_fetchobject.inc.php'; // Must be 'include', not 'include_once'
149
150$result = restrictedArea($user, 'commande', $id); // After the fetch: the page may be called with the ref only, the security check must be done on the object found
151
152// Permissions / Rights
153$usercanread = $user->hasRight("commande", "lire");
154$usercancreate = $user->hasRight("commande", "creer");
155$usercandelete = $user->hasRight("commande", "supprimer");
156
157// Advanced permissions
158$usercanclose = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !empty($usercancreate)) || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'close')));
159$usercanvalidate = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $usercancreate) || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'validate')));
160$usercancancel = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $usercancreate) || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'annuler')));
161$usercansend = (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || $user->hasRight('commande', 'order_advance', 'send'));
162$usercangeneratedoc = (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || $user->hasRight('commande', 'order_advance', 'generetedoc'));
163
164$usermustrespectpricemin = ((getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('produit', 'ignore_price_min_advance')) || !getDolGlobalString('MAIN_USE_ADVANCED_PERMS'));
165$usercancreatepurchaseorder = ($user->hasRight('fournisseur', 'commande', 'creer') || $user->hasRight('supplier_order', 'creer'));
166
167$permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
168$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
169$permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
170$permissiontoeditextra = $usercancreate;
171if (GETPOST('attribute', 'aZ09') && isset($extrafields->attributes[$object->table_element]['perms'][GETPOST('attribute', 'aZ09')])) {
172 // For action 'update_extras', is there a specific permission set for the attribute to update
173 $permissiontoeditextra = dol_eval((string) $extrafields->attributes[$object->table_element]['perms'][GETPOST('attribute', 'aZ09')]);
174}
175
176$error = 0;
177
178$date_delivery = dol_mktime(GETPOSTINT('liv_hour'), GETPOSTINT('liv_min'), 0, GETPOSTINT('liv_month'), GETPOSTINT('liv_day'), GETPOSTINT('liv_year'));
179
180$selectedLines = array();
181
182
183/*
184 * Actions
185 */
186
187$parameters = array('socid' => $socid);
188// Note that $action and $object may be modified by some hooks
189$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action);
190if ($reshook < 0) {
191 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
192}
193
194if (empty($reshook)) {
195 $backurlforlist = DOL_URL_ROOT . '/commande/list.php';
196
197 if (empty($backtopage) || ($cancel && empty($id))) {
198 if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
199 if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
200 $backtopage = $backurlforlist;
201 } else {
202 $backtopage = DOL_URL_ROOT . '/commande/card.php?id=' . ((!empty($id) && $id > 0) ? $id : '__ID__');
203 }
204 }
205 }
206
207 $selectedLines = GETPOST('toselect', 'array:int');
208
209 if ($cancel) {
210 if (!empty($backtopageforcancel)) {
211 header("Location: " . $backtopageforcancel);
212 exit;
213 } elseif (!empty($backtopage)) {
214 header("Location: " . $backtopage);
215 exit;
216 }
217 $action = '';
218 }
219
220 include DOL_DOCUMENT_ROOT . '/core/actions_setnotes.inc.php'; // Must be 'include', not 'include_once'
221
222 include DOL_DOCUMENT_ROOT . '/core/actions_dellink.inc.php'; // Must be 'include', not 'include_once'
223
224 include DOL_DOCUMENT_ROOT . '/core/actions_lineupdown.inc.php'; // Must be 'include', not 'include_once'
225
226 // Action clone object
227 if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) {
228 if (!($socid > 0)) {
229 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('IdThirdParty')), null, 'errors');
230 } else {
231 if ($object->id > 0) {
232 // We clone object to avoid to denaturate loaded object when setting some properties for clone or if createFromClone modifies the object.
233 $objectutil = dol_clone($object, 1);
234
235 $result = $objectutil->createFromClone($user, $socid);
236 if ($result > 0) {
237 $warningMsgLineList = array();
238 // check all product lines are to sell otherwise add a warning message for each product line is not to sell
239 foreach ($object->lines as $line) {
240 if (!is_object($line->product)) {
241 $line->fetch_product();
242 }
243 if (is_object($line->product) && $line->product->id > 0) {
244 if (empty($line->product->status)) {
245 $warningMsgLineList[$line->id] = $langs->trans('WarningLineProductNotToSell', $line->product->ref);
246 }
247 }
248 }
249 if (!empty($warningMsgLineList)) {
250 setEventMessages('', $warningMsgLineList, 'warnings');
251 }
252
253 header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $result);
254 exit;
255 } else {
256 setEventMessages($objectutil->error, $objectutil->errors, 'errors');
257 $action = '';
258 }
259 }
260 }
261 } elseif ($action == 'reopen' && $usercancreate) {
262 // Reopen a closed order
264 if (getDolGlobalInt('ORDER_REOPEN_TO_DRAFT')) {
265 $idwarehouse = GETPOSTINT('idwarehouse');
266 $result = $object->setDraft($user, $idwarehouse);
267 if ($result < 0) {
268 setEventMessages($object->error, $object->errors, 'errors');
269 }
270 } else {
271 $result = $object->set_reopen($user);
272 if ($result > 0) {
273 setEventMessages($langs->trans('OrderReopened', $object->ref), null);
274 } else {
275 setEventMessages($object->error, $object->errors, 'errors');
276 }
277 }
278 }
279 } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) {
280 // Remove order
281 $result = $object->delete($user);
282 if ($result > 0) {
283 header('Location: list.php?restore_lastsearch_values=1');
284 exit;
285 } else {
286 setEventMessages($object->error, $object->errors, 'errors');
287 }
288 } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
289 // Remove a product line
290 $result = $object->deleteLine($user, $lineid);
291 if ($result > 0) {
292 // reorder lines
293 $object->line_order(true);
294 // Define output language
295 $outputlangs = $langs;
296 $newlang = '';
297 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
298 $newlang = GETPOST('lang_id', 'aZ09');
299 }
300 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
301 $newlang = $object->thirdparty->default_lang;
302 }
303 if (!empty($newlang)) {
304 $outputlangs = new Translate("", $conf);
305 $outputlangs->setDefaultLang($newlang);
306 }
307 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
308 $ret = $object->fetch($object->id); // Reload to get new records
309 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
310 }
311
312 header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id);
313 exit;
314 } else {
315 setEventMessages($object->error, $object->errors, 'errors');
316 }
317 } elseif ($action == 'confirm_delete_subtotalline' && $confirm == 'yes' && $usercancreate) {
318 $result = $object->deleteSubtotalLine($langs, GETPOSTINT('lineid'), (bool) GETPOST('deletecorrespondingsubtotalline'), $user);
319 if ($result > 0) {
320 // reorder lines
321 $object->line_order(true);
322 // Define output language
323 $outputlangs = $langs;
324 $newlang = '';
325 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
326 $newlang = GETPOST('lang_id', 'aZ09');
327 }
328 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
329 $newlang = $object->thirdparty->default_lang;
330 }
331 if (!empty($newlang)) {
332 $outputlangs = new Translate("", $conf);
333 $outputlangs->setDefaultLang($newlang);
334 }
335 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
336 $ret = $object->fetch($object->id); // Reload to get new records
337 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
338 }
339
340 header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id);
341 exit;
342 } else {
343 setEventMessages($object->error, $object->errors, 'errors');
344 }
345 } elseif ($action == 'classin' && $usercancreate) {
346 // Link to a project
347 $object->setProject(GETPOSTINT('projectid'));
348 } elseif ($action == 'add' && $usercancreate) {
349 // Add order
350 $datecommande = dol_mktime(12, 0, 0, GETPOSTINT('remonth'), GETPOSTINT('reday'), GETPOSTINT('reyear'));
351 $date_delivery = dol_mktime(GETPOSTINT('liv_hour'), GETPOSTINT('liv_min'), 0, GETPOSTINT('liv_month'), GETPOSTINT('liv_day'), GETPOSTINT('liv_year'));
352
353 if ($datecommande == '') {
354 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Date')), null, 'errors');
355 $action = 'create';
356 $error++;
357 }
358
359 if ($socid < 1) {
360 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors');
361 $action = 'create';
362 $error++;
363 }
364
365 if (!$error) {
366 $object->socid = $socid;
367 $object->fetch_thirdparty();
368
369 $db->begin();
370
371 $object->date_commande = $datecommande;
372 $object->note_private = GETPOST('note_private', 'restricthtml');
373 $object->note_public = GETPOST('note_public', 'restricthtml');
374 $object->source = GETPOSTINT('source_id');
375 $object->fk_project = GETPOSTINT('projectid');
376 $object->ref_client = GETPOST('ref_client', 'alpha');
377 $object->model_pdf = GETPOST('model');
378 $object->cond_reglement_id = GETPOSTINT('cond_reglement_id');
379 $object->deposit_percent = GETPOSTFLOAT('cond_reglement_id_deposit_percent');
380 $object->mode_reglement_id = GETPOSTINT('mode_reglement_id');
381 $object->fk_account = GETPOSTINT('fk_account');
382 $object->availability_id = GETPOSTINT('availability_id');
383 $object->demand_reason_id = GETPOSTINT('demand_reason_id');
384 $object->delivery_date = $date_delivery;
385 $object->shipping_method_id = GETPOSTINT('shipping_method_id');
386 $object->warehouse_id = GETPOSTINT('warehouse_id');
387 $object->fk_delivery_address = GETPOSTINT('fk_address');
388 $object->contact_id = GETPOSTINT('contactid');
389 $object->fk_incoterms = GETPOSTINT('incoterm_id');
390 $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
391 $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
392 $object->multicurrency_tx = GETPOSTFLOAT('originmulticurrency_tx');
393 // Fill array 'array_options' with data from add form
394 $ret = $extrafields->setOptionalsFromPost(null, $object);
395 if ($ret < 0) {
396 $error++;
397 }
398
399 // If creation from another object of another module (Example: origin=propal, originid=1)
400 if (!empty($origin) && !empty($originid)) {
401 // Parse element/subelement (ex: project_task)
402 $element = $subelement = $origin;
403 $regs = array();
404 if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
405 $element = $regs[1];
406 $subelement = $regs[2];
407 }
408
409 // For compatibility
410 if ($element == 'order') {
411 $element = $subelement = 'commande';
412 }
413 if ($element == 'propal') {
414 $element = 'comm/propal';
415 $subelement = 'propal';
416 }
417 if ($element == 'contract') {
418 $element = $subelement = 'contrat';
419 }
420
421 $object->origin = $origin; // deprecated
422 $object->origin_type = $origin;
423 $object->origin_id = $originid;
424
425 // Possibility to add external linked objects with hooks
426 $object->linked_objects[$object->origin_type] = $object->origin_id;
427 $other_linked_objects = GETPOST('other_linked_objects', 'array');
428 if (!empty($other_linked_objects)) {
429 $object->linked_objects = array_merge($object->linked_objects, $other_linked_objects);
430 }
431
432 if (!$error) {
433 $object_id = $object->create($user);
434
435 if ($object_id > 0) {
436 dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
437
438 $classname = ucfirst($subelement);
439 $srcobject = new $classname($db);
440 '@phan-var-force Commande|Propal|Contrat $srcobject';
443 dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines");
444 $result = $srcobject->fetch($object->origin_id);
445 if ($result > 0) {
446 $lines = $srcobject->lines;
447 if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
448 $srcobject->fetch_lines();
449 $lines = $srcobject->lines;
450 }
451
452 $fk_parent_line = 0;
453 $num = count($lines);
454
455 for ($i = 0; $i < $num; $i++) {
456 if (!in_array($lines[$i]->id, $selectedLines)) {
457 continue; // Skip unselected lines
458 }
459
460 $label = (!empty($lines[$i]->label) ? $lines[$i]->label : '');
461 $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : '');
462 $product_type = (!empty($lines[$i]->product_type) ? $lines[$i]->product_type : 0);
463
464 // Dates
465 // TODO mutualiser
466 $date_start = $lines[$i]->date_debut_prevue;
467 if ($lines[$i]->date_debut_reel) {
468 $date_start = $lines[$i]->date_debut_reel;
469 }
470 if ($lines[$i]->date_start) {
471 $date_start = $lines[$i]->date_start;
472 }
473 $date_end = $lines[$i]->date_fin_prevue;
474 if ($lines[$i]->date_fin_reel) {
475 $date_end = $lines[$i]->date_fin_reel;
476 }
477 if ($lines[$i]->date_end) {
478 $date_end = $lines[$i]->date_end;
479 }
480
481 // Reset fk_parent_line for no child products and special product
482 if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
483 $fk_parent_line = 0;
484 }
485
486 // Extrafields
487 if (method_exists($lines[$i], 'fetch_optionals')) { // For avoid conflicts if trigger used
488 $lines[$i]->fetch_optionals();
489 $array_options = $lines[$i]->array_options;
490 }
491
492 $tva_tx = $lines[$i]->tva_tx;
493 if (!empty($lines[$i]->vat_src_code) && !preg_match('/\‍(/', $tva_tx)) {
494 $tva_tx .= ' (' . $lines[$i]->vat_src_code . ')';
495 }
496
497 $result = $object->addline(
498 $desc,
499 $lines[$i]->subprice,
500 $lines[$i]->qty,
501 $tva_tx,
502 $lines[$i]->localtax1_tx,
503 $lines[$i]->localtax2_tx,
504 $lines[$i]->fk_product,
505 $lines[$i]->remise_percent,
506 $lines[$i]->info_bits,
507 $lines[$i]->fk_remise_except,
508 'HT',
509 0,
510 $date_start,
511 $date_end,
512 $product_type,
513 $lines[$i]->rang,
514 $lines[$i]->special_code,
515 $fk_parent_line,
516 $lines[$i]->fk_fournprice,
517 $lines[$i]->pa_ht,
518 $label,
519 $array_options,
520 $lines[$i]->fk_unit,
521 $object->origin,
522 $lines[$i]->rowid,
523 0,
524 $lines[$i]->ref_ext,
525 0
526 );
527
528 if ($result < 0) {
529 $error++;
530 break;
531 }
532
533 foreach ($object->lines as $line) {
534 if ($line->id == $result) {
535 $line->extraparams = $lines[$i]->extraparams;
536 $line->setExtraParameters();
537 }
538 }
539
540 // Defined the new fk_parent_line
541 if ($result > 0 && $lines[$i]->product_type == 9) {
542 $fk_parent_line = $result;
543 }
544 }
545 } else {
546 setEventMessages($srcobject->error, $srcobject->errors, 'errors');
547 $error++;
548 }
549
550 // Now we create same links to contact than the ones found on origin object
551 /* Useless, already into the create
552 if (getDolGlobalString('MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN')) {
553 $originforcontact = $object->origin;
554 $originidforcontact = $object->origin_id;
555 if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order
556 {
557 $originforcontact=$srcobject->origin;
558 $originidforcontact=$srcobject->origin_id;
559 }
560 $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
561 $sqlcontact.= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'";
562
563 $resqlcontact = $db->query($sqlcontact);
564 if ($resqlcontact)
565 {
566 while($objcontact = $db->fetch_object($resqlcontact))
567 {
568 //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n";
569 $object->add_contact($objcontact->fk_socpeople, $objcontact->code);
570 }
571 }
572 else dol_print_error($resqlcontact);
573 }*/
574
575 // Hooks
576 $parameters = array('objFrom' => $srcobject);
577 // Note that $action and $object may be modified by hook
578 $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action);
579 if ($reshook < 0) {
580 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
581 $error++;
582 }
583 } else {
584 setEventMessages($object->error, $object->errors, 'errors');
585 $error++;
586 }
587 } else {
588 // Required extrafield left blank, error message already defined by setOptionalsFromPost()
589 $action = 'create';
590 }
591 } else {
592 if (!$error) {
593 $object_id = $object->create($user);
594 }
595 }
596
597 // Insert default contacts if defined
598 if ($object_id > 0) {
599 if (GETPOSTINT('contactid')) {
600 // $result = $object->add_contact(GETPOSTINT('contactid'), 'CUSTOMER', 'external');
601 $result = $object->add_contact(GETPOSTINT('contactid'), $type_contact_code, 'external');
602 if ($result < 0) {
603 setEventMessages($langs->trans("ErrorFailedToAddContact"), null, 'errors');
604 $error++;
605 }
606 }
607
608 $id = $object_id;
609 $action = '';
610 }
611
612 if (isModEnabled('category')) {
613 $categories = GETPOST('categories', 'array');
614 if (method_exists($object, 'setCategories')) {
615 $object->setCategories($categories);
616 }
617 }
618
619 // End of object creation, we show it
620 if ($object_id > 0 && !$error) {
621 $db->commit();
622 header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object_id);
623 exit();
624 } else {
625 $db->rollback();
626 $action = 'create';
627 setEventMessages($object->error, $object->errors, 'errors');
628 }
629 }
630 } elseif ($action == 'classifybilled' && $usercancreate) {
631 $ret = $object->classifyBilled($user);
632
633 if ($ret < 0) {
634 setEventMessages($object->error, $object->errors, 'errors');
635 }
636 } elseif ($action == 'classifyunbilled' && $usercancreate) {
637 $ret = $object->classifyUnBilled($user);
638 if ($ret < 0) {
639 setEventMessages($object->error, $object->errors, 'errors');
640 }
641 } elseif ($action == 'setref_client' && $usercancreate) {
642 // Positionne ref commande client
643 $result = $object->set_ref_client($user, GETPOST('ref_client'));
644 if ($result < 0) {
645 setEventMessages($object->error, $object->errors, 'errors');
646 }
647 } elseif ($action == 'setremise' && $usercancreate) {
648 $result = $object->setDiscount($user, price2num(GETPOST('remise'), 2));
649 if ($result < 0) {
650 setEventMessages($object->error, $object->errors, 'errors');
651 }
652 } elseif ($action == 'setabsolutediscount' && $usercancreate) {
653 if (GETPOST('remise_id')) {
654 if ($object->id > 0) {
655 $object->insert_discount(GETPOSTINT('remise_id'));
656 } else {
657 dol_print_error($db, $object->error);
658 }
659 }
660 } elseif ($action == 'setdate' && $usercancreate) {
661 $date = dol_mktime(0, 0, 0, GETPOSTINT('order_month'), GETPOSTINT('order_day'), GETPOSTINT('order_year'));
662
663 $result = $object->set_date($user, $date);
664 if ($result < 0) {
665 setEventMessages($object->error, $object->errors, 'errors');
666 }
667 } elseif ($action == 'setdate_livraison' && $usercancreate) {
668 $date_delivery = dol_mktime(GETPOSTINT('liv_hour'), GETPOSTINT('liv_min'), 0, GETPOSTINT('liv_month'), GETPOSTINT('liv_day'), GETPOSTINT('liv_year'));
669
670 $object->fetch($id);
671 $result = $object->setDeliveryDate($user, $date_delivery);
672 if ($result < 0) {
673 setEventMessages($object->error, $object->errors, 'errors');
674 }
675 } elseif ($action == 'setmode' && $usercancreate) {
676 $result = $object->setPaymentMethods(GETPOSTINT('mode_reglement_id'));
677 if ($result < 0) {
678 setEventMessages($object->error, $object->errors, 'errors');
679 }
680 } elseif ($action == 'setposinfo' && $usercancreate) {
681 $object->fetch($id);
682 $object->module_source = GETPOST('posmodule');
683 $object->pos_source = GETPOST('posterminal');
684 $result = $object->update($user);
685 if ($result < 0) {
686 dol_print_error($db, $object->error);
687 }
688 } elseif ($action == 'setmulticurrencycode' && $usercancreate) {
689 // Multicurrency Code
690 $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
691 } elseif ($action == 'setmulticurrencyrate' && $usercancreate) {
692 // Multicurrency rate
693 $result = $object->setMulticurrencyRate(GETPOSTFLOAT('multicurrency_tx'), GETPOSTINT('calculation_mode'));
694 } elseif ($action == 'setavailability' && $usercancreate) {
695 $result = $object->availability(GETPOSTINT('availability_id'));
696 if ($result < 0) {
697 setEventMessages($object->error, $object->errors, 'errors');
698 }
699 } elseif ($action == 'setdemandreason' && $usercancreate) {
700 $result = $object->demand_reason(GETPOSTINT('demand_reason_id'));
701 if ($result < 0) {
702 setEventMessages($object->error, $object->errors, 'errors');
703 }
704 } elseif ($action == 'setconditions' && $usercancreate) {
705 $result = $object->setPaymentTerms(GETPOSTINT('cond_reglement_id'), GETPOSTFLOAT('cond_reglement_id_deposit_percent'));
706 if ($result < 0) {
707 dol_print_error($db, $object->error);
708 } else {
709 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
710 // Define output language
711 $outputlangs = $langs;
712 $newlang = GETPOST('lang_id', 'alpha');
713 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
714 $newlang = $object->thirdparty->default_lang;
715 }
716 if (!empty($newlang)) {
717 $outputlangs = new Translate("", $conf);
718 $outputlangs->setDefaultLang($newlang);
719 }
720
721 $ret = $object->fetch($object->id); // Reload to get new records
722 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
723 }
724 }
725 } elseif ($action == 'set_incoterms' && isModEnabled('incoterm') && $usercancreate) {
726 // Set incoterm
727 $result = $object->setIncoterms(GETPOSTINT('incoterm_id'), GETPOST('location_incoterms'));
728 if ($result < 0) {
729 setEventMessages($object->error, $object->errors, 'errors');
730 }
731 } elseif ($action == 'setbankaccount' && $usercancreate) {
732 // bank account
733 $result = $object->setBankAccount(GETPOSTINT('fk_account'));
734 if ($result < 0) {
735 setEventMessages($object->error, $object->errors, 'errors');
736 }
737 } elseif ($action == 'setshippingmethod' && $usercancreate) {
738 // shipping method
739 $result = $object->setShippingMethod(GETPOSTINT('shipping_method_id'));
740 if ($result < 0) {
741 setEventMessages($object->error, $object->errors, 'errors');
742 }
743 } elseif ($action == 'setwarehouse' && $usercancreate) {
744 // warehouse
745 $result = $object->setWarehouse(GETPOSTINT('warehouse_id'));
746 if ($result < 0) {
747 setEventMessages($object->error, $object->errors, 'errors');
748 }
749 //} elseif ($action == 'setremisepercent' && $usercancreate) {
750 // $result = $object->setDiscount($user, price2num(GETPOST('remise_percent'), '', 2));
751 //} elseif ($action == 'setremiseabsolue' && $usercancreate) {
752 // $result = $object->set_remise_absolue($user, price2num(GETPOST('remise_absolue'), 'MU', 2));
753 } elseif ($action == 'settags' && isModEnabled('category') && $usercancreate) {
754 $result = $object->setCategories(GETPOST('categories', 'array'));
755 if ($result < 0) {
756 setEventMessages($object->error, $object->errors, 'errors');
757 }
758 } elseif ($action == 'addline' && GETPOST('updateallvatlinesblock', 'alpha') && GETPOST('vatforblocklines', 'alpha') !== '' && $usercancreate) {
759 $tx_tva = GETPOST('vatforblocklines') ? GETPOST('vatforblocklines') : 0;
760 $object->updateSubtotalLineBlockLines($langs, $object->getRangOfLine($lineid), 'tva', $tx_tva);
761 } elseif ($action == 'addline' && GETPOST('updatealldiscountlinesblock', 'alpha') && GETPOST('discountforblocklines', 'alpha') !== '' && $usercancreate) {
762 $discount = GETPOST('discountforblocklines') ? GETPOST('discountforblocklines') : 0;
763 $object->updateSubtotalLineBlockLines($langs, $object->getRangOfLine($lineid), 'discount', $discount);
764 } elseif ($action == 'addline' && GETPOST('submitforalllines', 'aZ09') && (GETPOST('alldate_start', 'alpha') || GETPOST('alldate_end', 'alpha')) && $usercancreate) {
765 // Define date start and date end for all line
766 $alldate_start = dol_mktime(GETPOSTINT('alldate_starthour'), GETPOSTINT('alldate_startmin'), 0, GETPOSTINT('alldate_startmonth'), GETPOSTINT('alldate_startday'), GETPOSTINT('alldate_startyear'));
767 $alldate_end = dol_mktime(GETPOSTINT('alldate_endhour'), GETPOSTINT('alldate_endmin'), 0, GETPOSTINT('alldate_endmonth'), GETPOSTINT('alldate_endday'), GETPOSTINT('alldate_endyear'));
768 foreach ($object->lines as $line) {
769 if ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
770 continue;
771 }
772 if ($line->product_type == 1) { // only service line
773 $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $alldate_start, $alldate_end, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice);
774 }
775 }
776 } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('vatforalllines', 'alpha') !== '' && $usercancreate) {
777 // Define vat_rate
778 $vat_rate = (GETPOST('vatforalllines') ? GETPOST('vatforalllines') : 0);
779 $vat_rate = str_replace('*', '', $vat_rate);
780 $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
781 $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
782 foreach ($object->lines as $line) {
783 if ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
784 continue;
785 }
786 $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $line->info_bits, $line->date_start, $line->date_end, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice);
787 }
788 } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('remiseforalllines', 'alpha') !== '' && $usercancreate) {
789 // Define remise_percent
790 $remise_percent = (GETPOST('remiseforalllines') ? GETPOST('remiseforalllines') : 0);
791 $remise_percent = str_replace('*', '', $remise_percent);
792 foreach ($object->lines as $line) {
793 if ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
794 continue;
795 }
796 $tvatx = $line->tva_tx;
797 if (!empty($line->vat_src_code)) {
798 $tvatx .= ' (' . $line->vat_src_code . ')';
799 }
800 $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, (float) $remise_percent, $tvatx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice);
801 }
802 } elseif ($action == 'addline' && $usercancreate && (
803 (GETPOST('submitforallmargins', 'alpha') && GETPOST('marginforalllines', 'alpha') !== '') ||
804 (GETPOST('submitforallmark', 'alpha') && GETPOST('markforalllines', 'alpha') !== ''))) {
805 $outlangs = $langs;
806 // Define margin
807 $margin_rate = GETPOSTISSET('marginforalllines') ? GETPOST('marginforalllines', 'int') : '';
808 $mark_rate = GETPOSTISSET('markforalllines') ? GETPOST('markforalllines', 'int') : '';
809 foreach ($object->lines as &$line) if ($line->subprice > 0) {
810 if ($line->special_code == SUBTOTALS_SPECIAL_CODE) {
811 continue;
812 }
813 $subprice_multicurrency = $line->subprice;
814 if (is_numeric($margin_rate) && $margin_rate > 0) {
815 $line->subprice = (float) price2num((float) $line->pa_ht * (1 + (float) $margin_rate / 100), 'MU');
816 } elseif (is_numeric($mark_rate) && $mark_rate > 0) {
817 $line->subprice = (float) ($line->pa_ht / (1 - ((float) $mark_rate / 100)));
818 } else {
819 $line->subprice = (float) $line->pa_ht;
820 }
821
822 $prod = new Product($db);
823 $res = $prod->fetch($line->fk_product);
824 if ($res > 0) {
825 if ($prod->price_min > $line->subprice) {
826 $price_subprice = price($line->subprice, 0, $outlangs, 1, -1, -1, 'auto');
827 $price_price_min = price($prod->price_min, 0, $outlangs, 1, -1, -1, 'auto');
828 setEventMessages($prod->ref . ' - ' . $prod->label . ' (' . $price_subprice . ' < ' . $price_price_min . ' ' . strtolower($langs->trans("MinPrice")) . ')' . "\n", null, 'warnings');
829 } else {
830 setEventMessages($prod->error, $prod->errors, 'errors');
831 }
832 } elseif ($line->fk_product) { // Display errors only for non-free lines
833 setEventMessages($prod->error, $prod->errors, 'errors');
834 }
835 // Manage $line->subprice and $line->multicurrency_subprice
836 $multicurrency_subprice = (float) $line->subprice * $line->multicurrency_subprice / $subprice_multicurrency;
837 // Update DB
838 $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->product_ref, $line->special_code, $line->array_options, $line->fk_unit, $multicurrency_subprice);
839 // Update $object with new margin info
840 if ($result > 0) {
841 if (is_numeric($margin_rate) && empty($mark_rate)) {
842 $line->marge_tx = $margin_rate;
843 } elseif (is_numeric($mark_rate) && empty($margin_rate)) {
844 $line->marque_tx = $mark_rate;
845 }
846 $line->total_ht = $line->qty * (float) $line->subprice;
847 $line->total_tva = $line->tva_tx * $line->qty * (float) $line->subprice;
848 $line->total_ttc = (1 + $line->tva_tx) * $line->qty * (float) $line->subprice;
849 // Manage $line->subprice and $line->multicurrency_subprice
850 $line->multicurrency_total_ht = $line->qty * (float) $subprice_multicurrency * $line->multicurrency_subprice / $line->subprice;
851 $line->multicurrency_total_tva = $line->tva_tx * $line->qty * (float) $subprice_multicurrency * $line->multicurrency_subprice / $line->subprice;
852 $line->multicurrency_total_ttc = (1 + $line->tva_tx) * $line->qty * (float) $subprice_multicurrency * $line->multicurrency_subprice / $line->subprice;
853 // Used previous $line->subprice and $line->multicurrency_subprice above, now they can be set to their new values
854 $line->multicurrency_subprice = $multicurrency_subprice;
855 } else {
856 setEventMessages($object->error, $object->errors, 'errors');
857 }
858 }
859 } elseif ($action == 'confirm_addtitleline' && $usercancreate) {
860 // Handling adding a new title line for subtotals module
861
862 $langs->load('subtotals');
863
864 $desc = GETPOST('subtotallinedesc', 'alphanohtml');
865 $depth = GETPOSTINT('subtotallinelevel') ?? 1;
866
867 $subtotal_options = array();
868
869 foreach (Commande::$TITLE_OPTIONS as $option) {
870 $value = GETPOST($option, 'alphanohtml');
871 if ($value) {
872 $subtotal_options[$option] = $value == 'on' ? 1 : $value;
873 }
874 }
875
876 // Insert line
877 $result = $object->addSubtotalLine($langs, $desc, (int) $depth, $subtotal_options);
878
879 if ($result >= 0) {
880 if ($result == 0) {
881 setEventMessages($object->error, $object->errors, 'warnings');
882 }
883 $ret = $object->fetch($object->id); // Reload to get new records
884 $object->fetch_thirdparty();
885
886 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
887 // Define output language
888 $outputlangs = $langs;
889 $newlang = GETPOST('lang_id', 'alpha');
890 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
891 $newlang = $object->thirdparty->default_lang;
892 }
893 if (!empty($newlang)) {
894 $outputlangs = new Translate("", $conf);
895 $outputlangs->setDefaultLang($newlang);
896 }
897
898 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
899 }
900 } else {
901 setEventMessages($object->error, $object->errors, 'errors');
902 }
903 header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id);
904 exit();
905 } elseif ($action == 'confirm_addsubtotalline' && $usercancreate) {
906 // Handling adding a new subtotal line for subtotals module
907
908 $langs->load('subtotals');
909
910 $choosen_line = GETPOST('subtotaltitleline', 'alphanohtml');
911 foreach ($object->lines as $line) {
912 if ($line->desc == $choosen_line && $line->special_code == SUBTOTALS_SPECIAL_CODE) {
913 $desc = $line->desc;
914 $depth = -$line->qty;
915 }
916 }
917
918 $subtotal_options = array();
919
920 foreach (Commande::$SUBTOTAL_OPTIONS as $option) {
921 $value = GETPOST($option, 'alphanohtml');
922 if ($value) {
923 $subtotal_options[$option] = $value == 'on' ? 1 : $value;
924 }
925 }
926
927 // Insert line
928 if (isset($desc) && isset($depth)) {
929 $result = $object->addSubtotalLine($langs, $desc, (int) $depth, $subtotal_options);
930 } else {
931 $object->errors[] = $langs->trans("CorrespondingTitleNotFound");
932 }
933
934 if (isset($result) && $result >= 0) {
935 $ret = $object->fetch($object->id); // Reload to get new records
936 $object->fetch_thirdparty();
937
938 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
939 // Define output language
940 $outputlangs = $langs;
941 $newlang = GETPOST('lang_id', 'alpha');
942 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
943 $newlang = $object->thirdparty->default_lang;
944 }
945 if (!empty($newlang)) {
946 $outputlangs = new Translate("", $conf);
947 $outputlangs->setDefaultLang($newlang);
948 }
949
950 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
951 }
952 } else {
953 setEventMessages($object->error, $object->errors, 'errors');
954 }
955 header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id);
956 exit();
957 } elseif ($action == 'addline' && !GETPOST('submitforalllines', 'alpha') && $usercancreate) { // Add a new line
958 $langs->load('errors');
959 $error = 0;
960
961 // Set if we used free entry or predefined product
962 $predef = '';
963 $line_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
964
965 $price_ht = '';
966 $price_ht_devise = '';
967 $price_ttc = '';
968 $price_ttc_devise = '';
969
970 if (GETPOST('price_ht') !== '') {
971 $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
972 }
973 if (GETPOST('multicurrency_price_ht') !== '') {
974 $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
975 }
976 if (GETPOST('price_ttc') !== '') {
977 $price_ttc = price2num(GETPOST('price_ttc'), 'MU', 2);
978 }
979 if (GETPOST('multicurrency_price_ttc') !== '') {
980 $price_ttc_devise = price2num(GETPOST('multicurrency_price_ttc'), 'CU', 2);
981 }
982
983 $prod_entry_mode = GETPOST('prod_entry_mode', 'aZ09');
984 if ($prod_entry_mode == 'free') {
985 $idprod = 0;
986 } else {
987 $idprod = GETPOSTINT('idprod');
988
989 if (getDolGlobalString('MAIN_DISABLE_FREE_LINES') && $idprod <= 0) {
990 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors');
991 $error++;
992 }
993 }
994
995 $tva_tx = GETPOST('tva_tx', 'alpha');
996
997 $qty = price2num(GETPOST('qty' . $predef, 'alpha'), 'MS', 2);
998
999 $remise_percent = (GETPOSTISSET('remise_percent' . $predef) ? price2num(GETPOST('remise_percent' . $predef, 'alpha'), '', 2) : 0);
1000 if (empty($remise_percent)) {
1001 $remise_percent = 0;
1002 }
1003
1004 // Extrafields
1005 $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
1006 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
1007 // Unset extrafield
1008 if (is_array($extralabelsline)) {
1009 // Get extra fields
1010 foreach ($extralabelsline as $key => $value) {
1011 unset($_POST["options_" . $key]);
1012 }
1013 }
1014
1015 $price_to_test_sign = ($price_ht ? $price_ht : $price_ttc);
1016
1017 if ((empty($idprod) || $idprod < 0) && ($price_to_test_sign < 0) && ($qty < 0)) {
1018 $langs->load("errors");
1019 setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
1020 $error++;
1021 }
1022 if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
1023 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
1024 $error++;
1025 }
1026 if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && $price_ht === '' && $price_ht_devise === '' && $price_ttc === '' && $price_ttc_devise === '') { // Unit price can be 0 but not ''. Also price can be negative for order.
1027 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
1028 $error++;
1029 }
1030 if ($qty == '') {
1031 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
1032 $error++;
1033 }
1034
1035 if ($qty < 0 && !getDolGlobalString('ORDER_ENABLE_NEGATIVE_QTY')) {
1036 setEventMessages($langs->trans('FieldCannotBeNegative', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
1037 $error++;
1038 }
1039
1040 if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && empty($line_desc)) {
1041 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
1042 $error++;
1043 }
1044
1045 if (!$error && isModEnabled('variants') && $prod_entry_mode != 'free') {
1046 if ($combinations = GETPOST('combinations', 'array:alphanohtml')) {
1047 //Check if there is a product with the given combination
1048 $prodcomb = new ProductCombination($db);
1049
1050 if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
1051 $idprod = $res->fk_product_child;
1052 } else {
1053 setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
1054 $error++;
1055 }
1056 }
1057 }
1058
1059 if (!$error && (!empty($line_desc) || (!empty($idprod) && $idprod > 0))) {
1060 $pu_ht = 0;
1061 $pu_ttc = 0;
1062 $pu_ht_devise = 0;
1063 $pu_ttc_devise = 0;
1064 $price_min = 0;
1065 $price_min_ttc = 0;
1066 $tva_npr = 0;
1067 $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
1068
1069 // Clean parameters
1070 $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'));
1071 $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'));
1072
1073 $db->begin();
1074
1075 // Ecrase $pu par celui du produit
1076 // Ecrase $desc par celui du produit
1077 // Ecrase $base_price_type par celui du produit
1078 if (!empty($idprod) && $idprod > 0) {
1079 $prod = new Product($db);
1080 $prod->fetch($idprod);
1081
1082 $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
1083
1084 // Update if prices fields are defined
1085 /*$tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
1086 $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
1087 if (empty($tva_tx)) {
1088 $tva_npr = 0;
1089 }*/
1090
1091 // Price unique per product
1092 $pu_ht = $prod->price;
1093 $pu_ttc = $prod->price_ttc;
1094 $price_min = $prod->price_min;
1095 $price_min_ttc = $prod->price_min_ttc;
1096 $price_base_type = $prod->price_base_type;
1097
1098 if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) {
1099 // If price per customer
1100 require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
1101
1102 $prodcustprice = new ProductCustomerPrice($db);
1103
1104 $filter = array('t.fk_product' => (string) $prod->id, 't.fk_soc' => (string) $object->thirdparty->id);
1105
1106 // If a price per customer exist
1107 $pricebycustomerexist = false;
1108 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
1109 if ($result >= 0) {
1110 // If there is some prices specific to the customer
1111 if (count($prodcustprice->lines) > 0) {
1112 $date_now = (int) floor(dol_now() / 86400) * 86400; // date without hours
1113 foreach ($prodcustprice->lines as $k => $custprice_line) {
1114 if ($custprice_line->date_begin <= $date_now && (empty($custprice_line->date_end) || $date_now <= $custprice_line->date_end)) {
1115 $pricebycustomerexist = true;
1116 $pu_ht = price($custprice_line->price);
1117 $pu_ttc = price($custprice_line->price_ttc);
1118 $price_min = price($custprice_line->price_min);
1119 $price_min_ttc = price($custprice_line->price_min_ttc);
1120 $price_base_type = $custprice_line->price_base_type;
1121 /*$tva_tx = $custprice_line->tva_tx;
1122 if ($custprice_line->default_vat_code && !preg_match('/\‍(.*\‍)/', (string) $tva_tx)) {
1123 $tva_tx .= ' (' . $custprice_line->default_vat_code . ')';
1124 }
1125 $tva_npr = $custprice_line->recuperableonly;
1126 if (empty($tva_tx)) {
1127 $tva_npr = 0;
1128 }*/
1129 break;
1130 }
1131 }
1132 }
1133 } else {
1134 setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
1135 }
1136
1137 if (!$pricebycustomerexist && !empty($object->thirdparty->price_level)) { // If price per segment
1138 $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
1139 $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
1140 $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
1141 $price_min_ttc = $prod->multiprices_min_ttc[$object->thirdparty->price_level];
1142 // A price level with no price row leaves multiprices_base_type empty (null or ''), and an empty
1143 // value is not 'HT' for addline(), which then takes the price as TTC and stores it with the VAT added.
1144 $price_base_type = (empty($prod->multiprices_base_type[$object->thirdparty->price_level]) ? 'HT' : $prod->multiprices_base_type[$object->thirdparty->price_level]);
1145 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) { // using this option is a bug. kept for backward compatibility
1146 if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) {
1147 $tva_tx = $prod->multiprices_tva_tx[$object->thirdparty->price_level];
1148 }
1149 if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) {
1150 $tva_npr = $prod->multiprices_recuperableonly[$object->thirdparty->price_level];
1151 }
1152 }
1153 }
1154 } elseif (getDolGlobalString('PRODUIT_MULTIPRICES') && !empty($object->thirdparty->price_level)) { // If price per segment
1155 $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
1156 $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
1157 $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
1158 $price_min_ttc = $prod->multiprices_min_ttc[$object->thirdparty->price_level];
1159 // A price level with no price row leaves multiprices_base_type empty (null or ''), and an empty
1160 // value is not 'HT' for addline(), which then takes the price as TTC and stores it with the VAT added.
1161 $price_base_type = (empty($prod->multiprices_base_type[$object->thirdparty->price_level]) ? 'HT' : $prod->multiprices_base_type[$object->thirdparty->price_level]);
1162 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) { // using this option is a bug. kept for backward compatibility
1163 if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) {
1164 $tva_tx = $prod->multiprices_tva_tx[$object->thirdparty->price_level];
1165 }
1166 if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) {
1167 $tva_npr = $prod->multiprices_recuperableonly[$object->thirdparty->price_level];
1168 }
1169 }
1170 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
1171 // If price per customer
1172 require_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php';
1173
1174 $prodcustprice = new ProductCustomerPrice($db);
1175
1176 $filter = array('t.fk_product' => (string) $prod->id, 't.fk_soc' => (string) $object->thirdparty->id);
1177
1178 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
1179 if ($result >= 0) {
1180 // If there is some prices specific to the customer
1181 if (count($prodcustprice->lines) > 0) {
1182 $date_now = (int) floor(dol_now() / 86400) * 86400; // date without hours
1183 foreach ($prodcustprice->lines as $k => $custprice_line) {
1184 if ($custprice_line->date_begin <= $date_now && (empty($custprice_line->date_end) || $date_now <= $custprice_line->date_end)) {
1185 $pu_ht = price($custprice_line->price);
1186 $pu_ttc = price($custprice_line->price_ttc);
1187 $price_min = price($custprice_line->price_min);
1188 $price_min_ttc = price($custprice_line->price_min_ttc);
1189 $price_base_type = $custprice_line->price_base_type;
1190 /*$tva_tx = $custprice_line->tva_tx;
1191 if ($custprice_line->default_vat_code && !preg_match('/\‍(.*\‍)/', $tva_tx)) {
1192 $tva_tx .= ' (' . $custprice_line->default_vat_code . ')';
1193 }
1194 $tva_npr = $custprice_line->recuperableonly;
1195 if (empty($tva_tx)) {
1196 $tva_npr = 0;
1197 }*/
1198 break;
1199 }
1200 }
1201 }
1202 } else {
1203 setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
1204 }
1205 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY')) {
1206 // If price per quantity
1207 if ($prod->prices_by_qty[0]) { // yes, this product has some prices per quantity
1208 // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
1209 $pqp = GETPOSTINT('pbq');
1210
1211 // Search price into product_price_by_qty from $prod->id
1212 foreach ($prod->prices_by_qty_list[0] as $priceforthequantityarray) {
1213 if ($priceforthequantityarray['rowid'] != $pqp) {
1214 continue;
1215 }
1216 // We found the price
1217 if ($priceforthequantityarray['price_base_type'] == 'HT') {
1218 $pu_ht = $priceforthequantityarray['unitprice'];
1219 } else {
1220 $pu_ttc = $priceforthequantityarray['unitprice'];
1221 }
1222 // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST.
1223 break;
1224 }
1225 }
1226 } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
1227 // If price per quantity and customer
1228 if ($prod->prices_by_qty[$object->thirdparty->price_level]) { // yes, this product has some prices per quantity
1229 // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
1230 $pqp = GETPOSTINT('pbq');
1231 // Search price into product_price_by_qty from $prod->id
1232 foreach ($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) {
1233 if ($priceforthequantityarray['rowid'] != $pqp) {
1234 continue;
1235 }
1236 // We found the price
1237 if ($priceforthequantityarray['price_base_type'] == 'HT') {
1238 $pu_ht = $priceforthequantityarray['unitprice'];
1239 } else {
1240 $pu_ttc = $priceforthequantityarray['unitprice'];
1241 }
1242 // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST.
1243 break;
1244 }
1245 }
1246 }
1247
1248 $tmpvat = (float) price2num(preg_replace('/\s*\‍(.*\‍)/', '', $tva_tx));
1249 $tmpprodvat = (float) price2num(preg_replace('/\s*\‍(.*\‍)/', '', (string) $prod->tva_tx));
1250
1251 // Set unit price to use
1252 if (!empty($price_ht) || (string) $price_ht === '0') {
1253 $pu_ht = (float) price2num($price_ht, 'MU');
1254 $pu_ttc = (float) price2num((float) $pu_ht * (1 + ((float) $tmpvat / 100)), 'MU');
1255 } elseif (!empty($price_ht_devise) || (string) $price_ht_devise === '0') {
1256 $pu_ht_devise = price2num($price_ht_devise, 'MU');
1257 $pu_ttc_devise = (float) price2num((float) $pu_ht_devise * (1 + ((float) $tmpvat / 100)), 'MU');
1258 $pu_ht = '';
1259 $pu_ttc = '';
1260 } elseif (!empty($price_ttc) || (string) $price_ttc === '0') {
1261 $pu_ttc = (float) price2num($price_ttc, 'MU');
1262 $pu_ht = (float) price2num((float) $pu_ttc / (1 + ((float) $tmpvat / 100)), 'MU');
1263 } elseif (!empty($price_ttc_devise) || (string) $price_ttc_devise === '0') {
1264 $pu_ttc_devise = (float) price2num($price_ttc_devise, 'MU');
1265 $pu_ht_devise = (float) price2num((float) $pu_ttc_devise / (1 + ((float) $tmpvat / 100)), 'MU');
1266 $pu_ht = '';
1267 $pu_ttc = '';
1268 } elseif ($tmpvat != $tmpprodvat) {
1269 // Is this still used ?
1270 if ($price_base_type != 'HT') {
1271 $pu_ht = (float) price2num((float) $pu_ttc / (1 + ((float) $tmpvat / 100)), 'MU');
1272 } else {
1273 $pu_ttc = (float) price2num((float) $pu_ht * (1 + ((float) $tmpvat / 100)), 'MU');
1274 }
1275 }
1276
1277 $desc = '';
1278
1279 // Define output language
1280 if (getDolGlobalInt('MAIN_MULTILANGS') && getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
1281 $outputlangs = $langs;
1282 $newlang = '';
1283 if (/* empty($newlang) && */GETPOST('lang_id', 'aZ09')) {
1284 $newlang = GETPOST('lang_id', 'aZ09');
1285 }
1286 if (empty($newlang)) {
1287 $newlang = $object->thirdparty->default_lang;
1288 }
1289 if (!empty($newlang)) {
1290 $outputlangs = new Translate("", $conf);
1291 $outputlangs->setDefaultLang($newlang);
1292 }
1293
1294 $desc = (!empty($prod->multilangs[$outputlangs->defaultlang]["description"])) ? $prod->multilangs[$outputlangs->defaultlang]["description"] : $prod->description;
1295 } else {
1296 $desc = $prod->description;
1297 }
1298
1299 if (getDolGlobalInt('PRODUIT_AUTOFILL_DESC') == 0) {
1300 // 'DoNotAutofillButAutoConcat'
1301 $desc = dol_concatdesc($desc, $line_desc, false, getDolGlobalString('MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION') ? true : false);
1302 } else {
1303 //'AutoFillFormFieldBeforeSubmit' or 'DoNotUseDescriptionOfProdut' => User has already done the modification they want
1304 $desc = $line_desc;
1305 }
1306
1307 // Add custom code and origin country into description
1308 if (!getDolGlobalString('MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE') && (!empty($prod->customcode) || !empty($prod->country_code))) {
1309 $tmptxt = '(';
1310 // Define output language
1311 if (getDolGlobalInt('MAIN_MULTILANGS') && getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
1312 $outputlangs = $langs;
1313 $newlang = '';
1314 if (/* empty($newlang) && */GETPOST('lang_id', 'alpha')) {
1315 $newlang = GETPOST('lang_id', 'alpha');
1316 }
1317 if (empty($newlang)) {
1318 $newlang = $object->thirdparty->default_lang;
1319 }
1320 if (!empty($newlang)) {
1321 $outputlangs = new Translate("", $conf);
1322 $outputlangs->setDefaultLang($newlang);
1323 $outputlangs->load('products');
1324 }
1325 if (!empty($prod->customcode)) {
1326 $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomsCode") . ': ' . $prod->customcode;
1327 }
1328 if (!empty($prod->customcode) && !empty($prod->country_code)) {
1329 $tmptxt .= ' - ';
1330 }
1331 if (!empty($prod->country_code)) {
1332 $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, '', $db, $outputlangs, 0);
1333 }
1334 } else {
1335 if (!empty($prod->customcode)) {
1336 $tmptxt .= $langs->transnoentitiesnoconv("CustomsCode") . ': ' . $prod->customcode;
1337 }
1338 if (!empty($prod->customcode) && !empty($prod->country_code)) {
1339 $tmptxt .= ' - ';
1340 }
1341 if (!empty($prod->country_code)) {
1342 $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin") . ': ' . getCountry($prod->country_code, '', $db, $langs, 0);
1343 }
1344 }
1345 $tmptxt .= ')';
1346 $desc = dol_concatdesc($desc, $tmptxt);
1347 }
1348
1349 $type = $prod->type;
1350 $fk_unit = $prod->fk_unit;
1351 } else {
1352 $pu_ht = price2num($price_ht, 'MU');
1353 $pu_ttc = price2num($price_ttc, 'MU');
1354 $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
1355 $tva_tx = str_replace('*', '', $tva_tx);
1356 if (empty($tva_tx)) {
1357 $tva_npr = 0;
1358 }
1359 $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
1360 $desc = $line_desc;
1361 $type = GETPOST('type');
1362 $fk_unit = GETPOST('units', 'alpha');
1363 $pu_ht_devise = price2num($price_ht_devise, 'MU');
1364 $pu_ttc_devise = price2num($price_ttc_devise, 'MU');
1365
1366 if ($pu_ttc && !$pu_ht) {
1367 $price_base_type = 'TTC';
1368 }
1369 }
1370
1371 $info_bits = 0;
1372 if ($tva_npr) {
1373 $info_bits |= 0x01;
1374 }
1375
1376 // Local Taxes
1377 $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
1378 $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
1379
1380 // Margin
1381 $fournprice = (int) (GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : 0); // This can be id of supplier price, or 'pmpprice' or 'costprice', or 'inputprice', we force to keep ID only
1382 $buyingprice = price2num((GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''), '', 2); // If buying_price is '0', we must keep this value
1383
1384 // Prepare a price equivalent for minimum price check
1385 $pu_equivalent = $pu_ht;
1386 $pu_equivalent_ttc = $pu_ttc;
1387
1388 $currency_tx = $object->multicurrency_tx;
1389
1390 // Check if we have a foreign currency
1391 // If so, we update the pu_equiv as the equivalent price in base currency
1392 if ($pu_ht == '' && $pu_ht_devise != '' && $currency_tx != '' && !empty((float) $currency_tx)) {
1393 $pu_equivalent = (float) $pu_ht_devise / (float) $currency_tx;
1394 }
1395 if ($pu_ttc == '' && $pu_ttc_devise != '' && $currency_tx != '' && !empty((float) $currency_tx)) {
1396 $pu_equivalent_ttc = (float) $pu_ttc_devise / (float) $currency_tx;
1397 }
1398
1399 // TODO $pu_equivalent or $pu_equivalent_ttc must be calculated from the one not null taking into account all taxes
1400 /*
1401 if ($pu_equivalent) {
1402 $tmp = calcul_price_total(1, $pu_equivalent, 0, $tva_tx, -1, -1, 0, 'HT', $info_bits, $type);
1403 $pu_equivalent_ttc = ...
1404 } else {
1405 $tmp = calcul_price_total(1, $pu_equivalent_ttc, 0, $tva_tx, -1, -1, 0, 'TTC', $info_bits, $type);
1406 $pu_equivalent_ht = ...
1407 }
1408 */
1409
1410 //var_dump(price2num($price_min)); var_dump(price2num($pu_ht)); var_dump($remise_percent);
1411 //var_dump(price2num($price_min_ttc)); var_dump(price2num($pu_ttc)); var_dump($remise_percent);exit;
1412
1413 $desc = dol_htmlcleanlastbr($desc);
1414
1415 // Check price is not lower than minimum
1416 if ($usermustrespectpricemin) {
1417 if ($pu_equivalent && $price_min && (((float) price2num($pu_equivalent) * (1 - $remise_percent / 100)) < (float) price2num($price_min)) && $price_base_type == 'HT') {
1418 $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
1419 setEventMessages($mesg, null, 'errors');
1420 $error++;
1421 } elseif ($pu_equivalent_ttc && $price_min_ttc && (((float) price2num($pu_equivalent_ttc) * (1 - $remise_percent / 100)) < (float) price2num($price_min_ttc)) && $price_base_type == 'TTC') {
1422 $mesg = $langs->trans("CantBeLessThanMinPriceInclTax", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
1423 setEventMessages($mesg, null, 'errors');
1424 $error++;
1425 }
1426 }
1427
1428 if (!$error) {
1429 // Insert line
1430 $result = $object->addline($desc, $pu_ht, (float) $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $info_bits, 0, $price_base_type, $pu_ttc, $date_start, $date_end, $type, min($rank, count($object->lines) + 1), 0, GETPOSTINT('fk_parent_line'), (int) $fournprice, $buyingprice, $label, $array_options, $fk_unit, '', 0, (float) $pu_ht_devise);
1431
1432 if ($result > 0) {
1433 $db->commit();
1434
1435 $ret = $object->fetch($object->id); // Reload to get new records
1436 if ($ret > 0) {
1437 $object->fetch_thirdparty();
1438 }
1439
1440 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1441 // Define output language
1442 $outputlangs = $langs;
1443 $newlang = GETPOST('lang_id', 'alpha');
1444 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1445 $newlang = $object->thirdparty->default_lang;
1446 }
1447 if (!empty($newlang)) {
1448 $outputlangs = new Translate("", $conf);
1449 $outputlangs->setDefaultLang($newlang);
1450 }
1451
1452 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1453 }
1454
1455 unset($_POST['prod_entry_mode']);
1456
1457 unset($_POST['qty']);
1458 unset($_POST['type']);
1459 unset($_POST['remise_percent']);
1460 unset($_POST['price_ht']);
1461 unset($_POST['multicurrency_price_ht']);
1462 unset($_POST['price_ttc']);
1463 unset($_POST['tva_tx']);
1464 unset($_POST['product_ref']);
1465 unset($_POST['product_label']);
1466 unset($_POST['product_desc']);
1467 unset($_POST['fournprice']);
1468 unset($_POST['buying_price']);
1469 unset($_POST['np_marginRate']);
1470 unset($_POST['np_markRate']);
1471 unset($_POST['dp_desc']);
1472 unset($_POST['idprod']);
1473 unset($_POST['units']);
1474
1475 unset($_POST['date_starthour']);
1476 unset($_POST['date_startmin']);
1477 unset($_POST['date_startsec']);
1478 unset($_POST['date_startday']);
1479 unset($_POST['date_startmonth']);
1480 unset($_POST['date_startyear']);
1481 unset($_POST['date_endhour']);
1482 unset($_POST['date_endmin']);
1483 unset($_POST['date_endsec']);
1484 unset($_POST['date_endday']);
1485 unset($_POST['date_endmonth']);
1486 unset($_POST['date_endyear']);
1487 } else {
1488 $db->rollback();
1489
1490 setEventMessages($object->error, $object->errors, 'errors');
1491 }
1492 }
1493 }
1494 } elseif ($action == 'updatetitleline' && GETPOSTISSET("save") && $usercancreate && !GETPOST('cancel', 'alpha')) {
1495 // Handling updating a title line for subtotals module
1496
1497 $langs->load('subtotals');
1498
1499 $desc = GETPOST('line_desc', 'alphanohtml') ?? $langs->trans("Title");
1500 $depth = GETPOSTINT('line_depth') ?? 1;
1501
1502 $subtotal_options = array();
1503
1504 foreach (Commande::$TITLE_OPTIONS as $option) {
1505 $value = GETPOST($option, 'alphanohtml');
1506 if ($value) {
1507 $subtotal_options[$option] = $value == 'on' ? 1 : $value;
1508 }
1509 }
1510
1511 // Update line
1512 $result = $object->updateSubtotalLine($langs, GETPOSTINT('lineid'), $desc, $depth, $subtotal_options);
1513
1514 if ($result >= 0) {
1515 if ($result == 0) {
1516 setEventMessages($object->error, $object->errors, 'warnings');
1517 }
1518 $ret = $object->fetch($object->id); // Reload to get new records
1519 $object->fetch_thirdparty();
1520
1521 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1522 // Define output language
1523 $outputlangs = $langs;
1524 $newlang = GETPOST('lang_id', 'alpha');
1525 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1526 $newlang = $object->thirdparty->default_lang;
1527 }
1528 if (!empty($newlang)) {
1529 $outputlangs = new Translate("", $conf);
1530 $outputlangs->setDefaultLang($newlang);
1531 }
1532
1533 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1534 }
1535 } else {
1536 setEventMessages($object->error, $object->errors, 'errors');
1537 }
1538 } elseif ($action == 'updatesubtotalline' && GETPOSTISSET("save") && $usercancreate && !GETPOST('cancel', 'alpha')) {
1539 // Handling updating a subtotal line for subtotals module
1540
1541 $langs->load('subtotals');
1542
1543 $desc = GETPOST('line_desc', 'alphanohtml');
1544 $depth = GETPOSTINT('line_depth');
1545
1546 $subtotal_options = array();
1547
1548 foreach (Commande::$SUBTOTAL_OPTIONS as $option) {
1549 $value = GETPOST($option, 'alphanohtml');
1550 if ($value) {
1551 $subtotal_options[$option] = $value == 'on' ? 1 : $value;
1552 }
1553 }
1554
1555 // Update line
1556 $result = $object->updateSubtotalLine($langs, GETPOSTINT('lineid'), $desc, $depth, $subtotal_options);
1557
1558 if ($result > 0) {
1559 $ret = $object->fetch($object->id); // Reload to get new records
1560 $object->fetch_thirdparty();
1561
1562 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1563 // Define output language
1564 $outputlangs = $langs;
1565 $newlang = GETPOST('lang_id', 'alpha');
1566 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1567 $newlang = $object->thirdparty->default_lang;
1568 }
1569 if (!empty($newlang)) {
1570 $outputlangs = new Translate("", $conf);
1571 $outputlangs->setDefaultLang($newlang);
1572 }
1573
1574 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1575 }
1576 } else {
1577 setEventMessages($object->error, $object->errors, 'errors');
1578 }
1579 } elseif ($action == 'updateline' && $usercancreate && GETPOST('save')) {
1580 // Update a line
1581
1582 // Clean parameters
1583 $date_start = '';
1584 $date_end = '';
1585 $date_start = dol_mktime(GETPOSTINT('date_starthour'), GETPOSTINT('date_startmin'), GETPOSTINT('date_startsec'), GETPOSTINT('date_startmonth'), GETPOSTINT('date_startday'), GETPOSTINT('date_startyear'));
1586 $date_end = dol_mktime(GETPOSTINT('date_endhour'), GETPOSTINT('date_endmin'), GETPOSTINT('date_endsec'), GETPOSTINT('date_endmonth'), GETPOSTINT('date_endday'), GETPOSTINT('date_endyear'));
1587
1588 $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml'));
1589
1590 // Define info_bits
1591 $info_bits = 0;
1592 if (preg_match('/\*/', GETPOST('tva_tx'))) {
1593 $info_bits |= 0x01;
1594 }
1595
1596 // Define vat_rate
1597 $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx', 'alpha') : 0);
1598 $vat_rate = str_replace('*', '', $vat_rate);
1599 $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
1600 $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
1601 $pu_ht = price2num(GETPOST('price_ht'), '', 2);
1602 $pu_ttc = price2num(GETPOST('price_ttc'), '', 2);
1603
1604 $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2);
1605 $pu_ttc_devise = price2num(GETPOST('multicurrency_subprice_ttc'), '', 2);
1606
1607 $qty = price2num(GETPOST('qty', 'alpha'), 'MS');
1608
1609 // Prepare a price equivalent for minimum price check
1610 $pu_equivalent = $pu_ht;
1611 $pu_equivalent_ttc = $pu_ttc;
1612
1613 $currency_tx = $object->multicurrency_tx;
1614
1615 // Check if we have a foreign currency
1616 // If so, we update the pu_equiv as the equivalent price in base currency
1617 if ($pu_ht == '' && $pu_ht_devise != '' && $currency_tx != '' && !empty((float) $currency_tx)) {
1618 $pu_equivalent = (float) $pu_ht_devise / (float) $currency_tx;
1619 }
1620 if ($pu_ttc == '' && $pu_ttc_devise != '' && $currency_tx != '' && !empty((float) $currency_tx)) {
1621 $pu_equivalent_ttc = (float) $pu_ttc_devise / (float) $currency_tx;
1622 }
1623
1624 // TODO $pu_equivalent or $pu_equivalent_ttc must be calculated from the one not null taking into account all taxes
1625 /*
1626 if ($pu_equivalent) {
1627 $tmp = calcul_price_total(1, $pu_equivalent, 0, $vat_rate, -1, -1, 0, 'HT', $info_bits, $type);
1628 $pu_equivalent_ttc = ...
1629 } else {
1630 $tmp = calcul_price_total(1, $pu_equivalent_ttc, 0, $vat_rate, -1, -1, 0, 'TTC', $info_bits, $type);
1631 $pu_equivalent_ht = ...
1632 }
1633 */
1634
1635 // Add buying price
1636 $fournprice = (int) (GETPOST('fournprice') ? GETPOST('fournprice') : ''); // This can be id of supplier price, or 'pmpprice' or 'costprice', or 'inputprice', we force to keep ID only
1637 $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we must keep this value
1638
1639 // Extrafields Lines
1640 $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
1641 $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
1642 // Unset extrafield POST Data
1643 if (is_array($extralabelsline)) {
1644 foreach ($extralabelsline as $key => $value) {
1645 unset($_POST["options_" . $key]);
1646 }
1647 }
1648
1649 // Define special_code for special lines
1650 $special_code = GETPOSTINT('special_code');
1651 if (!GETPOST('qty')) {
1652 $special_code = 3;
1653 }
1654
1655 $remise_percent = GETPOST('remise_percent') != '' ? price2num(GETPOST('remise_percent'), '', 2) : 0;
1656
1657 $pu = $pu_ht;
1658 $price_base_type = 'HT';
1659 if (empty($pu) && !empty($pu_ttc)) {
1660 $pu = $pu_ttc;
1661 $price_base_type = 'TTC';
1662 }
1663
1664 // Check minimum price
1665 $productid = GETPOSTINT('productid');
1666 if (!empty($productid)) {
1667 $product = new Product($db);
1668 $product->fetch($productid);
1669
1670 $type = $product->type;
1671
1672 $price_min = $product->price_min;
1673 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !empty($object->thirdparty->price_level)) {
1674 $price_min = $product->multiprices_min[$object->thirdparty->price_level];
1675 }
1676 $price_min_ttc = $product->price_min_ttc;
1677 if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !empty($object->thirdparty->price_level)) {
1678 $price_min_ttc = $product->multiprices_min_ttc[$object->thirdparty->price_level];
1679 }
1680
1681 $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
1682
1683 // Check price is not lower than minimum
1684 if ($usermustrespectpricemin) {
1685 if ($pu_equivalent && $price_min && (((float) price2num($pu_equivalent) * (1 - (float) $remise_percent / 100)) < (float) price2num($price_min)) && $price_base_type == 'HT') {
1686 $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
1687 setEventMessages($mesg, null, 'errors');
1688 $error++;
1689 $action = 'editline';
1690 } elseif ($pu_equivalent_ttc && $price_min_ttc && (((float) price2num($pu_equivalent_ttc) * (1 - (float) $remise_percent / 100)) < (float) price2num($price_min_ttc)) && $price_base_type == 'TTC') {
1691 $mesg = $langs->trans("CantBeLessThanMinPriceInclTax", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
1692 setEventMessages($mesg, null, 'errors');
1693 $error++;
1694 $action = 'editline';
1695 }
1696 }
1697 } else {
1698 $type = GETPOST('type');
1699 $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
1700
1701 // Check parameters
1702 if (GETPOST('type') < 0) {
1703 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
1704 $error++;
1705 $action = 'editline';
1706 }
1707 }
1708
1709 if ($qty < 0 && !getDolGlobalString('ORDER_ENABLE_NEGATIVE_QTY')) {
1710 setEventMessages($langs->trans('FieldCannotBeNegative', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
1711 $error++;
1712 $action = 'editline';
1713 }
1714
1715 $object->loadExpeditions();
1716 if (isset($object->expeditions[GETPOST('lineid', 'int')])) {
1717 if ($qty < $object->expeditions[GETPOST('lineid', 'int')]) {
1718 setEventMessages($langs->trans('ErrorQtyOrderedLessQtyShipped'), null, 'errors');
1719 $error++;
1720 $action = 'editline';
1721 }
1722 }
1723
1724 if (!$error) {
1725 $db->begin();
1726
1727 if (!$user->hasRight('margins', 'creer')) {
1728 foreach ($object->lines as &$line) {
1729 if ($line->id == GETPOSTINT('lineid')) {
1730 $fournprice = $line->fk_fournprice;
1731 $buyingprice = $line->pa_ht;
1732 break;
1733 }
1734 }
1735 }
1736
1737 $qty = price2num(GETPOST('qty', 'alpha'), 'MS');
1738
1739 $result = $object->updateline(GETPOSTINT('lineid'), $description, (float) $pu, (float) $qty, $remise_percent, $vat_rate, $localtax1_rate, $localtax2_rate, $price_base_type, $info_bits, $date_start, $date_end, $type, GETPOSTINT('fk_parent_line'), 0, (int) $fournprice, $buyingprice, $label, $special_code, $array_options, GETPOSTINT('units'), (float) $pu_ht_devise);
1740
1741 if ($result >= 0) {
1742 $db->commit();
1743
1744 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1745 // Define output language
1746 $outputlangs = $langs;
1747 $newlang = '';
1748 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
1749 $newlang = GETPOST('lang_id', 'aZ09');
1750 }
1751 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1752 $newlang = $object->thirdparty->default_lang;
1753 }
1754 if (!empty($newlang)) {
1755 $outputlangs = new Translate("", $conf);
1756 $outputlangs->setDefaultLang($newlang);
1757 }
1758
1759 $ret = $object->fetch($object->id); // Reload to get new records
1760 $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1761 }
1762
1763 unset($_POST['qty']);
1764 unset($_POST['type']);
1765 unset($_POST['productid']);
1766 unset($_POST['remise_percent']);
1767 unset($_POST['price_ht']);
1768 unset($_POST['multicurrency_price_ht']);
1769 unset($_POST['price_ttc']);
1770 unset($_POST['tva_tx']);
1771 unset($_POST['product_ref']);
1772 unset($_POST['product_label']);
1773 unset($_POST['product_desc']);
1774 unset($_POST['fournprice']);
1775 unset($_POST['buying_price']);
1776
1777 unset($_POST['date_starthour']);
1778 unset($_POST['date_startmin']);
1779 unset($_POST['date_startsec']);
1780 unset($_POST['date_startday']);
1781 unset($_POST['date_startmonth']);
1782 unset($_POST['date_startyear']);
1783 unset($_POST['date_endhour']);
1784 unset($_POST['date_endmin']);
1785 unset($_POST['date_endsec']);
1786 unset($_POST['date_endday']);
1787 unset($_POST['date_endmonth']);
1788 unset($_POST['date_endyear']);
1789 } else {
1790 $db->rollback();
1791
1792 setEventMessages($object->error, $object->errors, 'errors');
1793 }
1794 }
1795 } elseif ($action == 'updateline' && $usercancreate && GETPOST('cancel', 'alpha')) {
1796 header('Location: ' . $_SERVER['PHP_SELF'] . '?id=' . $object->id); // To re-display card in edit mode
1797 exit();
1798 } elseif ($action == 'confirm_validate' && $confirm == 'yes' && $usercanvalidate) {
1799 $idwarehouse = GETPOSTINT('idwarehouse');
1800
1801 $qualified_for_stock_change = 0;
1802 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
1803 $qualified_for_stock_change = $object->hasProductsOrServices(2);
1804 } else {
1805 $qualified_for_stock_change = $object->hasProductsOrServices(1);
1806 }
1807
1808 // Check parameters
1809 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') && $qualified_for_stock_change) {
1810 if (!$idwarehouse || $idwarehouse == -1) {
1811 $error++;
1812 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
1813 $action = '';
1814 }
1815 }
1816
1817 if (!$error) {
1818 $locationTarget = '';
1819
1820 $db->begin();
1821
1822 $result = $object->valid($user, $idwarehouse);
1823 if ($result >= 0) {
1824 $error = 0;
1825 $deposit = null;
1826
1827 $deposit_percent_from_payment_terms = (float) getDictionaryValue('c_payment_term', 'deposit_percent', $object->cond_reglement_id);
1828
1829 if (
1830 GETPOST('generate_deposit', 'alpha') == 'on' && !empty($deposit_percent_from_payment_terms)
1831 && isModEnabled('invoice') && $user->hasRight('facture', 'creer')
1832 ) {
1833 require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
1834
1835 $date = dol_mktime(0, 0, 0, GETPOSTINT('datefmonth'), GETPOSTINT('datefday'), GETPOSTINT('datefyear'));
1836 $forceFields = array();
1837
1838 if (GETPOSTISSET('date_pointoftax')) {
1839 $forceFields['date_pointoftax'] = dol_mktime(0, 0, 0, GETPOSTINT('date_pointoftaxmonth'), GETPOSTINT('date_pointoftaxday'), GETPOSTINT('date_pointoftaxyear'));
1840 }
1841
1842 $deposit = Facture::createDepositFromOrigin($object, $date, GETPOSTINT('cond_reglement_id'), $user, 0, GETPOSTINT('validate_generated_deposit') == 'on', $forceFields);
1843
1844 if ($deposit) {
1845 setEventMessage('DepositGenerated');
1846 $locationTarget = DOL_URL_ROOT . '/compta/facture/card.php?id=' . $deposit->id;
1847 } else {
1848 $error++;
1849 setEventMessages($object->error, $object->errors, 'errors');
1850 }
1851 }
1852
1853 // Define output language
1854 if (! $error) {
1855 $db->commit();
1856
1857 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1858 $outputlangs = $langs;
1859 $newlang = '';
1860 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
1861 $newlang = GETPOST('lang_id', 'aZ09');
1862 }
1863 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1864 $newlang = $object->thirdparty->default_lang;
1865 }
1866 if (!empty($newlang)) {
1867 $outputlangs = new Translate("", $conf);
1868 $outputlangs->setDefaultLang($newlang);
1869 }
1870 $model = $object->model_pdf;
1871 $ret = $object->fetch($id); // Reload to get new records
1872
1873 $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1874
1875 if ($deposit) {
1876 $deposit->fetch($deposit->id); // Reload to get new records
1877 $deposit->generateDocument($deposit->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
1878 }
1879 }
1880
1881 if ($locationTarget) {
1882 header('Location: ' . $locationTarget);
1883 exit;
1884 }
1885 } else {
1886 $db->rollback();
1887 }
1888 } else {
1889 $db->rollback();
1890 setEventMessages($object->error, $object->errors, 'errors');
1891 }
1892 }
1893 } elseif ($action == 'confirm_modif' && $usercancreate) {
1894 // Go back to draft status
1895 $idwarehouse = GETPOST('idwarehouse');
1896
1897 $qualified_for_stock_change = 0;
1898 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
1899 $qualified_for_stock_change = $object->hasProductsOrServices(2);
1900 } else {
1901 $qualified_for_stock_change = $object->hasProductsOrServices(1);
1902 }
1903
1904 // Check parameters
1905 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') && $qualified_for_stock_change) {
1906 if (!$idwarehouse || $idwarehouse == -1) {
1907 $error++;
1908 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
1909 $action = '';
1910 }
1911 }
1912
1913 if (!$error) {
1914 $result = $object->setDraft($user, $idwarehouse);
1915 if ($result >= 0) {
1916 // Define output language
1917 if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1918 $outputlangs = $langs;
1919 $newlang = '';
1920 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
1921 $newlang = GETPOST('lang_id', 'aZ09');
1922 }
1923 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
1924 $newlang = $object->thirdparty->default_lang;
1925 }
1926 if (!empty($newlang)) {
1927 $outputlangs = new Translate("", $conf);
1928 $outputlangs->setDefaultLang($newlang);
1929 }
1930 $model = $object->model_pdf;
1931 $ret = $object->fetch($id); // Reload to get new records
1932
1933 $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1934 }
1935 } else {
1936 setEventMessages($object->error, $object->errors, 'errors');
1937 }
1938 }
1939 } elseif ($action == 'confirm_shipped' && $confirm == 'yes' && $usercanclose) {
1940 $result = $object->cloture($user);
1941 if ($result < 0) {
1942 setEventMessages($object->error, $object->errors, 'errors');
1943 }
1944 } elseif ($action == 'confirm_cancel' && $confirm == 'yes' && $usercancancel) {
1945 $idwarehouse = GETPOSTINT('idwarehouse');
1946
1947 $qualified_for_stock_change = 0;
1948 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
1949 $qualified_for_stock_change = $object->hasProductsOrServices(2);
1950 } else {
1951 $qualified_for_stock_change = $object->hasProductsOrServices(1);
1952 }
1953
1954 // Check parameters
1955 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') && $qualified_for_stock_change) {
1956 if (!$idwarehouse || $idwarehouse == -1) {
1957 $error++;
1958 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
1959 $action = '';
1960 }
1961 }
1962
1963 if (!$error) {
1964 $result = $object->cancel($user, $idwarehouse);
1965
1966 if ($result < 0) {
1967 setEventMessages($object->error, $object->errors, 'errors');
1968 }
1969 }
1970 }
1971
1972 if ($action == 'update_extras' && $permissiontoeditextra) {
1973 $object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
1974
1975 $attribute_name = GETPOST('attribute', 'aZ09');
1976
1977 // Fill array 'array_options' with data from update form
1978 $ret = $extrafields->setOptionalsFromPost(null, $object, $attribute_name);
1979 if ($ret < 0) {
1980 $error++;
1981 }
1982
1983 if (!$error) {
1984 // Actions on extra fields
1985 $result = $object->updateExtraField($attribute_name, 'ORDER_MODIFY');
1986 if ($result < 0) {
1987 setEventMessages($object->error, $object->errors, 'errors');
1988 $error++;
1989 }
1990 }
1991
1992 if ($error) {
1993 $action = 'edit_extras';
1994 }
1995 }
1996
1997 // Add lines from objectlinked
1998 if ($action == 'import_lines_from_object' && $usercancreate && $object->status == Commande::STATUS_DRAFT) {
1999 $fromElement = GETPOST('fromelement');
2000 $fromElementid = GETPOST('fromelementid');
2001 $importLines = GETPOST('line_checkbox');
2002
2003 if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && preg_match('/^[a-zA-Z]+$/', $fromElement) && !empty($fromElementid)) {
2004 if ($fromElement == 'commande') {
2005 dol_include_once('/' . $fromElement . '/class/' . $fromElement . '.class.php');
2006 $lineClassName = 'OrderLine';
2007 } elseif ($fromElement == 'propal') {
2008 dol_include_once('/comm/' . $fromElement . '/class/' . $fromElement . '.class.php');
2009 $lineClassName = 'PropaleLigne';
2010 } elseif ($fromElement == 'facture') {
2011 dol_include_once('/compta/' . $fromElement . '/class/' . $fromElement . '.class.php');
2012 $lineClassName = 'FactureLigne';
2013 }
2014 $nextRang = count($object->lines) + 1;
2015 $importCount = 0;
2016 $error = 0;
2017 foreach ($importLines as $lineId) {
2018 $lineId = intval($lineId);
2019 $originLine = new $lineClassName($db);
2020 if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) {
2021 $originLine->fetch_optionals();
2022 $desc = $originLine->desc;
2023 $pu_ht = $originLine->subprice;
2024 $qty = $originLine->qty;
2025 $txtva = $originLine->tva_tx;
2026 $txlocaltax1 = $originLine->localtax1_tx;
2027 $txlocaltax2 = $originLine->localtax2_tx;
2028 $fk_product = $originLine->fk_product;
2029 $remise_percent = $originLine->remise_percent;
2030 $date_start = $originLine->date_start;
2031 $date_end = $originLine->date_end;
2032 $fk_code_ventilation = 0;
2033 $info_bits = $originLine->info_bits;
2034 $fk_remise_except = $originLine->fk_remise_except;
2035 $price_base_type = 'HT';
2036 $pu_ttc = 0;
2037 $type = $originLine->product_type;
2038 $rang = $nextRang++;
2039 $special_code = $originLine->special_code;
2040 $origin = $originLine->element;
2041 $origin_id = $originLine->id;
2042 $fk_parent_line = 0;
2043 $fk_fournprice = $originLine->fk_fournprice;
2044 $pa_ht = $originLine->pa_ht;
2045 $label = $originLine->label;
2046 $array_options = $originLine->array_options;
2047 $situation_percent = 100;
2048 $fk_prev_id = '';
2049 $fk_unit = $originLine->fk_unit;
2050 $pu_ht_devise = $originLine->multicurrency_subprice;
2051
2052 $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $info_bits, $fk_remise_except, $price_base_type, $pu_ttc, $date_start, $date_end, $type, $rang, $special_code, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $array_options, $fk_unit, $origin, $origin_id, $pu_ht_devise);
2053
2054 if ($res > 0) {
2055 $importCount++;
2056 } else {
2057 $error++;
2058 }
2059 } else {
2060 $error++;
2061 }
2062 }
2063
2064 if ($error) {
2065 setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors');
2066 }
2067 }
2068 }
2069
2070 // Actions when printing a doc from card
2071 include DOL_DOCUMENT_ROOT . '/core/actions_printing.inc.php';
2072
2073 // Actions to build doc
2074 $upload_dir = !empty($conf->commande->multidir_output[$object->entity ?? $conf->entity]) ? $conf->commande->multidir_output[$object->entity ?? $conf->entity] : $conf->commande->dir_output;
2075 $permissiontoadd = $usercancreate;
2076 include DOL_DOCUMENT_ROOT . '/core/actions_builddoc.inc.php';
2077
2078 // Actions to send emails
2079 $triggersendname = 'ORDER_SENTBYMAIL';
2080 $paramname = 'id';
2081 $autocopy = 'MAIN_MAIL_AUTOCOPY_ORDER_TO'; // used to know the automatic BCC to add
2082 $trackid = 'ord' . $object->id;
2083 include DOL_DOCUMENT_ROOT . '/core/actions_sendmails.inc.php';
2084
2085
2086 if (!$error && getDolGlobalString('MAIN_DISABLE_CONTACTS_TAB') && $usercancreate) {
2087 if ($action == 'addcontact') { // Test on permission already done
2088 if ($object->id > 0) {
2089 $contactid = (GETPOST('userid') ? GETPOSTINT('userid') : GETPOSTINT('contactid'));
2090 $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
2091 $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
2092 }
2093
2094 if ($result >= 0) {
2095 header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
2096 exit();
2097 } else {
2098 if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2099 $langs->load("errors");
2100 setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
2101 } else {
2102 setEventMessages($object->error, $object->errors, 'errors');
2103 }
2104 }
2105 } elseif ($action == 'swapstatut') { // Test on permission already done
2106 // bascule du statut d'un contact
2107 if ($object->id > 0) {
2108 $result = $object->swapContactStatus(GETPOSTINT('ligne'));
2109 } else {
2110 dol_print_error($db);
2111 }
2112 } elseif ($action == 'deletecontact') { // Test on permission already done
2113 // Efface un contact
2114 $result = $object->delete_contact($lineid);
2115
2116 if ($result >= 0) {
2117 header("Location: " . $_SERVER['PHP_SELF'] . "?id=" . $object->id);
2118 exit();
2119 } else {
2120 dol_print_error($db);
2121 }
2122 }
2123 }
2124}
2125
2126
2127/*
2128 * View
2129 */
2130
2131$title = $object->ref . " - " . $langs->trans('Card');
2132if ($action == 'create') {
2133 $title = $langs->trans("NewOrder");
2134}
2135$help_url = 'EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes|DE:Modul_Kundenaufträge';
2136
2137llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-order page-card');
2138
2139$form = new Form($db);
2140$formfile = new FormFile($db);
2141$formorder = new FormOrder($db);
2142$formmargin = new FormMargin($db);
2143if (isModEnabled('project')) {
2144 $formproject = new FormProjets($db);
2145}
2146
2147// Mode creation
2148if ($action == 'create' && $usercancreate) {
2149 print load_fiche_titre($langs->trans('CreateOrder'), '', 'order');
2150
2151 $soc = new Societe($db);
2152 if ($socid > 0) {
2153 $res = $soc->fetch($socid);
2154 }
2155
2156 //$remise_absolue = 0;
2157
2158 $currency_code = $conf->currency;
2159
2160 $cond_reglement_id = GETPOSTINT('cond_reglement_id');
2161 $deposit_percent = GETPOSTFLOAT('cond_reglement_id_deposit_percent');
2162 $mode_reglement_id = GETPOSTINT('mode_reglement_id');
2163 $fk_account = GETPOSTINT('fk_account');
2164
2165 if (!empty($origin) && !empty($originid)) {
2166 // Parse element/subelement (ex: project_task)
2167 $element = $subelement = $origin;
2168 $regs = array();
2169 if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
2170 $element = $regs[1];
2171 $subelement = $regs[2];
2172 }
2173
2174 if ($element == 'project') {
2175 $projectid = $originid;
2176
2177 if (!$cond_reglement_id) {
2178 $cond_reglement_id = $soc->cond_reglement_id;
2179 }
2180 if (!$deposit_percent) {
2181 $deposit_percent = $soc->deposit_percent;
2182 }
2183 if (!$mode_reglement_id) {
2184 $mode_reglement_id = $soc->mode_reglement_id;
2185 }
2186 if (!$remise_percent) {
2187 $remise_percent = $soc->remise_percent;
2188 }
2189 } else {
2190 // For compatibility
2191 if ($element == 'order' || $element == 'commande') {
2192 $element = $subelement = 'commande';
2193 } elseif ($element == 'propal') {
2194 $element = 'comm/propal';
2195 $subelement = 'propal';
2196 } elseif ($element == 'contract') {
2197 $element = $subelement = 'contrat';
2198 }
2199
2200 dol_include_once('/' . $element . '/class/' . $subelement . '.class.php');
2201
2202 $classname = ucfirst($subelement);
2203 $objectsrc = new $classname($db);
2204 '@phan-var-force Commande|Propal|Contrat $objectsrc'; // Can possibly be other class but CommonObject is too general
2205 $objectsrc->fetch($originid);
2206 if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
2207 $objectsrc->fetch_lines();
2208 }
2209 $objectsrc->fetch_thirdparty();
2210
2211 // Replicate extrafields
2212 $objectsrc->fetch_optionals();
2213 $object->array_options = $objectsrc->array_options;
2214
2215 $projectid = (int) $objectsrc->fk_project;
2216 $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : '');
2217
2218 $soc = $objectsrc->thirdparty;
2219 $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0));
2220 $deposit_percent = (!empty($objectsrc->deposit_percent) ? $objectsrc->deposit_percent : (!empty($soc->deposit_percent) ? $soc->deposit_percent : null));
2221 $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
2222 $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
2223 $availability_id = (!empty($objectsrc->availability_id) ? $objectsrc->availability_id : 0);
2224 $shipping_method_id = (!empty($objectsrc->shipping_method_id) ? $objectsrc->shipping_method_id : (!empty($soc->shipping_method_id) ? $soc->shipping_method_id : 0));
2225 $warehouse_id = (!empty($objectsrc->warehouse_id) ? $objectsrc->warehouse_id : (!empty($soc->warehouse_id) ? $soc->warehouse_id : 0));
2226 $demand_reason_id = (!empty($objectsrc->demand_reason_id) ? $objectsrc->demand_reason_id : (!empty($soc->demand_reason_id) ? $soc->demand_reason_id : 0));
2227 // $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0));
2228 // $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
2229 $dateorder = !getDolGlobalString('MAIN_AUTOFILL_DATE_ORDER') ? -1 : '';
2230
2231 $date_delivery = (!empty($objectsrc->delivery_date) ? $objectsrc->delivery_date : '');
2232
2233 if (isModEnabled("multicurrency")) {
2234 if (!empty($objectsrc->multicurrency_code)) {
2235 $currency_code = $objectsrc->multicurrency_code;
2236 }
2237 if (getDolGlobalString('MULTICURRENCY_USE_ORIGIN_TX') && !empty($objectsrc->multicurrency_tx)) {
2238 $currency_tx = $objectsrc->multicurrency_tx;
2239 }
2240 }
2241
2242 $note_private = $object->getDefaultCreateValueFor('note_private', (!empty($objectsrc->note_private) ? $objectsrc->note_private : null));
2243 $note_public = $object->getDefaultCreateValueFor('note_public', (!empty($objectsrc->note_public) ? $objectsrc->note_public : null));
2244
2245 // Object source contacts list
2246 $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1);
2247 }
2248 } else {
2249 $cond_reglement_id = empty($soc->cond_reglement_id) ? $cond_reglement_id : $soc->cond_reglement_id;
2250 $deposit_percent = empty($soc->deposit_percent) ? $deposit_percent : $soc->deposit_percent;
2251 $mode_reglement_id = empty($soc->mode_reglement_id) ? $mode_reglement_id : $soc->mode_reglement_id;
2252 $fk_account = empty($soc->mode_reglement_id) ? $fk_account : $soc->fk_account;
2253 $availability_id = 0;
2254 $shipping_method_id = empty($soc->shipping_method_id) ? $shipping_method_id : $soc->shipping_method_id;
2255 $warehouse_id = $soc->fk_warehouse;
2256 $demand_reason_id = $soc->demand_reason_id;
2257 // $remise_percent = $soc->remise_percent;
2258 // $remise_absolue = 0;
2259 $dateorder = !getDolGlobalString('MAIN_AUTOFILL_DATE_ORDER') ? -1 : '';
2260
2261 if (isModEnabled("multicurrency") && !empty($soc->multicurrency_code)) {
2262 $currency_code = $soc->multicurrency_code;
2263 }
2264
2265 $note_private = $object->getDefaultCreateValueFor('note_private');
2266 $note_public = $object->getDefaultCreateValueFor('note_public');
2267 }
2268
2269 // If form was posted (but error returned), we must reuse the value posted in priority (standard Dolibarr behaviour)
2270 if (!GETPOST('changecompany')) {
2271 if (GETPOSTISSET('cond_reglement_id')) {
2272 $cond_reglement_id = GETPOSTINT('cond_reglement_id');
2273 }
2274 if (GETPOSTISSET('deposit_percent')) {
2275 $deposit_percent = GETPOSTFLOAT('deposit_percent');
2276 }
2277 if (GETPOSTISSET('mode_reglement_id')) {
2278 $mode_reglement_id = GETPOSTINT('mode_reglement_id');
2279 }
2280 if (GETPOSTISSET('cond_reglement_id')) {
2281 $fk_account = GETPOSTINT('fk_account');
2282 }
2283 }
2284
2285 // Warehouse default if null
2286 if ($soc->fk_warehouse > 0) {
2287 $warehouse_id = $soc->fk_warehouse;
2288 }
2289 if (isModEnabled('stock') && empty($warehouse_id) && getDolGlobalString('WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER')) {
2290 if (empty($object->warehouse_id) && getDolGlobalString('MAIN_DEFAULT_WAREHOUSE')) {
2291 $warehouse_id = getDolGlobalString('MAIN_DEFAULT_WAREHOUSE');
2292 }
2293 if (empty($object->warehouse_id) && getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER') && !empty($user->fk_warehouse)) {
2294 $warehouse_id = $user->fk_warehouse;
2295 }
2296 }
2297
2298 print '<form name="crea_commande" action="' . $_SERVER["PHP_SELF"] . '" method="POST">';
2299 print '<input type="hidden" name="token" value="' . newToken() . '">';
2300 print '<input type="hidden" name="action" value="add">';
2301 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
2302 print '<input type="hidden" name="remise_percent" value="' . $soc->remise_percent . '">';
2303 print '<input type="hidden" name="origin" value="' . $origin . '">';
2304 print '<input type="hidden" name="originid" value="' . $originid . '">';
2305 print '<input type="hidden" name="backtopage" value="' . $backtopage . '">';
2306 if (!empty($currency_tx)) {
2307 print '<input type="hidden" name="originmulticurrency_tx" value="' . $currency_tx . '">';
2308 }
2309
2310 print dol_get_fiche_head([]);
2311
2312 // Call Hook tabContentCreateOrder
2313 $parameters = array();
2314 // Note that $action and $object may be modified by hook
2315 $reshook = $hookmanager->executeHooks('tabContentCreateOrder', $parameters, $object, $action);
2316 if (empty($reshook)) {
2317 print '<table class="border centpercent">';
2318
2319 // Reference
2320 print '<tr><td class="titlefieldcreate fieldrequired">' . $langs->trans('Ref') . '</td><td>' . $langs->trans("Draft") . '</td></tr>';
2321
2322 // Reference client
2323 print '<tr><td>' . $langs->trans('RefCustomer') . '</td><td>';
2324 if (getDolGlobalString('MAIN_USE_PROPAL_REFCLIENT_FOR_ORDER') && !empty($origin) && !empty($originid)) {
2325 print '<input type="text" name="ref_client" value="' . $ref_client . '"></td>';
2326 } else {
2327 print '<input type="text" name="ref_client" value="' . GETPOST('ref_client') . '"></td>';
2328 }
2329 print '</tr>';
2330
2331 // Thirdparty
2332 print '<tr>';
2333 print '<td class="fieldrequired">' . $langs->trans('Customer') . '</td>';
2334 if ($socid > 0) {
2335 print '<td>';
2336 print $soc->getNomUrl(1, 'customer');
2337 print '<input type="hidden" name="socid" value="' . $soc->id . '">';
2338 print '</td>';
2339 } else {
2340 print '<td class="valuefieldcreate">';
2341 $filter = '((s.client:IN:1,2,3) AND (s.status:=:1))';
2342 print img_picto('', 'company', 'class="pictofixedwidth"') . $form->select_company('', 'socid', $filter, 'SelectThirdParty', 1, 0, array(), 0, 'minwidth175 maxwidth500 widthcentpercentminusxx');
2343 // reload page to retrieve customer information
2344 if (!getDolGlobalString('RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED')) {
2345 print '<script>
2346 $(document).ready(function() {
2347 $("#socid").change(function() {
2348 console.log("We have changed the company - Reload page");
2349 var socid = $(this).val();
2350 // reload page
2351 $("input[name=action]").val("create");
2352 $("input[name=changecompany]").val("1");
2353 $("form[name=crea_commande]").submit();
2354 });
2355 });
2356 </script>';
2357 }
2358 print ' <a href="' . DOL_URL_ROOT . '/societe/card.php?action=create&customer=3&fournisseur=0&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?action=create') . '"><span class="fa fa-plus-circle valignmiddle paddingleft" title="' . $langs->trans("AddThirdParty") . '"></span></a>';
2359 print '</td>';
2360 }
2361 print '</tr>' . "\n";
2362
2363 // Contact of order
2364 if ($socid > 0) {
2365 // Contacts (ask contact only if thirdparty already defined).
2366 // print "<tr><td>".$langs->trans("DefaultContact").'</td><td>';
2367 print "<tr><td>";
2368 print $form->textwithpicto($langs->trans("DefaultContact"), $langs->trans("TypeContact_commande_external_" . $type_contact_code));
2369 print '</td><td>';
2370 print img_picto('', 'contact', 'class="pictofixedwidth"');
2371 //print $form->selectcontacts($soc->id, $contactid, 'contactid', 1, empty($srccontactslist) ? "" : $srccontactslist, '', 1, 'maxwidth300 widthcentpercentminusx');
2372 print $form->select_contact($soc->id, $contactid, 'contactid', 1, empty($srccontactslist) ? "" : $srccontactslist, '', 1, 'maxwidth300 widthcentpercentminusx', true);
2373 print '</td></tr>';
2374
2375 // Ligne info remises tiers
2376 print '<tr><td>' . $langs->trans('Discounts') . '</td><td>';
2377
2378 $absolute_discount = $soc->getAvailableDiscounts();
2379
2380 $thirdparty = $soc;
2381 $discount_type = 0;
2382 $backtopage = $_SERVER["PHP_SELF"] . '?socid=' . $thirdparty->id . '&action=' . $action . '&origin=' . urlencode((string) (GETPOST('origin'))) . '&originid=' . urlencode((string) (GETPOSTINT('originid')));
2383 include DOL_DOCUMENT_ROOT . '/core/tpl/object_discounts.tpl.php';
2384
2385 print '</td></tr>';
2386 }
2387
2388 // Date
2389 $dateorder = (getDolGlobalString('MAIN_DO_NOT_AUTOFILL_DATE_ORDER') ? -1 : ''); // By default '' so we will autofill date. -1 means keep empty.
2390
2391 print '<tr><td class="fieldrequired">' . $langs->trans('Date') . '</td><td>';
2392 print img_picto('', 'action', 'class="pictofixedwidth"');
2393 print $form->selectDate($dateorder, 're', 0, 0, 0, "crea_commande", 1, 1); // Always autofill date with current date
2394 print '</td></tr>';
2395
2396 // Date delivery planned
2397 print '<tr><td>' . $langs->trans("DateDeliveryPlanned") . '</td>';
2398 print '<td colspan="3">';
2399 $date_delivery = ($date_delivery ? $date_delivery : $object->delivery_date);
2400 print img_picto('', 'action', 'class="pictofixedwidth"');
2401 print $form->selectDate($date_delivery ? $date_delivery : -1, 'liv_', 1, 1, 1);
2402 print "</td>\n";
2403 print '</tr>';
2404
2405 // Delivery delay
2406 print '<tr class="fielddeliverydelay"><td>' . $langs->trans('AvailabilityPeriod') . '</td><td>';
2407 print img_picto('', 'clock', 'class="pictofixedwidth"');
2408 $form->selectAvailabilityDelay((GETPOSTISSET('availability_id') ? GETPOST('availability_id') : $availability_id), 'availability_id', '', 1, 'maxwidth200 widthcentpercentminusx');
2409 print '</td></tr>';
2410
2411 // Terms of payment
2412 print '<tr><td class="nowrap">' . $langs->trans('PaymentConditionsShort') . '</td><td>';
2413 print img_picto('', 'payment', 'class="pictofixedwidth"');
2414 print $form->getSelectConditionsPaiements((int) $cond_reglement_id, 'cond_reglement_id', 1, 1, 0, 'maxwidth200 widthcentpercentminusx', (float) $deposit_percent);
2415 print '</td></tr>';
2416
2417 // Payment mode
2418 print '<tr><td>' . $langs->trans('PaymentMode') . '</td><td>';
2419 print img_picto('', 'bank', 'class="pictofixedwidth"');
2420 print $form->select_types_paiements((string) $mode_reglement_id, 'mode_reglement_id', 'CRDT', 0, 1, 0, 0, 1, 'maxwidth200 widthcentpercentminusx', 1);
2421 print '</td></tr>';
2422
2423 // Bank Account
2424 if (getDolGlobalString('BANK_ASK_PAYMENT_BANK_DURING_ORDER') && isModEnabled("bank")) {
2425 print '<tr><td>' . $langs->trans('BankAccount') . '</td><td>';
2426 print img_picto('', 'bank_account', 'class="pictofixedwidth"') . $form->select_comptes((int) $fk_account, 'fk_account', 0, '', 1, '', 0, 'maxwidth200 widthcentpercentminusx', 1);
2427 print '</td></tr>';
2428 }
2429
2430 // Shipping Method
2431 if (isModEnabled('shipping')) {
2432 print '<tr><td>' . $langs->trans('SendingMethod') . '</td><td>';
2433 print img_picto('', 'object_dolly', 'class="pictofixedwidth"');
2434 $form->selectShippingMethod(((GETPOSTISSET('shipping_method_id') && GETPOSTINT('shipping_method_id') > 0) ? GETPOST('shipping_method_id') : $shipping_method_id), 'shipping_method_id', '', 1, '', 0, 'maxwidth200 widthcentpercentminusx'); // -1 is the "no value" placeholder for this select, not 0, so it must not override the fresh thirdparty default after a company change
2435 print '</td></tr>';
2436 }
2437
2438 // Warehouse
2439 if (isModEnabled('stock') && getDolGlobalString('WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER')) {
2440 require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
2441 $formproduct = new FormProduct($db);
2442 print '<tr><td>' . $langs->trans('Warehouse') . '</td><td>';
2443 print img_picto('', 'stock', 'class="pictofixedwidth"') . $formproduct->selectWarehouses(((GETPOSTISSET('warehouse_id') && !GETPOSTINT('changecompany')) ? GETPOST('warehouse_id') : $warehouse_id), 'warehouse_id', '', 1, 0, 0, '', 0, 0, array(), 'maxwidth500 widthcentpercentminusxx');
2444 print '</td></tr>';
2445 }
2446
2447 // Source / Channel - What trigger creation
2448 print '<tr><td>' . $langs->trans('Source') . '</td><td>';
2449 print img_picto('', 'question', 'class="pictofixedwidth"');
2450 $form->selectInputReason((GETPOSTISSET('demand_reason_id') ? GETPOST('demand_reason_id') : $demand_reason_id), 'demand_reason_id', '', 1, 'maxwidth200 widthcentpercentminusx');
2451 print '</td></tr>';
2452
2453 // TODO How record was recorded OrderMode (llx_c_input_method)
2454
2455 // Project
2456 if (isModEnabled('project')) {
2457 $langs->load("projects");
2458 print '<tr>';
2459 print '<td>'.$langs->trans("Project").'</td><td>';
2460 print img_picto('', 'project', 'class="pictofixedwidth"').$formproject->select_projects((($soc->id > 0 && !getDolGlobalString('PROJECT_CAN_ALWAYS_LINK_TO_ALL_CUSTOMERS')) ? $soc->id : -1), (GETPOSTISSET('projectid') ? GETPOST('projectid') : $projectid), 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx');
2461 print ' <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$soc->id.'&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id).'"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans("AddProject").'"></span></a>';
2462 print '</td>';
2463 print '</tr>';
2464 }
2465
2466 // Incoterms
2467 if (isModEnabled('incoterm')) {
2468 print '<tr>';
2469 print '<td><label for="incoterm_id">' . $form->textwithpicto($langs->trans("IncotermLabel"), !empty($objectsrc->fk_incoterms) ? (string) $objectsrc->fk_incoterms : (string) $soc->fk_incoterms, 1) . '</label></td>';
2470 print '<td class="maxwidthonsmartphone">';
2471 $incoterm_id = GETPOST('incoterm_id');
2472 $location_incoterms = GETPOST('location_incoterms');
2473 if (empty($incoterm_id)) {
2474 $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms);
2475 $location_incoterms = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms);
2476 }
2477 print img_picto('', 'incoterm', 'class="pictofixedwidth"');
2478 print $form->select_incoterms($incoterm_id, $location_incoterms);
2479 print '</td></tr>';
2480 }
2481
2482 // Other attributes
2483 $parameters = array();
2484 if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
2485 $parameters['objectsrc'] = $objectsrc;
2486 }
2487 $parameters['socid'] = $socid;
2488
2489 // Note that $action and $object may be modified by hook
2490 $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);
2491 print $hookmanager->resPrint;
2492 if (empty($reshook)) {
2493 if (getDolGlobalString('THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER') && !empty($soc->id)) {
2494 // copy from thirdparty
2495 $tpExtrafields = new ExtraFields($db);
2496 $tpExtrafieldLabels = $tpExtrafields->fetch_name_optionals_label($soc->table_element);
2497 if ($soc->fetch_optionals() > 0) {
2498 $object->array_options = array_merge($object->array_options, $soc->array_options);
2499 }
2500 }
2501
2502 print $object->showOptionals($extrafields, 'create', $parameters);
2503 }
2504
2505 // Template to use by default
2506 print '<tr><td>' . $langs->trans('DefaultModel') . '</td>';
2507 print '<td>';
2508 include_once DOL_DOCUMENT_ROOT . '/core/modules/commande/modules_commande.php';
2510 $preselected = getDolGlobalString('COMMANDE_ADDON_PDF');
2511 print img_picto('', 'pdf', 'class="pictofixedwidth"');
2512 print $form->selectarray('model', $liste, $preselected, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth200 widthcentpercentminusx', 1);
2513 print "</td></tr>";
2514
2515 // Multicurrency
2516 if (isModEnabled("multicurrency")) {
2517 print '<tr>';
2518 print '<td>' . $form->editfieldkey("Currency", 'multicurrency_code', '', $object, 0) . '</td>';
2519 print '<td class="maxwidthonsmartphone">';
2520 print img_picto('', 'currency', 'class="pictofixedwidth"') . $form->selectMultiCurrency(((GETPOSTISSET('multicurrency_code') && !GETPOST('changecompany')) ? GETPOST('multicurrency_code') : $currency_code), 'multicurrency_code', 0, '', false, 'maxwidth200 widthcentpercentminusx');
2521 print '</td></tr>';
2522 }
2523
2524 // Categories
2525 if (isModEnabled('category')) {
2526 print '<tr><td>' . $langs->trans("Categories") . '</td><td colspan="3">';
2527 print $form->selectCategories(Categorie::TYPE_ORDER, 'categories', $object);
2528 print "</td></tr>";
2529 }
2530
2531 // Note public
2532 print '<tr>';
2533 print '<td class="tdtop">' . $langs->trans('NotePublic') . '</td>';
2534 print '<td>';
2535
2536 $doleditor = new DolEditor('note_public', (string) $note_public, '', 80, 'dolibarr_notes', 'In', false, false, !getDolGlobalString('FCKEDITOR_ENABLE_NOTE_PUBLIC') ? 0 : 1, ROWS_3, '90%');
2537 print $doleditor->Create(1);
2538 // print '<textarea name="note_public" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_public.'</textarea>';
2539 print '</td></tr>';
2540
2541 // Note private
2542 if (empty($user->socid)) {
2543 print '<tr>';
2544 print '<td class="tdtop">' . $langs->trans('NotePrivate') . '</td>';
2545 print '<td>';
2546
2547 $doleditor = new DolEditor('note_private', (string) $note_private, '', 80, 'dolibarr_notes', 'In', false, false, !getDolGlobalString('FCKEDITOR_ENABLE_NOTE_PRIVATE') ? 0 : 1, ROWS_3, '90%');
2548 print $doleditor->Create(1);
2549 // print '<textarea name="note" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'</textarea>';
2550 print '</td></tr>';
2551 }
2552
2553 if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
2554 // TODO for compatibility
2555 if ($origin == 'contrat') {
2556 // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
2557 //$objectsrc->remise_absolue = $remise_absolue;
2558 //$objectsrc->remise_percent = $remise_percent;
2559 $objectsrc->update_price(1);
2560 }
2561
2562 print "\n<!-- " . $classname . " info -->\n";
2563 print '<input type="hidden" name="amount" value="' . $objectsrc->total_ht . '">' . "\n";
2564 print '<input type="hidden" name="total" value="' . $objectsrc->total_ttc . '">' . "\n";
2565 print '<input type="hidden" name="tva" value="' . $objectsrc->total_tva . '">' . "\n";
2566 print '<input type="hidden" name="origin" value="' . $objectsrc->element . '">';
2567 print '<input type="hidden" name="originid" value="' . $objectsrc->id . '">';
2568
2569 switch ($classname) {
2570 case 'Propal':
2571 $newclassname = 'CommercialProposal';
2572 break;
2573 case 'Commande':
2574 $newclassname = 'Order';
2575 break;
2576 case 'Expedition':
2577 $newclassname = 'Sending';
2578 break;
2579 case 'Contrat':
2580 $newclassname = 'Contract';
2581 break;
2582 default:
2583 $newclassname = $classname;
2584 }
2585
2586 print '<tr><td>' . $langs->trans($newclassname) . '</td><td>' . $objectsrc->getNomUrl(1) . '</td></tr>';
2587
2588 // Amount
2589 print '<tr><td>' . $langs->trans('AmountHT') . '</td><td>' . price($objectsrc->total_ht) . '</td></tr>';
2590 print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td>' . price($objectsrc->total_tva) . "</td></tr>";
2591 if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1 RE
2592 print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td><td>' . price($objectsrc->total_localtax1) . "</td></tr>";
2593 }
2594
2595 if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2 IRPF
2596 print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td><td>' . price($objectsrc->total_localtax2) . "</td></tr>";
2597 }
2598
2599 print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td>' . price($objectsrc->total_ttc) . "</td></tr>";
2600
2601 if (isModEnabled("multicurrency")) {
2602 print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht, 0, $langs, 1, -1, -1, $objectsrc->multicurrency_code).'</td></tr>';
2603 print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva, 0, $langs, 1, -1, -1, $objectsrc->multicurrency_code)."</td></tr>";
2604 print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc, 0, $langs, 1, -1, -1, $objectsrc->multicurrency_code)."</td></tr>";
2605 }
2606 }
2607
2608 print "\n";
2609
2610 print '</table>';
2611 }
2612
2613 print dol_get_fiche_end();
2614
2615 print $form->buttonsSaveCancel("CreateDraft");
2616
2617 // Show origin lines
2618 if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
2619 $title = $langs->trans('ProductsAndServices');
2620 print load_fiche_titre($title);
2621
2622 print '<div class="div-table-responsive-no-min">';
2623 print '<table class="noborder centpercent">';
2624
2625 $objectsrc->printOriginLinesList('', $selectedLines);
2626
2627 print '</table>';
2628 print '</div>';
2629 }
2630
2631 print '</form>';
2632} else {
2633 // Mode view
2634 $now = dol_now();
2635
2636 if ($object->id > 0) {
2637 $product_static = new Product($db);
2638
2639 $soc = new Societe($db);
2640 $soc->fetch($object->socid);
2641
2642 $author = new User($db);
2643 $author->fetch($object->user_author_id);
2644
2645 $object->fetch_thirdparty();
2646 $res = $object->fetch_optionals();
2647
2648 $head = commande_prepare_head($object);
2649 print dol_get_fiche_head($head, 'order', $langs->trans("CustomerOrder"), -1, $object->picto, 0, '', '', 0, '', 1);
2650
2651 $formconfirm = '';
2652
2653 // Confirmation to delete
2654 if ($action == 'delete') {
2655 $formconfirm = $form->formconfirm(dolBuildUrl($_SERVER["PHP_SELF"], ['id' => $object->id]), $langs->trans('DeleteOrder'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1);
2656 }
2657
2658 // Confirmation of validation
2659 if ($action == 'validate') {
2660 // We check that object has a temporary ref
2661 $ref = substr($object->ref, 1, 4);
2662 if ($ref == 'PROV' || $ref == '') {
2663 $numref = $object->getNextNumRef($soc);
2664 if (empty($numref)) {
2665 $error++;
2666 setEventMessages($object->error, $object->errors, 'errors');
2667 }
2668 } else {
2669 $numref = (string) $object->ref;
2670 }
2671
2672 $text = $langs->trans('ConfirmValidateOrder', $numref);
2673 if (isModEnabled('notification')) {
2674 require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php';
2675 $notify = new Notify($db);
2676 $text .= '<br>';
2677 $text .= $notify->confirmMessage('ORDER_VALIDATE', $object->socid, $object);
2678 }
2679
2680 $qualified_for_stock_change = 0;
2681 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
2682 $qualified_for_stock_change = $object->hasProductsOrServices(2);
2683 } else {
2684 $qualified_for_stock_change = $object->hasProductsOrServices(1);
2685 }
2686
2687 $formquestion = array();
2688 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') && $qualified_for_stock_change) {
2689 $langs->load("stocks");
2690 require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
2691 $formproduct = new FormProduct($db);
2692 $forcecombo = 0;
2693 if ($conf->browser->name == 'ie') {
2694 $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
2695 }
2696 $formquestion = array(
2697 // 'text' => $langs->trans("ConfirmClone"),
2698 // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
2699 // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
2700 array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOSTINT('idwarehouse') ? GETPOSTINT('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
2701 );
2702 }
2703
2704 // mandatoryPeriod
2705 $nbMandated = 0;
2706 foreach ($object->lines as $line) {
2707 $res = $line->fetch_product();
2708 if ($res > 0) {
2709 if ($line->product->isService() && $line->product->isMandatoryPeriod() && (empty($line->date_start) || empty($line->date_end))) {
2710 $nbMandated++;
2711 break;
2712 }
2713 }
2714 }
2715 if ($nbMandated > 0) {
2716 if (getDolGlobalString('SERVICE_STRICT_MANDATORY_PERIOD')) {
2717 setEventMessages($langs->trans("mandatoryPeriodNeedTobeSetMsgValidate"), null, 'errors');
2718 $error++;
2719 } else {
2720 $text .= '<div><span class="clearboth nowraponall warning">' . img_warning() . $langs->trans("mandatoryPeriodNeedTobeSetMsgValidate") . '</span></div>';
2721 }
2722 }
2723
2724 if (getDolGlobalInt('SALE_ORDER_SUGGEST_DOWN_PAYMENT_INVOICE_CREATION')) {
2725 // This is a hidden option:
2726 // Suggestion to create invoice during order validation is not enabled by default.
2727 // Such choice should be managed by the workflow module and trigger. This option generates conflicts with some setup.
2728 // It may also break step of creating an order when invoicing must be done from proposals and not from orders
2729 $deposit_percent_from_payment_terms = (float) getDictionaryValue('c_payment_term', 'deposit_percent', $object->cond_reglement_id);
2730
2731 if (!empty($deposit_percent_from_payment_terms) && isModEnabled('invoice') && $user->hasRight('facture', 'creer')) {
2732 require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
2733
2734 $object->fetchObjectLinked();
2735
2736 $eligibleForDepositGeneration = true;
2737
2738 if (array_key_exists('facture', $object->linkedObjects)) {
2739 foreach ($object->linkedObjects['facture'] as $invoice) {
2740 '@phan-var-force Facture $invoice';
2741 if ($invoice->type == Facture::TYPE_DEPOSIT) {
2742 $eligibleForDepositGeneration = false;
2743 break;
2744 }
2745 }
2746 }
2747
2748 if ($eligibleForDepositGeneration && array_key_exists('propal', $object->linkedObjects)) {
2749 foreach ($object->linkedObjects['propal'] as $proposal) {
2750 $proposal->fetchObjectLinked();
2751
2752 if (array_key_exists('facture', $proposal->linkedObjects)) {
2753 foreach ($proposal->linkedObjects['facture'] as $invoice) {
2754 '@phan-var-force Facture $invoice';
2755 if ($invoice->type == Facture::TYPE_DEPOSIT) {
2756 $eligibleForDepositGeneration = false;
2757 break 2;
2758 }
2759 }
2760 }
2761 }
2762 }
2763
2764 if ($eligibleForDepositGeneration) {
2765 $formquestion[] = array(
2766 'type' => 'checkbox',
2767 'tdclass' => '',
2768 'name' => 'generate_deposit',
2769 'label' => $form->textwithpicto($langs->trans('GenerateDeposit', $object->deposit_percent), $langs->trans('DepositGenerationPermittedByThePaymentTermsSelected'))
2770 );
2771
2772 $formquestion[] = array(
2773 'type' => 'date',
2774 'tdclass' => 'fieldrequired showonlyifgeneratedeposit',
2775 'name' => 'datef',
2776 'label' => $langs->trans('DateInvoice'),
2777 'value' => dol_now(),
2778 'datenow' => true
2779 );
2780
2781 if (getDolGlobalString('INVOICE_POINTOFTAX_DATE')) {
2782 $formquestion[] = array(
2783 'type' => 'date',
2784 'tdclass' => 'fieldrequired showonlyifgeneratedeposit',
2785 'name' => 'date_pointoftax',
2786 'label' => $langs->trans('DatePointOfTax'),
2787 'value' => dol_now(),
2788 'datenow' => true
2789 );
2790 }
2791
2792 $paymentTermsSelect = $form->getSelectConditionsPaiements(0, 'cond_reglement_id', -1, 0, 0, 'minwidth200');
2793
2794 $formquestion[] = array(
2795 'type' => 'other',
2796 'tdclass' => 'fieldrequired showonlyifgeneratedeposit',
2797 'name' => 'cond_reglement_id',
2798 'label' => $langs->trans('PaymentTerm'),
2799 'value' => $paymentTermsSelect
2800 );
2801
2802 $formquestion[] = array(
2803 'type' => 'checkbox',
2804 'tdclass' => 'showonlyifgeneratedeposit',
2805 'name' => 'validate_generated_deposit',
2806 'label' => $langs->trans('ValidateGeneratedDeposit')
2807 );
2808
2809 $formquestion[] = array(
2810 'type' => 'onecolumn',
2811 'value' => '
2812 <script>
2813 $(document).ready(function() {
2814 $("[name=generate_deposit]").change(function () {
2815 let $self = $(this);
2816 let $target = $(".showonlyifgeneratedeposit").parent(".tagtr");
2817
2818 if (! $self.parents(".tagtr").is(":hidden") && $self.is(":checked")) {
2819 $target.show();
2820 } else {
2821 $target.hide();
2822 }
2823
2824 return true;
2825 });
2826 });
2827 </script>
2828 '
2829 );
2830 }
2831 }
2832 }
2833
2834 if (!$error) {
2835 $formconfirm = $form->formconfirm(dolBuildUrl($_SERVER["PHP_SELF"], ['id' => $object->id]), $langs->trans('ValidateOrder'), $text, 'confirm_validate', $formquestion, 0, 1, 240);
2836 }
2837 }
2838
2839 // Confirm back to draft status
2840 if ($action == 'modif') {
2841 $qualified_for_stock_change = 0;
2842 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
2843 $qualified_for_stock_change = $object->hasProductsOrServices(2);
2844 } else {
2845 $qualified_for_stock_change = $object->hasProductsOrServices(1);
2846 }
2847
2848 $text = $langs->trans('ConfirmUnvalidateOrder', $object->ref);
2849 $formquestion = array();
2850 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') && $qualified_for_stock_change) {
2851 $langs->load("stocks");
2852 require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
2853 $formproduct = new FormProduct($db);
2854 $forcecombo = 0;
2855 if ($conf->browser->name == 'ie') {
2856 $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
2857 }
2858 $formquestion = [
2859 // 'text' => $langs->trans("ConfirmClone"),
2860 // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
2861 // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
2862 [
2863 'type' => 'other',
2864 'name' => 'idwarehouse',
2865 'label' => $langs->trans("SelectWarehouseForStockIncrease"),
2866 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)
2867 ]
2868 ];
2869 }
2870
2871 $formconfirm = $form->formconfirm(dolBuildUrl($_SERVER["PHP_SELF"], ['id' => $object->id]), $langs->trans('UnvalidateOrder'), $text, 'confirm_modif', $formquestion, "yes", 1, 220);
2872 }
2873
2874 // Confirmation of closing
2875 if ($action == 'shipped') {
2876 $formconfirm = $form->formconfirm(dolBuildUrl($_SERVER["PHP_SELF"], ['id' => $object->id]), $langs->trans('CloseOrder'), $langs->trans('ConfirmCloseOrder'), 'confirm_shipped', '', 0, 1);
2877 }
2878
2879 // Confirmation of cancellation
2880 if ($action == 'cancel') {
2881 $qualified_for_stock_change = 0;
2882 if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
2883 $qualified_for_stock_change = $object->hasProductsOrServices(2);
2884 } else {
2885 $qualified_for_stock_change = $object->hasProductsOrServices(1);
2886 }
2887
2888 $text = $langs->trans('ConfirmCancelOrder', $object->ref);
2889 $formquestion = array();
2890 if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') && $qualified_for_stock_change) {
2891 $langs->load("stocks");
2892 require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
2893 $formproduct = new FormProduct($db);
2894 $forcecombo = 0;
2895 if ($conf->browser->name == 'ie') {
2896 $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
2897 }
2898 $formquestion = array(
2899 // 'text' => $langs->trans("ConfirmClone"),
2900 // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
2901 // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
2902 array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
2903 );
2904 }
2905
2906 $formconfirm = $form->formconfirm(dolBuildUrl($_SERVER["PHP_SELF"], ['id' => $object->id]), $langs->trans("Cancel"), $text, 'confirm_cancel', $formquestion, 0, 1);
2907 }
2908
2909 // Confirmation to delete line
2910 if ($action == 'ask_deleteline') {
2911 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1);
2912 }
2913
2914 // Confirmation de la suppression d'une ligne subtotal
2915 if ($action == 'ask_subtotal_deleteline') {
2916 $langs->load("subtotals");
2917 $title = "DeleteSubtotalLine";
2918 $question = "ConfirmDeleteSubtotalLine";
2919 if (GETPOST('type') == 'title') {
2920 $formconfirm = array(array('type' => 'checkbox', 'name' => 'deletecorrespondingsubtotalline', 'label' => $langs->trans("DeleteCorrespondingSubtotalLine"), 'value' => 0));
2921 $title = "DeleteTitleLine";
2922 $question = "ConfirmDeleteTitleLine";
2923 }
2924 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&lineid=' . $lineid, $langs->trans($title), $langs->trans($question), 'confirm_delete_subtotalline', $formconfirm, 'no', 1);
2925 }
2926
2927 // Clone confirmation
2928 if ($action == 'clone') {
2929 $filter = '(s.client:IN:1,2,3)';
2930 // Create an array for form
2931 $formquestion = array(
2932 array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOSTINT('socid'), 'socid', $filter, '', 0, 0, array(), 0, 'maxwidth300'))
2933 );
2934 $formconfirm = $form->formconfirm(dolBuildUrl($_SERVER["PHP_SELF"], ['id' => $object->id]), $langs->trans('ToClone'), $langs->trans('ConfirmCloneOrder', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
2935 }
2936
2937 // Subtotal line form
2938 if ($action == 'add_title_line') {
2939 $langs->load('subtotals');
2940 $type = 'title';
2941 $depth_array = $object->getPossibleLevels($langs);
2942 include DOL_DOCUMENT_ROOT . '/core/tpl/subtotal_create.tpl.php';
2943 } elseif ($action == 'add_subtotal_line') {
2944 $langs->load('subtotals');
2945 $type = 'subtotal';
2946 $titles = $object->getPossibleTitles();
2947 include DOL_DOCUMENT_ROOT . '/core/tpl/subtotal_create.tpl.php';
2948 }
2949
2950 // Call Hook formConfirm
2951 $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
2952 // Note that $action and $object may be modified by hook
2953 $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action);
2954 if (empty($reshook)) {
2955 $formconfirm .= $hookmanager->resPrint;
2956 } elseif ($reshook > 0) {
2957 $formconfirm = $hookmanager->resPrint;
2958 }
2959
2960 // Print form confirm
2961 print $formconfirm;
2962
2963
2964 // Order card
2965
2966 $linkback = '<a href="' . DOL_URL_ROOT . '/commande/list.php?restore_lastsearch_values=1' . (!empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans("BackToList") . '</a>';
2967
2968 $morehtmlref = '<div class="refidno">';
2969 // Ref customer
2970 $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, (int) $usercancreate, 'string', '', 0, 1);
2971 $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, (int) $usercancreate, 'string' . (isset($conf->global->THIRDPARTY_REF_INPUT_SIZE) ? ':' . getDolGlobalString('THIRDPARTY_REF_INPUT_SIZE') : ''), '', null, null, '', 1);
2972 // Thirdparty
2973 $morehtmlref .= '<br>' . $soc->getNomUrl(1, 'customer');
2974 if (!getDolGlobalString('MAIN_DISABLE_OTHER_LINK') && $object->thirdparty->id > 0) {
2975 $morehtmlref .= ' (<a href="' . DOL_URL_ROOT . '/commande/list.php?socid=' . ((int) $object->thirdparty->id) . '">' . $langs->trans("OtherOrders") . '</a>)';
2976 }
2977 // Project
2978 if (isModEnabled('project')) {
2979 $langs->load("projects");
2980 $morehtmlref .= '<br>';
2981 if ($usercancreate) {
2982 $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
2983 if ($action != 'classify') {
2984 $morehtmlref .= '<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> ';
2985 }
2986 $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, (string) $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
2987 } else {
2988 if (!empty($object->fk_project)) {
2989 $proj = new Project($db);
2990 $proj->fetch($object->fk_project);
2991 $morehtmlref .= $proj->getNomUrl(1);
2992 if ($proj->title) {
2993 $morehtmlref .= '<span class="opacitymedium"> - ' . dol_escape_htmltag($proj->title) . '</span>';
2994 }
2995 }
2996 }
2997 }
2998 $morehtmlref .= '</div>';
2999
3000 dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
3001
3002 // Call Hook tabContentViewOrder
3003 $parameters = array();
3004 // Note that $action and $object may be modified by hook
3005 $reshook = $hookmanager->executeHooks('tabContentViewOrder', $parameters, $object, $action);
3006 if (empty($reshook)) {
3007 print '<div class="fichecenter">';
3008 print '<div class="fichehalfleft">';
3009 print '<div class="underbanner clearboth"></div>';
3010
3011 print '<table class="border tableforfield centpercent">';
3012
3013 // POS
3014 if (isModEnabled('takepos') || $object->module_source || getDolGlobalString('ORDER_ALLOW_POS_SOURCE_EDIT')) {
3015 $langs->load("cashdesk");
3016 print '<tr><td class="fieldname_type">';
3017 print '<table class="nobordernopadding centpercent"><tr><td>';
3018 print $form->textwithpicto($langs->trans('PointOfSale'), $langs->trans('POSInfo'));
3019 print '</td>';
3020 if ($action != 'editposinfo' && $usercancreate) {
3021 print '<td class="right"><a class="editfielda" href="' . $_SERVER["PHP_SELF"] . '?action=editposinfo&token=' . newToken() . '&id=' . $object->id . '">' . img_edit($langs->trans('SetPOSInfo'), 1) . '</a></td>';
3022 }
3023 print '</tr></table>';
3024 print '</td><td class="valuefield fieldname_type">';
3025 print '<form method="POST" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" name="formposinfo">';
3026 print '<input type="hidden" name="action" value="setposinfo">';
3027 print '<input type="hidden" name="token" value="' . newToken() . '">';
3028 if ($action == 'editposinfo') {
3029 print '<input type="text" class="maxwidth150" name="posmodule" placeholder="' . $langs->trans("POSModule") . '" value="' . $object->module_source . '"> ';
3030 print '<input type="text" class="maxwidth100" name="posterminal" placeholder="' . $langs->trans("Terminal") . '" value="' . $object->pos_source . '">';
3031 print '<input type="submit" class="button" name="submitposinfo" value="' . $langs->trans("Submit") . '">';
3032 } else {
3033 if ($object->module_source) {
3034 print '<span class="opacitymediumbycolor paddingleft">' . dolPrintHTML(ucfirst($object->module_source) . ' - ' . $langs->transnoentitiesnoconv("Terminal") . ' ' . $object->pos_source) . '</span>';
3035 }
3036 }
3037 print '</form>';
3038 print '</td></tr>';
3039 }
3040
3041 if ($soc->outstanding_limit) {
3042 // Outstanding Bill
3043 print '<tr><td class="titlefield">';
3044 print $langs->trans('OutstandingBill');
3045 print '</td><td class="valuefield">';
3046 $arrayoutstandingbills = $soc->getOutstandingBills();
3047 print price($arrayoutstandingbills['opened']) . ' / ';
3048 print price($soc->outstanding_limit, 0, '', 1, -1, -1, $conf->currency);
3049 print '</td>';
3050 print '</tr>';
3051 }
3052
3053 // Relative and absolute discounts
3054 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
3055 $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
3056 $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be subtracted to payments only and not to total of final invoice
3057 } else {
3058 $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
3059 $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
3060 }
3061
3062 $addrelativediscount = '<a href="' . DOL_URL_ROOT . '/comm/remise.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"]) . '?facid=' . $object->id . '">' . $langs->trans("EditRelativeDiscounts") . '</a>';
3063 $addabsolutediscount = '<a href="' . DOL_URL_ROOT . '/comm/remx.php?id=' . $soc->id . '&backtopage=' . urlencode($_SERVER["PHP_SELF"]) . '?facid=' . $object->id . '">' . $langs->trans("EditGlobalDiscounts") . '</a>';
3064 $addcreditnote = '<a href="' . DOL_URL_ROOT . '/compta/facture/card.php?action=create&socid=' . $soc->id . '&type=2&backtopage=' . urlencode($_SERVER["PHP_SELF"]) . '?facid=' . $object->id . '">' . $langs->trans("AddCreditNote") . '</a>';
3065
3066 print '<tr><td class="titlefield">' . $langs->trans('Discounts') . '</td><td class="valuefield">';
3067
3068 $absolute_discount = $soc->getAvailableDiscounts(null, $filterabsolutediscount);
3069 $absolute_creditnote = $soc->getAvailableDiscounts(null, $filtercreditnote);
3070 $absolute_discount = price2num($absolute_discount, 'MT');
3071 $absolute_creditnote = price2num($absolute_creditnote, 'MT');
3072
3073 $thirdparty = $soc;
3074 $discount_type = 0;
3075 $backtopage = $_SERVER["PHP_SELF"] . '?id=' . $object->id;
3076 include DOL_DOCUMENT_ROOT . '/core/tpl/object_discounts.tpl.php';
3077
3078 print '</td></tr>';
3079
3080 // Date
3081 print '<tr><td>';
3082 $editenable = $usercancreate && $object->status == Commande::STATUS_DRAFT;
3083 print $form->editfieldkey("Date", 'date', '', $object, (int) $editenable);
3084 print '</td><td class="valuefield">';
3085 if ($action == 'editdate') {
3086 print '<form name="setdate" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="post">';
3087 print '<input type="hidden" name="token" value="' . newToken() . '">';
3088 print '<input type="hidden" name="action" value="setdate">';
3089 print '<input type="hidden" name="backtopage" value="' . $backtopage . '">';
3090 print $form->selectDate($object->date, 'order_', 0, 0, 0, "setdate");
3091 print '<input type="submit" class="button button-edit" value="' . $langs->trans('Modify') . '">';
3092 print '</form>';
3093 } else {
3094 print $object->date ? dol_print_date($object->date, 'day') : '&nbsp;';
3095 if ($object->hasDelay() && empty($object->delivery_date)) { // If there is a delivery date planned, warning should be on this date
3096 print ' ' . img_picto($langs->trans("Late") . ' : ' . $object->showDelay(), "warning");
3097 }
3098 }
3099 print '</td>';
3100 print '</tr>';
3101
3102 // Delivery date planned
3103 print '<tr><td>';
3104 $editenable = $usercancreate;
3105 print $form->editfieldkey("DateDeliveryPlanned", 'date_livraison', '', $object, (int) $editenable);
3106 print '</td><td class="valuefield">';
3107 if ($action == 'editdate_livraison') {
3108 print '<form name="setdate_livraison" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="post">';
3109 print '<input type="hidden" name="token" value="' . newToken() . '">';
3110 print '<input type="hidden" name="action" value="setdate_livraison">';
3111 print '<input type="hidden" name="backtopage" value="' . $backtopage . '">';
3112 print $form->selectDate($object->delivery_date ? $object->delivery_date : -1, 'liv_', 1, 1, 0, "setdate_livraison", 1, 0);
3113 print '<input type="submit" class="button button-edit" value="' . $langs->trans('Modify') . '">';
3114 print '</form>';
3115 } else {
3116 print $object->delivery_date ? dol_print_date($object->delivery_date, 'dayhour') : '&nbsp;';
3117 if ($object->hasDelay() && !empty($object->delivery_date)) {
3118 print ' ' . img_picto($langs->trans("Late") . ' : ' . $object->showDelay(), "warning");
3119 }
3120 }
3121 print '</td>';
3122 print '</tr>';
3123
3124 // Delivery delay
3125 print '<tr class="fielddeliverydelay"><td>';
3126 $editenable = $usercancreate;
3127 print $form->editfieldkey("AvailabilityPeriod", 'availability', '', $object, (int) $editenable);
3128 print '</td><td class="valuefield">';
3129 if ($action == 'editavailability') {
3130 $form->form_availability($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->availability_id, 'availability_id', 1);
3131 } else {
3132 $form->form_availability($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->availability_id, 'none', 1);
3133 }
3134 print '</td></tr>';
3135
3136 // Shipping Method
3137 if (isModEnabled('shipping')) {
3138 print '<tr><td>';
3139 $editenable = $usercancreate;
3140 print $form->editfieldkey("SendingMethod", 'shippingmethod', '', $object, (int) $editenable);
3141 print '</td><td class="valuefield">';
3142 if ($action == 'editshippingmethod') {
3143 $form->formSelectShippingMethod($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->shipping_method_id, 'shipping_method_id', 1);
3144 } else {
3145 $form->formSelectShippingMethod($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->shipping_method_id, 'none');
3146 }
3147 print '</td>';
3148 print '</tr>';
3149 }
3150
3151 // Warehouse
3152 if (isModEnabled('stock') && getDolGlobalString('WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER')) {
3153 $langs->load('stocks');
3154 require_once DOL_DOCUMENT_ROOT . '/product/class/html.formproduct.class.php';
3155 $formproduct = new FormProduct($db);
3156 print '<tr><td>';
3157 $editenable = $usercancreate;
3158 print $form->editfieldkey("Warehouse", 'warehouse', '', $object, (int) $editenable);
3159 print '</td><td class="valuefield">';
3160 if ($action == 'editwarehouse') {
3161 $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->warehouse_id, 'warehouse_id', 1);
3162 } else {
3163 $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->warehouse_id, 'none');
3164 }
3165 print '</td>';
3166 print '</tr>';
3167 }
3168
3169 // Source reason (why we have an order)
3170 print '<tr><td>';
3171 $editenable = $usercancreate;
3172 print $form->editfieldkey("Source", 'demandreason', '', $object, (int) $editenable);
3173 print '</td><td class="valuefield">';
3174 if ($action == 'editdemandreason') {
3175 $form->formInputReason($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->demand_reason_id, 'demand_reason_id', 1);
3176 } else {
3177 $form->formInputReason($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->demand_reason_id, 'none');
3178 }
3179 print '</td></tr>';
3180
3181 // Terms of payment
3182 print '<tr><td>';
3183 $editenable = $usercancreate;
3184 print $form->editfieldkey("PaymentConditionsShort", 'conditions', '', $object, (int) $editenable);
3185 print '</td><td class="valuefield">';
3186 if ($action == 'editconditions') {
3187 $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->cond_reglement_id, 'cond_reglement_id', 1, '', 1, $object->deposit_percent);
3188 } else {
3189 $form->form_conditions_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->cond_reglement_id, 'none', 1, '', 1, $object->deposit_percent);
3190 }
3191 print '</td>';
3192
3193 print '</tr>';
3194
3195 // Mode of payment
3196 print '<tr><td>';
3197 $editenable = $usercancreate;
3198 print $form->editfieldkey("PaymentMode", 'mode', '', $object, (int) $editenable);
3199 print '</td><td class="valuefield">';
3200 if ($action == 'editmode') {
3201 $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1);
3202 } else {
3203 $form->form_modes_reglement($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->mode_reglement_id, 'none');
3204 }
3205 print '</td></tr>';
3206
3207 // TODO Order mode (how we receive order). Not yet implemented
3208 /*
3209 print '<tr><td>';
3210 $editenable = $usercancreate;
3211 print $form->editfieldkey("SourceMode", 'inputmode', '', $object, $editenable);
3212 print '</td><td>';
3213 if ($action == 'editinputmode') {
3214 $form->formInputMode($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->source, 'input_mode_id', 1);
3215 } else {
3216 $form->formInputMode($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->source, 'none');
3217 }
3218 print '</td></tr>';
3219 */
3220
3221 $tmparray = $object->getTotalWeightVolume();
3222 $totalWeight = $tmparray['weight'];
3223 $totalVolume = $tmparray['volume'];
3224 if ($totalWeight) {
3225 print '<tr><td>' . $langs->trans("CalculatedWeight") . '</td>';
3226 print '<td class="valuefield">';
3227 print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, getDolGlobalInt('MAIN_WEIGHT_DEFAULT_ROUND', -1), getDolGlobalString('MAIN_WEIGHT_DEFAULT_UNIT', 'no'));
3228 print '</td></tr>';
3229 }
3230 if ($totalVolume) {
3231 print '<tr><td>' . $langs->trans("CalculatedVolume") . '</td>';
3232 print '<td class="valuefield">';
3233 print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, getDolGlobalInt('MAIN_VOLUME_DEFAULT_ROUND', -1), getDolGlobalString('MAIN_VOLUME_DEFAULT_UNIT', 'no'));
3234 print '</td></tr>';
3235 }
3236
3237 // TODO How record was recorded OrderMode (llx_c_input_method)
3238
3239 // Incoterms
3240 if (isModEnabled('incoterm')) {
3241 print '<tr><td>';
3242 $editenable = $usercancreate;
3243 print $form->editfieldkey("IncotermLabel", 'incoterm', '', $object, (int) $editenable);
3244 print '</td>';
3245 print '<td class="valuefield">';
3246 if ($action != 'editincoterm') {
3247 print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
3248 } else {
3249 print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'] . '?id=' . $object->id);
3250 }
3251 print '</td></tr>';
3252 }
3253
3254 // Bank Account
3255 if (getDolGlobalString('BANK_ASK_PAYMENT_BANK_DURING_ORDER') && isModEnabled("bank")) {
3256 print '<tr><td>';
3257 $editenable = $usercancreate;
3258 print $form->editfieldkey("BankAccount", 'bankaccount', '', $object, (int) $editenable);
3259 print '</td><td class="valuefield">';
3260 if ($action == 'editbankaccount') {
3261 $form->formSelectAccount($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->fk_account, 'fk_account', 1);
3262 } else {
3263 $form->formSelectAccount($_SERVER['PHP_SELF'] . '?id=' . $object->id, (string) $object->fk_account, 'none');
3264 }
3265 print '</td>';
3266 print '</tr>';
3267 }
3268
3269 // Tags-Categories
3270 if (isModEnabled('category')) {
3271 print '<tr><td>';
3272 print '<table class="nobordernopadding centpercent"><tr><td>';
3273 print $langs->trans("Categories");
3274 print '<td><td class="right">';
3275 if ($usercancreate) {
3276 print '<a class="editfielda" href="' . DOL_URL_ROOT . '/commande/card.php?id=' . $object->id . '&action=edittags&token=' . newToken() . '">' . img_edit() . '</a>';
3277 } else {
3278 print '&nbsp;';
3279 }
3280 print '</td></tr></table>';
3281 print '</td>';
3282 print '<td>';
3283 if ($action == 'edittags') {
3284 print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '?id=' . $object->id . '">';
3285 print '<input type="hidden" name="action" value="settags">';
3286 print '<input type="hidden" name="token" value="' . newToken() . '">';
3287 print $form->selectCategories(Categorie::TYPE_ORDER, 'categories', $object);
3288 print '<input type="submit" class="button valignmiddle smallpaddingimp" value="' . $langs->trans("Modify") . '">';
3289 print '</form>';
3290 } else {
3291 print $form->showCategories($object->id, Categorie::TYPE_ORDER, 1);
3292 }
3293 print "</td></tr>";
3294 }
3295
3296 // Other attributes
3297 include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
3298
3299 print '</table>';
3300
3301 print '</div>';
3302 print '<div class="fichehalfright">';
3303 print '<div class="underbanner clearboth"></div>';
3304
3305 print '<table class="border tableforfield centpercent">';
3306
3307 include DOL_DOCUMENT_ROOT . '/core/tpl/object_currency_amount.tpl.php';
3308
3309 $alert = '';
3310 if (getDolGlobalString('ORDER_MANAGE_MIN_AMOUNT') && $object->total_ht < $object->thirdparty->order_min_amount) {
3311 $alert = ' ' . img_warning($langs->trans('OrderMinAmount') . ': ' . price($object->thirdparty->order_min_amount));
3312 }
3313
3314 print '<tr>';
3315 print '<td class="titlefieldmiddle">' . $langs->trans('AmountHT') . '</td>';
3316 print '<td class="nowrap amountcard right">' . price($object->total_ht, 0, $langs, 0, -1, -1, $conf->currency) . '</td>';
3317 if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
3318 // Multicurrency Amount HT
3319 print '<td class="nowrap amountcard right">' . price($object->multicurrency_total_ht, 0, $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
3320 }
3321 print '</tr>';
3322
3323 print '<tr>';
3324 print '<td class="titlefieldmiddle">' . $langs->trans('AmountVAT') . '</td>';
3325 print '<td class="nowrap amountcard right">' . price($object->total_tva, 0, $langs, 0, -1, -1, $conf->currency) . '</td>';
3326 if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
3327 // Multicurrency Amount VAT
3328 print '<td class="nowrap amountcard right">' . price($object->multicurrency_total_tva, 0, $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
3329 }
3330 print '</tr>';
3331
3332 // Amount Local Taxes
3333 if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) {
3334 print '<tr>';
3335 print '<td class="titlefieldmiddle">' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td>';
3336 print '<td class="nowrap amountcard right">' . price($object->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency) . '</td>';
3337 if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
3338 $object->multicurrency_total_localtax1 = price2num($object->total_localtax1 * $object->multicurrency_tx, 'MT');
3339
3340 print '<td class="nowrap amountcard right">' . price($object->multicurrency_total_localtax1, 0, $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
3341 }
3342 print '</tr>';
3343 }
3344
3345 // Amount Local Taxes
3346 if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) {
3347 print '<tr>';
3348 print '<td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td>';
3349 print '<td class="nowrap amountcard right">' . price($object->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency) . '</td>';
3350 if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
3351 $object->multicurrency_total_localtax2 = price2num($object->total_localtax2 * $object->multicurrency_tx, 'MT');
3352
3353 print '<td class="nowrap amountcard right">' . price($object->multicurrency_total_localtax2, 0, $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
3354 }
3355 print '</tr>';
3356 }
3357
3358 print '<tr>';
3359 print '<td>' . $langs->trans('AmountTTC') . '</td>';
3360 print '<td class="valuefield nowrap right amountcard">' . price($object->total_ttc, 1, '', 1, -1, -1, $conf->currency) . '</td>';
3361 if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
3362 // Multicurrency Amount TTC
3363 print '<td class="valuefield nowrap right amountcard">' . price($object->multicurrency_total_ttc, 1, '', 1, -1, -1, $object->multicurrency_code) . '</td>';
3364 }
3365 print '</tr>' . "\n";
3366
3367 print '</table>';
3368
3369 // Statut
3370 //print '<tr><td>' . $langs->trans('Status') . '</td><td>' . $object->getLibStatut(4) . '</td></tr>';
3371
3372 // Margin Infos
3373 if (isModEnabled('margin')) {
3374 $formmargin->displayMarginInfos($object);
3375 }
3376
3377
3378 print '</div>';
3379 print '</div>'; // Close fichecenter
3380
3381 print '<div class="clearboth"></div><br>';
3382
3383 if (getDolGlobalString('MAIN_DISABLE_CONTACTS_TAB')) {
3384 $blocname = 'contacts';
3385 $title = $langs->trans('ContactsAddresses');
3386 include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_showhide.tpl.php';
3387 }
3388
3389 if (getDolGlobalString('MAIN_DISABLE_NOTES_TAB')) {
3390 $blocname = 'notes';
3391 $title = $langs->trans('Notes');
3392 include DOL_DOCUMENT_ROOT . '/core/tpl/bloc_showhide.tpl.php';
3393 }
3394
3395 /*
3396 * Lines
3397 */
3398
3399 // Get object lines
3400 $result = $object->getLinesArray();
3401
3402 // Add products/services form
3403 //$forceall = 1;
3404 global $inputalsopricewithtax;
3405 $inputalsopricewithtax = 1;
3406
3407 print '<form name="addproduct" id="addproduct" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '" method="POST">
3408 <input type="hidden" name="token" value="' . newToken() . '">
3409 <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline') . '">
3410 <input type="hidden" name="mode" value="">
3411 <input type="hidden" name="page_y" value="">
3412 <input type="hidden" name="id" value="' . $object->id . '">
3413 <input type="hidden" name="backtopage" value="' . $backtopage . '">
3414 ';
3415
3416 if (!empty($conf->use_javascript_ajax) && $object->status == Commande::STATUS_DRAFT) {
3417 if (isModEnabled('subtotals')) {
3418 include DOL_DOCUMENT_ROOT . '/core/tpl/subtotal_ajaxrow.tpl.php';
3419 } else {
3420 include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
3421 }
3422 }
3423
3424 print '<div class="div-table-responsive-no-min">';
3425 print '<table id="tablelines" class="noborder noshadow" width="100%">';
3426
3427 // Show object lines
3428 if (!empty($object->lines)) {
3429 $object->printObjectLines($action, $mysoc, $soc, $lineid, 1);
3430 }
3431
3432 /*
3433 * Form to add new line
3434 */
3435 if ($object->status == Commande::STATUS_DRAFT && $usercancreate && $action != 'selectlines') {
3436 if ($action != 'editline') {
3437 // Add free products/services
3438
3439 $parameters = array();
3440 // Note that $action and $object may be modified by hook
3441 $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action);
3442 if ($reshook < 0) {
3443 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
3444 }
3445 if (empty($reshook)) {
3446 $object->formAddObjectLine(1, $mysoc, $soc);
3447 }
3448 } else {
3449 $parameters = array();
3450 $reshook = $hookmanager->executeHooks('formEditObjectLine', $parameters, $object, $action);
3451 }
3452 }
3453 print '</table>';
3454 print '</div>';
3455
3456 print "</form>\n";
3457 }
3458
3459 print dol_get_fiche_end();
3460
3461 /*
3462 * Buttons for actions
3463 */
3464 if ($action != 'presend' && $action != 'editline') {
3465 print '<div class="tabsAction">';
3466
3467 $parameters = array();
3468 $arrayforbutaction = array();
3469 // Note that $action and $object may be modified by hook
3470 $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action);
3471 if (empty($reshook)) {
3472 $numlines = count($object->lines);
3473
3474 // Reopen a closed order
3475 if (($object->status == Commande::STATUS_CLOSED || $object->status == Commande::STATUS_CANCELED) && $usercancreate && (!$object->billed || !getDolGlobalInt('ORDER_DONT_REOPEN_BILLED'))) {
3476 print dolGetButtonAction('', $langs->trans('ReOpen'), 'default', $_SERVER["PHP_SELF"] . '?action=reopen&amp;token=' . newToken() . '&amp;id=' . $object->id, '');
3477 }
3478
3479 // Send
3480 if (empty($user->socid)) {
3481 if ($object->status > Commande::STATUS_DRAFT || getDolGlobalString('COMMANDE_SENDBYEMAIL_FOR_ALL_STATUS')) {
3482 if ($usercansend) {
3483 print dolGetButtonAction('', $langs->trans('SendMail'), 'email', $_SERVER["PHP_SELF"] . '?action=presend&token=' . newToken() . '&id=' . $object->id . '&mode=init#formmailbeforetitle', '');
3484 } else {
3485 print dolGetButtonAction('', $langs->trans('SendMail'), 'email', $_SERVER['PHP_SELF'] . '#', '', false);
3486 }
3487 }
3488 }
3489
3490 // Subtotal
3491 if ($object->status == Commande::STATUS_DRAFT && isModEnabled('subtotals')
3492 && (getDolGlobalInt('SUBTOTAL_TITLE_'.strtoupper($object->element)) || getDolGlobalInt('SUBTOTAL_'.strtoupper($object->element)))) {
3493 $langs->load('subtotals');
3494
3495 $url_button = array();
3496
3497 $url_button[] = array(
3498 'lang' => 'subtotals',
3499 'enabled' => (isModEnabled('order') && $object->status == Commande::STATUS_DRAFT && getDolGlobalInt('SUBTOTAL_TITLE_'.strtoupper($object->element))),
3500 'perm' => (bool) $usercancreate,
3501 'label' => $langs->trans('AddTitleLine'),
3502 'url' => '/commande/card.php?id=' . $object->id . '&action=add_title_line&token=' . newToken()
3503 );
3504
3505 $url_button[] = array(
3506 'lang' => 'subtotals',
3507 'enabled' => (isModEnabled('order') && $object->status == Commande::STATUS_DRAFT && getDolGlobalInt('SUBTOTAL_'.strtoupper($object->element))),
3508 'perm' => (bool) $usercancreate,
3509 'label' => $langs->trans('AddSubtotalLine'),
3510 'url' => '/commande/card.php?id=' . $object->id . '&action=add_subtotal_line&token=' . newToken()
3511 );
3512 print dolGetButtonAction('', $langs->trans('SubTotal'), 'default', $url_button, '', true);
3513 }
3514
3515 // Valid
3516 if ($object->status == Commande::STATUS_DRAFT && ($object->total_ttc >= 0 || getDolGlobalString('ORDER_ENABLE_NEGATIVE')) && $usercanvalidate) {
3517 if ($numlines > 0) {
3518 print dolGetButtonAction('', $langs->trans('Validate'), 'default', $_SERVER["PHP_SELF"] . '?action=validate&amp;token=' . newToken() . '&amp;id=' . $object->id, (string) $object->id, 1);
3519 } else {
3520 $langs->load("errors");
3521 print dolGetButtonAction($langs->trans("ErrorObjectMustHaveLinesToBeValidated", $object->ref), $langs->trans('Validate'), 'default', $_SERVER["PHP_SELF"] . '?action=validate&amp;token=' . newToken() . '&amp;id=' . $object->id, (string) $object->id, -1);
3522 }
3523 }
3524 // Edit
3525 if (($object->status == Commande::STATUS_VALIDATED || ($object->status == Commande::STATUS_SHIPMENTONPROCESS && getDolGlobalString('EDIT_ORDER_SHIPMENT_ON_PROCESS'))) && $usercancreate) {
3526 print dolGetButtonAction('', $langs->trans('Modify'), 'default', $_SERVER["PHP_SELF"] . '?action=modif&amp;token=' . newToken() . '&amp;id=' . $object->id, '');
3527 }
3528
3529 // Create a purchase order
3530
3531 if (!getDolGlobalInt('COMMANDE_DISABLE_ADD_PURCHASE_ORDER')) {
3532 $arrayforbutaction[] = array(
3533 'lang' => 'orders',
3534 'enabled' => (isModEnabled("supplier_order") && $object->status > Commande::STATUS_DRAFT),
3535 'perm' => $usercancreatepurchaseorder,
3536 'label' => 'AddPurchaseOrder',
3537 'url' => '/fourn/commande/card.php?action=create&amp;origin=' . urlencode($object->element) . '&amp;originid=' . ((int) $object->id)
3538 );
3539 }
3540
3541 /*if (isModEnabled("supplier_order") && $object->status > Commande::STATUS_DRAFT && $object->getNbOfServicesLines() > 0) {
3542 if ($usercancreatepurchaseorder) { isModEnabled("supplier_order") && $object->status > Commande::STATUS_DRAFT && $object->getNbOfServicesLines() > 0
3543 print dolGetButtonAction('', $langs->trans('AddPurchaseOrder'), 'default', DOL_URL_ROOT.'/fourn/commande/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id, '');
3544 }
3545 }*/
3546
3547 // Create intervention
3548 if (!getDolGlobalInt('COMMANDE_DISABLE_ADD_INTERVENTION')) {
3549 $arrayforbutaction[] = array(
3550 'lang' => 'interventions',
3551 'enabled' => (isModEnabled("intervention") && $object->status > Commande::STATUS_DRAFT && $object->status < Commande::STATUS_CLOSED && $object->getNbOfServicesLines() > 0),
3552 'perm' => ($user->hasRight('ficheinter', 'creer') == 1),
3553 'label' => 'AddIntervention',
3554 'url' => '/fichinter/card.php?action=create&origin=' . urlencode($object->element) . '&originid=' . ((int) $object->id) . '&socid=' . ((int) $object->socid),
3555 );
3556 }
3557
3558 // Create contract
3559 $arrayforbutaction[] = array(
3560 'lang' => 'contracts',
3561 'enabled' => (isModEnabled("contract") && ($object->status == Commande::STATUS_VALIDATED || $object->status == Commande::STATUS_SHIPMENTONPROCESS || $object->status == Commande::STATUS_CLOSED)),
3562 'perm' => ($user->hasRight('contrat', 'creer') == 1),
3563 'label' => 'AddContract',
3564 'url' => '/contrat/card.php?action=create&amp;origin=' . $object->element . '&amp;originid=' . $object->id . '&amp;socid=' . $object->socid,
3565 );
3566 /*if (isModEnabled('contract') && ($object->status == Commande::STATUS_VALIDATED || $object->status == Commande::STATUS_SHIPMENTONPROCESS || $object->status == Commande::STATUS_CLOSED)) {
3567 $langs->load("contracts");
3568
3569 if ($user->hasRight('contrat', 'creer')) {
3570 print dolGetButtonAction('', $langs->trans('AddContract'), 'default', DOL_URL_ROOT.'/contrat/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid, '');
3571 }
3572 }*/
3573
3574 $numshipping = 0;
3575
3576 // Create shipment
3577 if (isModEnabled('shipping')) {
3578 $numshipping = $object->countNbOfShipments();
3579
3580 if ($object->status > Commande::STATUS_DRAFT && $object->status < Commande::STATUS_CLOSED && ($object->getNbOfProductsLines() > 0 || getDolGlobalString('STOCK_SUPPORTS_SERVICES') || (getDolGlobalString('SHIPMENT_SUPPORTS_SERVICES') && $object->getNbOfServicesLines() > 0))) {
3581 if ((getDolGlobalInt('MAIN_SUBMODULE_EXPEDITION') && $user->hasRight('expedition', 'creer')) || (getDolGlobalInt('MAIN_SUBMODULE_DELIVERY') && $user->hasRight('expedition', 'delivery', 'creer'))) {
3582 // Add button to create shipment into the combo
3583 $arrayforbutaction[] = array(
3584 'lang' => 'sendings',
3585 'enabled' => (isModEnabled("shipping") && ($object->status > Commande::STATUS_DRAFT && $object->status < Commande::STATUS_CLOSED && ($object->getNbOfProductsLines() > 0 || getDolGlobalString('STOCK_SUPPORTS_SERVICES') || (getDolGlobalString('SHIPMENT_SUPPORTS_SERVICES') && $object->getNbOfServicesLines() > 0)))),
3586 'perm' => $user->hasRight('expedition', 'creer'),
3587 'label' => 'CreateShipment',
3588 'url' => '/expedition/shipment.php?id=' . $object->id
3589 );
3590 } else {
3591 //c$langs->load("errors");
3592 //print dolGetButtonAction($langs->trans('ErrorModuleSetupNotComplete'), $langs->trans('CreateShipment'), 'default', $_SERVER['PHP_SELF']. '#', '', false);
3593 $arrayforbutaction[] = array(
3594 'lang' => 'sendings',
3595 'enabled' => (isModEnabled("shipping") && ($object->status > Commande::STATUS_DRAFT && $object->status < Commande::STATUS_CLOSED && ($object->getNbOfProductsLines() > 0 || getDolGlobalString('STOCK_SUPPORTS_SERVICES') || (getDolGlobalString('SHIPMENT_SUPPORTS_SERVICES') && $object->getNbOfServicesLines() > 0)))),
3596 'perm' => 0,
3597 'label' => 'CreateShipment',
3598 'url' => '/expedition/shipment.php?id=' . $object->id
3599 );
3600 }
3601 }
3602 }
3603
3604 // Create bill
3605 $arrayforbutaction[] = array(
3606 'lang' => 'bills',
3607 'enabled' => (isModEnabled('invoice') && $object->status > Commande::STATUS_DRAFT && !$object->billed && $object->total_ttc >= 0),
3608 'perm' => ($user->hasRight('facture', 'creer') && !getDolGlobalInt('WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER')),
3609 'label' => 'CreateBill',
3610 'url' => '/compta/facture/card.php?action=create&amp;token=' . newToken() . '&amp;origin=' . urlencode($object->element) . '&amp;originid=' . $object->id . '&amp;socid=' . $object->socid
3611 );
3612 /*
3613 if (isModEnabled('facture') && $object->status > Commande::STATUS_DRAFT && !$object->billed && $object->total_ttc >= 0) {
3614 if (isModEnabled('facture') && $user->hasRight('facture', 'creer') && empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) {
3615 print dolGetButtonAction('', $langs->trans('CreateBill'), 'default', DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;token='.newToken().'&amp;origin='.urlencode($object->element).'&amp;originid='.$object->id.'&amp;socid='.$object->socid, '');
3616 }
3617 }*/
3618
3619 $actionButtonsParameters = [
3620 "areDropdownButtons" => !getDolGlobalInt("MAIN_REMOVE_DROPDOWN_CREATE_BUTTONS_ON_ORDER")
3621 ];
3622
3623 if ($numlines > 0) {
3624 print dolGetButtonAction('', $langs->trans("Create"), 'default', $arrayforbutaction, (string) $object->id, 1, $actionButtonsParameters);
3625 } else {
3626 print dolGetButtonAction($langs->trans("ErrorObjectMustHaveLinesToBeValidated", $object->ref), $langs->trans("Create"), 'default', $arrayforbutaction, (string) $object->id, 0, $actionButtonsParameters);
3627 }
3628
3629 // Set to shipped
3630 if (($object->status == Commande::STATUS_VALIDATED || $object->status == Commande::STATUS_SHIPMENTONPROCESS) && $usercanclose) {
3631 print dolGetButtonAction('', $langs->trans('ClassifyShipped'), 'default', $_SERVER["PHP_SELF"] . '?action=shipped&amp;token=' . newToken() . '&amp;id=' . $object->id, '');
3632 }
3633
3634 // Set billed or unbilled
3635 // Note: Even if module invoice is not enabled, we should be able to use button "Classified billed"
3636 if ($object->status > Commande::STATUS_DRAFT && !$object->billed && $object->total_ttc >= 0) {
3637 if ($usercancreate && $object->status >= Commande::STATUS_VALIDATED && !getDolGlobalString('ORDER_DISABLE_CLASSIFY_BILLED_FROM_ORDER') && !getDolGlobalString('WORKFLOW_BILL_ON_SHIPMENT')) {
3638 print dolGetButtonAction('', $langs->trans('ClassifyBilled'), 'default', $_SERVER["PHP_SELF"] . '?action=classifybilled&amp;token=' . newToken() . '&amp;id=' . $object->id, '');
3639 }
3640 }
3641 if ($object->status > Commande::STATUS_DRAFT && $object->billed) {
3642 if ($usercancreate && $object->status >= Commande::STATUS_VALIDATED && !getDolGlobalString('ORDER_DISABLE_CLASSIFY_BILLED_FROM_ORDER') && !getDolGlobalString('WORKFLOW_BILL_ON_SHIPMENT')) {
3643 print dolGetButtonAction('', $langs->trans('ClassifyUnBilled'), 'delete', $_SERVER["PHP_SELF"] . '?action=classifyunbilled&amp;token=' . newToken() . '&amp;id=' . $object->id, '');
3644 }
3645 }
3646
3647 // Clone
3648 if ($usercancreate) {
3649 print dolGetButtonAction('', $langs->trans('ToClone'), 'default', $_SERVER["PHP_SELF"] . '?action=clone&token=' . newToken() . '&id=' . $object->id . '&socid=' . $object->socid, '');
3650 }
3651
3652 // Cancel order
3653 if ($object->status == Commande::STATUS_VALIDATED && !empty($usercancancel)) {
3654 print '<a class="butActionDelete" href="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=cancel&token=' . newToken() . '">' . $langs->trans("CancelOrder") . '</a>';
3655 }
3656
3657 // Delete order
3658 if ($usercandelete) {
3659 if ($numshipping == 0) {
3660 print dolGetButtonAction('', $langs->trans('Delete'), 'delete', $_SERVER["PHP_SELF"] . '?action=delete&token=' . newToken() . '&id=' . $object->id, '');
3661 } else {
3662 print dolGetButtonAction($langs->trans('ShippingExist'), $langs->trans('Delete'), 'default', $_SERVER['PHP_SELF'] . '#', '', false);
3663 }
3664 }
3665 }
3666 print '</div>';
3667 }
3668
3669 // Select mail models is same action as presend
3670 if (GETPOST('modelselected')) {
3671 $action = 'presend';
3672 }
3673
3674 if ($action != 'presend') {
3675 print '<div class="fichecenter"><div class="fichehalfleft">';
3676 print '<a name="builddoc"></a>'; // ancre
3677 // Documents
3678 $objref = dol_sanitizeFileName($object->ref);
3679 $relativepath = $objref . '/' . $objref . '.pdf';
3680 $filedir = $conf->commande->multidir_output[$object->entity ?? $conf->entity] . '/' . $objref;
3681 $urlsource = dolBuildUrl($_SERVER["PHP_SELF"], ["id" => $object->id]);
3682 $genallowed = $usercanread;
3683 $delallowed = $usercancreate;
3684 $tooltipAfterComboOfModels = '';
3685 if (getDolGlobalString('MAIN_PDF_ADD_TERMSOFSALE_ORDER')) {
3686 $tooltipAfterComboOfModels = $langs->trans("AccordingToYourSetupTheFileWillBeConcatenated", getDolGlobalString('MAIN_INFO_ORDER_TERMSOFSALE'));
3687 }
3688
3689 print $formfile->showdocuments('commande', $objref, $filedir, $urlsource, $genallowed, (int) $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang, '', $object, 0, 'remove_file', $tooltipAfterComboOfModels);
3690
3691
3692 // Show links to link elements
3693 $tmparray = $form->showLinkToObjectBlock($object, array(), array('order'), 1);
3694 $linktoelem = $tmparray['linktoelem'];
3695 $htmltoenteralink = $tmparray['htmltoenteralink'];
3696 print $htmltoenteralink;
3697
3698 $compatibleImportElementsList = false;
3699 if (
3700 $usercancreate
3701 && $object->status == Commande::STATUS_DRAFT
3702 ) {
3703 $compatibleImportElementsList = array('commande', 'propal', 'facture', 'subscription'); // import from linked elements
3704 }
3705 $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList);
3706
3707 // Show online payment link
3708 // The list can be complete by the hook 'doValidatePayment' executed inside getValidOnlinePaymentMethods()
3709 include_once DOL_DOCUMENT_ROOT . '/core/lib/payments.lib.php';
3710 $validpaymentmethod = getValidOnlinePaymentMethods('');
3711 $useonlinepayment = count($validpaymentmethod);
3712
3713 if (getDolGlobalString('ORDER_HIDE_ONLINE_PAYMENT_ON_ORDER')) {
3714 $useonlinepayment = 0;
3715 }
3716 if ($object->status != Commande::STATUS_DRAFT && $useonlinepayment) {
3717 print '<br><!-- Link to pay -->';
3718 require_once DOL_DOCUMENT_ROOT . '/core/lib/payments.lib.php';
3719 print showOnlinePaymentUrl('order', $object->ref) . '<br>';
3720 }
3721
3722 print '</div><div class="fichehalfright">';
3723
3724 $MAXEVENT = 10;
3725
3726 //button to go to messaging from the events box
3727 $morehtmlcenter = dolGetButtonTitle($langs->trans('FullConversation'), '', 'fa fa-comments imgforviewmode', dolBuildUrl(DOL_URL_ROOT . '/commande/messaging.php', ['id' => $object->id]));
3728 $morehtmlcenter .= dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-bars imgforviewmode', dolBuildUrl(DOL_URL_ROOT . '/commande/agenda.php', ['id' => $object->id]));
3729
3730 // List of actions on element
3731 include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php';
3732 $formactions = new FormActions($db);
3733 $somethingshown = $formactions->showactions($object, 'order', $socid, 1, '', $MAXEVENT, '', $morehtmlcenter); // Show all action for thirdparty
3734
3735 print '</div></div>';
3736 }
3737
3738 // Presend form
3739 $modelmail = 'order_send';
3740 $defaulttopic = 'SendOrderRef';
3741 $diroutput = getMultidirOutput($object);
3742 $trackid = 'ord' . $object->id;
3743
3744 include DOL_DOCUMENT_ROOT . '/core/tpl/card_presend.tpl.php';
3745 }
3746}
3747
3748// End of page
3749llxFooter();
3750$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 customers orders.
const STATUS_SHIPMENTONPROCESS
Shipment on process.
const STATUS_CLOSED
Closed (Sent, billed or not)
const STATUS_CANCELED
Canceled status.
const STATUS_DRAFT
Draft status.
const STATUS_VALIDATED
Validated status.
Class to manage a WYSIWYG editor.
Class to manage standard extra fields.
static createDepositFromOrigin(CommonObject $origin, $date, $payment_terms_id, User $user, $notrigger=0, $autoValidateDeposit=false, $overrideFields=array())
Creates a deposit from a proposal or an order by grouping lines by VAT rates.
const TYPE_DEPOSIT
Deposit invoice.
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 permettant la generation de composants html autre Only common components are here.
Class to manage HTML output components for orders Before adding component here, check they are not in...
Class with static methods for building HTML components related to products Only components common to ...
Class to manage building of HTML components.
static liste_modeles($db, $maxfilenamelength=0)
Return list of active generation modules.
Class to manage the table of subscription to notifications.
Class ProductCombination Used to represent the relation between a product and one of its variants.
File of class to manage predefined price products or services by customer.
Class to manage products or services.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
Class to manage Dolibarr users.
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
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.
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_warning($titlealt='default', $moreatt='', $morecss='pictowarning')
Show warning logo.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dolBuildUrl($url, $params=[], $addtoken=false)
Return path of url.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
dolPrintHTML($s, $allowiframe=0)
Return a string (that can be on several lines) ready to be output on a HTML page.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dolGetButtonTitle($label, $helpText='', $iconClass='fa fa-file', $url='', $id='', $status=1, $params=array())
Function dolGetButtonTitle : this kind of buttons are used in title in list.
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.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
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.
showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round=-1, $forceunitoutput='no', $use_short_label=0)
Output a dimension with best unit.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOSTFLOAT($paramname, $rounding='', $option=2)
Return the value of a $_GET or $_POST supervariable, converted into float.
dolGetButtonAction($label, $text='', $actionType='default', $url='', $id='', $userRight=1, $params=array())
Function dolGetButtonAction.
dol_htmlcleanlastbr($stringtodecode)
This function remove all ending and br at end.
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...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
if(!function_exists( 'utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists( 'str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists( 'str_contains')) 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.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
img_edit($titlealt='default', $float=0, $other='')
Show logo edit/modify fiche.
getDictionaryValue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
Return the value of a filed into a dictionary for the record $id.
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...
commande_prepare_head(Commande $object)
Prepare array with list of tabs.
Definition order.lib.php:36
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $mode=0)
Check permissions of a user to show a page and an object.