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