1<?php
2/* Copyright (C) 2001-2007  Rodolphe Quiedeville    <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2017  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-2014  Juanjo Menent           <jmenent@2byte.es>
9 * Copyright (C) 2010-2019  Philippe Grand          <philippe.grand@atoo-net.com>
10 * Copyright (C) 2012-2013  Christophe Battarel     <christophe.battarel@altairis.fr>
11 * Copyright (C) 2013-2014  Florian Henry           <florian.henry@open-concept.pro>
12 * Copyright (C) 2014       Ferran Marcet           <fmarcet@2byte.es>
13 * Copyright (C) 2018       Frédéric France         <frederic.france@netlogic.fr>
14 * Copyright (C) 2020		Tobias Sekan			<tobias.sekan@startmail.com>
15 *
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 3 of the License, or
19 * (at your option) any later version.
20 *
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 * GNU General Public License for more details.
25 *
26 * You should have received a copy of the GNU General Public License
27 * along with this program. If not, see <https://www.gnu.org/licenses/>.
28 */
29
30/**
31 *	\file		htdocs/supplier_proposal/card.php
32 *	\ingroup	supplier_proposal
33 *	\brief		Card supplier proposal
34 */
35
36require '../main.inc.php';
37require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
38require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
39require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
40require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
41require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
42require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php';
43require_once DOL_DOCUMENT_ROOT.'/core/lib/supplier_proposal.lib.php';
44require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
45require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
46if (!empty($conf->projet->enabled)) {
47	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
48	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
49}
50
51// Load translation files required by the page
52$langs->loadLangs(array('companies', 'supplier_proposal', 'compta', 'bills', 'propal', 'orders', 'products', 'deliveries', 'sendings'));
53if (!empty($conf->margin->enabled)) {
54	$langs->load('margins');
55}
56
57$error = 0;
58
59$id = GETPOST('id', 'int');
60$ref = GETPOST('ref', 'alpha');
61$socid = GETPOST('socid', 'int');
62$action = GETPOST('action', 'aZ09');
63$origin = GETPOST('origin', 'alpha');
64$originid = GETPOST('originid', 'int');
65$confirm = GETPOST('confirm', 'alpha');
66$projectid = GETPOST('projectid', 'int');
67$lineid = GETPOST('lineid', 'int');
68$contactid = GETPOST('contactid', 'int');
69
70// PDF
71$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
72$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
73$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
74
75// Nombre de ligne pour choix de produit/service predefinis
76$NBLINES = 4;
77
78// Security check
79if (!empty($user->socid)) {
80	$socid = $user->socid;
81}
82$result = restrictedArea($user, 'supplier_proposal', $id);
83
84// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
85$hookmanager->initHooks(array('supplier_proposalcard', 'globalcard'));
86
87$object = new SupplierProposal($db);
88$extrafields = new ExtraFields($db);
89
90// fetch optionals attributes and labels
91$extrafields->fetch_name_optionals_label($object->table_element);
92
93// Load object
94if ($id > 0 || !empty($ref)) {
95	$ret = $object->fetch($id, $ref);
96	if ($ret > 0) {
97		$ret = $object->fetch_thirdparty();
98	}
99	if ($ret < 0) {
100		dol_print_error('', $object->error);
101	}
102}
103
104// Common permissions
105$usercanread = $user->rights->supplier_proposal->lire;
106$usercancreate		= $user->rights->supplier_proposal->creer;
107$usercandelete		= $user->rights->supplier_proposal->supprimer;
108
109// Advanced permissions
110$usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->supplier_proposal->validate_advance)));
111$usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->supplier_proposal->send_advance);
112
113// Additional area permissions
114$usercanclose = $user->rights->supplier_proposal->cloturer;
115$usercancreateorder = ($user->rights->fournisseur->commande->creer || $user->rights->supplier_order->creer);
116
117// Permissions for includes
118$permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
119$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
120$permissiontoedit = $usercancreate; // Used by the include of actions_lineupdown.inc.php
121$permissiontoadd = $usercancreate;
122
123
124/*
125 * Actions
126 */
127
128$parameters = array('socid' => $socid);
129$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
130if ($reshook < 0) {
131	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
132}
133
134if (empty($reshook)) {
135	if ($cancel) {
136		if (!empty($backtopage)) {
137			header("Location: ".$backtopage);
138			exit;
139		}
140		$action = '';
141	}
142
143	include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
144
145	include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
146
147	include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
148
149	// Action clone object
150	if ($action == 'confirm_clone' && $confirm == 'yes') {
151		if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) {
152			setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
153		} else {
154			if ($object->id > 0) {
155				$result = $object->createFromClone($user, $socid);
156				if ($result > 0) {
157					header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
158					exit();
159				} else {
160					setEventMessages($object->error, $object->errors, 'errors');
161					$action = '';
162				}
163			}
164		}
165	} elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) {
166		// Delete askprice
167		$result = $object->delete($user);
168		if ($result > 0) {
169			header('Location: '.DOL_URL_ROOT.'/supplier_proposal/list.php');
170			exit();
171		} else {
172			$langs->load("errors");
173			setEventMessages($langs->trans($object->error), null, 'errors');
174		}
175	} elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
176		// Remove line
177		$result = $object->deleteline($lineid);
178		// reorder lines
179		if ($result) {
180			$object->line_order(true);
181		}
182
183		if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
184			// Define output language
185			$outputlangs = $langs;
186			if (!empty($conf->global->MAIN_MULTILANGS)) {
187				$outputlangs = new Translate("", $conf);
188				$newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $object->thirdparty->default_lang);
189				$outputlangs->setDefaultLang($newlang);
190			}
191			$ret = $object->fetch($id); // Reload to get new records
192			$object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
193		}
194
195		header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
196		exit();
197	} elseif ($action == 'confirm_validate' && $confirm == 'yes' && $usercanvalidate) {
198		// Validation
199		$result = $object->valid($user);
200		if ($result >= 0) {
201			if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
202						// Define output language
203				if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
204					$outputlangs = $langs;
205					$newlang = '';
206					if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
207						$newlang = GETPOST('lang_id', 'aZ09');
208					}
209					if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
210						$newlang = $object->thirdparty->default_lang;
211					}
212					if (!empty($newlang)) {
213						$outputlangs = new Translate("", $conf);
214						$outputlangs->setDefaultLang($newlang);
215					}
216					$model = $object->model_pdf;
217					$ret = $object->fetch($id); // Reload to get new records
218
219					$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
220				}
221			}
222		} else {
223			$langs->load("errors");
224			if (count($object->errors) > 0) {
225				setEventMessages($object->error, $object->errors, 'errors');
226			} else {
227				setEventMessages($langs->trans($object->error), null, 'errors');
228			}
229		}
230	} elseif ($action == 'setdate_livraison' && $usercancreate) {
231		$result = $object->setDeliveryDate($user, dol_mktime(12, 0, 0, $_POST['liv_month'], $_POST['liv_day'], $_POST['liv_year']));
232		if ($result < 0) {
233			dol_print_error($db, $object->error);
234		}
235	} elseif ($action == 'add' && $usercancreate) {
236		// Create supplier proposal
237		$object->socid = $socid;
238		$object->fetch_thirdparty();
239
240		$date_delivery = dol_mktime(12, 0, 0, GETPOST('liv_month'), GETPOST('liv_day'), GETPOST('liv_year'));
241
242		if ($socid < 1) {
243			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Supplier")), null, 'errors');
244			$action = 'create';
245			$error++;
246		}
247
248		if (!$error) {
249			$db->begin();
250
251			// Si on a selectionne une demande a copier, on realise la copie
252			if (GETPOST('createmode') == 'copy' && GETPOST('copie_supplier_proposal')) {
253				if ($object->fetch(GETPOST('copie_supplier_proposal')) > 0) {
254					$object->ref = GETPOST('ref');
255					$object->date_livraison = $date_delivery; // deprecated
256					$object->delivery_date = $date_delivery;
257					$object->shipping_method_id = GETPOST('shipping_method_id', 'int');
258					$object->cond_reglement_id = GETPOST('cond_reglement_id');
259					$object->mode_reglement_id = GETPOST('mode_reglement_id');
260					$object->fk_account = GETPOST('fk_account', 'int');
261					$object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
262					$object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU', 2);
263					$object->socid = GETPOST('socid');
264					$object->fk_project = GETPOST('projectid', 'int');
265					$object->model_pdf = GETPOST('model');
266					$object->author = $user->id; // deprecated
267					$object->note = GETPOST('note', 'restricthtml');
268					$object->note_private = GETPOST('note', 'restricthtml');
269					$object->statut = SupplierProposal::STATUS_DRAFT;
270				} else {
271					setEventMessages($langs->trans("ErrorFailedToCopyProposal", GETPOST('copie_supplier_proposal')), null, 'errors');
272				}
273			} else {
274				$object->ref = GETPOST('ref');
275				$object->date_livraison = $date_delivery;
276				$object->delivery_date = $date_delivery;
277				$object->demand_reason_id = GETPOST('demand_reason_id');
278				$object->shipping_method_id = GETPOST('shipping_method_id', 'int');
279				$object->cond_reglement_id = GETPOST('cond_reglement_id');
280				$object->mode_reglement_id = GETPOST('mode_reglement_id');
281				$object->fk_account = GETPOST('fk_account', 'int');
282				$object->fk_project = GETPOST('projectid', 'int');
283				$object->model_pdf = GETPOST('model');
284				$object->author = $user->id; // deprecated
285				$object->note = GETPOST('note', 'restricthtml');
286				$object->note_private = GETPOST('note', 'restricthtml');
287
288				$object->origin = GETPOST('origin');
289				$object->origin_id = GETPOST('originid');
290
291				// Multicurrency
292				if (!empty($conf->multicurrency->enabled)) {
293					$object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
294				}
295
296				// Fill array 'array_options' with data from add form
297				$ret = $extrafields->setOptionalsFromPost(null, $object);
298				if ($ret < 0) {
299					$error++;
300					$action = 'create';
301				}
302			}
303
304			if (!$error) {
305				if ($origin && $originid) {
306					$element = 'supplier_proposal';
307					$subelement = 'supplier_proposal';
308
309					$object->origin = $origin;
310					$object->origin_id = $originid;
311
312					// Possibility to add external linked objects with hooks
313					$object->linked_objects [$object->origin] = $object->origin_id;
314					if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) {
315						$object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
316					}
317
318					$id = $object->create($user);
319					if ($id > 0) {
320						dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
321
322						$classname = ucfirst($subelement);
323						$srcobject = new $classname($db);
324
325						dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
326						$result = $srcobject->fetch($object->origin_id);
327
328						if ($result > 0) {
329							$lines = $srcobject->lines;
330							if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
331								$srcobject->fetch_lines();
332								$lines = $srcobject->lines;
333							}
334
335							$fk_parent_line = 0;
336							$num = count($lines);
337							for ($i = 0; $i < $num; $i++) {
338								$label = (!empty($lines[$i]->label) ? $lines[$i]->label : '');
339								$desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->libelle);
340
341								// Positive line
342								$product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
343
344								// Reset fk_parent_line for no child products and special product
345								if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
346									$fk_parent_line = 0;
347								}
348
349								// Extrafields
350								if (method_exists($lines[$i], 'fetch_optionals')) {
351									$lines[$i]->fetch_optionals();
352									$array_options = $lines[$i]->array_options;
353								}
354
355								$result = $object->addline(
356									$desc,
357									$lines[$i]->subprice,
358									$lines[$i]->qty,
359									$lines[$i]->tva_tx,
360									$lines[$i]->localtax1_tx,
361									$lines[$i]->localtax2_tx,
362									$lines[$i]->fk_product,
363									$lines[$i]->remise_percent,
364									'HT',
365									0,
366									$lines[$i]->info_bits,
367									$product_type,
368									$lines[$i]->rang,
369									$lines[$i]->special_code,
370									$fk_parent_line,
371									$lines[$i]->fk_fournprice,
372									$lines[$i]->pa_ht,
373									$label,
374									$array_options,
375									$lines[$i]->ref_supplier,
376									$lines[$i]->fk_unit
377								);
378
379								if ($result > 0) {
380									$lineid = $result;
381								} else {
382									$lineid = 0;
383									$error++;
384									break;
385								}
386
387								// Defined the new fk_parent_line
388								if ($result > 0 && $lines[$i]->product_type == 9) {
389									$fk_parent_line = $result;
390								}
391							}
392
393							// Hooks
394							$parameters = array('objFrom' => $srcobject);
395							$reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
396																											   // modified by hook
397							if ($reshook < 0) {
398								$error++;
399							}
400						} else {
401							setEventMessages($srcobject->error, $srcobject->errors, 'errors');
402							$error++;
403						}
404					} else {
405						setEventMessages($object->error, $object->errors, 'errors');
406						$error++;
407					}
408				} else {
409					// Standard creation
410					$id = $object->create($user);
411				}
412
413				if ($id > 0) {
414					if (!$error) {
415						$db->commit();
416
417						// Define output language
418						if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
419							$outputlangs = $langs;
420							$newlang = '';
421							if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
422								$newlang = GETPOST('lang_id', 'aZ09');
423							}
424							if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
425								$newlang = $object->thirdparty->default_lang;
426							}
427							if (!empty($newlang)) {
428								$outputlangs = new Translate("", $conf);
429								$outputlangs->setDefaultLang($newlang);
430							}
431							$model = $object->model_pdf;
432
433							$ret = $object->fetch($id); // Reload to get new records
434							$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
435							if ($result < 0) {
436								dol_print_error($db, $result);
437							}
438						}
439
440						header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id);
441						exit();
442					} else {
443						$db->rollback();
444						$action = 'create';
445					}
446				} else {
447					setEventMessages($object->error, $object->errors, 'errors');
448					$db->rollback();
449					$action = 'create';
450				}
451			}
452		}
453	} elseif ($action == 'confirm_reopen' && $usercanclose && !GETPOST('cancel', 'alpha')) {
454		// Reopen proposal
455		// prevent browser refresh from reopening proposal several times
456		if ($object->statut == SupplierProposal::STATUS_SIGNED || $object->statut == SupplierProposal::STATUS_NOTSIGNED || $object->statut == SupplierProposal::STATUS_CLOSE) {
457			$object->reopen($user, SupplierProposal::STATUS_VALIDATED);
458		}
459	} elseif ($action == 'close' && $usercanclose && !GETPOST('cancel', 'alpha')) {
460		// Close proposal
461		// prevent browser refresh from reopening proposal several times
462		if ($object->statut == SupplierProposal::STATUS_SIGNED) {
463			$object->setStatut(SupplierProposal::STATUS_CLOSE);
464		}
465	} elseif ($action == 'setstatut' && $usercanclose && !GETPOST('cancel', 'alpha')) {
466		// Set accepted/refused
467		if (!GETPOST('statut')) {
468			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("CloseAs")), null, 'errors');
469			$action = 'statut';
470		} else {
471			// prevent browser refresh from closing proposal several times
472			if ($object->statut == SupplierProposal::STATUS_VALIDATED) {
473				$object->cloture($user, GETPOST('statut'), GETPOST('note', 'restricthtml'));
474			}
475		}
476	}
477
478	// Actions when printing a doc from card
479	include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
480
481	// Actions to send emails
482	$triggersendname = 'PROPOSAL_SUPPLIER_SENTBYMAIL';
483	$autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO';
484	$trackid = 'spro'.$object->id;
485	include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
486
487	// Actions to build doc
488	$upload_dir = $conf->supplier_proposal->dir_output;
489	include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
490
491
492	// Go back to draft
493	if ($action == 'modif' && $usercancreate) {
494		$object->setDraft($user);
495
496		if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
497			// Define output language
498			$outputlangs = $langs;
499			if (!empty($conf->global->MAIN_MULTILANGS)) {
500				$outputlangs = new Translate("", $conf);
501				$newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $object->thirdparty->default_lang);
502				$outputlangs->setDefaultLang($newlang);
503			}
504			$ret = $object->fetch($id); // Reload to get new records
505			$object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
506		}
507	} elseif ($action == "setabsolutediscount" && $usercancreate) {
508		if (GETPOST("remise_id", 'int')) {
509			if ($object->id > 0) {
510				$result = $object->insert_discount(GETPOST("remise_id", 'int'));
511				if ($result < 0) {
512					setEventMessages($object->error, $object->errors, 'errors');
513				}
514			}
515		}
516	}
517
518	// Add a product line
519	if ($action == 'addline' && $usercancreate) {
520		$langs->load('errors');
521		$error = 0;
522
523		// Set if we used free entry or predefined product
524		$predef = '';
525		$product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
526		$date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year'));
527		$date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year'));
528		$ref_supplier = GETPOST('fourn_ref', 'alpha');
529		$prod_entry_mode = GETPOST('prod_entry_mode');
530		if ($prod_entry_mode == 'free')	{
531			$idprod = 0;
532			$price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
533			$tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
534		} else {
535			$idprod = GETPOST('idprod', 'int');
536			$price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
537			$tva_tx = '';
538		}
539
540		$qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS');
541		$remise_percent = price2num(GETPOST('remise_percent'.$predef), 2);
542		$price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
543
544		// Extrafields
545		$extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
546		$array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
547		// Unset extrafield
548		if (is_array($extralabelsline)) {
549			// Get extra fields
550			foreach ($extralabelsline as $key => $value) {
551				unset($_POST["options_".$key]);
552			}
553		}
554
555		if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
556			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
557			$error++;
558		}
559
560		if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') { 	// Unit price can be 0 but not ''. Also price can be negative for proposal.
561			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPrice")), null, 'errors');
562			$error++;
563		}
564		if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && empty($product_desc)) {
565			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors');
566			$error++;
567		}
568		if (!$error && ($qty >= 0)) {
569			$pu_ht = price2num($price_ht, 'MU');
570			$pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
571			$price_min = 0;
572			$price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
573
574			$db->begin();
575
576			// Ecrase $pu par celui du produit
577			// Ecrase $desc par celui du produit
578			// Ecrase $txtva par celui du produit
579			if (($prod_entry_mode != 'free') && empty($error)) {	// With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or ''
580				$productsupplier = new ProductFournisseur($db);
581
582				$idprod = 0;
583				if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') {
584					$idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...)
585				}
586
587				$reg = array();
588				if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) {
589					$idprod = $reg[1];
590					$res = $productsupplier->fetch($idprod); // Load product from its ID
591					// Call to init some price properties of $productsupplier
592					// So if a supplier price already exists for another thirdparty (first one found), we use it as reference price
593					if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) {
594						$fksoctosearch = 0;
595						$productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
596						if ($productsupplier->fourn_socid != $socid) {	// The price we found is for another supplier, so we clear supplier price
597							$productsupplier->ref_supplier = '';
598						}
599					} else {
600						$fksoctosearch = $object->thirdparty->id;
601						$productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
602					}
603				} elseif (GETPOST('idprodfournprice', 'alpha') > 0) {
604					//$qtytosearch=$qty; 	   // Just to see if a price exists for the quantity. Not used to found vat.
605					$qtytosearch = -1; // We force qty to -1 to be sure to find if the supplier price that exists
606					$idprod = $productsupplier->get_buyprice(GETPOST('idprodfournprice', 'alpha'), $qtytosearch);
607					$res = $productsupplier->fetch($idprod);
608				}
609
610				if ($idprod > 0) {
611					$label = $productsupplier->label;
612
613					// if we use supplier description of the products
614					if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) {
615						$desc = $productsupplier->desc_supplier;
616					} else {
617						$desc = $productsupplier->description;
618					}
619
620					if (trim($product_desc) != trim($desc)) {
621						$desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
622					}
623
624					$type = $productsupplier->type;
625					$price_base_type = ($productsupplier->fourn_price_base_type ? $productsupplier->fourn_price_base_type : 'HT');
626
627					$ref_supplier = $productsupplier->ref_supplier;
628
629					$tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha'));
630					$tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha'));
631					if (empty($tva_tx)) {
632						$tva_npr = 0;
633					}
634					$localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr);
635					$localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr);
636
637					if (empty($pu_ht)) {
638						$pu_ht = 0; // If pu is '' or null, we force to have a numeric value
639					}
640
641					// If GETPOST('idprodfournprice') is a numeric, we can use it. If it is empty or if it is 'idprod_123', we should use -1 (not used)
642					$fournprice = (is_numeric(GETPOST('idprodfournprice', 'alpha')) ? GETPOST('idprodfournprice', 'alpha') : -1);
643					$buyingprice = 0;
644					$pu_ht_devise = price2num($price_ht_devise, 'MU');
645
646					$result = $object->addline(
647						$desc,
648						$pu_ht,
649						$qty,
650						$tva_tx,
651						$localtax1_tx,
652						$localtax2_tx,
653						$productsupplier->id,
654						$remise_percent,
655						$price_base_type,
656						$pu_ttc,
657						$tva_npr,
658						$type,
659						-1,
660						0,
661						GETPOST('fk_parent_line'),
662						$fournprice,
663						$buyingprice,
664						$label,
665						$array_options,
666						$ref_supplier,
667						$productsupplier->fk_unit,
668						'',
669						0,
670						$pu_ht_devise,
671						$date_start,
672						$date_end
673					);
674
675					//var_dump($tva_tx);var_dump($productsupplier->fourn_pu);var_dump($price_base_type);exit;
676					if ($result < 0) {
677						$error++;
678						setEventMessages($object->error, $object->errors, 'errors');
679					}
680				}
681				if ($idprod == -99 || $idprod == 0) {
682					// Product not selected
683					$error++;
684					$langs->load("errors");
685					setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")).' '.$langs->trans("or").' '.$langs->trans("NoPriceDefinedForThisSupplier"), null, 'errors');
686				}
687				if ($idprod == -1) {
688					// Quantity too low
689					$error++;
690					$langs->load("errors");
691					setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors');
692				}
693			} elseif ((GETPOST('price_ht') !== '' || GETPOST('price_ttc') !== '' || GETPOST('multicurrency_price_ht') != '') && empty($error)) {    // Free product.  // $price_ht is already set
694				$pu_ht = price2num($price_ht, 'MU');
695				$pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
696				$tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
697				$tva_tx = str_replace('*', '', $tva_tx);
698				$label = (GETPOST('product_label') ? GETPOST('product_label') : '');
699				$desc = $product_desc;
700				$type = GETPOST('type');
701
702				$fk_unit = GETPOST('units', 'alpha');
703
704				if (!preg_match('/\((.*)\)/', $tva_tx)) {
705					$tva_tx = price2num($tva_tx); // When vat is text input field
706				}
707
708				// Local Taxes
709				$localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
710				$localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
711
712				if ($price_ht !== '') {
713					$pu_ht = price2num($price_ht, 'MU'); // $pu_ht must be rounded according to settings
714				} else {
715					$pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
716					$pu_ht = price2num($pu_ttc / (1 + ($tva_tx / 100)), 'MU'); // $pu_ht must be rounded according to settings
717				}
718				$price_base_type = 'HT';
719				$pu_ht_devise = price2num($price_ht_devise, 'MU');
720
721				$result = $object->addline(
722					$desc,
723					$pu_ht,
724					$qty,
725					$tva_tx,
726					$localtax1_tx,
727					$localtax2_tx,
728					$idprod,
729					$remise_percent,
730					$price_base_type,
731					$pu_ttc,
732					$info_bits,
733					$type,
734					-1, // rang
735					0, // special_code
736					GETPOST('fk_parent_line'),
737					$fournprice,
738					$buyingprice,
739					$label,
740					$array_options,
741					$ref_supplier,
742					$fk_unit,
743					'', // origin
744					0, // origin_id
745					$pu_ht_devise
746				);
747			}
748
749
750			if (!$error && $result > 0) {
751				$db->commit();
752
753				$ret = $object->fetch($object->id); // Reload to get new records
754
755				// Define output language
756				if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
757					$outputlangs = $langs;
758					$newlang = '';
759					if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
760						$newlang = GETPOST('lang_id', 'aZ09');
761					}
762					if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
763						$newlang = $object->thirdparty->default_lang;
764					}
765					if (!empty($newlang)) {
766						$outputlangs = new Translate("", $conf);
767						$outputlangs->setDefaultLang($newlang);
768					}
769					$model = $object->model_pdf;
770					$ret = $object->fetch($id); // Reload to get new records
771
772					$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
773					if ($result < 0) {
774						dol_print_error($db, $result);
775					}
776				}
777
778				unset($_POST['prod_entry_mode']);
779
780				unset($_POST['qty']);
781				unset($_POST['type']);
782				unset($_POST['remise_percent']);
783				unset($_POST['pu']);
784				unset($_POST['price_ht']);
785				unset($_POST['multicurrency_price_ht']);
786				unset($_POST['price_ttc']);
787				unset($_POST['tva_tx']);
788				unset($_POST['label']);
789				unset($_POST['product_ref']);
790				unset($_POST['product_label']);
791				unset($_POST['product_desc']);
792				unset($_POST['fournprice']);
793				unset($_POST['buying_price']);
794				unset($localtax1_tx);
795				unset($localtax2_tx);
796				unset($_POST['np_marginRate']);
797				unset($_POST['np_markRate']);
798				unset($_POST['dp_desc']);
799				unset($_POST['idprodfournprice']);
800				unset($_POST['idprod']);
801
802				unset($_POST['date_starthour']);
803				unset($_POST['date_startmin']);
804				unset($_POST['date_startsec']);
805				unset($_POST['date_startday']);
806				unset($_POST['date_startmonth']);
807				unset($_POST['date_startyear']);
808				unset($_POST['date_endhour']);
809				unset($_POST['date_endmin']);
810				unset($_POST['date_endsec']);
811				unset($_POST['date_endday']);
812				unset($_POST['date_endmonth']);
813				unset($_POST['date_endyear']);
814			} else {
815				$db->rollback();
816
817				setEventMessages($object->error, $object->errors, 'errors');
818			}
819		}
820	} elseif ($action == 'updateline' && $usercancreate && GETPOST('save') == $langs->trans("Save")) {
821		// Mise a jour d'une ligne dans la demande de prix
822		$vat_rate = (GETPOST('tva_tx') ?GETPOST('tva_tx') : 0);
823
824		// Define info_bits
825		$info_bits = 0;
826		if (preg_match('/\*/', $vat_rate)) {
827			$info_bits |= 0x01;
828		}
829
830		// Clean parameters
831		$description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml'));
832
833		// Define vat_rate
834		$vat_rate = str_replace('*', '', $vat_rate);
835		$localtax1_rate = get_localtax($vat_rate, 1, $mysoc, $object->thirdparty);
836		$localtax2_rate = get_localtax($vat_rate, 2, $mysoc, $object->thirdparty);
837
838		if (GETPOST('price_ht') != '') {
839			$ht = price2num(GETPOST('price_ht'), '', 2);
840		}
841
842		if (GETPOST('price_ttc') != '') {
843			$reg = array();
844			$vatratecleaned = $vat_rate;
845			if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) {      // If vat is "xx (yy)"
846				$vatratecleaned = trim($reg[1]);
847				$vatratecode = $reg[2];
848			}
849
850			$ttc = price2num(GETPOST('price_ttc'), '', 2);
851			$ht = $ttc / (1 + ($vatratecleaned / 100));
852		}
853
854		$price_base_type = 'HT';
855		$pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), 'CU');
856
857		// Add buying price
858		$fournprice = (GETPOST('fournprice') ? GETPOST('fournprice') : '');
859		$buyingprice = (GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
860
861		// Extrafields Lines
862		$extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
863		$array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
864		// Unset extrafield POST Data
865		if (is_array($extralabelsline)) {
866			foreach ($extralabelsline as $key => $value) {
867				unset($_POST["options_".$key]);
868			}
869		}
870
871		// Define special_code for special lines
872		$special_code = GETPOST('special_code');
873		if (!GETPOST('qty')) {
874			$special_code = 3;
875		}
876
877		// Check minimum price
878		$productid = GETPOST('productid', 'int');
879		if (!empty($productid)) {
880			$productsupplier = new ProductFournisseur($db);
881			if (!empty($conf->global->SUPPLIER_PROPOSAL_WITH_PREDEFINED_PRICES_ONLY)) {
882				if ($productid > 0 && $productsupplier->get_buyprice(0, price2num($_POST['qty']), $productid, 'none', GETPOST('socid', 'int')) < 0) {
883					setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings');
884				}
885			}
886
887			$product = new Product($db);
888			$res = $product->fetch($productid);
889
890			$type = $product->type;
891
892			$price_min = $product->price_min;
893			if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) {
894				$price_min = $product->multiprices_min [$object->thirdparty->price_level];
895			}
896
897			$label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
898		} else {
899			$type = GETPOST('type');
900			$label = (GETPOST('product_label') ? GETPOST('product_label') : '');
901
902			// Check parameters
903			if (GETPOST('type') < 0) {
904				setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
905				$error++;
906			}
907		}
908
909		if (!$error) {
910			$db->begin();
911
912			$ref_supplier = GETPOST('fourn_ref', 'alpha');
913			$fk_unit = GETPOST('units');
914
915			$result = $object->updateline(
916				GETPOST('lineid', 'int'),
917				$ht,
918				price2num(GETPOST('qty'), 'MS', 2),
919				price2num(GETPOST('remise_percent'), '', 2),
920				$vat_rate,
921				$localtax1_rate,
922				$localtax2_rate,
923				$description,
924				$price_base_type,
925				$info_bits,
926				$special_code,
927				GETPOST('fk_parent_line', 'int'),
928				0,
929				$fournprice,
930				$buyingprice,
931				$label,
932				$type,
933				$array_options,
934				$ref_supplier,
935				$fk_unit,
936				$pu_ht_devise
937			);
938
939			if ($result >= 0) {
940				$db->commit();
941
942				if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
943					// Define output language
944					$outputlangs = $langs;
945					if (!empty($conf->global->MAIN_MULTILANGS)) {
946						$outputlangs = new Translate("", $conf);
947						$newlang = (GETPOST('lang_id', 'aZ09') ? GETPOST('lang_id', 'aZ09') : $object->thirdparty->default_lang);
948						$outputlangs->setDefaultLang($newlang);
949					}
950					$ret = $object->fetch($id); // Reload to get new records
951					$object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
952				}
953
954				unset($_POST['qty']);
955				unset($_POST['type']);
956				unset($_POST['productid']);
957				unset($_POST['remise_percent']);
958				unset($_POST['price_ht']);
959				unset($_POST['multicurrency_price_ht']);
960				unset($_POST['price_ttc']);
961				unset($_POST['tva_tx']);
962				unset($_POST['product_ref']);
963				unset($_POST['product_label']);
964				unset($_POST['product_desc']);
965				unset($_POST['fournprice']);
966				unset($_POST['buying_price']);
967
968				unset($_POST['date_starthour']);
969				unset($_POST['date_startmin']);
970				unset($_POST['date_startsec']);
971				unset($_POST['date_startday']);
972				unset($_POST['date_startmonth']);
973				unset($_POST['date_startyear']);
974				unset($_POST['date_endhour']);
975				unset($_POST['date_endmin']);
976				unset($_POST['date_endsec']);
977				unset($_POST['date_endday']);
978				unset($_POST['date_endmonth']);
979				unset($_POST['date_endyear']);
980			} else {
981				$db->rollback();
982
983				setEventMessages($object->error, $object->errors, 'errors');
984			}
985		}
986	} elseif ($action == 'updateline' && $usercancreate && GETPOST('cancel', 'alpha') == $langs->trans("Cancel")) {
987		header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); // Pour reaffichage de la fiche en cours d'edition
988		exit();
989	} elseif ($action == 'classin' && $usercancreate) {
990		// Set project
991		$object->setProject(GETPOST('projectid'), 'int');
992	} elseif ($action == 'setavailability' && $usercancreate) {
993		// Delivery delay
994		$result = $object->availability($_POST['availability_id']);
995	} elseif ($action == 'setconditions' && $usercancreate) {
996		// Terms of payments
997		$result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
998	} elseif ($action == 'setremisepercent' && $usercancreate) {
999		$result = $object->set_remise_percent($user, price2num(GETPOST('remise_percent'), '', 2));
1000	} elseif ($action == 'setremiseabsolue' && $usercancreate) {
1001		$result = $object->set_remise_absolue($user, price2num(GETPOST('remise_absolue'), 'MU', 2));
1002	} elseif ($action == 'setmode' && $usercancreate) {
1003		// Payment mode
1004		$result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
1005	} elseif ($action == 'setmulticurrencycode' && $usercancreate) {
1006		// Multicurrency Code
1007		$result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
1008	} elseif ($action == 'setmulticurrencyrate' && $usercancreate) {
1009		// Multicurrency rate
1010		$result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int'));
1011	} elseif ($action == 'update_extras') {
1012		$object->oldcopy = dol_clone($object);
1013
1014		// Fill array 'array_options' with data from update form
1015		$ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
1016		if ($ret < 0) {
1017			$error++;
1018		}
1019
1020		if (!$error) {
1021			$result = $object->insertExtraFields('PROPOSAL_SUPPLIER_MODIFY');
1022			if ($result < 0) {
1023				setEventMessages($object->error, $object->errors, 'errors');
1024				$error++;
1025			}
1026		}
1027
1028		if ($error) {
1029			$action = 'edit_extras';
1030		}
1031	}
1032}
1033
1034
1035/*
1036 * View
1037 */
1038$title = $langs->trans('CommRequest')." - ".$langs->trans('Card');
1039$help_url = 'EN:Ask_Price_Supplier|FR:Demande_de_prix_fournisseur';
1040llxHeader('', $title, $help_url);
1041
1042$form = new Form($db);
1043$formother = new FormOther($db);
1044$formfile = new FormFile($db);
1045$formmargin = new FormMargin($db);
1046$companystatic = new Societe($db);
1047if (!empty($conf->projet->enabled)) {
1048	$formproject = new FormProjets($db);
1049}
1050
1051$now = dol_now();
1052
1053// Add new askprice
1054if ($action == 'create') {
1055	$currency_code = $conf->currency;
1056
1057	print load_fiche_titre($langs->trans("NewAskPrice"), '', 'supplier_proposal');
1058
1059	$soc = new Societe($db);
1060	if ($socid > 0) {
1061		$res = $soc->fetch($socid);
1062	}
1063
1064	// Load objectsrc
1065	if (!empty($origin) && !empty($originid)) {
1066		$element = 'supplier_proposal';
1067		$subelement = 'supplier_proposal';
1068
1069		dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
1070
1071		$classname = ucfirst($subelement);
1072		$objectsrc = new $classname($db);
1073		$objectsrc->fetch($originid);
1074		if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
1075			$objectsrc->fetch_lines();
1076		}
1077		$objectsrc->fetch_thirdparty();
1078
1079		$projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : '');
1080		$soc = $objectsrc->thirdparty;
1081
1082		$cond_reglement_id 	= (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0)); // TODO maybe add default value option
1083		$mode_reglement_id 	= (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
1084		$remise_percent 	= (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_supplier_percent) ? $soc->remise_supplier_percent : 0));
1085		$remise_absolue 	= (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
1086
1087		// Replicate extrafields
1088		$objectsrc->fetch_optionals();
1089		$object->array_options = $objectsrc->array_options;
1090
1091		if (!empty($conf->multicurrency->enabled)) {
1092			if (!empty($objectsrc->multicurrency_code)) {
1093				$currency_code = $objectsrc->multicurrency_code;
1094			}
1095			if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) {
1096				$currency_tx = $objectsrc->multicurrency_tx;
1097			}
1098		}
1099	} else {
1100		$cond_reglement_id 	= $soc->cond_reglement_supplier_id;
1101		$mode_reglement_id 	= $soc->mode_reglement_supplier_id;
1102		if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) {
1103			$currency_code = $soc->multicurrency_code;
1104		}
1105	}
1106
1107	$object = new SupplierProposal($db);
1108
1109	print '<form name="addprop" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
1110	print '<input type="hidden" name="token" value="'.newToken().'">';
1111	print '<input type="hidden" name="action" value="add">';
1112	if ($origin != 'project' && $originid) {
1113		print '<input type="hidden" name="origin" value="'.$origin.'">';
1114		print '<input type="hidden" name="originid" value="'.$originid.'">';
1115	}
1116
1117	print dol_get_fiche_head();
1118
1119	print '<table class="border centpercent">';
1120
1121	// Reference
1122	print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td colspan="2">'.$langs->trans("Draft").'</td></tr>';
1123
1124	// Third party
1125	print '<tr>';
1126	print '<td class="fieldrequired">'.$langs->trans('Supplier').'</td>';
1127	if ($socid > 0) {
1128		print '<td colspan="2">';
1129		print $soc->getNomUrl(1);
1130		print '<input type="hidden" name="socid" value="'.$soc->id.'">';
1131		print '</td>';
1132	} else {
1133		print '<td colspan="2">';
1134		print img_picto('', 'company').$form->select_company('', 'socid', 's.fournisseur=1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300');
1135		print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&client=0&fournisseur=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
1136		print '</td>';
1137	}
1138	print '</tr>'."\n";
1139
1140	if ($soc->id > 0) {
1141		// Discounts for third party
1142		print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
1143
1144		$absolute_discount = $soc->getAvailableDiscounts('', '', 0, 1);
1145
1146		$thirdparty = $soc;
1147		$discount_type = 1;
1148		$backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$thirdparty->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid'));
1149		include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
1150
1151		print '</td></tr>';
1152	}
1153
1154	// Terms of payment
1155	print '<tr><td class="nowrap">'.$langs->trans('PaymentConditionsShort').'</td><td colspan="2">';
1156	$form->select_conditions_paiements(GETPOST('cond_reglement_id') > 0 ? GETPOST('cond_reglement_id') : $cond_reglement_id, 'cond_reglement_id', -1, 1);
1157	print '</td></tr>';
1158
1159	// Mode of payment
1160	print '<tr><td>'.$langs->trans('PaymentMode').'</td><td colspan="2">';
1161	$form->select_types_paiements(GETPOST('mode_reglement_id') > 0 ? GETPOST('mode_reglement_id') : $mode_reglement_id, 'mode_reglement_id');
1162	print '</td></tr>';
1163
1164	// Bank Account
1165	if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && !empty($conf->banque->enabled)) {
1166		print '<tr><td>'.$langs->trans('BankAccount').'</td><td colspan="2">';
1167		$form->select_comptes(GETPOST('fk_account') > 0 ? GETPOST('fk_account', 'int') : $fk_account, 'fk_account', 0, '', 1);
1168		print '</td></tr>';
1169	}
1170
1171	// Shipping Method
1172	if (!empty($conf->expedition->enabled)) {
1173		print '<tr><td>'.$langs->trans('SendingMethod').'</td><td colspan="2">';
1174		print $form->selectShippingMethod(GETPOST('shipping_method_id') > 0 ? GETPOST('shipping_method_id', 'int') : $shipping_method_id, 'shipping_method_id', '', 1);
1175		print '</td></tr>';
1176	}
1177
1178	// Delivery date (or manufacturing)
1179	print '<tr><td>'.$langs->trans("DeliveryDate").'</td>';
1180	print '<td colspan="2">';
1181	$datedelivery = dol_mktime(0, 0, 0, GETPOST('liv_month'), GETPOST('liv_day'), GETPOST('liv_year'));
1182	if ($conf->global->DATE_LIVRAISON_WEEK_DELAY != "") {
1183		$tmpdte = time() + ((7 * $conf->global->DATE_LIVRAISON_WEEK_DELAY) * 24 * 60 * 60);
1184		$syear = date("Y", $tmpdte);
1185		$smonth = date("m", $tmpdte);
1186		$sday = date("d", $tmpdte);
1187		print $form->selectDate($syear."-".$smonth."-".$sday, 'liv_', '', '', '', "addask");
1188	} else {
1189		print $form->selectDate($datedelivery ? $datedelivery : -1, 'liv_', '', '', '', "addask", 1, 1);
1190	}
1191	print '</td></tr>';
1192
1193
1194	// Model
1195	print '<tr>';
1196	print '<td>'.$langs->trans("DefaultModel").'</td>';
1197	print '<td colspan="2">';
1198	$list = ModelePDFSupplierProposal::liste_modeles($db);
1199	$preselected = ($conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_DEFAULT ? $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF_ODT_DEFAULT : $conf->global->SUPPLIER_PROPOSAL_ADDON_PDF);
1200	print $form->selectarray('model', $list, $preselected, 0, 0, 0, '', 0, 0, 0, '', '', 1);
1201	print "</td></tr>";
1202
1203	// Project
1204	if (!empty($conf->projet->enabled)) {
1205		$langs->load("projects");
1206
1207		$formproject = new FormProjets($db);
1208
1209		if ($origin == 'project') {
1210			$projectid = ($originid ? $originid : 0);
1211		}
1212
1213		print '<tr>';
1214		print '<td>'.$langs->trans("Project").'</td><td colspan="2">';
1215		print img_picto('', 'project').$formproject->select_projects(($soc->id > 0 ? $soc->id : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500');
1216		print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$soc->id.'&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id).'"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans("AddProject").'"></span></a>';
1217
1218		print '</td>';
1219		print '</tr>';
1220	}
1221
1222	// Multicurrency
1223	if (!empty($conf->multicurrency->enabled)) {
1224		print '<tr>';
1225		print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
1226		print '<td colspan="3" class="maxwidthonsmartphone">';
1227		print $form->selectMultiCurrency($currency_code, 'multicurrency_code');
1228		print '</td></tr>';
1229	}
1230
1231	// Other attributes
1232	$parameters = array('colspan' => ' colspan="3"', 'cols' => 3);
1233	$reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1234	print $hookmanager->resPrint;
1235	if (empty($reshook)) {
1236		print $object->showOptionals($extrafields, 'create', $parameters);
1237	}
1238
1239
1240	// Lines from source
1241	if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
1242		// TODO for compatibility
1243		if ($origin == 'contrat') {
1244			// Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
1245			$objectsrc->remise_absolue = $remise_absolue;
1246			$objectsrc->remise_percent = $remise_percent;
1247			$objectsrc->update_price(1, - 1, 1);
1248		}
1249
1250		print "\n<!-- ".$classname." info -->";
1251		print "\n";
1252		print '<input type="hidden" name="amount"   value="'.$objectsrc->total_ht.'">'."\n";
1253		print '<input type="hidden" name="total"    value="'.$objectsrc->total_ttc.'">'."\n";
1254		print '<input type="hidden" name="tva"      value="'.$objectsrc->total_tva.'">'."\n";
1255		print '<input type="hidden" name="origin"   value="'.$objectsrc->element.'">';
1256		print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
1257
1258		print '<tr><td>'.$langs->trans('CommRequest').'</td><td colspan="2">'.$objectsrc->getNomUrl(1).'</td></tr>';
1259		print '<tr><td>'.$langs->trans('AmountHT').'</td><td colspan="2">'.price($objectsrc->total_ht).'</td></tr>';
1260		print '<tr><td>'.$langs->trans('AmountVAT').'</td><td colspan="2">'.price($objectsrc->total_tva)."</td></tr>";
1261		if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { 		// Localtax1
1262			print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax1)."</td></tr>";
1263		}
1264
1265		if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { 		// Localtax2
1266			print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax2)."</td></tr>";
1267		}
1268		print '<tr><td>'.$langs->trans('AmountTTC').'</td><td colspan="2">'.price($objectsrc->total_ttc)."</td></tr>";
1269
1270		if (!empty($conf->multicurrency->enabled)) {
1271			print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_ht).'</td></tr>';
1272			print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_tva)."</td></tr>";
1273			print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_ttc)."</td></tr>";
1274		}
1275	}
1276
1277	print "</table>\n";
1278
1279
1280	/*
1281	 * Combobox pour la fonction de copie
1282	  */
1283
1284	if (empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) {
1285		print '<input type="hidden" name="createmode" value="empty">';
1286	}
1287
1288	if (!empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) {
1289		print '<br><table>';
1290
1291		// For backward compatibility
1292		print '<tr>';
1293		print '<td><input type="radio" name="createmode" value="copy"></td>';
1294		print '<td>'.$langs->trans("CopyAskFrom").' </td>';
1295		print '<td>';
1296		$liste_ask = array();
1297		$liste_ask [0] = '';
1298
1299		$sql = "SELECT p.rowid as id, p.ref, s.nom";
1300		$sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal p";
1301		$sql .= ", ".MAIN_DB_PREFIX."societe s";
1302		$sql .= " WHERE s.rowid = p.fk_soc";
1303		$sql .= " AND p.entity = ".$conf->entity;
1304		$sql .= " AND p.fk_statut <> ".SupplierProposal::STATUS_DRAFT;
1305		$sql .= " ORDER BY Id";
1306
1307		$resql = $db->query($sql);
1308		if ($resql) {
1309			$num = $db->num_rows($resql);
1310			$i = 0;
1311			while ($i < $num) {
1312				$row = $db->fetch_row($resql);
1313				$askPriceSupplierRefAndSocName = $row [1]." - ".$row [2];
1314				$liste_ask [$row [0]] = $askPriceSupplierRefAndSocName;
1315				$i++;
1316			}
1317			print $form->selectarray("copie_supplier_proposal", $liste_ask, 0);
1318		} else {
1319			dol_print_error($db);
1320		}
1321		print '</td></tr>';
1322
1323		print '<tr><td class="tdtop"><input type="radio" name="createmode" value="empty" checked></td>';
1324		print '<td valign="top" colspan="2">'.$langs->trans("CreateEmptyAsk").'</td></tr>';
1325	}
1326
1327	if (!empty($conf->global->SUPPLIER_PROPOSAL_CLONE_ON_CREATE_PAGE)) {
1328		print '</table>';
1329	}
1330
1331	print dol_get_fiche_end();
1332
1333	print '<div class="center">';
1334	print '<input type="submit" class="button" value="'.$langs->trans("CreateDraft").'">';
1335	print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1336	print '<input type="button" class="button button-cancel" value="'.$langs->trans("Cancel").'" onClick="javascript:history.go(-1)">';
1337	print '</div>';
1338
1339	print "</form>";
1340
1341
1342	// Show origin lines
1343	if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
1344		print '<br>';
1345
1346		$title = $langs->trans('ProductsAndServices');
1347		print load_fiche_titre($title);
1348
1349		print '<table class="noborder centpercent">';
1350
1351		$objectsrc->printOriginLinesList();
1352
1353		print '</table>';
1354	}
1355} else {
1356	/*
1357	 * Show object in view mode
1358	 */
1359
1360	$soc = new Societe($db);
1361	$soc->fetch($object->socid);
1362
1363	$head = supplier_proposal_prepare_head($object);
1364	print dol_get_fiche_head($head, 'comm', $langs->trans('CommRequest'), -1, 'supplier_proposal');
1365
1366	$formconfirm = '';
1367
1368	// Clone confirmation
1369	if ($action == 'clone') {
1370		// Create an array for form
1371		$formquestion = array(
1372			// 'text' => $langs->trans("ConfirmClone"),
1373			// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
1374			// array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' =>
1375			// 1),
1376			array(
1377				'type' => 'other',
1378				'name' => 'socid',
1379				'label' => $langs->trans("SelectThirdParty"),
1380				'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', 's.fournisseur=1'))
1381			);
1382		// Paiement incomplet. On demande si motif = escompte ou autre
1383		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneAsk', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
1384	} elseif ($action == 'delete') {
1385		// Confirm delete
1386		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteAsk'), $langs->trans('ConfirmDeleteAsk', $object->ref), 'confirm_delete', '', 0, 1);
1387	} elseif ($action == 'reopen') {
1388		// Confirm reopen
1389		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ReOpen'), $langs->trans('ConfirmReOpenAsk', $object->ref), 'confirm_reopen', '', 0, 1);
1390	} elseif ($action == 'ask_deleteline') {
1391		// Confirmation delete product/service line
1392		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1);
1393	} elseif ($action == 'validate') {
1394		// Confirm validate askprice
1395		$error = 0;
1396
1397		// on verifie si l'objet est en numerotation provisoire
1398		$ref = substr($object->ref, 1, 4);
1399		if ($ref == 'PROV') {
1400			$numref = $object->getNextNumRef($soc);
1401			if (empty($numref)) {
1402				$error++;
1403				setEventMessages($object->error, $object->errors, 'errors');
1404			}
1405		} else {
1406			$numref = $object->ref;
1407		}
1408
1409		$text = $langs->trans('ConfirmValidateAsk', $numref);
1410		if (!empty($conf->notification->enabled)) {
1411			require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
1412			$notify = new Notify($db);
1413			$text .= '<br>';
1414			$text .= $notify->confirmMessage('PROPOSAL_SUPPLIER_VALIDATE', $object->socid, $object);
1415		}
1416
1417		if (!$error) {
1418			$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateAsk'), $text, 'confirm_validate', '', 0, 1);
1419		}
1420	}
1421
1422	// Call Hook formConfirm
1423	$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
1424	$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1425	if (empty($reshook)) {
1426		$formconfirm .= $hookmanager->resPrint;
1427	} elseif ($reshook > 0) {
1428		$formconfirm = $hookmanager->resPrint;
1429	}
1430
1431	// Print form confirm
1432	print $formconfirm;
1433
1434
1435	// Supplier proposal card
1436	$linkback = '<a href="'.DOL_URL_ROOT.'/supplier_proposal/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
1437
1438
1439	$morehtmlref = '<div class="refidno">';
1440	// Ref supplier
1441	//$morehtmlref.=$form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreateorder, 'string', '', 0, 1);
1442	//$morehtmlref.=$form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreateorder, 'string', '', null, null, '', 1);
1443	// Thirdparty
1444	$morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
1445	if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
1446		$morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/supplier_proposal/list.php?socid='.$object->thirdparty->id.'&search_societe='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherProposals").'</a>)';
1447	}
1448	// Project
1449	if (!empty($conf->projet->enabled)) {
1450		$langs->load("projects");
1451		$morehtmlref .= '<br>'.$langs->trans('Project').' ';
1452		if ($usercancreate) {
1453			if ($action != 'classify') {
1454				$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
1455			}
1456			if ($action == 'classify') {
1457				//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
1458				$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
1459				$morehtmlref .= '<input type="hidden" name="action" value="classin">';
1460				$morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
1461				$morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
1462				$morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
1463				$morehtmlref .= '</form>';
1464			} else {
1465				$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
1466			}
1467		} else {
1468			if (!empty($object->fk_project)) {
1469				$proj = new Project($db);
1470				$proj->fetch($object->fk_project);
1471				$morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
1472				$morehtmlref .= $proj->ref;
1473				$morehtmlref .= '</a>';
1474			} else {
1475				$morehtmlref .= '';
1476			}
1477		}
1478	}
1479	$morehtmlref .= '</div>';
1480
1481
1482	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
1483
1484
1485	print '<div class="fichecenter">';
1486	print '<div class="fichehalfleft">';
1487	print '<div class="underbanner clearboth"></div>';
1488
1489	print '<table class="border tableforfield" width="100%">';
1490
1491	// Relative and absolute discounts
1492	if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
1493		$filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
1494		$filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
1495	} else {
1496		$filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')";
1497		$filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')";
1498	}
1499
1500	print '<tr><td class="titlefield">'.$langs->trans('Discounts').'</td><td>';
1501
1502	$absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount, 0, 1);
1503	$absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote, 0, 1);
1504	$absolute_discount = price2num($absolute_discount, 'MT');
1505	$absolute_creditnote = price2num($absolute_creditnote, 'MT');
1506
1507	$thirdparty = $soc;
1508	$discount_type = 1;
1509	$backtopage = urlencode($_SERVER["PHP_SELF"].'?id='.$object->id);
1510	include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
1511
1512	print '</td></tr>';
1513
1514	// Payment term
1515	print '<tr><td class="titlefield">';
1516	print '<table class="nobordernopadding" width="100%"><tr><td>';
1517	print $langs->trans('PaymentConditionsShort');
1518	print '</td>';
1519	if ($action != 'editconditions' && $object->statut != SupplierProposal::STATUS_NOTSIGNED) {
1520		print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetConditions'), 1).'</a></td>';
1521	}
1522	print '</tr></table>';
1523	print '</td><td class="valuefield">';
1524	if ($action == 'editconditions') {
1525		$form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id', 1);
1526	} else {
1527		$form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none', 1);
1528	}
1529	print '</td>';
1530	print '</tr>';
1531
1532	// Delivery date
1533	$langs->load('deliveries');
1534	print '<tr><td>';
1535	print '<table class="nobordernopadding" width="100%"><tr><td>';
1536	print $langs->trans('DeliveryDate');
1537	print '</td>';
1538	if ($action != 'editdate_livraison' && $object->statut == SupplierProposal::STATUS_VALIDATED) {
1539		print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_livraison&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetDeliveryDate'), 1).'</a></td>';
1540	}
1541	print '</tr></table>';
1542	print '</td><td class="valuefield">';
1543	if ($action == 'editdate_livraison') {
1544		print '<form name="editdate_livraison" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post" class="formconsumeproduce">';
1545		print '<input type="hidden" name="token" value="'.newToken().'">';
1546		print '<input type="hidden" name="action" value="setdate_livraison">';
1547		print $form->selectDate($object->delivery_date, 'liv_', '', '', '', "editdate_livraison");
1548		print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">';
1549		print '</form>';
1550	} else {
1551		print dol_print_date($object->delivery_date, 'daytext');
1552	}
1553	print '</td>';
1554	print '</tr>';
1555
1556	// Payment mode
1557	print '<tr>';
1558	print '<td>';
1559	print '<table class="nobordernopadding" width="100%"><tr><td>';
1560	print $langs->trans('PaymentMode');
1561	print '</td>';
1562	if ($action != 'editmode' && $object->statut != SupplierProposal::STATUS_NOTSIGNED) {
1563		print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMode'), 1).'</a></td>';
1564	}
1565	print '</tr></table>';
1566	print '</td><td class="valuefield">';
1567	if ($action == 'editmode') {
1568		$form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'DBIT', 1, 1);
1569	} else {
1570		$form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none');
1571	}
1572	print '</td></tr>';
1573
1574	// Multicurrency
1575	if (!empty($conf->multicurrency->enabled)) {
1576		// Multicurrency code
1577		print '<tr>';
1578		print '<td>';
1579		print '<table class="nobordernopadding" width="100%"><tr><td>';
1580		print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0);
1581		print '</td>';
1582		if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_VALIDATED) {
1583			print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencycode&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>';
1584		}
1585		print '</tr></table>';
1586		print '</td><td class="valuefield">';
1587		if ($action == 'editmulticurrencycode') {
1588			$form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code');
1589		} else {
1590			$form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'none');
1591		}
1592		print '</td></tr>';
1593
1594		// Multicurrency rate
1595		if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
1596			print '<tr>';
1597			print '<td>';
1598			print '<table class="nobordernopadding" width="100%"><tr><td>';
1599			print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0);
1600			print '</td>';
1601			if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_VALIDATED && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
1602				print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencyrate&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>';
1603			}
1604			print '</tr></table>';
1605			print '</td><td class="valuefield">';
1606			if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
1607				if ($action == 'actualizemulticurrencyrate') {
1608					list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
1609				}
1610				$form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
1611			} else {
1612				$form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
1613				if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
1614					print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
1615					print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
1616					print '</div>';
1617				}
1618			}
1619			print '</td></tr>';
1620		}
1621	}
1622
1623	/* Not for supplier proposals
1624	if ($soc->outstanding_limit)
1625	{
1626		// Outstanding Bill
1627		print '<tr><td>';
1628		print $langs->trans('OutstandingBill');
1629		print '</td><td class="valuefield">';
1630		$arrayoutstandingbills = $soc->getOutstandingBills('supplier');
1631		$outstandingBills = $arrayoutstandingbills['opened'];
1632		print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency);
1633		print '</td>';
1634		print '</tr>';
1635	}*/
1636
1637	if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && !empty($conf->banque->enabled)) {
1638		// Bank Account
1639		print '<tr><td>';
1640		print '<table width="100%" class="nobordernopadding"><tr><td>';
1641		print $langs->trans('BankAccount');
1642		print '</td>';
1643		if ($action != 'editbankaccount' && $usercancreate) {
1644			print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'</a></td>';
1645		}
1646		print '</tr></table>';
1647		print '</td><td class="valuefield">';
1648		if ($action == 'editbankaccount') {
1649			$form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
1650		} else {
1651			$form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
1652		}
1653		print '</td>';
1654		print '</tr>';
1655	}
1656
1657	// Other attributes
1658	include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
1659
1660	print '</table>';
1661
1662	print '</div>';
1663	print '<div class="fichehalfright">';
1664	print '<div class="ficheaddleft">';
1665	print '<div class="underbanner clearboth"></div>';
1666
1667	print '<table class="border tableforfield centpercent">';
1668
1669	if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) {
1670		// Multicurrency Amount HT
1671		print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>';
1672		print '<td class="valuefield">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
1673		print '</tr>';
1674
1675		// Multicurrency Amount VAT
1676		print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).'</td>';
1677		print '<td class="valuefield">'.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
1678		print '</tr>';
1679
1680		// Multicurrency Amount TTC
1681		print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).'</td>';
1682		print '<td class="valuefield">'.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
1683		print '</tr>';
1684	}
1685
1686	// Amount HT
1687	print '<tr><td class="titlefieldmiddle">'.$langs->trans('AmountHT').'</td>';
1688	print '<td class="valuefield">'.price($object->total_ht, '', $langs, 0, - 1, - 1, $conf->currency).'</td>';
1689	print '</tr>';
1690
1691	// Amount VAT
1692	print '<tr><td>'.$langs->trans('AmountVAT').'</td>';
1693	print '<td class="valuefield">'.price($object->total_tva, '', $langs, 0, - 1, - 1, $conf->currency).'</td>';
1694	print '</tr>';
1695
1696	// Amount Local Taxes
1697	if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { 	// Localtax1
1698		print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>';
1699		print '<td class="valuefield nowrap">'.price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency).'</td>';
1700		print '</tr>';
1701	}
1702	if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { 	// Localtax2
1703		print '<tr><td height="10">'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>';
1704		print '<td class="valuefield nowrap">'.price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency).'</td>';
1705		print '</tr>';
1706	}
1707
1708	// Amount TTC
1709	print '<tr><td height="10">'.$langs->trans('AmountTTC').'</td>';
1710	print '<td class="valuefield nowrap">'.price($object->total_ttc, '', $langs, 0, - 1, - 1, $conf->currency).'</td>';
1711	print '</tr>';
1712
1713	print '</table>';
1714
1715	// Margin Infos
1716	/*if (! empty($conf->margin->enabled)) {
1717	   $formmargin->displayMarginInfos($object);
1718	}*/
1719
1720	print '</div>';
1721	print '</div>';
1722	print '</div>';
1723
1724	print '<div class="clearboth"></div><br>';
1725
1726	if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
1727		$blocname = 'contacts';
1728		$title = $langs->trans('ContactsAddresses');
1729		include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1730	}
1731
1732	if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
1733		$blocname = 'notes';
1734		$title = $langs->trans('Notes');
1735		include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
1736	}
1737
1738	/*
1739	 * Lines
1740	 */
1741
1742	// Show object lines
1743	$result = $object->getLinesArray();
1744
1745	print '	<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#add' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">
1746	<input type="hidden" name="token" value="' . newToken().'">
1747	<input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">
1748	<input type="hidden" name="mode" value="">
1749	<input type="hidden" name="id" value="' . $object->id.'">
1750	';
1751
1752	if (!empty($conf->use_javascript_ajax) && $object->statut == SupplierProposal::STATUS_DRAFT) {
1753		include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
1754	}
1755
1756	print '<div class="div-table-responsive-no-min">';
1757	print '<table id="tablelines" class="noborder noshadow" width="100%">';
1758
1759	// Add free products/services form
1760	global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax;
1761	$forceall = 1; $dateSelector = 0; $inputalsopricewithtax = 1;
1762	$senderissupplier = 2; // $senderissupplier=2 is same than 1 but disable test on minimum qty.
1763	if (!empty($conf->global->SUPPLIER_PROPOSAL_WITH_PREDEFINED_PRICES_ONLY)) {
1764		$senderissupplier = 1;
1765	}
1766
1767	if (!empty($object->lines)) {
1768		$ret = $object->printObjectLines($action, $soc, $mysoc, $lineid, $dateSelector);
1769	}
1770
1771	// Form to add new line
1772	if ($object->statut == SupplierProposal::STATUS_DRAFT && $usercancreate) {
1773		if ($action != 'editline') {
1774			// Add products/services form
1775
1776			$parameters = array();
1777			$reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1778			if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1779			if (empty($reshook))
1780				$object->formAddObjectLine($dateSelector, $soc, $mysoc);
1781		}
1782	}
1783
1784	print '</table>';
1785	print '</div>';
1786	print "</form>\n";
1787
1788	print dol_get_fiche_end();
1789
1790	if ($action == 'statut') {
1791		// Form to set proposal accepted/refused
1792		$form_close = '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST" id="formacceptrefuse" class="formconsumeproduce paddingbottom paddingleft paddingright">';
1793		$form_close .= '<input type="hidden" name="token" value="'.newToken().'">';
1794		$form_close .= '<input type="hidden" name="action" value="setstatut">';
1795
1796		if (!empty($conf->global->SUPPLIER_PROPOSAL_UPDATE_PRICE_ON_SUPPlIER_PROPOSAL)) {
1797			$form_close .= '<p class="notice">'.$langs->trans('SupplierProposalRefFournNotice').'</p>'; // TODO Suggest a permanent checkbox instead of option
1798		}
1799		$form_close .= '<table class="border centpercent marginleftonly marginrightonly">';
1800		$form_close .= '<tr><td>'.$langs->trans("CloseAs").'</td><td class="left">';
1801		$form_close .= '<select id="statut" name="statut" class="flat">';
1802		$form_close .= '<option value="0">&nbsp;</option>';
1803		$form_close .= '<option value="2">'.$langs->trans('SupplierProposalStatusSigned').'</option>';
1804		$form_close .= '<option value="3">'.$langs->trans('SupplierProposalStatusNotSigned').'</option>';
1805		$form_close .= '</select>';
1806		$form_close .= '</td></tr>';
1807		$form_close .= '<tr><td class="left">'.$langs->trans('Note').'</td><td class="left"><textarea cols="70" rows="'.ROWS_3.'" wrap="soft" name="note">';
1808		$form_close .= $object->note_private;
1809		$form_close .= '</textarea></td></tr>';
1810		$form_close .= '</table>';
1811		$form_close .= '<center>';
1812		$form_close .= '<input type="submit" class="button button-save" name="validate" value="'.$langs->trans("Save").'">';
1813		$form_close .= ' &nbsp; <input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
1814		$form_close .= '<a name="acceptedrefused">&nbsp;</a>';
1815		$form_close .= '</center>';
1816		$form_close .= '</form>';
1817
1818		print $form_close;
1819	}
1820
1821	/*
1822	 * Boutons Actions
1823	 */
1824	if ($action != 'presend') {
1825		print '<div class="tabsAction">';
1826
1827		$parameters = array();
1828		$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
1829																									   // modified by hook
1830		if (empty($reshook)) {
1831			if ($action != 'statut' && $action != 'editline') {
1832				// Validate
1833				if ($object->statut == SupplierProposal::STATUS_DRAFT && $object->total_ttc >= 0 && count($object->lines) > 0 && $usercanvalidate) {
1834					if (count($object->lines) > 0) {
1835						print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=validate">'.$langs->trans('Validate').'</a></div>';
1836					}
1837					// else print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans('Validate').'</a>';
1838				}
1839
1840				// Edit
1841				if ($object->statut == SupplierProposal::STATUS_VALIDATED && $usercancreate) {
1842					print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=modif">'.$langs->trans('Modify').'</a></div>';
1843				}
1844
1845				// ReOpen
1846				if (($object->statut == SupplierProposal::STATUS_SIGNED || $object->statut == SupplierProposal::STATUS_NOTSIGNED || $object->statut == SupplierProposal::STATUS_CLOSE) && $usercanclose) {
1847					print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen'.(empty($conf->global->MAIN_JUMP_TAG) ? '' : '#reopen').'"';
1848					print '>'.$langs->trans('ReOpen').'</a></div>';
1849				}
1850
1851				// Send
1852				if (empty($user->socid)) {
1853					if ($object->statut == SupplierProposal::STATUS_VALIDATED || $object->statut == SupplierProposal::STATUS_SIGNED) {
1854						if ($usercansend) {
1855							print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>';
1856						} else {
1857							print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('SendMail').'</a></div>';
1858						}
1859					}
1860				}
1861
1862				// Create an order
1863				if (((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled)) && $object->statut == SupplierProposal::STATUS_SIGNED) {
1864					if ($usercancreateorder) {
1865						print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/fourn/commande/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("AddSupplierOrderShort").'</a></div>';
1866					}
1867				}
1868
1869				// Set accepted/refused
1870				if ($object->statut == SupplierProposal::STATUS_VALIDATED && $usercanclose) {
1871					print '<div class="inline-block divButAction"><a class="butAction reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=statut'.(empty($conf->global->MAIN_JUMP_TAG) ? '' : '#acceptedrefused').'"';
1872					print '>'.$langs->trans('SetAcceptedRefused').'</a></div>';
1873				}
1874
1875				// Close
1876				if ($object->statut == SupplierProposal::STATUS_SIGNED && $usercanclose) {
1877					print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=close'.(empty($conf->global->MAIN_JUMP_TAG) ? '' : '#close').'"';
1878					print '>'.$langs->trans('Close').'</a></div>';
1879				}
1880
1881				// Clone
1882				if ($usercancreate) {
1883					print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$object->socid.'&amp;action=clone&amp;object='.$object->element.'">'.$langs->trans("ToClone").'</a></div>';
1884				}
1885
1886				// Delete
1887				if (($object->statut == SupplierProposal::STATUS_DRAFT && $usercancreate) || $usercandelete) {
1888					print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'"';
1889					print '>'.$langs->trans('Delete').'</a></div>';
1890				}
1891			}
1892		}
1893
1894		print '</div>';
1895	}
1896
1897	if ($action != 'presend') {
1898		print '<div class="fichecenter"><div class="fichehalfleft">';
1899
1900		/*
1901		 * Generated documents
1902		 */
1903		$filename = dol_sanitizeFileName($object->ref);
1904		$filedir = $conf->supplier_proposal->dir_output."/".dol_sanitizeFileName($object->ref);
1905		$urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
1906		$genallowed = $usercanread;
1907		$delallowed = $usercancreate;
1908
1909		print $formfile->showdocuments('supplier_proposal', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang);
1910
1911
1912		// Show links to link elements
1913		$linktoelem = $form->showLinkToObjectBlock($object, null, array('supplier_proposal'));
1914		$somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
1915
1916
1917		print '</div><div class="fichehalfright"><div class="ficheaddleft">';
1918
1919		// List of actions on element
1920		include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
1921		$formactions = new FormActions($db);
1922		$somethingshown = $formactions->showactions($object, 'supplier_proposal', $socid, 1);
1923
1924		print '</div></div></div>';
1925	}
1926
1927	// Select mail models is same action as presend
1928	if (GETPOST('modelselected')) {
1929		$action = 'presend';
1930	}
1931
1932	// Presend form
1933	$modelmail = 'supplier_proposal_send';
1934	$defaulttopic = 'SendAskRef';
1935	$diroutput = $conf->supplier_proposal->dir_output;
1936	$autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO';
1937	$trackid = 'spro'.$object->id;
1938
1939	include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
1940}
1941
1942// End of page
1943llxFooter();
1944$db->close();
1945