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