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