1<?php
2/* Copyright (C) 2003-2006	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
3 * Copyright (C) 2005-2012	Laurent Destailleur		<eldy@users.sourceforge.net>
4 * Copyright (C) 2005-2012	Regis Houssin			<regis.houssin@inodbox.com>
5 * Copyright (C) 2012-2015	Juanjo Menent			<jmenent@2byte.es>
6 * Copyright (C) 2018       Frédéric France         <frederic.france@netlogic.fr>
7 * Copyright (C) 2018       Philippe Grand          <philippe.grand@atoo-net.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23/**
24 *	\file       htdocs/expedition/shipment.php
25 *	\ingroup    expedition
26 *  \brief      Tab shipments/delivery receipts on the order
27 */
28
29require '../main.inc.php';
30require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
31require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
32require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
33require_once DOL_DOCUMENT_ROOT.'/core/lib/order.lib.php';
34require_once DOL_DOCUMENT_ROOT.'/core/lib/sendings.lib.php';
35require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
36if (!empty($conf->projet->enabled)) {
37	require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
38	require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
39}
40if (!empty($conf->stock->enabled)) {
41	require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
42}
43if (!empty($conf->propal->enabled)) {
44	require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
45}
46if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) {
47	require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
48}
49
50// Load translation files required by the page
51$langs->loadLangs(array('orders', 'sendings', 'companies', 'bills', 'propal', 'deliveries', 'stocks', 'productbatch', 'incoterm', 'other'));
52
53$id     = GETPOST('id', 'int'); // id of order
54$ref    = GETPOST('ref', 'alpha');
55$action = GETPOST('action', 'aZ09');
56
57$hookmanager->initHooks(array('ordershipmentcard'));
58
59
60// Security check
61$socid = 0;
62if (!empty($user->socid)) {
63	$socid = $user->socid;
64}
65$result = restrictedArea($user, 'commande', $id);
66
67$object = new Commande($db);
68$shipment = new Expedition($db);
69$extrafields = new ExtraFields($db);
70
71// fetch optionals attributes and labels
72$extrafields->fetch_name_optionals_label($object->table_element);
73
74// Load object
75include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once
76
77// Security check
78if ($user->socid) {
79	$socid = $user->socid;
80}
81
82$result = restrictedArea($user, 'expedition', 0, '');	// We use 0 for id, because there is no particular shipment on this tab, only id of order is known
83
84
85
86/*
87 * Actions
88 */
89
90$parameters = array('socid' => $socid);
91$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
92if ($reshook < 0) {
93	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
94}
95
96if (empty($reshook)) {
97	// Categorisation dans projet
98	if ($action == 'classin') {
99		$object->fetch($id);
100		$object->setProject(GETPOST('projectid', 'int'));
101	}
102
103	if ($action == 'confirm_cloture' && GETPOST('confirm', 'alpha') == 'yes') {
104		$object->fetch($id);
105		$result = $object->cloture($user);
106	} elseif ($action == 'setref_client' && $user->rights->commande->creer) {
107		// Positionne ref commande client
108		$result = $object->set_ref_client($user, GETPOST('ref_client'));
109		if ($result < 0) {
110			setEventMessages($object->error, $object->errors, 'errors');
111		}
112	}
113
114	if ($action == 'setdatedelivery' && $user->rights->commande->creer) {
115		//print "x ".$_POST['liv_month'].", ".$_POST['liv_day'].", ".$_POST['liv_year'];
116		$datedelivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int'));
117
118		$object->fetch($id);
119		$result = $object->setDeliveryDate($user, $datedelivery);
120		if ($result < 0) {
121			setEventMessages($object->error, $object->errors, 'errors');
122		}
123	}
124	/*
125	if ($action == 'setdeliveryaddress' && $user->rights->commande->creer)
126	{
127		$object = new Commande($db);
128		$object->fetch($id);
129		$object->setDeliveryAddress(GETPOST('delivery_address_id','int'));
130		if ($result < 0)
131			setEventMessages($object->error, $object->errors, 'errors');
132	}
133	*/
134	if ($action == 'setmode' && $user->rights->commande->creer) {
135		$object->fetch($id);
136		$result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
137		if ($result < 0) {
138			setEventMessages($object->error, $object->errors, 'errors');
139		}
140	}
141
142	if ($action == 'setavailability' && $user->rights->commande->creer) {
143		$object->fetch($id);
144		$result = $object->availability(GETPOST('availability_id'));
145		if ($result < 0) {
146			setEventMessages($object->error, $object->errors, 'errors');
147		}
148	}
149
150	if ($action == 'setdemandreason' && $user->rights->commande->creer) {
151		$object->fetch($id);
152		$result = $object->demand_reason(GETPOST('demand_reason_id'));
153		if ($result < 0) {
154			setEventMessages($object->error, $object->errors, 'errors');
155		}
156	}
157
158	if ($action == 'setconditions' && $user->rights->commande->creer) {
159		$object->fetch($id);
160		$result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
161		if ($result < 0) {
162			setEventMessages($object->error, $object->errors, 'errors');
163		}
164	} elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) {
165		// Set incoterm
166		$result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
167		if ($result < 0) {
168			setEventMessages($object->error, $object->errors, 'errors');
169		}
170	}
171
172	// shipping method
173	if ($action == 'setshippingmethod' && $user->rights->commande->creer) {
174		$object->fetch($id);
175		$result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int'));
176		if ($result < 0) {
177			setEventMessages($object->error, $object->errors, 'errors');
178		}
179	}
180
181	// warehouse
182	if ($action == 'setwarehouse' && $user->rights->commande->creer) {
183		$object->fetch($id);
184		$result = $object->setWarehouse(GETPOST('warehouse_id', 'int'));
185		if ($result < 0) {
186			setEventMessages($object->error, $object->errors, 'errors');
187		}
188	}
189
190	if ($action == 'update_extras') {
191		$object->oldcopy = dol_clone($object);
192
193		// Fill array 'array_options' with data from update form
194		$ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
195		if ($ret < 0) {
196			$error++;
197		}
198
199		if (!$error) {
200			// Actions on extra fields
201			$result = $object->insertExtraFields('SHIPMENT_MODIFY');
202			if ($result < 0) {
203				setEventMessages($object->error, $object->errors, 'errors');
204				$error++;
205			}
206		}
207
208		if ($error) {
209			$action = 'edit_extras';
210		}
211	}
212
213	if ($action == 'set_thirdparty' && $user->rights->commande->creer) {
214		$object->fetch($id);
215		$object->setValueFrom('fk_soc', $socid, '', '', 'date', '', $user, 'ORDER_MODIFY');
216
217		header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id);
218		exit();
219	}
220
221	include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
222}
223
224/*
225 * View
226 */
227
228$form = new Form($db);
229$formfile = new FormFile($db);
230$formproduct = new FormProduct($db);
231if (!empty($conf->projet->enabled)) {
232	$formproject = new FormProjets($db);
233}
234
235$title = $langs->trans('Order')." - ".$langs->trans('Shipments');
236$help_url = 'EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes|DE:Modul_Kundenaufträge';
237llxHeader('', $title, $help_url);
238
239
240if ($id > 0 || !empty($ref)) {
241	$object = new Commande($db);
242	if ($object->fetch($id, $ref) > 0) {
243		$object->loadExpeditions(1);
244
245		$product_static = new Product($db);
246
247		$soc = new Societe($db);
248		$soc->fetch($object->socid);
249
250		$author = new User($db);
251		$author->fetch($object->user_author_id);
252
253		$res = $object->fetch_optionals();
254
255		$head = commande_prepare_head($object);
256		print dol_get_fiche_head($head, 'shipping', $langs->trans("CustomerOrder"), -1, 'order');
257
258
259		$formconfirm = '';
260
261		// Confirm validation
262		if ($action == 'cloture') {
263			$formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".urlencode($id), $langs->trans("CloseShipment"), $langs->trans("ConfirmCloseShipment"), "confirm_cloture");
264		}
265
266		// Call Hook formConfirm
267		$parameters = array('formConfirm' => $formconfirm);
268		$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
269		if (empty($reshook)) {
270			$formconfirm .= $hookmanager->resPrint;
271		} elseif ($reshook > 0) {
272			$formconfirm = $hookmanager->resPrint;
273		}
274
275		// Print form confirm
276		print $formconfirm;
277
278
279		// Order card
280
281		$linkback = '<a href="'.DOL_URL_ROOT.'/commande/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '?socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
282
283
284		$morehtmlref = '<div class="refidno">';
285		// Ref customer
286		$morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->commande->creer, 'string', '', 0, 1);
287		$morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $user->rights->commande->creer, 'string', '', null, null, '', 1);
288		// Thirdparty
289		$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$soc->getNomUrl(1);
290		// Project
291		if (!empty($conf->projet->enabled)) {
292			$langs->load("projects");
293			$morehtmlref .= '<br>'.$langs->trans('Project').' ';
294			if ($user->rights->commande->creer) {
295				if ($action != 'classify') {
296					$morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
297				}
298				if ($action == 'classify') {
299					//$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
300					$morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
301					$morehtmlref .= '<input type="hidden" name="action" value="classin">';
302					$morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
303					$morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
304					$morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
305					$morehtmlref .= '</form>';
306				} else {
307					$morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
308				}
309			} else {
310				if (!empty($object->fk_project)) {
311					$proj = new Project($db);
312					$proj->fetch($object->fk_project);
313					$morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
314					$morehtmlref .= $proj->ref;
315					$morehtmlref .= '</a>';
316				} else {
317					$morehtmlref .= '';
318				}
319			}
320		}
321		$morehtmlref .= '</div>';
322
323
324		dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
325
326
327		print '<div class="fichecenter">';
328		print '<div class="fichehalfleft">';
329		print '<div class="underbanner clearboth"></div>';
330
331		print '<table class="border centpercent tableforfield">';
332
333		// Discounts for third party
334		if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
335			$filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
336			$filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
337		} else {
338			$filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
339			$filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
340		}
341
342		print '<tr><td class="titlefield">'.$langs->trans('Discounts').'</td><td colspan="3">';
343
344		$absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount);
345		$absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote);
346		$absolute_discount = price2num($absolute_discount, 'MT');
347		$absolute_creditnote = price2num($absolute_creditnote, 'MT');
348
349		$thirdparty = $soc;
350		$discount_type = 0;
351		$backtopage = urlencode($_SERVER["PHP_SELF"].'?id='.$object->id);
352		$cannotApplyDiscount = 1;
353		include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
354		print '</td></tr>';
355
356		// Date
357		print '<tr><td>'.$langs->trans('Date').'</td>';
358		print '<td colspan="2">';
359		print dol_print_date($object->date, 'day');
360		if ($object->hasDelay() && empty($object->delivery_date)) {
361			print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning");
362		}
363		print '</td>';
364		print '</tr>';
365
366		// Delivery date planned
367		print '<tr><td height="10">';
368		print '<table class="nobordernopadding" width="100%"><tr><td>';
369		print $langs->trans('DateDeliveryPlanned');
370		print '</td>';
371
372		if ($action != 'editdate_livraison') {
373			print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_livraison&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).'</a></td>';
374		}
375		print '</tr></table>';
376		print '</td><td colspan="2">';
377		if ($action == 'editdate_livraison') {
378			print '<form name="setdate_livraison" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
379			print '<input type="hidden" name="token" value="'.newToken().'">';
380			print '<input type="hidden" name="action" value="setdatedelivery">';
381			print $form->selectDate($object->delivery_date ? $object->delivery_date : -1, 'liv_', 1, 1, '', "setdate_livraison", 1, 0);
382			print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">';
383			print '</form>';
384		} else {
385			print dol_print_date($object->delivery_date, 'dayhour');
386			if ($object->hasDelay() && !empty($object->delivery_date)) {
387				print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning");
388			}
389		}
390		print '</td>';
391		// Note on several rows
392		//print '<td rowspan="'.$nbrow.'" valign="top">'.$langs->trans('NotePublic').' :<br>';
393		//print nl2br($object->note_public);
394		//print '</td>';
395		print '</tr>';
396
397		// Shipping Method
398		print '<tr><td>';
399		print '<table width="100%" class="nobordernopadding"><tr><td>';
400		print $langs->trans('SendingMethod');
401		print '</td>';
402		if ($action != 'editshippingmethod' && $user->rights->expedition->creer) {
403			print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editshippingmethod&amp;id='.$object->id.'">'.img_edit($langs->trans('SetShippingMode'), 1).'</a></td>';
404		}
405		print '</tr></table>';
406		print '</td><td colspan="2">';
407		if ($action == 'editshippingmethod') {
408			$form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1);
409		} else {
410			$form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none');
411		}
412		print '</td>';
413		print '</tr>';
414
415		// Warehouse
416		if (!empty($conf->stock->enabled) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) {
417			require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
418			$formproduct = new FormProduct($db);
419			print '<tr><td>';
420			print '<table width="100%" class="nobordernopadding"><tr><td>';
421			print $langs->trans('Warehouse');
422			print '</td>';
423			if ($action != 'editwarehouse' && $user->rights->commande->creer) {
424				print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editwarehouse&amp;id='.$object->id.'">'.img_edit($langs->trans('SetWarehouse'), 1).'</a></td>';
425			}
426			print '</tr></table>';
427			print '</td><td colspan="2">';
428			if ($action == 'editwarehouse') {
429				$formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1);
430			} else {
431				$formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'none');
432			}
433			print '</td>';
434			print '</tr>';
435		}
436
437		// Terms of payment
438		/*
439		print '<tr><td height="10">';
440		print '<table class="nobordernopadding" width="100%"><tr><td>';
441		print $langs->trans('PaymentConditionsShort');
442		print '</td>';
443
444		if ($action != 'editconditions' && $object->statut == Expedition::STATUS_VALIDATED) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;id='.$object->id.'">'.img_edit($langs->trans('SetConditions'),1).'</a></td>';
445		print '</tr></table>';
446		print '</td><td colspan="2">';
447		if ($action == 'editconditions')
448		{
449			$form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->cond_reglement_id,'cond_reglement_id');
450		}
451		else
452		{
453			$form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->cond_reglement_id,'none');
454		}
455		print '</td></tr>';
456
457		// Mode of payment
458		print '<tr><td>';
459		print '<table class="nobordernopadding" width="100%"><tr><td>';
460		print $langs->trans('PaymentMode');
461		print '</td>';
462		if ($action != 'editmode' && $object->statut == Expedition::STATUS_VALIDATED) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->trans('SetMode'),1).'</a></td>';
463		print '</tr></table>';
464		print '</td><td colspan="2">';
465		if ($action == 'editmode')
466		{
467			$form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->mode_reglement_id,'mode_reglement_id');
468		}
469		else
470		{
471			$form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->mode_reglement_id,'none');
472		}
473		print '</td></tr>';*/
474
475		// Availability
476		print '<tr><td height="10">';
477		print '<table class="nobordernopadding" width="100%"><tr><td>';
478		print $langs->trans('AvailabilityPeriod');
479		print '</td>';
480		if ($action != 'editavailability') {
481			print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editavailability&amp;id='.$object->id.'">'.img_edit($langs->trans('SetAvailability'), 1).'</a></td>';
482		}
483		print '</tr></table>';
484		print '</td><td colspan="3">';
485		if ($action == 'editavailability') {
486			$form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'availability_id', 1);
487		} else {
488			$form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'none', 1);
489		}
490		print '</td></tr>';
491
492		// Source
493		print '<tr><td height="10">';
494		print '<table class="nobordernopadding" width="100%"><tr><td>';
495		print $langs->trans('Source');
496		print '</td>';
497		if ($action != 'editdemandreason') {
498			print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdemandreason&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDemandReason'), 1).'</a></td>';
499		}
500		print '</tr></table>';
501		print '</td><td colspan="3">';
502		if ($action == 'editdemandreason') {
503			$form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'demand_reason_id', 1);
504		} else {
505			$form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'none');
506		}
507
508		$tmparray = $object->getTotalWeightVolume();
509		$totalWeight = $tmparray['weight'];
510		$totalVolume = $tmparray['volume'];
511		if ($totalWeight || $totalVolume) {
512			print '<tr><td>'.$langs->trans("CalculatedWeight").'</td>';
513			print '<td>';
514			print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND) ? $conf->global->MAIN_WEIGHT_DEFAULT_ROUND : -1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? $conf->global->MAIN_WEIGHT_DEFAULT_UNIT : 'no');
515			print '</td></tr>';
516			print '<tr><td>'.$langs->trans("CalculatedVolume").'</td>';
517			print '<td>';
518			print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND) ? $conf->global->MAIN_VOLUME_DEFAULT_ROUND : -1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT) ? $conf->global->MAIN_VOLUME_DEFAULT_UNIT : 'no');
519			print '</td></tr>';
520		}
521
522		// TODO How record was recorded OrderMode (llx_c_input_method)
523
524		// Incoterms
525		if (!empty($conf->incoterm->enabled)) {
526			print '<tr><td>';
527			print '<table width="100%" class="nobordernopadding"><tr><td>';
528			print $langs->trans('IncotermLabel');
529			print '<td><td class="right">';
530			if ($user->rights->commande->creer) {
531				print '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'/expedition/shipment.php?id='.$object->id.'&action=editincoterm">'.img_edit().'</a>';
532			} else {
533				print '&nbsp;';
534			}
535			print '</td></tr></table>';
536			print '</td>';
537			print '<td colspan="3">';
538			if ($action != 'editincoterm') {
539				print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
540			} else {
541				print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
542			}
543			print '</td></tr>';
544		}
545
546		$expe = new Expedition($db);
547		$extrafields->fetch_name_optionals_label($expe->table_element);
548
549		// Other attributes
550		$cols = 2;
551		include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
552
553		print '</table>';
554
555		print '</div>';
556		print '<div class="fichehalfright">';
557		print '<div class="ficheaddleft">';
558		print '<div class="underbanner clearboth"></div>';
559
560		print '<table class="border centpercent tableforfield">';
561
562		if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) {
563			// Multicurrency Amount HT
564			print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>';
565			print '<td class="nowrap">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
566			print '</tr>';
567
568			// Multicurrency Amount VAT
569			print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).'</td>';
570			print '<td class="nowrap">'.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
571			print '</tr>';
572
573			// Multicurrency Amount TTC
574			print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).'</td>';
575			print '<td class="nowrap">'.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
576			print '</tr>';
577		}
578
579		// Total HT
580		print '<tr><td class="titlefieldmiddle">'.$langs->trans('AmountHT').'</td>';
581		print '<td>'.price($object->total_ht, 0, '', 1, -1, -1, $conf->currency).'</td>';
582		print '</tr>';
583
584		// Total VAT
585		print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($object->total_tva, 0, '', 1, -1, -1, $conf->currency).'</td>';
586		print '</tr>';
587
588		// Amount Local Taxes
589		if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { 		// Localtax1
590			print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>';
591			print '<td>'.price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
592		}
593		if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { 		// Localtax2 IRPF
594			print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>';
595			print '<td>'.price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
596		}
597
598		// Total TTC
599		print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($object->total_ttc, 0, '', 1, -1, -1, $conf->currency).'</td>';
600		print '</tr>';
601
602		print '</table>';
603
604		print '</div>';
605		print '</div>';
606		print '</div>';
607
608		print '<div class="clearboth"></div><br>';
609
610
611
612		/**
613		 *  Lines or orders with quantity shipped and remain to ship
614		 *  Note: Qty shipped are already available into $object->expeditions[fk_product]
615		 */
616		print '<table class="noborder noshadow" width="100%">';
617
618		$sql = "SELECT cd.rowid, cd.fk_product, cd.product_type as type, cd.label, cd.description,";
619		$sql .= " cd.price, cd.tva_tx, cd.subprice,";
620		$sql .= " cd.qty,";
621		$sql .= ' cd.date_start,';
622		$sql .= ' cd.date_end,';
623		$sql .= ' cd.special_code,';
624		$sql .= ' p.rowid as prodid, p.label as product_label, p.entity, p.ref, p.fk_product_type as product_type, p.description as product_desc,';
625		$sql .= ' p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,';
626		$sql .= ' p.surface, p.surface_units, p.volume, p.volume_units';
627		$sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd";
628		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
629		$sql .= " WHERE cd.fk_commande = ".((int) $object->id);
630		$sql .= " ORDER BY cd.rang, cd.rowid";
631
632		//print $sql;
633		dol_syslog("shipment.php", LOG_DEBUG);
634		$resql = $db->query($sql);
635		if ($resql) {
636			$num = $db->num_rows($resql);
637			$i = 0;
638
639			print '<tr class="liste_titre">';
640			print '<td>'.$langs->trans("Description").'</td>';
641			print '<td class="center">'.$langs->trans("QtyOrdered").'</td>';
642			print '<td class="center">'.$langs->trans("QtyShipped").'</td>';
643			print '<td class="center">'.$langs->trans("KeepToShip").'</td>';
644			if (!empty($conf->stock->enabled)) {
645				print '<td class="center">'.$langs->trans("RealStock").'</td>';
646			} else {
647				print '<td>&nbsp;</td>';
648			}
649			print "</tr>\n";
650
651			$toBeShipped = array();
652			$toBeShippedTotal = 0;
653			while ($i < $num) {
654				$objp = $db->fetch_object($resql);
655
656				$parameters = array('i' => $i, 'line' => $objp, 'num' => $num);
657				$reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $object, $action);
658				if ($reshook < 0) {
659					setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
660				}
661
662				if (empty($reshook)) {
663					// Show product and description
664					$type = isset($objp->type) ? $objp->type : $objp->product_type;
665
666					// Try to enhance type detection using date_start and date_end for free lines where type
667					// was not saved.
668					if (!empty($objp->date_start)) {
669						$type = 1;
670					}
671					if (!empty($objp->date_end)) {
672						$type = 1;
673					}
674
675					print '<tr class="oddeven">';
676
677					// Product label
678					if ($objp->fk_product > 0) {
679						// Define output language
680						if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
681							$object->fetch_thirdparty();
682
683							$prod = new Product($db);
684							$prod->id = $objp->fk_product;
685							$prod->entity = $objp->entity;
686							$prod->getMultiLangs();
687
688							$outputlangs = $langs;
689							$newlang = '';
690							if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
691								$newlang = GETPOST('lang_id', 'aZ09');
692							}
693							if (empty($newlang)) {
694								$newlang = $object->thirdparty->default_lang;
695							}
696							if (!empty($newlang)) {
697								$outputlangs = new Translate("", $conf);
698								$outputlangs->setDefaultLang($newlang);
699							}
700
701							$label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $objp->product_label;
702						} else {
703							$label = (!empty($objp->label) ? $objp->label : $objp->product_label);
704						}
705
706						print '<td>';
707						print '<a name="'.$objp->rowid.'"></a>'; // ancre pour retourner sur la ligne
708
709						// Show product and description
710						$product_static->type = $type;
711						$product_static->id = $objp->fk_product;
712						$product_static->ref = $objp->ref;
713						$product_static->entity = $objp->entity;
714
715						$product_static->weight = $objp->weight;
716						$product_static->weight_units = $objp->weight_units;
717						$product_static->length = $objp->length;
718						$product_static->length_units = $objp->length_units;
719						$product_static->width = $objp->width;
720						$product_static->width_units = $objp->width_units;
721						$product_static->height = $objp->height;
722						$product_static->height_units = $objp->height_units;
723						$product_static->surface = $objp->surface;
724						$product_static->surface_units = $objp->surface_units;
725						$product_static->volume = $objp->volume;
726						$product_static->volume_units = $objp->volume_units;
727
728						$text = $product_static->getNomUrl(1);
729						$text .= ' - '.$label;
730						$description = ($conf->global->PRODUIT_DESC_IN_FORM ? '' : dol_htmlentitiesbr($objp->description)).'<br>';
731						$description .= $product_static->show_photos('product', $conf->product->multidir_output[$product_static->entity], 1, 1, 0, 0, 0, 80);
732						print $form->textwithtooltip($text, $description, 3, '', '', $i);
733
734						// Show range
735						print_date_range($db->jdate($objp->date_start), $db->jdate($objp->date_end));
736
737						// Add description in form
738						if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) {
739							print ($objp->description && $objp->description != $objp->product_label) ? '<br>'.dol_htmlentitiesbr($objp->description) : '';
740						}
741
742						print '</td>';
743					} else {
744						print "<td>";
745						if ($type == 1) {
746							$text = img_object($langs->trans('Service'), 'service');
747						} else {
748							$text = img_object($langs->trans('Product'), 'product');
749						}
750
751						if (!empty($objp->label)) {
752							$text .= ' <strong>'.$objp->label.'</strong>';
753							print $form->textwithtooltip($text, $objp->description, 3, '', '', $i);
754						} else {
755							print $text.' '.nl2br($objp->description);
756						}
757
758						// Show range
759						print_date_range($db->jdate($objp->date_start), $db->jdate($objp->date_end));
760						print "</td>\n";
761					}
762
763					// Qty ordered
764					print '<td class="center">'.$objp->qty.'</td>';
765
766					// Qty already shipped
767					$qtyProdCom = $objp->qty;
768					print '<td class="center">';
769					// Nb of sending products for this line of order
770					$qtyAlreadyShipped = (!empty($object->expeditions[$objp->rowid]) ? $object->expeditions[$objp->rowid] : 0);
771					print $qtyAlreadyShipped;
772					print '</td>';
773
774					// Qty remains to ship
775					print '<td class="center">';
776					if ($type == 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
777						$toBeShipped[$objp->fk_product] = $objp->qty - $qtyAlreadyShipped;
778						$toBeShippedTotal += $toBeShipped[$objp->fk_product];
779						print $toBeShipped[$objp->fk_product];
780					} else {
781						print '0 ('.$langs->trans("Service").')';
782					}
783					print '</td>';
784
785					if ($objp->fk_product > 0) {
786						$product = new Product($db);
787						$product->fetch($objp->fk_product);
788						$product->load_stock('warehouseopen');
789					}
790
791					if ($objp->fk_product > 0 && ($type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) && !empty($conf->stock->enabled)) {
792						print '<td class="center">';
793						print $product->stock_reel;
794						if ($product->stock_reel < $toBeShipped[$objp->fk_product]) {
795							print ' '.img_warning($langs->trans("StockTooLow"));
796						}
797						print '</td>';
798					} else {
799						print '<td>&nbsp;</td>';
800					}
801					print "</tr>\n";
802
803					// Show subproducts lines
804					if ($objp->fk_product > 0 && !empty($conf->global->PRODUIT_SOUSPRODUITS)) {
805						// Set tree of subproducts in product->sousprods
806						$product->get_sousproduits_arbo();
807						//var_dump($product->sousprods);exit;
808
809						// Define a new tree with quantiies recalculated
810						$prods_arbo = $product->get_arbo_each_prod($qtyProdCom);
811						//var_dump($prods_arbo);
812						if (count($prods_arbo) > 0) {
813							foreach ($prods_arbo as $key => $value) {
814								$img = '';
815								if ($value['stock'] < $value['stock_alert']) {
816									$img = img_warning($langs->trans("StockTooLow"));
817								}
818								print '<tr class="oddeven"><td>&nbsp; &nbsp; &nbsp; -> <a href="'.DOL_URL_ROOT."/product/card.php?id=".$value['id'].'">'.$value['fullpath'].'</a> ('.$value['nb'].')</td>';
819								print '<td class="center"> '.$value['nb_total'].'</td>';
820								print '<td>&nbsp;</td>';
821								print '<td>&nbsp;</td>';
822								print '<td class="center">'.$value['stock'].' '.$img.'</td></tr>'."\n";
823							}
824						}
825					}
826				}
827				$i++;
828			}
829			$db->free($resql);
830
831			if (!$num) {
832				print '<tr '.$bc[false].'><td colspan="5">'.$langs->trans("NoArticleOfTypeProduct").'<br>';
833			}
834
835			print "</table>";
836		} else {
837			dol_print_error($db);
838		}
839
840		print '</div>';
841
842
843		/*
844		 * Boutons Actions
845		 */
846
847		if (empty($user->socid)) {
848			print '<div class="tabsAction">';
849
850			// Bouton expedier sans gestion des stocks
851			if (empty($conf->stock->enabled) && ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED)) {
852				if ($user->rights->expedition->creer) {
853					print '<a class="butAction" href="'.DOL_URL_ROOT.'/expedition/card.php?action=create&amp;origin=commande&amp;object_id='.$id.'">'.$langs->trans("CreateShipment").'</a>';
854					if ($toBeShippedTotal <= 0) {
855						print ' '.img_warning($langs->trans("WarningNoQtyLeftToSend"));
856					}
857				} else {
858					print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("CreateShipment").'</a>';
859				}
860			}
861			print "</div>";
862		}
863
864
865		// Bouton expedier avec gestion des stocks
866
867		if (!empty($conf->stock->enabled) && $object->statut == Commande::STATUS_DRAFT) {
868			print $langs->trans("ValidateOrderFirstBeforeShipment");
869		}
870
871		if (!empty($conf->stock->enabled) && ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED)) {
872			if ($user->rights->expedition->creer) {
873				//print load_fiche_titre($langs->trans("CreateShipment"));
874				print '<div class="tabsAction">';
875
876				print '<form method="GET" action="'.DOL_URL_ROOT.'/expedition/card.php">';
877				print '<input type="hidden" name="action" value="create">';
878				//print '<input type="hidden" name="id" value="'.$object->id.'">';
879				print '<input type="hidden" name="shipping_method_id" value="'.$object->shipping_method_id.'">';
880				print '<input type="hidden" name="origin" value="commande">';
881				print '<input type="hidden" name="origin_id" value="'.$object->id.'">';
882				print '<input type="hidden" name="projectid" value="'.$object->fk_project.'">';
883				//print '<table class="border centpercent">';
884
885				$langs->load("stocks");
886
887				//print '<tr>';
888
889				if (!empty($conf->stock->enabled)) {
890					//print '<td>';
891					print $langs->trans("WarehouseSource");
892					//print '</td>';
893					//print '<td>';
894					print $formproduct->selectWarehouses(!empty($object->warehouse_id) ? $object->warehouse_id : 'ifone', 'entrepot_id', '', 1, 0, 0, '', 0, 0, array(), 'minwidth200');
895					if (count($formproduct->cache_warehouses) <= 0) {
896						print ' &nbsp; '.$langs->trans("WarehouseSourceNotDefined").' <a href="'.DOL_URL_ROOT.'/product/stock/card.php?action=create">'.$langs->trans("AddOne").'</a>';
897					}
898					//print '</td>';
899				}
900				//print '<td class="center">';
901				print '<input type="submit" class="butAction" named="save" value="'.$langs->trans("CreateShipment").'">';
902				if ($toBeShippedTotal <= 0) {
903					print ' '.img_warning($langs->trans("WarningNoQtyLeftToSend"));
904				}
905				//print '</td></tr>';
906
907				//print "</table>";
908				print "</form>\n";
909
910				print '</div>';
911
912				$somethingshown = 1;
913			} else {
914				print '<div class="tabsAction">';
915				print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("CreateShipment").'</a>';
916				print '</div>';
917			}
918		}
919
920		show_list_sending_receive('commande', $object->id);
921	} else {
922		/* Order not found */
923		setEventMessages($langs->trans("NonExistentOrder"), null, 'errors');
924	}
925}
926
927// End of page
928llxFooter();
929$db->close();
930