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