PageRenderTime 155ms CodeModel.GetById 112ms app.highlight 33ms RepoModel.GetById 1ms app.codeStats 0ms

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

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