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