PageRenderTime 38ms CodeModel.GetById 3ms app.highlight 27ms RepoModel.GetById 1ms app.codeStats 0ms

/htdocs/expedition/class/expedition.class.php

https://github.com/asterix14/dolibarr
PHP | 1203 lines | 868 code | 149 blank | 186 comment | 136 complexity | 0a1b33e713926a7f77439f0de4999940 MD5 | raw file
   1<?php
   2/* Copyright (C) 2003-2008 Rodolphe Quiedeville  <rodolphe@quiedeville.org>
   3 * Copyright (C) 2005-2011 Regis Houssin         <regis@dolibarr.fr>
   4 * Copyright (C) 2007      Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
   5 * Copyright (C) 2006-2008 Laurent Destailleur   <eldy@users.sourceforge.net>
   6 * Copyright (C) 2011      Juanjo Menent		 <jmenent@2byte.es>
   7 *
   8 * This program is free software; you can redistribute it and/or modify
   9 * it under the terms of the GNU General Public License as published by
  10 * the Free Software Foundation; either version 2 of the License, or
  11 * (at your option) any later version.
  12 *
  13 * This program is distributed in the hope that it will be useful,
  14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16 * GNU General Public License for more details.
  17 *
  18 * You should have received a copy of the GNU General Public License
  19 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  20 */
  21
  22/**
  23 *  \file       htdocs/expedition/class/expedition.class.php
  24 *  \ingroup    expedition
  25 *  \brief      Fichier de la classe de gestion des expeditions
  26 */
  27
  28require_once(DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php");
  29if ($conf->propal->enabled) require_once(DOL_DOCUMENT_ROOT."/comm/propal/class/propal.class.php");
  30if ($conf->commande->enabled) require_once(DOL_DOCUMENT_ROOT."/commande/class/commande.class.php");
  31
  32
  33/**
  34 *	\class      Expedition
  35 *	\brief      Class to manage shippings
  36 */
  37class Expedition extends CommonObject
  38{
  39	public $element="shipping";
  40	public $fk_element="fk_expedition";
  41	public $table_element="expedition";
  42
  43	var $id;
  44	var $socid;
  45	var $ref_customer;
  46	var $ref_ext;
  47	var $ref_int;
  48	var $brouillon;
  49	var $entrepot_id;
  50	var $modelpdf;
  51	var $origin;
  52	var $origin_id;
  53	var $lines=array();
  54	var $expedition_method_id; // TODO deprecated
  55	var $shipping_method_id;
  56	var $tracking_number;
  57	var $tracking_url;
  58	var $statut;
  59
  60	var $trueWeight;
  61	var $weight_units;
  62	var $trueWidth;
  63	var $width_units;
  64	var $trueHeight;
  65	var $height_units;
  66	var $trueDepth;
  67	var $depth_units;
  68	// A denormalized value
  69	var $trueSize;
  70
  71	var $date_delivery;		// Date delivery planed
  72	var $date_expedition;	// Date delivery real
  73	var $date_creation;
  74	var $date_valid;
  75
  76	/**
  77	 *	Constructor
  78	 *
  79	 *  @param		DoliDB		$DB      Database handler
  80	 */
  81	function Expedition($DB)
  82	{
  83		$this->db = $DB;
  84		$this->lines = array();
  85		$this->products = array();
  86
  87		// List of long language codes for status
  88		$this->statuts[-1] = 'StatusSendingCanceled';
  89		$this->statuts[0]  = 'StatusSendingDraft';
  90		$this->statuts[1]  = 'StatusSendingValidated';
  91	}
  92
  93	/**
  94	 *	Return next contract ref
  95	 *
  96	 *	@param	Societe		$soc	Objet society
  97	 *	@return string				Free reference for contract
  98	 */
  99	function getNextNumRef($soc)
 100	{
 101		global $db, $langs, $conf;
 102		$langs->load("sendings");
 103
 104		$dir = DOL_DOCUMENT_ROOT . "/core/modules/expedition";
 105
 106	    if (empty($conf->global->EXPEDITION_ADDON_NUMBER))
 107        {
 108            $conf->global->EXPEDITION_ADDON_NUMBER='mod_expedition_safor';
 109        }
 110
 111		$file = $conf->global->EXPEDITION_ADDON_NUMBER.".php";
 112
 113		// Chargement de la classe de numerotation
 114		$classname = $conf->global->EXPEDITION_ADDON_NUMBER;
 115
 116		$result=include_once($dir.'/'.$file);
 117		if ($result)
 118		{
 119			$obj = new $classname();
 120			$numref = "";
 121			$numref = $obj->getNextValue($soc,$this);
 122
 123			if ( $numref != "")
 124			{
 125				return $numref;
 126			}
 127			else
 128			{
 129				dol_print_error($db,"Expedition::getNextNumRef ".$obj->error);
 130				return "";
 131			}
 132		}
 133		else
 134		{
 135			print $langs->trans("Error")." ".$langs->trans("Error_EXPEDITION_ADDON_NUMBER_NotDefined");
 136			return "";
 137		}
 138	}
 139
 140	/**
 141	 *  Create expedition en base
 142	 *
 143	 *  @param	User	$user       Objet du user qui cree
 144	 *  @return int 				<0 si erreur, id expedition creee si ok
 145	 */
 146	function create($user)
 147	{
 148		global $conf, $langs;
 149
 150		require_once DOL_DOCUMENT_ROOT ."/product/stock/class/mouvementstock.class.php";
 151		$error = 0;
 152
 153		// Clean parameters
 154		$this->brouillon = 1;
 155		$this->tracking_number = dol_sanitizeFileName($this->tracking_number);
 156
 157		$this->user = $user;
 158
 159
 160		$this->db->begin();
 161
 162		$sql = "INSERT INTO ".MAIN_DB_PREFIX."expedition (";
 163		$sql.= "ref";
 164		$sql.= ", entity";
 165		$sql.= ", ref_customer";
 166		$sql.= ", ref_int";
 167		$sql.= ", date_creation";
 168		$sql.= ", fk_user_author";
 169		$sql.= ", date_expedition";
 170		$sql.= ", date_delivery";
 171		$sql.= ", fk_soc";
 172		$sql.= ", fk_address";
 173		$sql.= ", fk_expedition_methode";
 174		$sql.= ", tracking_number";
 175		$sql.= ", weight";
 176		$sql.= ", size";
 177		$sql.= ", width";
 178		$sql.= ", height";
 179		$sql.= ", weight_units";
 180		$sql.= ", size_units";
 181		$sql.= ") VALUES (";
 182		$sql.= "'(PROV)'";
 183		$sql.= ", ".$conf->entity;
 184		$sql.= ", ".($this->ref_customer?"'".$this->ref_customer."'":"null");
 185		$sql.= ", ".($this->ref_int?"'".$this->ref_int."'":"null");
 186		$sql.= ", '".$this->db->idate(gmmktime())."'";
 187		$sql.= ", ".$user->id;
 188		$sql.= ", ".($this->date_expedition>0?"'".$this->db->idate($this->date_expedition)."'":"null");
 189		$sql.= ", ".($this->date_delivery>0?"'".$this->db->idate($this->date_delivery)."'":"null");
 190		$sql.= ", ".$this->socid;
 191		$sql.= ", ".($this->fk_delivery_address>0?$this->fk_delivery_address:"null");
 192		$sql.= ", ".($this->expedition_method_id>0?$this->expedition_method_id:"null");
 193		$sql.= ", '".$this->db->escape($this->tracking_number)."'";
 194		$sql.= ", ".$this->weight;
 195		$sql.= ", ".$this->sizeS;	// TODO Should use this->trueDepth
 196		$sql.= ", ".$this->sizeW;	// TODO Should use this->trueWidth
 197		$sql.= ", ".$this->sizeH;	// TODO Should use this->trueHeight
 198		$sql.= ", ".$this->weight_units;
 199		$sql.= ", ".$this->size_units;
 200		$sql.= ")";
 201
 202		$resql=$this->db->query($sql);
 203		if ($resql)
 204		{
 205			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."expedition");
 206
 207			$sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
 208			$sql.= " SET ref = '(PROV".$this->id.")'";
 209			$sql.= " WHERE rowid = ".$this->id;
 210
 211			dol_syslog("Expedition::create sql=".$sql, LOG_DEBUG);
 212			if ($this->db->query($sql))
 213			{
 214				// Insertion des lignes
 215				$num=count($this->lines);
 216				for ($i = 0; $i < $num; $i++)
 217				{
 218					if (! $this->create_line($this->lines[$i]->entrepot_id, $this->lines[$i]->origin_line_id, $this->lines[$i]->qty) > 0)
 219					{
 220						$error++;
 221					}
 222				}
 223
 224				if (! $error && $this->id && $this->origin_id)
 225				{
 226					$ret = $this->add_object_linked();
 227					if (!$ret)
 228					{
 229						$error++;
 230					}
 231
 232					// TODO uniformiser les statuts
 233					$ret = $this->setStatut(2,$this->origin_id,$this->origin);
 234					if (! $ret)
 235					{
 236						$error++;
 237					}
 238				}
 239
 240				if (! $error)
 241				{
 242					// Appel des triggers
 243					include_once(DOL_DOCUMENT_ROOT."/core/class/interfaces.class.php");
 244					$interface=new Interfaces($this->db);
 245					$result=$interface->run_triggers('SHIPPING_CREATE',$this,$user,$langs,$conf);
 246					if ($result < 0) { $error++; $this->errors=$interface->errors; }
 247					// Fin appel triggers
 248
 249					$this->db->commit();
 250					return $this->id;
 251				}
 252				else
 253				{
 254					$error++;
 255					$this->error=$this->db->lasterror()." - sql=$sql";
 256					$this->db->rollback();
 257					return -3;
 258				}
 259			}
 260			else
 261			{
 262				$error++;
 263				$this->error=$this->db->lasterror()." - sql=$sql";
 264				$this->db->rollback();
 265				return -2;
 266			}
 267		}
 268		else
 269		{
 270			$error++;
 271			$this->error=$this->db->error()." - sql=$sql";
 272			$this->db->rollback();
 273			return -1;
 274		}
 275	}
 276
 277	/**
 278	 *
 279	 *
 280	 */
 281	function create_line($entrepot_id, $origin_line_id, $qty)
 282	{
 283		$error = 0;
 284
 285		$sql = "INSERT INTO ".MAIN_DB_PREFIX."expeditiondet (";
 286		$sql.= "fk_expedition";
 287		$sql.= ", fk_entrepot";
 288		$sql.= ", fk_origin_line";
 289		$sql.= ", qty";
 290		$sql.= ") VALUES (";
 291		$sql.= $this->id;
 292		$sql.= ", ".($entrepot_id?$entrepot_id:'null');
 293		$sql.= ", ".$origin_line_id;
 294		$sql.= ", ".$qty;
 295		$sql.= ")";
 296
 297		if (! $this->db->query($sql))
 298		{
 299			$error++;
 300		}
 301
 302		if (! $error) return 1;
 303		else return -1;
 304	}
 305
 306	/**
 307	 *	Get object and lines from database
 308	 *
 309	 *	@param	int		$id       	Id of object to load
 310	 * 	@param	string	$ref		Ref of object
 311	 * 	@param	string	$ref_ext	External reference of object
 312     * 	@param	string	$ref_int	Internal reference of other object
 313	 *	@return int			        >0 if OK, <0 if KO
 314	 */
 315	function fetch($id, $ref='', $ref_ext='', $ref_int='')
 316	{
 317		global $conf;
 318
 319		// Check parameters
 320		if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
 321
 322		$sql = "SELECT e.rowid, e.ref, e.fk_soc as socid, e.date_creation, e.ref_customer, e.ref_ext, e.ref_int, e.fk_user_author, e.fk_statut";
 323		$sql.= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height";
 324		$sql.= ", e.date_expedition as date_expedition, e.model_pdf, e.fk_address, e.date_delivery";
 325		$sql.= ", e.fk_expedition_methode, e.tracking_number";
 326		$sql.= ", el.fk_source as origin_id, el.sourcetype as origin";
 327		$sql.= " FROM ".MAIN_DB_PREFIX."expedition as e";
 328		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = e.rowid AND el.targettype = '".$this->element."'";
 329		$sql.= " WHERE e.entity = ".$conf->entity;
 330		if ($id)   	  $sql.= " AND e.rowid=".$id;
 331        if ($ref)     $sql.= " AND e.ref='".$this->db->escape($ref)."'";
 332        if ($ref_ext) $sql.= " AND e.ref_ext='".$this->db->escape($ref_ext)."'";
 333        if ($ref_int) $sql.= " AND e.ref_int='".$this->db->escape($ref_int)."'";
 334
 335		dol_syslog("Expedition::fetch sql=".$sql);
 336		$result = $this->db->query($sql);
 337		if ($result)
 338		{
 339			if ($this->db->num_rows($result))
 340			{
 341				$obj = $this->db->fetch_object($result);
 342
 343				$this->id                   = $obj->rowid;
 344				$this->ref                  = $obj->ref;
 345				$this->socid                = $obj->socid;
 346				$this->ref_customer			= $obj->ref_customer;
 347				$this->ref_ext				= $obj->ref_ext;
 348				$this->ref_int				= $obj->ref_int;
 349				$this->statut               = $obj->fk_statut;
 350				$this->user_author_id       = $obj->fk_user_author;
 351				$this->date_creation        = $this->db->jdate($obj->date_creation);
 352				$this->date                 = $this->db->jdate($obj->date_expedition);	// TODO obsolete
 353				$this->date_expedition      = $this->db->jdate($obj->date_expedition);	// TODO obsolete
 354				$this->date_shipping        = $this->db->jdate($obj->date_expedition);	// Date real
 355				$this->date_delivery        = $this->db->jdate($obj->date_delivery);	// Date planed
 356				$this->fk_delivery_address  = $obj->fk_address;
 357				$this->modelpdf             = $obj->model_pdf;
 358				$this->expedition_method_id = $obj->fk_expedition_methode; // TODO deprecated
 359				$this->shipping_method_id	= $obj->fk_expedition_methode;
 360				$this->tracking_number      = $obj->tracking_number;
 361				$this->origin               = ($obj->origin?$obj->origin:'commande'); // For compatibility
 362				$this->origin_id            = $obj->origin_id;
 363
 364				$this->trueWeight           = $obj->weight;
 365				$this->weight_units         = $obj->weight_units;
 366
 367				$this->trueWidth            = $obj->width;
 368				$this->width_units          = $obj->size_units;
 369				$this->trueHeight           = $obj->height;
 370				$this->height_units         = $obj->size_units;
 371				$this->trueDepth            = $obj->size;
 372				$this->depth_units          = $obj->size_units;
 373
 374				// A denormalized value
 375				$this->trueSize           	= $obj->size."x".$obj->width."x".$obj->height;
 376				$this->size_units           = $obj->size_units;
 377
 378				$this->db->free($result);
 379
 380				if ($this->statut == 0) $this->brouillon = 1;
 381
 382				$file = $conf->expedition->dir_output . "/" .get_exdir($expedition->id,2) . "/" . $this->id.".pdf";
 383				$this->pdf_filename = $file;
 384
 385				// Tracking url
 386				$this->GetUrlTrackingStatus($obj->tracking_number);
 387
 388				/*
 389				 * Lines
 390				 */
 391				$result=$this->fetch_lines();
 392				if ($result < 0)
 393				{
 394					return -3;
 395				}
 396
 397				return 1;
 398			}
 399			else
 400			{
 401				dol_syslog('Expedition::Fetch Error rowid='.$rowid.' numrows=0 sql='.$sql);
 402				$this->error='Delivery with id '.$rowid.' not found sql='.$sql;
 403				return -2;
 404			}
 405		}
 406		else
 407		{
 408			dol_syslog('Expedition::Fetch Error rowid='.$rowid.' Erreur dans fetch de l\'expedition');
 409			$this->error=$this->db->error();
 410			return -1;
 411		}
 412	}
 413
 414	/**
 415	 *  Validate object and update stock if option enabled
 416	 *
 417	 *  @param      User		$user       Object user that validate
 418	 *  @return     int						<0 if OK, >0 if KO
 419	 */
 420	function valid($user)
 421	{
 422		global $conf, $langs;
 423
 424        require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
 425
 426		dol_syslog("Expedition::valid");
 427
 428		// Protection
 429		if ($this->statut)
 430		{
 431			dol_syslog("Expedition::valid no draft status", LOG_WARNING);
 432			return 0;
 433		}
 434
 435		if (! $user->rights->expedition->valider)
 436		{
 437			$this->error='Permission denied';
 438			dol_syslog("Expedition::valid ".$this->error, LOG_ERR);
 439			return -1;
 440		}
 441
 442		$this->db->begin();
 443
 444		$error = 0;
 445
 446		// Define new ref
 447		$soc = new Societe($this->db);
 448		$soc->fetch($this->socid);
 449
 450		// Class of company linked to order
 451		$result=$soc->set_as_client();
 452
 453		// Define new ref
 454		if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref)))
 455		{
 456			$numref = $this->getNextNumRef($soc);
 457		}
 458		else
 459		{
 460			$numref = "EXP".$this->id;
 461		}
 462
 463		$now=dol_now();
 464
 465		// Validate
 466		$sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
 467		$sql.= " ref='".$numref."'";
 468		$sql.= ", fk_statut = 1";
 469		$sql.= ", date_valid = '".$this->db->idate($now)."'";
 470		$sql.= ", fk_user_valid = ".$user->id;
 471		$sql.= " WHERE rowid = ".$this->id;
 472
 473		dol_syslog("Expedition::valid update expedition sql=".$sql);
 474		$resql=$this->db->query($sql);
 475		if (! $resql)
 476		{
 477			dol_syslog("Expedition::valid Echec update - 10 - sql=".$sql, LOG_ERR);
 478			$this->error=$this->db->lasterror();
 479			$error++;
 480		}
 481
 482		// If stock increment is done on sending (recommanded choice)
 483		if (! $error && $conf->stock->enabled && $conf->global->STOCK_CALCULATE_ON_SHIPMENT)
 484		{
 485			require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php";
 486
 487			$langs->load("agenda");
 488
 489			// Loop on each product line to add a stock movement
 490			// TODO possibilite d'expedier a partir d'une propale ou autre origine
 491			$sql = "SELECT cd.fk_product, cd.subprice, ed.qty, ed.fk_entrepot";
 492			$sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
 493			$sql.= " ".MAIN_DB_PREFIX."expeditiondet as ed";
 494			$sql.= " WHERE ed.fk_expedition = ".$this->id;
 495			$sql.= " AND cd.rowid = ed.fk_origin_line";
 496
 497			dol_syslog("Expedition::valid select details sql=".$sql);
 498			$resql=$this->db->query($sql);
 499			if ($resql)
 500			{
 501			    $cpt = $this->db->num_rows($resql);
 502                for ($i = 0; $i < $cpt; $i++)
 503				{
 504					dol_syslog("Expedition::valid movement index ".$i);
 505					$obj = $this->db->fetch_object($resql);
 506
 507					//var_dump($this->lines[$i]);
 508					$mouvS = new MouvementStock($this->db);
 509					// We decrement stock of product (and sub-products)
 510					// We use warehouse selected for each line
 511					$result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, $obj->subprice, $langs->trans("ShipmentValidatedInDolibarr",$numref));
 512					if ($result < 0) { $error++; break; }
 513
 514					$i++;
 515				}
 516			}
 517			else
 518			{
 519				$this->db->rollback();
 520				$this->error=$this->db->error();
 521				dol_syslog("Expedition::valid ".$this->error, LOG_ERR);
 522				return -2;
 523			}
 524		}
 525
 526		if (! $error)
 527		{
 528			// On efface le repertoire de pdf provisoire
 529			$expeditionref = dol_sanitizeFileName($this->ref);
 530			if ($conf->expedition->dir_output)
 531			{
 532				$dir = $conf->expedition->dir_output . "/" . $expeditionref;
 533				$file = $dir . "/" . $expeditionref . ".pdf";
 534				if (file_exists($file))
 535				{
 536					if (!dol_delete_file($file))
 537					{
 538						$this->error=$langs->trans("ErrorCanNotDeleteFile",$file);
 539					}
 540				}
 541				if (file_exists($dir))
 542				{
 543					if (!dol_delete_dir($dir))
 544					{
 545						$this->error=$langs->trans("ErrorCanNotDeleteDir",$dir);
 546					}
 547				}
 548			}
 549		}
 550
 551		// Set new ref and current status
 552		if (! $error)
 553		{
 554			$this->ref = $numref;
 555			$this->statut = 1;
 556		}
 557
 558		if (! $error)
 559		{
 560			// Appel des triggers
 561			include_once(DOL_DOCUMENT_ROOT."/core/class/interfaces.class.php");
 562			$interface=new Interfaces($this->db);
 563			$result=$interface->run_triggers('SHIPPING_VALIDATE',$this,$user,$langs,$conf);
 564			if ($result < 0) { $error++; $this->errors=$interface->errors; }
 565			// Fin appel triggers
 566		}
 567
 568		if (! $error)
 569		{
 570			$this->db->commit();
 571			return 1;
 572		}
 573		else
 574		{
 575			foreach($this->errors as $errmsg)
 576			{
 577	            dol_syslog(get_class($this)."::valid ".$errmsg, LOG_ERR);
 578	            $this->error.=($this->error?', '.$errmsg:$errmsg);
 579			}
 580			$this->db->rollback();
 581			return -1*$error;
 582		}
 583	}
 584
 585
 586	/**
 587	 *	Cree un bon de livraison a partir de l'expedition
 588	 *
 589	 *	@param	User	$user       Utilisateur
 590	 *  @return int  				<0 if KO, >=0 if OK
 591	 */
 592	function create_delivery($user)
 593	{
 594		global $conf;
 595
 596		if ($conf->livraison_bon->enabled)
 597		{
 598			if ($this->statut == 1)
 599			{
 600				// Expedition validee
 601				include_once(DOL_DOCUMENT_ROOT."/livraison/class/livraison.class.php");
 602				$delivery = new Livraison($this->db);
 603				$result=$delivery->create_from_sending($user, $this->id);
 604				if ($result > 0)
 605				{
 606					return $result;
 607				}
 608				else
 609				{
 610					$this->error=$delivery->error;
 611					return $result;
 612				}
 613			}
 614			else return 0;
 615		}
 616		else return 0;
 617	}
 618
 619	/**
 620	 * Ajoute une ligne
 621	 *
 622	 */
 623	function addline( $entrepot_id, $id, $qty )
 624	{
 625		$num = count($this->lines);
 626		$line = new ExpeditionLigne($this->db);
 627
 628		$line->entrepot_id = $entrepot_id;
 629		$line->origin_line_id = $id;
 630		$line->qty = $qty;
 631
 632		$this->lines[$num] = $line;
 633	}
 634
 635	/**
 636	 *
 637	 *
 638	 */
 639	function deleteline($lineid)
 640	{
 641		if ($this->statut == 0)
 642		{
 643			$sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet";
 644			$sql.= " WHERE rowid = ".$lineid;
 645
 646			if ($this->db->query($sql) )
 647			{
 648				$this->update_price();
 649
 650				return 1;
 651			}
 652			else
 653			{
 654				return 0;
 655			}
 656		}
 657	}
 658
 659    /**
 660     *  Update database
 661     *
 662     *  @param	User	$user        	User that modify
 663     *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
 664     *  @return int 			       	<0 if KO, >0 if OK
 665     */
 666    function update($user=0, $notrigger=0)
 667    {
 668    	global $conf, $langs;
 669		$error=0;
 670
 671		// Clean parameters
 672
 673		if (isset($this->ref)) $this->ref=trim($this->ref);
 674		if (isset($this->entity)) $this->entity=trim($this->entity);
 675		if (isset($this->ref_customer)) $this->ref_customer=trim($this->ref_customer);
 676		if (isset($this->socid)) $this->socid=trim($this->socid);
 677		if (isset($this->fk_user_author)) $this->fk_user_author=trim($this->fk_user_author);
 678		if (isset($this->fk_user_valid)) $this->fk_user_valid=trim($this->fk_user_valid);
 679		if (isset($this->fk_adresse_livraison)) $this->fk_adresse_livraison=trim($this->fk_adresse_livraison);
 680		if (isset($this->expedition_method_id)) $this->expedition_method_id=trim($this->expedition_method_id);
 681		if (isset($this->tracking_number)) $this->tracking_number=trim($this->tracking_number);
 682		if (isset($this->statut)) $this->statut=trim($this->statut);
 683		if (isset($this->trueDepth)) $this->trueDepth=trim($this->trueDepth);
 684		if (isset($this->trueWidth)) $this->trueWidth=trim($this->trueWidth);
 685		if (isset($this->trueHeight)) $this->trueHeight=trim($this->trueHeight);
 686		if (isset($this->size_units)) $this->size_units=trim($this->size_units);
 687		if (isset($this->weight_units)) $this->weight_units=trim($this->weight_units);
 688		if (isset($this->trueWeight)) $this->weight=trim($this->trueWeight);
 689		if (isset($this->note)) $this->note=trim($this->note);
 690		if (isset($this->model_pdf)) $this->model_pdf=trim($this->model_pdf);
 691
 692
 693
 694		// Check parameters
 695		// Put here code to add control on parameters values
 696
 697        // Update request
 698        $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
 699
 700		$sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
 701		$sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
 702		$sql.= " ref_customer=".(isset($this->ref_customer)?"'".$this->db->escape($this->ref_customer)."'":"null").",";
 703		$sql.= " fk_soc=".(isset($this->socid)?$this->socid:"null").",";
 704		$sql.= " date_creation=".(dol_strlen($this->date_creation)!=0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
 705		$sql.= " fk_user_author=".(isset($this->fk_user_author)?$this->fk_user_author:"null").",";
 706		$sql.= " date_valid=".(dol_strlen($this->date_valid)!=0 ? "'".$this->db->idate($this->date_valid)."'" : 'null').",";
 707		$sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->fk_user_valid:"null").",";
 708		$sql.= " date_expedition=".(dol_strlen($this->date_expedition)!=0 ? "'".$this->db->idate($this->date_expedition)."'" : 'null').",";
 709		$sql.= " date_delivery=".(dol_strlen($this->date_delivery)!=0 ? "'".$this->db->idate($this->date_delivery)."'" : 'null').",";
 710		$sql.= " fk_address=".(isset($this->fk_adresse_livraison)?$this->fk_adresse_livraison:"null").",";
 711		$sql.= " fk_expedition_methode=".((isset($this->expedition_method_id) && $this->expedition_method_id > 0)?$this->expedition_method_id:"null").",";
 712		$sql.= " tracking_number=".(isset($this->tracking_number)?"'".$this->db->escape($this->tracking_number)."'":"null").",";
 713		$sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
 714		$sql.= " height=".(isset($this->trueHeight)?$this->trueHeight:"null").",";
 715		$sql.= " width=".(isset($this->trueWidth)?$this->trueWidth:"null").",";
 716		$sql.= " size_units=".(isset($this->size_units)?$this->size_units:"null").",";
 717		$sql.= " size=".(isset($this->trueDepth)?$this->trueDepth:"null").",";
 718		$sql.= " weight_units=".(isset($this->weight_units)?$this->weight_units:"null").",";
 719		$sql.= " weight=".(isset($this->trueWeight)?$this->trueWeight:"null").",";
 720		$sql.= " note=".(isset($this->note)?"'".$this->db->escape($this->note)."'":"null").",";
 721		$sql.= " model_pdf=".(isset($this->model_pdf)?"'".$this->db->escape($this->model_pdf)."'":"null").",";
 722		$sql.= " entity=".$conf->entity;
 723
 724        $sql.= " WHERE rowid=".$this->id;
 725
 726		$this->db->begin();
 727
 728		dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG);
 729        $resql = $this->db->query($sql);
 730    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
 731
 732		if (! $error)
 733		{
 734			if (! $notrigger)
 735			{
 736	            // Call triggers
 737	            include_once(DOL_DOCUMENT_ROOT."/core/class/interfaces.class.php");
 738	            $interface=new Interfaces($this->db);
 739	            $result=$interface->run_triggers('SHIPPING_MODIFY',$this,$user,$langs,$conf);
 740	            if ($result < 0) { $error++; $this->errors=$interface->errors; }
 741	            // End call triggers
 742	    	}
 743		}
 744
 745        // Commit or rollback
 746		if ($error)
 747		{
 748			foreach($this->errors as $errmsg)
 749			{
 750	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
 751	            $this->error.=($this->error?', '.$errmsg:$errmsg);
 752			}
 753			$this->db->rollback();
 754			return -1*$error;
 755		}
 756		else
 757		{
 758			$this->db->commit();
 759			return 1;
 760		}
 761    }
 762
 763    /**
 764	 * 	Delete shipping
 765	 *
 766	 * 	@return	void
 767	 */
 768	function delete()
 769	{
 770		global $conf, $langs, $user;
 771
 772        require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
 773		$this->db->begin();
 774
 775		$sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet";
 776		$sql.= " WHERE fk_expedition = ".$this->id;
 777
 778		if ( $this->db->query($sql) )
 779		{
 780			$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element";
 781			$sql.= " WHERE fk_target = ".$this->id;
 782			$sql.= " AND targettype = '".$this->element."'";
 783
 784			if ( $this->db->query($sql) )
 785			{
 786				$sql = "DELETE FROM ".MAIN_DB_PREFIX."expedition";
 787				$sql.= " WHERE rowid = ".$this->id;
 788
 789				if ( $this->db->query($sql) )
 790				{
 791					$this->db->commit();
 792
 793					// On efface le repertoire de pdf provisoire
 794					$expref = dol_sanitizeFileName($this->ref);
 795					if ($conf->expedition->dir_output)
 796					{
 797						$dir = $conf->expedition->dir_output . "/" . $expref ;
 798						$file = $conf->expedition->dir_output . "/" . $expref . "/" . $expref . ".pdf";
 799						if (file_exists($file))
 800						{
 801							if (!dol_delete_file($file))
 802							{
 803								$this->error=$langs->trans("ErrorCanNotDeleteFile",$file);
 804								return 0;
 805							}
 806						}
 807						if (file_exists($dir))
 808						{
 809							if (!dol_delete_dir($dir))
 810							{
 811								$this->error=$langs->trans("ErrorCanNotDeleteDir",$dir);
 812								return 0;
 813							}
 814						}
 815					}
 816
 817					// Call triggers
 818		            include_once(DOL_DOCUMENT_ROOT."/core/class/interfaces.class.php");
 819		            $interface=new Interfaces($this->db);
 820		            $result=$interface->run_triggers('SHIPPING_DELETE',$this,$user,$langs,$conf);
 821		            if ($result < 0) { $error++; $this->errors=$interface->errors; }
 822		            // End call triggers
 823
 824					// TODO il faut incrementer le stock si on supprime une expedition validee
 825					return 1;
 826				}
 827				else
 828				{
 829					$this->error=$this->db->lasterror()." - sql=$sql";
 830					$this->db->rollback();
 831					return -3;
 832				}
 833			}
 834			else
 835			{
 836				$this->error=$this->db->lasterror()." - sql=$sql";
 837				$this->db->rollback();
 838				return -2;
 839			}
 840		}
 841		else
 842		{
 843			$this->error=$this->db->lasterror()." - sql=$sql";
 844			$this->db->rollback();
 845			return -1;
 846		}
 847	}
 848
 849	/**
 850	 *	Load lines
 851	 *
 852	 *	@return	void
 853	 */
 854	function fetch_lines()
 855	{
 856		// TODO: recuperer les champs du document associe a part
 857
 858		$sql = "SELECT cd.rowid, cd.fk_product, cd.description, cd.qty as qty_asked";
 859		$sql.= ", ed.qty as qty_shipped, ed.fk_origin_line, ed.fk_entrepot";
 860		$sql.= ", p.ref as product_ref, p.fk_product_type, p.label, p.weight, p.weight_units, p.volume, p.volume_units";
 861		$sql.= " FROM (".MAIN_DB_PREFIX."expeditiondet as ed,";
 862		$sql.= " ".MAIN_DB_PREFIX."commandedet as cd)";
 863		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = cd.fk_product";
 864		$sql.= " WHERE ed.fk_expedition = ".$this->id;
 865		$sql.= " AND ed.fk_origin_line = cd.rowid";
 866
 867		dol_syslog("Expedition::fetch_lines sql=".$sql);
 868		$resql = $this->db->query($sql);
 869		if ($resql)
 870		{
 871			$num = $this->db->num_rows($resql);
 872			$i = 0;
 873			while ($i < $num)
 874			{
 875				$line = new ExpeditionLigne($this->db);
 876				$obj = $this->db->fetch_object($resql);
 877
 878				$line->fk_origin_line 	= $obj->fk_origin_line;
 879				$line->origin_line_id 	= $obj->fk_origin_line;	// TODO deprecated
 880				$line->entrepot_id    	= $obj->fk_entrepot;
 881				$line->fk_product     	= $obj->fk_product;
 882				$line->fk_product_type	= $obj->fk_product_type;
 883				$line->ref				= $obj->product_ref;		// TODO deprecated
 884                $line->product_ref		= $obj->product_ref;
 885				$line->label          	= $obj->label;
 886				$line->libelle        	= $obj->label;			// TODO deprecated
 887				$line->description    	= $obj->description;
 888				$line->qty_asked      	= $obj->qty_asked;
 889				$line->qty_shipped    	= $obj->qty_shipped;
 890				$line->weight         	= $obj->weight;
 891				$line->weight_units   	= $obj->weight_units;
 892				$line->volume         	= $obj->volume;
 893				$line->volume_units   	= $obj->volume_units;
 894
 895				$this->lines[$i] = $line;
 896
 897				$i++;
 898			}
 899			$this->db->free($resql);
 900			return 1;
 901		}
 902		else
 903		{
 904			$this->error=$this->db->error();
 905			dol_syslog('Expedition::fetch_lines: Error '.$this->error, LOG_ERR);
 906			return -3;
 907		}
 908	}
 909
 910	/**
 911	 * Renvoie nom clicable (avec eventuellement le picto)
 912	 *
 913	 * @param	int		$withpicto		0=Pas de picto, 1=Inclut le picto dans le lien, 2=Picto seul
 914	 * @return	string					Chaine avec URL
 915	 */
 916	function getNomUrl($withpicto=0,$option=0,$max=0,$short=0)
 917	{
 918		global $langs;
 919
 920		$result='';
 921
 922		$url = DOL_URL_ROOT.'/expedition/fiche.php?id='.$this->id;
 923
 924		if ($short) return $url;
 925
 926		$linkstart = '<a href="'.$url.'">';
 927		$linkend='</a>';
 928
 929		$picto='sending';
 930		$label=$langs->trans("ShowSending").': '.$this->ref;
 931
 932		if ($withpicto) $result.=($linkstart.img_object($label,$picto).$linkend);
 933		if ($withpicto && $withpicto != 2) $result.=' ';
 934		$result.=$linkstart.$this->ref.$linkend;
 935		return $result;
 936	}
 937
 938	/**
 939	 * Retourne le libelle du statut d'une expedition
 940	 *
 941	 * @return     string      Libelle
 942	 */
 943	function getLibStatut($mode=0)
 944	{
 945		return $this->LibStatut($this->statut,$mode);
 946	}
 947
 948	/**
 949	 * Return label of a status
 950	 *
 951	 * @param      int		$statut		Id statut
 952	 * @param      int		$mode       0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
 953	 * @return     string				Label of status
 954	 */
 955	function LibStatut($statut,$mode)
 956	{
 957		global $langs;
 958
 959		if ($mode==0)
 960		{
 961			if ($statut==0) return $langs->trans($this->statuts[$statut]);
 962			if ($statut==1) return $langs->trans($this->statuts[$statut]);
 963		}
 964		if ($mode==1)
 965		{
 966			if ($statut==0) return $langs->trans('StatusSendingDraftShort');
 967			if ($statut==1) return $langs->trans('StatusSendingValidatedShort');
 968		}
 969		if ($mode == 3)
 970		{
 971			if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0');
 972			if ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut4');
 973		}
 974		if ($mode == 4)
 975		{
 976			if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]);
 977			if ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]);
 978		}
 979		if ($mode == 5)
 980		{
 981			if ($statut==0) return $langs->trans('StatusSendingDraftShort').' '.img_picto($langs->trans($this->statuts[$statut]),'statut0');
 982			if ($statut==1) return $langs->trans('StatusSendingValidatedShort').' '.img_picto($langs->trans($this->statuts[$statut]),'statut4');
 983		}
 984	}
 985
 986	/**
 987     *  Initialise an instance with random values.
 988     *  Used to build previews or test instances.
 989     *	id must be 0 if object instance is a specimen.
 990     *
 991     *  @return	void
 992	 */
 993	function initAsSpecimen()
 994	{
 995		global $user,$langs,$conf;
 996
 997		$now=dol_now();
 998
 999		dol_syslog("Expedition::initAsSpecimen");
1000
1001		// Charge tableau des produits prodids
1002		$prodids = array();
1003		$sql = "SELECT rowid";
1004		$sql.= " FROM ".MAIN_DB_PREFIX."product";
1005		$sql.= " WHERE entity = ".$conf->entity;
1006		$resql = $this->db->query($sql);
1007		if ($resql)
1008		{
1009			$num_prods = $this->db->num_rows($resql);
1010			$i = 0;
1011			while ($i < $num_prods)
1012			{
1013				$i++;
1014				$row = $this->db->fetch_row($resql);
1015				$prodids[$i] = $row[0];
1016			}
1017		}
1018
1019		$order=new Commande($this->db);
1020		$order->initAsSpecimen();
1021
1022		// Initialise parametres
1023		$this->id=0;
1024		$this->ref = 'SPECIMEN_SHIP';
1025		$this->specimen=1;
1026		$this->statut               = 1;
1027		$this->livraison_id         = 0;
1028		$this->date                 = $now;
1029		$this->date_creation        = $now;
1030		$this->date_valid           = $now;
1031		$this->date_delivery        = $now;
1032		$this->date_expedition      = $now + 24*3600;
1033
1034		$this->entrepot_id          = 0;
1035		$this->fk_delivery_address  = 0;
1036		$this->socid                = 1;
1037
1038		$this->commande_id          = 0;
1039		$this->commande             = $order;
1040
1041        $this->origin_id            = 1;
1042        $this->origin               = 'commande';
1043
1044		$nbp = 5;
1045		$xnbp = 0;
1046		while ($xnbp < $nbp)
1047		{
1048			$line=new ExpeditionLigne($this->db);
1049			$line->desc=$langs->trans("Description")." ".$xnbp;
1050			$line->libelle=$langs->trans("Description")." ".$xnbp;
1051			$line->qty=10;
1052			$line->qty_asked=5;
1053			$line->qty_shipped=4;
1054			$line->fk_product=$this->commande->lines[$xnbp]->fk_product;
1055
1056			$this->lines[]=$line;
1057			$xnbp++;
1058		}
1059
1060	}
1061
1062	/**
1063	 * Set the planned delivery date
1064	 *
1065	 * @param      user        			Objet utilisateur qui modifie
1066	 * @param      date_livraison     	Date de livraison
1067	 * @return     int         			<0 si ko, >0 si ok
1068	 */
1069	function set_date_livraison($user, $date_livraison)
1070	{
1071		if ($user->rights->expedition->creer)
1072		{
1073			$sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
1074			$sql.= " SET date_delivery = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
1075			$sql.= " WHERE rowid = ".$this->id;
1076
1077			dol_syslog("Expedition::set_date_livraison sql=".$sql,LOG_DEBUG);
1078			$resql=$this->db->query($sql);
1079			if ($resql)
1080			{
1081				$this->date_delivery = $date_livraison;
1082				return 1;
1083			}
1084			else
1085			{
1086				$this->error=$this->db->error();
1087				dol_syslog("Commande::set_date_livraison ".$this->error,LOG_ERR);
1088				return -1;
1089			}
1090		}
1091		else
1092		{
1093			return -2;
1094		}
1095	}
1096
1097	/**
1098	 * Fetch deliveries method and return an array. Load array this->meths(rowid=>label).
1099	 *
1100	 * @return	void
1101	 */
1102	function fetch_delivery_methods()
1103	{
1104		global $langs;
1105		$meths = array();
1106
1107		$sql = "SELECT em.rowid, em.code, em.libelle";
1108		$sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
1109		$sql.= " WHERE em.active = 1";
1110		$sql.= " ORDER BY em.libelle ASC";
1111
1112		$resql = $this->db->query($sql);
1113		if ($resql)
1114		{
1115			while ($obj = $this->db->fetch_object($resql))
1116			{
1117				$label=$langs->trans('SendingMethod'.$obj->code);
1118				$this->meths[$obj->rowid] = ($label != 'SendingMethod'.$obj->code?$label:$obj->libelle);
1119			}
1120		}
1121	}
1122
1123	/**
1124	 *	Get tracking url status
1125	 *
1126	 *	@return	void
1127	 */
1128	function GetUrlTrackingStatus($value='')
1129	{
1130		$code='';
1131
1132		if (! empty($this->expedition_method_id))
1133		{
1134			$sql = "SELECT em.code";
1135			$sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
1136			$sql.= " WHERE em.rowid = ".$this->expedition_method_id;
1137
1138			$resql = $this->db->query($sql);
1139			if ($resql)
1140			{
1141				if ($obj = $this->db->fetch_object($resql))
1142				{
1143					$code = $obj->code;
1144				}
1145			}
1146		}
1147
1148		if ($code)
1149		{
1150			$classname = "methode_expedition_".strtolower($code);
1151
1152			$url='';
1153			if (file_exists(DOL_DOCUMENT_ROOT."/core/modules/expedition/methode_expedition_".strtolower($code).".modules.php") && ! empty($this->tracking_number))
1154			{
1155				require_once(DOL_DOCUMENT_ROOT."/core/modules/expedition/methode_expedition_".strtolower($code).".modules.php");
1156				$shipmethod = new $classname();
1157				$url = $shipmethod->provider_url_status($this->tracking_number);
1158			}
1159
1160			if ($url)
1161			{
1162				$this->tracking_url = sprintf('<a target="_blank" href="%s">'.($value?$value:'url').'</a>',$url,$url);
1163			}
1164			else
1165			{
1166				$this->tracking_url = $value;
1167			}
1168		}
1169		else
1170		{
1171			$this->tracking_url = $value;
1172		}
1173	}
1174}
1175
1176
1177/**
1178 * Classe de gestion des lignes de bons d'expedition
1179 */
1180class ExpeditionLigne
1181{
1182	var $db;
1183
1184	// From llx_expeditiondet
1185	var $qty;
1186	var $qty_shipped;
1187	var $fk_product;
1188
1189	// From llx_commandedet or llx_propaldet
1190	var $qty_asked;
1191	var $libelle;       // Label produit
1192	var $product_desc;  // Description produit
1193	var $ref;
1194
1195
1196	function ExpeditionLigne($DB)
1197	{
1198		$this->db=$DB;
1199	}
1200
1201}
1202
1203?>