expedition.class.php 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237
  1. <?php
  2. /* Copyright (C) 2003-2008 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.com>
  4. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
  5. * Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  6. * Copyright (C) 2011-2016 Juanjo Menent <jmenent@2byte.es>
  7. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  8. * Copyright (C) 2014 Cedric GROSS <c.gross@kreiz-it.fr>
  9. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  10. * Copyright (C) 2014-2015 Francis Appels <francis.appels@yahoo.com>
  11. * Copyright (C) 2015 Claudio Aschieri <c.aschieri@19.coop>
  12. * Copyright (C) 2016 Ferran Marcet <fmarcet@2byte.es>
  13. *
  14. * This program is free software; you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation; either version 3 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public License
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  26. */
  27. /**
  28. * \file htdocs/expedition/class/expedition.class.php
  29. * \ingroup expedition
  30. * \brief Fichier de la classe de gestion des expeditions
  31. */
  32. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  33. require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
  34. if (! empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  35. if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  36. if (! empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php';
  37. /**
  38. * Class to manage shipments
  39. */
  40. class Expedition extends CommonObject
  41. {
  42. public $element="shipping";
  43. public $fk_element="fk_expedition";
  44. public $table_element="expedition";
  45. public $table_element_line="expeditiondet";
  46. protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  47. var $socid;
  48. var $ref_customer;
  49. var $ref_int;
  50. var $brouillon;
  51. var $entrepot_id;
  52. var $lines=array();
  53. var $tracking_number;
  54. var $tracking_url;
  55. var $billed;
  56. var $model_pdf;
  57. var $trueWeight;
  58. var $weight_units;
  59. var $trueWidth;
  60. var $width_units;
  61. var $trueHeight;
  62. var $height_units;
  63. var $trueDepth;
  64. var $depth_units;
  65. // A denormalized value
  66. var $trueSize;
  67. var $date_delivery; // Date delivery planed
  68. /**
  69. * @deprecated
  70. * @see date_shipping
  71. */
  72. var $date;
  73. /**
  74. * @deprecated
  75. * @see date_shipping
  76. */
  77. var $date_expedition;
  78. /**
  79. * Effective delivery date
  80. * @var int
  81. */
  82. public $date_shipping;
  83. var $date_creation;
  84. var $date_valid;
  85. var $meths;
  86. var $listmeths; // List of carriers
  87. const STATUS_DRAFT = 0;
  88. const STATUS_VALIDATED = 1;
  89. const STATUS_CLOSED = 2;
  90. /**
  91. * Constructor
  92. *
  93. * @param DoliDB $db Database handler
  94. */
  95. function __construct($db)
  96. {
  97. $this->db = $db;
  98. $this->lines = array();
  99. $this->products = array();
  100. // List of long language codes for status
  101. $this->statuts = array();
  102. $this->statuts[-1] = 'StatusSendingCanceled';
  103. $this->statuts[0] = 'StatusSendingDraft';
  104. $this->statuts[1] = 'StatusSendingValidated';
  105. $this->statuts[2] = 'StatusSendingProcessed';
  106. }
  107. /**
  108. * Return next contract ref
  109. *
  110. * @param Societe $soc Thirdparty object
  111. * @return string Free reference for contract
  112. */
  113. function getNextNumRef($soc)
  114. {
  115. global $langs, $conf;
  116. $langs->load("sendings");
  117. if (!empty($conf->global->EXPEDITION_ADDON_NUMBER))
  118. {
  119. $mybool = false;
  120. $file = $conf->global->EXPEDITION_ADDON_NUMBER.".php";
  121. $classname = $conf->global->EXPEDITION_ADDON_NUMBER;
  122. // Include file with class
  123. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  124. foreach ($dirmodels as $reldir) {
  125. $dir = dol_buildpath($reldir."core/modules/expedition/");
  126. // Load file with numbering class (if found)
  127. $mybool|=@include_once $dir.$file;
  128. }
  129. if (! $mybool)
  130. {
  131. dol_print_error('',"Failed to include file ".$file);
  132. return '';
  133. }
  134. $obj = new $classname();
  135. $numref = "";
  136. $numref = $obj->getNextValue($soc,$this);
  137. if ( $numref != "")
  138. {
  139. return $numref;
  140. }
  141. else
  142. {
  143. dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  144. return "";
  145. }
  146. }
  147. else
  148. {
  149. print $langs->trans("Error")." ".$langs->trans("Error_EXPEDITION_ADDON_NUMBER_NotDefined");
  150. return "";
  151. }
  152. }
  153. /**
  154. * Create expedition en base
  155. *
  156. * @param User $user Objet du user qui cree
  157. * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers
  158. * @return int <0 si erreur, id expedition creee si ok
  159. */
  160. function create($user, $notrigger=0)
  161. {
  162. global $conf, $hookmanager;
  163. $now=dol_now();
  164. require_once DOL_DOCUMENT_ROOT .'/product/stock/class/mouvementstock.class.php';
  165. $error = 0;
  166. // Clean parameters
  167. $this->brouillon = 1;
  168. $this->tracking_number = dol_sanitizeFileName($this->tracking_number);
  169. $this->user = $user;
  170. $this->db->begin();
  171. $sql = "INSERT INTO ".MAIN_DB_PREFIX."expedition (";
  172. $sql.= "ref";
  173. $sql.= ", entity";
  174. $sql.= ", ref_customer";
  175. $sql.= ", ref_int";
  176. $sql.= ", date_creation";
  177. $sql.= ", fk_user_author";
  178. $sql.= ", date_expedition";
  179. $sql.= ", date_delivery";
  180. $sql.= ", fk_soc";
  181. $sql.= ", fk_address";
  182. $sql.= ", fk_shipping_method";
  183. $sql.= ", tracking_number";
  184. $sql.= ", weight";
  185. $sql.= ", size";
  186. $sql.= ", width";
  187. $sql.= ", height";
  188. $sql.= ", weight_units";
  189. $sql.= ", size_units";
  190. $sql.= ", note_private";
  191. $sql.= ", note_public";
  192. $sql.= ", model_pdf";
  193. $sql.= ", fk_incoterms, location_incoterms";
  194. $sql.= ") VALUES (";
  195. $sql.= "'(PROV)'";
  196. $sql.= ", ".$conf->entity;
  197. $sql.= ", ".($this->ref_customer?"'".$this->db->escape($this->ref_customer)."'":"null");
  198. $sql.= ", ".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null");
  199. $sql.= ", '".$this->db->idate($now)."'";
  200. $sql.= ", ".$user->id;
  201. $sql.= ", ".($this->date_expedition>0?"'".$this->db->idate($this->date_expedition)."'":"null");
  202. $sql.= ", ".($this->date_delivery>0?"'".$this->db->idate($this->date_delivery)."'":"null");
  203. $sql.= ", ".$this->socid;
  204. $sql.= ", ".($this->fk_delivery_address>0?$this->fk_delivery_address:"null");
  205. $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:"null");
  206. $sql.= ", '".$this->db->escape($this->tracking_number)."'";
  207. $sql.= ", ".$this->weight;
  208. $sql.= ", ".$this->sizeS; // TODO Should use this->trueDepth
  209. $sql.= ", ".$this->sizeW; // TODO Should use this->trueWidth
  210. $sql.= ", ".$this->sizeH; // TODO Should use this->trueHeight
  211. $sql.= ", ".$this->weight_units;
  212. $sql.= ", ".$this->size_units;
  213. $sql.= ", ".(!empty($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null");
  214. $sql.= ", ".(!empty($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null");
  215. $sql.= ", ".(!empty($this->model_pdf)?"'".$this->db->escape($this->model_pdf)."'":"null");
  216. $sql.= ", ".(int) $this->fk_incoterms;
  217. $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
  218. $sql.= ")";
  219. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  220. $resql=$this->db->query($sql);
  221. if ($resql)
  222. {
  223. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."expedition");
  224. $sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
  225. $sql.= " SET ref = '(PROV".$this->id.")'";
  226. $sql.= " WHERE rowid = ".$this->id;
  227. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  228. if ($this->db->query($sql))
  229. {
  230. // Insertion des lignes
  231. $num=count($this->lines);
  232. for ($i = 0; $i < $num; $i++)
  233. {
  234. if (! isset($this->lines[$i]->detail_batch))
  235. { // no batch management
  236. if (! $this->create_line($this->lines[$i]->entrepot_id, $this->lines[$i]->origin_line_id, $this->lines[$i]->qty, $this->lines[$i]->array_options) > 0)
  237. {
  238. $error++;
  239. }
  240. }
  241. else
  242. { // with batch management
  243. if (! $this->create_line_batch($this->lines[$i],$this->lines[$i]->array_options) > 0)
  244. {
  245. $error++;
  246. }
  247. }
  248. }
  249. if (! $error && $this->id && $this->origin_id)
  250. {
  251. $ret = $this->add_object_linked();
  252. if (!$ret)
  253. {
  254. $error++;
  255. }
  256. }
  257. // Actions on extra fields (by external module or standard code)
  258. // TODO le hook fait double emploi avec le trigger !!
  259. $hookmanager->initHooks(array('expeditiondao'));
  260. $parameters=array('socid'=>$this->id);
  261. $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  262. if (empty($reshook))
  263. {
  264. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
  265. {
  266. $result=$this->insertExtraFields();
  267. if ($result < 0)
  268. {
  269. $error++;
  270. }
  271. }
  272. }
  273. else if ($reshook < 0) $error++;
  274. if (! $error && ! $notrigger)
  275. {
  276. // Call trigger
  277. $result=$this->call_trigger('SHIPPING_CREATE',$user);
  278. if ($result < 0) { $error++; }
  279. // End call triggers
  280. if (! $error)
  281. {
  282. $this->db->commit();
  283. return $this->id;
  284. }
  285. else
  286. {
  287. foreach($this->errors as $errmsg)
  288. {
  289. dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
  290. $this->error.=($this->error?', '.$errmsg:$errmsg);
  291. }
  292. $this->db->rollback();
  293. return -1*$error;
  294. }
  295. }
  296. else
  297. {
  298. $error++;
  299. $this->error=$this->db->lasterror()." - sql=$sql";
  300. $this->db->rollback();
  301. return -3;
  302. }
  303. }
  304. else
  305. {
  306. $error++;
  307. $this->error=$this->db->lasterror()." - sql=$sql";
  308. $this->db->rollback();
  309. return -2;
  310. }
  311. }
  312. else
  313. {
  314. $error++;
  315. $this->error=$this->db->error()." - sql=$sql";
  316. $this->db->rollback();
  317. return -1;
  318. }
  319. }
  320. /**
  321. * Create a expedition line
  322. *
  323. * @param int $entrepot_id Id of warehouse
  324. * @param int $origin_line_id Id of source line
  325. * @param int $qty Quantity
  326. * @param array $array_options extrafields array
  327. * @return int <0 if KO, >0 if OK
  328. */
  329. function create_line($entrepot_id, $origin_line_id, $qty,$array_options=0)
  330. {
  331. global $conf;
  332. $error = 0;
  333. $sql = "INSERT INTO ".MAIN_DB_PREFIX."expeditiondet (";
  334. $sql.= "fk_expedition";
  335. $sql.= ", fk_entrepot";
  336. $sql.= ", fk_origin_line";
  337. $sql.= ", qty";
  338. $sql.= ") VALUES (";
  339. $sql.= $this->id;
  340. $sql.= ", ".($entrepot_id?$entrepot_id:'null');
  341. $sql.= ", ".$origin_line_id;
  342. $sql.= ", ".$qty;
  343. $sql.= ")";
  344. dol_syslog(get_class($this)."::create_line", LOG_DEBUG);
  345. if (! $this->db->query($sql))
  346. {
  347. $error++;
  348. }
  349. if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
  350. {
  351. $expeditionline = new ExpeditionLigne($this->db);
  352. $expeditionline->array_options=$array_options;
  353. $expeditionline->id= $this->db->last_insert_id(MAIN_DB_PREFIX.$expeditionline->table_element);
  354. $result=$expeditionline->insertExtraFields();
  355. if ($result < 0)
  356. {
  357. $this->error[]=$expeditionline->error;
  358. $error++;
  359. }
  360. }
  361. if (! $error) return 1;
  362. else return -1;
  363. }
  364. /**
  365. * Create the detail (eat-by date) of the expedition line
  366. *
  367. * @param object $line_ext full line informations
  368. * @param array $array_options extrafields array
  369. * @return int <0 if KO, >0 if OK
  370. */
  371. function create_line_batch($line_ext,$array_options=0)
  372. {
  373. $error = 0;
  374. $stockLocationQty = array(); // associated array with batch qty in stock location
  375. $tab=$line_ext->detail_batch;
  376. // create stockLocation Qty array
  377. foreach ($tab as $detbatch)
  378. {
  379. if ($detbatch->entrepot_id)
  380. {
  381. $stockLocationQty[$detbatch->entrepot_id] += $detbatch->dluo_qty;
  382. }
  383. }
  384. // create shipment lines
  385. foreach ($stockLocationQty as $stockLocation => $qty)
  386. {
  387. if ($this->create_line($stockLocation,$line_ext->origin_line_id,$qty,$array_options) < 0)
  388. {
  389. $error++;
  390. }
  391. else
  392. {
  393. // create shipment batch lines for stockLocation
  394. $line_id= $this->db->last_insert_id(MAIN_DB_PREFIX."expeditiondet");
  395. foreach ($tab as $detbatch)
  396. {
  397. if ($detbatch->entrepot_id == $stockLocation){
  398. if (! ($detbatch->create($line_id) >0)) // Create an expeditionlinebatch
  399. {
  400. $error++;
  401. }
  402. }
  403. }
  404. }
  405. }
  406. if (! $error) return 1;
  407. else return -1;
  408. }
  409. /**
  410. * Get object and lines from database
  411. *
  412. * @param int $id Id of object to load
  413. * @param string $ref Ref of object
  414. * @param string $ref_ext External reference of object
  415. * @param string $ref_int Internal reference of other object
  416. * @return int >0 if OK, 0 if not found, <0 if KO
  417. */
  418. function fetch($id, $ref='', $ref_ext='', $ref_int='')
  419. {
  420. global $conf;
  421. // Check parameters
  422. if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
  423. $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";
  424. $sql.= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height";
  425. $sql.= ", e.date_expedition as date_expedition, e.model_pdf, e.fk_address, e.date_delivery";
  426. $sql.= ", e.fk_shipping_method, e.tracking_number";
  427. $sql.= ", el.fk_source as origin_id, el.sourcetype as origin";
  428. $sql.= ", e.note_private, e.note_public";
  429. $sql.= ', e.fk_incoterms, e.location_incoterms';
  430. $sql.= ', i.libelle as libelle_incoterms';
  431. $sql.= " FROM ".MAIN_DB_PREFIX."expedition as e";
  432. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = e.rowid AND el.targettype = '".$this->element."'";
  433. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON e.fk_incoterms = i.rowid';
  434. $sql.= " WHERE e.entity IN (".getEntity('expedition', 1).")";
  435. if ($id) $sql.= " AND e.rowid=".$id;
  436. if ($ref) $sql.= " AND e.ref='".$this->db->escape($ref)."'";
  437. if ($ref_ext) $sql.= " AND e.ref_ext='".$this->db->escape($ref_ext)."'";
  438. if ($ref_int) $sql.= " AND e.ref_int='".$this->db->escape($ref_int)."'";
  439. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  440. $result = $this->db->query($sql);
  441. if ($result)
  442. {
  443. if ($this->db->num_rows($result))
  444. {
  445. $obj = $this->db->fetch_object($result);
  446. $this->id = $obj->rowid;
  447. $this->ref = $obj->ref;
  448. $this->socid = $obj->socid;
  449. $this->ref_customer = $obj->ref_customer;
  450. $this->ref_ext = $obj->ref_ext;
  451. $this->ref_int = $obj->ref_int;
  452. $this->statut = $obj->fk_statut;
  453. $this->user_author_id = $obj->fk_user_author;
  454. $this->date_creation = $this->db->jdate($obj->date_creation);
  455. $this->date = $this->db->jdate($obj->date_expedition); // TODO deprecated
  456. $this->date_expedition = $this->db->jdate($obj->date_expedition); // TODO deprecated
  457. $this->date_shipping = $this->db->jdate($obj->date_expedition); // Date real
  458. $this->date_delivery = $this->db->jdate($obj->date_delivery); // Date planed
  459. $this->fk_delivery_address = $obj->fk_address;
  460. $this->modelpdf = $obj->model_pdf;
  461. $this->shipping_method_id = $obj->fk_shipping_method;
  462. $this->tracking_number = $obj->tracking_number;
  463. $this->origin = ($obj->origin?$obj->origin:'commande'); // For compatibility
  464. $this->origin_id = $obj->origin_id;
  465. $this->billed = ($obj->fk_statut==2?1:0);
  466. $this->trueWeight = $obj->weight;
  467. $this->weight_units = $obj->weight_units;
  468. $this->trueWidth = $obj->width;
  469. $this->width_units = $obj->size_units;
  470. $this->trueHeight = $obj->height;
  471. $this->height_units = $obj->size_units;
  472. $this->trueDepth = $obj->size;
  473. $this->depth_units = $obj->size_units;
  474. $this->note_public = $obj->note_public;
  475. $this->note_private = $obj->note_private;
  476. // A denormalized value
  477. $this->trueSize = $obj->size."x".$obj->width."x".$obj->height;
  478. $this->size_units = $obj->size_units;
  479. //Incoterms
  480. $this->fk_incoterms = $obj->fk_incoterms;
  481. $this->location_incoterms = $obj->location_incoterms;
  482. $this->libelle_incoterms = $obj->libelle_incoterms;
  483. $this->db->free($result);
  484. if ($this->statut == 0) $this->brouillon = 1;
  485. $file = $conf->expedition->dir_output . "/" .get_exdir($this->id, 2, 0, 0, $this, 'shipment') . "/" . $this->id.".pdf";
  486. $this->pdf_filename = $file;
  487. // Tracking url
  488. $this->GetUrlTrackingStatus($obj->tracking_number);
  489. /*
  490. * Thirparty
  491. */
  492. $result=$this->fetch_thirdparty();
  493. // Retrieve all extrafields for expedition
  494. // fetch optionals attributes and labels
  495. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  496. $extrafields=new ExtraFields($this->db);
  497. $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
  498. $this->fetch_optionals($this->id,$extralabels);
  499. /*
  500. * Lines
  501. */
  502. $result=$this->fetch_lines();
  503. if ($result < 0)
  504. {
  505. return -3;
  506. }
  507. return 1;
  508. }
  509. else
  510. {
  511. dol_syslog(get_class($this).'::Fetch no expedition found', LOG_ERR);
  512. $this->error='Delivery with id '.$id.' not found';
  513. return 0;
  514. }
  515. }
  516. else
  517. {
  518. $this->error=$this->db->error();
  519. return -1;
  520. }
  521. }
  522. /**
  523. * Validate object and update stock if option enabled
  524. *
  525. * @param User $user Object user that validate
  526. * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers
  527. * @return int <0 if OK, >0 if KO
  528. */
  529. function valid($user, $notrigger=0)
  530. {
  531. global $conf, $langs;
  532. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  533. dol_syslog(get_class($this)."::valid");
  534. // Protection
  535. if ($this->statut)
  536. {
  537. dol_syslog(get_class($this)."::valid no draft status", LOG_WARNING);
  538. return 0;
  539. }
  540. if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->creer))
  541. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->expedition->shipping_advance->validate))))
  542. {
  543. $this->error='Permission denied';
  544. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  545. return -1;
  546. }
  547. $this->db->begin();
  548. $error = 0;
  549. // Define new ref
  550. $soc = new Societe($this->db);
  551. $soc->fetch($this->socid);
  552. // Class of company linked to order
  553. $result=$soc->set_as_client();
  554. // Define new ref
  555. if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
  556. {
  557. $numref = $this->getNextNumRef($soc);
  558. }
  559. else
  560. {
  561. $numref = "EXP".$this->id;
  562. }
  563. $this->newref = $numref;
  564. $now=dol_now();
  565. // Validate
  566. $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
  567. $sql.= " ref='".$numref."'";
  568. $sql.= ", fk_statut = 1";
  569. $sql.= ", date_valid = '".$this->db->idate($now)."'";
  570. $sql.= ", fk_user_valid = ".$user->id;
  571. $sql.= " WHERE rowid = ".$this->id;
  572. dol_syslog(get_class($this)."::valid update expedition", LOG_DEBUG);
  573. $resql=$this->db->query($sql);
  574. if (! $resql)
  575. {
  576. $this->error=$this->db->lasterror();
  577. $error++;
  578. }
  579. // If stock increment is done on sending (recommanded choice)
  580. if (! $error && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT))
  581. {
  582. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  583. $langs->load("agenda");
  584. // Loop on each product line to add a stock movement
  585. // TODO in future, shipment lines may not be linked to order line
  586. $sql = "SELECT cd.fk_product, cd.subprice,";
  587. $sql.= " ed.rowid, ed.qty, ed.fk_entrepot,";
  588. $sql.= " edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
  589. $sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
  590. $sql.= " ".MAIN_DB_PREFIX."expeditiondet as ed";
  591. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
  592. $sql.= " WHERE ed.fk_expedition = ".$this->id;
  593. $sql.= " AND cd.rowid = ed.fk_origin_line";
  594. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  595. $resql=$this->db->query($sql);
  596. if ($resql)
  597. {
  598. $cpt = $this->db->num_rows($resql);
  599. for ($i = 0; $i < $cpt; $i++)
  600. {
  601. $obj = $this->db->fetch_object($resql);
  602. if (empty($obj->edbrowid))
  603. {
  604. $qty = $obj->qty;
  605. }
  606. else
  607. {
  608. $qty = $obj->edbqty;
  609. }
  610. if ($qty <= 0) continue;
  611. dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
  612. //var_dump($this->lines[$i]);
  613. $mouvS = new MouvementStock($this->db);
  614. $mouvS->origin = &$this;
  615. if (empty($obj->edbrowid))
  616. {
  617. // line without batch detail
  618. // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record.
  619. $result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentValidatedInDolibarr",$numref));
  620. if ($result < 0) {
  621. $error++;
  622. $this->errors[]=$mouvS->error;
  623. break;
  624. }
  625. }
  626. else
  627. {
  628. // line with batch detail
  629. // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record.
  630. // Note: ->fk_origin_stock = id into table llx_product_batch (may be rename into llx_product_stock_batch in another version)
  631. $result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentValidatedInDolibarr",$numref), '', $obj->eatby, $obj->sellby, $obj->batch, $obj->fk_origin_stock);
  632. if ($result < 0) {
  633. $error++;
  634. $this->errors[]=$mouvS->error;
  635. break;
  636. }
  637. }
  638. }
  639. }
  640. else
  641. {
  642. $this->db->rollback();
  643. $this->error=$this->db->error();
  644. return -2;
  645. }
  646. // FIXME Set status of order to "delivered" if check box "set order as delivered if remain to ship is 0" is on and if sum of all validated shipment = products or order to ship (because we are in case of stock movement on shipment validation)
  647. }
  648. // Change status of order to "shipment in process"
  649. $ret = $this->setStatut(Commande::STATUS_SHIPMENTONPROCESS, $this->origin_id, $this->origin);
  650. if (! $ret)
  651. {
  652. $error++;
  653. }
  654. if (! $error && ! $notrigger)
  655. {
  656. // Call trigger
  657. $result=$this->call_trigger('SHIPPING_VALIDATE',$user);
  658. if ($result < 0) { $error++; }
  659. // End call triggers
  660. }
  661. if (! $error)
  662. {
  663. $this->oldref = $this->ref;
  664. // Rename directory if dir was a temporary ref
  665. if (preg_match('/^[\(]?PROV/i', $this->ref))
  666. {
  667. // On renomme repertoire ($this->ref = ancienne ref, $numfa = nouvelle ref)
  668. // in order not to lose the attached files
  669. $oldref = dol_sanitizeFileName($this->ref);
  670. $newref = dol_sanitizeFileName($numref);
  671. $dirsource = $conf->expedition->dir_output.'/sending/'.$oldref;
  672. $dirdest = $conf->expedition->dir_output.'/sending/'.$newref;
  673. if (file_exists($dirsource))
  674. {
  675. dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
  676. if (@rename($dirsource, $dirdest))
  677. {
  678. dol_syslog("Rename ok");
  679. // Rename docs starting with $oldref with $newref
  680. $listoffiles=dol_dir_list($conf->expedition->dir_output.'/sending/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/'));
  681. foreach($listoffiles as $fileentry)
  682. {
  683. $dirsource=$fileentry['name'];
  684. $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource);
  685. $dirsource=$fileentry['path'].'/'.$dirsource;
  686. $dirdest=$fileentry['path'].'/'.$dirdest;
  687. @rename($dirsource, $dirdest);
  688. }
  689. }
  690. }
  691. }
  692. }
  693. // Set new ref and current status
  694. if (! $error)
  695. {
  696. $this->ref = $numref;
  697. $this->statut = 1;
  698. }
  699. if (! $error)
  700. {
  701. $this->db->commit();
  702. return 1;
  703. }
  704. else
  705. {
  706. foreach($this->errors as $errmsg)
  707. {
  708. dol_syslog(get_class($this)."::valid ".$errmsg, LOG_ERR);
  709. $this->error.=($this->error?', '.$errmsg:$errmsg);
  710. }
  711. $this->db->rollback();
  712. return -1*$error;
  713. }
  714. }
  715. /**
  716. * Create a delivery receipt from a shipment
  717. *
  718. * @param User $user User
  719. * @return int <0 if KO, >=0 if OK
  720. */
  721. function create_delivery($user)
  722. {
  723. global $conf;
  724. if ($conf->livraison_bon->enabled)
  725. {
  726. if ($this->statut == 1 || $this->statut == 2)
  727. {
  728. // Expedition validee
  729. include_once DOL_DOCUMENT_ROOT.'/livraison/class/livraison.class.php';
  730. $delivery = new Livraison($this->db);
  731. $result=$delivery->create_from_sending($user, $this->id);
  732. if ($result > 0)
  733. {
  734. return $result;
  735. }
  736. else
  737. {
  738. $this->error=$delivery->error;
  739. return $result;
  740. }
  741. }
  742. else return 0;
  743. }
  744. else return 0;
  745. }
  746. /**
  747. * Add a expedition line.
  748. * If STOCK_WAREHOUSE_NOT_REQUIRED_FOR_SHIPMENTS is set, you can add a shipment line, with no stock source defined
  749. * If STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT is not set, you can add a shipment line, even if not enough into stock
  750. *
  751. * @param int $entrepot_id Id of warehouse
  752. * @param int $id Id of source line (order line)
  753. * @param int $qty Quantity
  754. * @param array $array_options extrafields array
  755. * @return int <0 if KO, >0 if OK
  756. */
  757. function addline($entrepot_id, $id, $qty,$array_options=0)
  758. {
  759. global $conf, $langs;
  760. $num = count($this->lines);
  761. $line = new ExpeditionLigne($this->db);
  762. $line->entrepot_id = $entrepot_id;
  763. $line->origin_line_id = $id;
  764. $line->qty = $qty;
  765. $orderline = new OrderLine($this->db);
  766. $orderline->fetch($id);
  767. if (! empty($conf->stock->enabled) && ! empty($orderline->fk_product))
  768. {
  769. $fk_product = $orderline->fk_product;
  770. if (! ($entrepot_id > 0) && empty($conf->global->STOCK_WAREHOUSE_NOT_REQUIRED_FOR_SHIPMENTS))
  771. {
  772. $langs->load("errors");
  773. $this->error=$langs->trans("ErrorWarehouseRequiredIntoShipmentLine");
  774. return -1;
  775. }
  776. if ($conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT)
  777. {
  778. // Check must be done for stock of product into warehouse if $entrepot_id defined
  779. $product=new Product($this->db);
  780. $result=$product->fetch($fk_product);
  781. if ($entrepot_id > 0) {
  782. $product->load_stock();
  783. $product_stock = $product->stock_warehouse[$entrepot_id]->real;
  784. }
  785. else
  786. $product_stock = $product->stock_reel;
  787. $product_type=$product->type;
  788. if ($product_type == 0 && $product_stock < $qty)
  789. {
  790. $langs->load("errors");
  791. $this->error=$langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $product->ref);
  792. $this->db->rollback();
  793. return -3;
  794. }
  795. }
  796. }
  797. // extrafields
  798. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
  799. $line->array_options = $array_options;
  800. $this->lines[$num] = $line;
  801. }
  802. /**
  803. * Add a shipment line with batch record
  804. *
  805. * @param array $dbatch Array of value (key 'detail' -> Array, key 'qty' total quantity for line, key ix_l : original line index)
  806. * @param array $array_options extrafields array
  807. * @return int <0 if KO, >0 if OK
  808. */
  809. function addline_batch($dbatch,$array_options=0)
  810. {
  811. global $conf,$langs;
  812. $num = count($this->lines);
  813. if ($dbatch['qty']>0)
  814. {
  815. $line = new ExpeditionLigne($this->db);
  816. $tab=array();
  817. foreach ($dbatch['detail'] as $key=>$value)
  818. {
  819. if ($value['q']>0)
  820. {
  821. // $value['q']=qty to move
  822. // $value['id_batch']=id into llx_product_batch of record to move
  823. //var_dump($value);
  824. $linebatch = new ExpeditionLineBatch($this->db);
  825. $ret=$linebatch->fetchFromStock($value['id_batch']); // load serial, sellby, eatby
  826. if ($ret<0)
  827. {
  828. $this->error=$linebatch->error;
  829. return -1;
  830. }
  831. $linebatch->dluo_qty=$value['q'];
  832. $tab[]=$linebatch;
  833. if ($conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT)
  834. {
  835. require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
  836. $prod_batch = new Productbatch($this->db);
  837. $prod_batch->fetch($value['id_batch']);
  838. if ($prod_batch->qty < $linebatch->dluo_qty)
  839. {
  840. $langs->load("errors");
  841. $this->errors[]=$langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $prod_batch->fk_product);
  842. dol_syslog(get_class($this)."::addline_batch error=Product ".$prod_batch->batch.": ".$this->errorsToString(), LOG_ERR);
  843. $this->db->rollback();
  844. return -1;
  845. }
  846. }
  847. //var_dump($linebatch);
  848. }
  849. }
  850. $line->entrepot_id = $linebatch->entrepot_id;
  851. $line->origin_line_id = $dbatch['ix_l'];
  852. $line->qty = $dbatch['qty'];
  853. $line->detail_batch=$tab;
  854. // extrafields
  855. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options)>0) // For avoid conflicts if trigger used
  856. $line->array_options = $array_options;
  857. //var_dump($line);
  858. $this->lines[$num] = $line;
  859. return 1;
  860. }
  861. }
  862. /**
  863. * Update database
  864. *
  865. * @param User $user User that modify
  866. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  867. * @return int <0 if KO, >0 if OK
  868. */
  869. function update($user=null, $notrigger=0)
  870. {
  871. global $conf;
  872. $error=0;
  873. // Clean parameters
  874. if (isset($this->ref)) $this->ref=trim($this->ref);
  875. if (isset($this->entity)) $this->entity=trim($this->entity);
  876. if (isset($this->ref_customer)) $this->ref_customer=trim($this->ref_customer);
  877. if (isset($this->socid)) $this->socid=trim($this->socid);
  878. if (isset($this->fk_user_author)) $this->fk_user_author=trim($this->fk_user_author);
  879. if (isset($this->fk_user_valid)) $this->fk_user_valid=trim($this->fk_user_valid);
  880. if (isset($this->fk_delivery_address)) $this->fk_delivery_address=trim($this->fk_delivery_address);
  881. if (isset($this->shipping_method_id)) $this->shipping_method_id=trim($this->shipping_method_id);
  882. if (isset($this->tracking_number)) $this->tracking_number=trim($this->tracking_number);
  883. if (isset($this->statut)) $this->statut=(int) $this->statut;
  884. if (isset($this->trueDepth)) $this->trueDepth=trim($this->trueDepth);
  885. if (isset($this->trueWidth)) $this->trueWidth=trim($this->trueWidth);
  886. if (isset($this->trueHeight)) $this->trueHeight=trim($this->trueHeight);
  887. if (isset($this->size_units)) $this->size_units=trim($this->size_units);
  888. if (isset($this->weight_units)) $this->weight_units=trim($this->weight_units);
  889. if (isset($this->trueWeight)) $this->weight=trim($this->trueWeight);
  890. if (isset($this->note_private)) $this->note=trim($this->note_private);
  891. if (isset($this->note_public)) $this->note=trim($this->note_public);
  892. if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf);
  893. // Check parameters
  894. // Put here code to add control on parameters values
  895. // Update request
  896. $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
  897. $sql.= " tms=".(dol_strlen($this->tms)!=0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
  898. $sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
  899. $sql.= " ref_customer=".(isset($this->ref_customer)?"'".$this->db->escape($this->ref_customer)."'":"null").",";
  900. $sql.= " fk_soc=".(isset($this->socid)?$this->socid:"null").",";
  901. $sql.= " date_creation=".(dol_strlen($this->date_creation)!=0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
  902. $sql.= " fk_user_author=".(isset($this->fk_user_author)?$this->fk_user_author:"null").",";
  903. $sql.= " date_valid=".(dol_strlen($this->date_valid)!=0 ? "'".$this->db->idate($this->date_valid)."'" : 'null').",";
  904. $sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->fk_user_valid:"null").",";
  905. $sql.= " date_expedition=".(dol_strlen($this->date_expedition)!=0 ? "'".$this->db->idate($this->date_expedition)."'" : 'null').",";
  906. $sql.= " date_delivery=".(dol_strlen($this->date_delivery)!=0 ? "'".$this->db->idate($this->date_delivery)."'" : 'null').",";
  907. $sql.= " fk_address=".(isset($this->fk_delivery_address)?$this->fk_delivery_address:"null").",";
  908. $sql.= " fk_shipping_method=".((isset($this->shipping_method_id) && $this->shipping_method_id > 0)?$this->shipping_method_id:"null").",";
  909. $sql.= " tracking_number=".(isset($this->tracking_number)?"'".$this->db->escape($this->tracking_number)."'":"null").",";
  910. $sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
  911. $sql.= " height=".(($this->trueHeight != '')?$this->trueHeight:"null").",";
  912. $sql.= " width=".(($this->trueWidth != '')?$this->trueWidth:"null").",";
  913. $sql.= " size_units=".(isset($this->size_units)?$this->size_units:"null").",";
  914. $sql.= " size=".(($this->trueDepth != '')?$this->trueDepth:"null").",";
  915. $sql.= " weight_units=".(isset($this->weight_units)?$this->weight_units:"null").",";
  916. $sql.= " weight=".(($this->trueWeight != '')?$this->trueWeight:"null").",";
  917. $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").",";
  918. $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
  919. $sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").",";
  920. $sql.= " entity=".$conf->entity;
  921. $sql.= " WHERE rowid=".$this->id;
  922. $this->db->begin();
  923. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  924. $resql = $this->db->query($sql);
  925. if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
  926. if (! $error)
  927. {
  928. if (! $notrigger)
  929. {
  930. // Call trigger
  931. $result=$this->call_trigger('SHIPPING_MODIFY',$user);
  932. if ($result < 0) { $error++; }
  933. // End call triggers
  934. }
  935. }
  936. // Commit or rollback
  937. if ($error)
  938. {
  939. foreach($this->errors as $errmsg)
  940. {
  941. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  942. $this->error.=($this->error?', '.$errmsg:$errmsg);
  943. }
  944. $this->db->rollback();
  945. return -1*$error;
  946. }
  947. else
  948. {
  949. $this->db->commit();
  950. return 1;
  951. }
  952. }
  953. /**
  954. * Delete shipment.
  955. * Warning, do not delete a shipment if a delivery is linked to (with table llx_element_element)
  956. *
  957. * @return int >0 if OK, 0 if deletion done but failed to delete files, <0 if KO
  958. */
  959. function delete()
  960. {
  961. global $conf, $langs, $user;
  962. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  963. if ($conf->productbatch->enabled)
  964. {
  965. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php';
  966. }
  967. $error=0;
  968. $this->error='';
  969. // Add a protection to refuse deleting if shipment has at least one delivery
  970. $this->fetchObjectLinked($this->id, 'shipping', 0, 'delivery'); // Get deliveries linked to this shipment
  971. if (count($this->linkedObjectsIds) > 0)
  972. {
  973. $this->error='ErrorThereIsSomeDeliveries';
  974. return -1;
  975. }
  976. $this->db->begin();
  977. // Stock control
  978. if ($conf->stock->enabled && $conf->global->STOCK_CALCULATE_ON_SHIPMENT && $this->statut > 0)
  979. {
  980. require_once(DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php");
  981. $langs->load("agenda");
  982. // Loop on each product line to add a stock movement
  983. $sql = "SELECT cd.fk_product, cd.subprice, ed.qty, ed.fk_entrepot, ed.rowid as expeditiondet_id";
  984. $sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
  985. $sql.= " ".MAIN_DB_PREFIX."expeditiondet as ed";
  986. $sql.= " WHERE ed.fk_expedition = ".$this->id;
  987. $sql.= " AND cd.rowid = ed.fk_origin_line";
  988. dol_syslog(get_class($this)."::delete select details", LOG_DEBUG);
  989. $resql=$this->db->query($sql);
  990. if ($resql)
  991. {
  992. $cpt = $this->db->num_rows($resql);
  993. for ($i = 0; $i < $cpt; $i++)
  994. {
  995. dol_syslog(get_class($this)."::delete movement index ".$i);
  996. $obj = $this->db->fetch_object($resql);
  997. $mouvS = new MouvementStock($this->db);
  998. // we do not log origin because it will be deleted
  999. $mouvS->origin = null;
  1000. // get lot/serial
  1001. $lotArray = null;
  1002. if ($conf->productbatch->enabled)
  1003. {
  1004. $lotArray = ExpeditionLineBatch::fetchAll($this->db,$obj->expeditiondet_id);
  1005. if (! is_array($lotArray))
  1006. {
  1007. $error++;$this->errors[]="Error ".$this->db->lasterror();
  1008. }
  1009. }
  1010. if (empty($lotArray)) {
  1011. // no lot/serial
  1012. // We increment stock of product (and sub-products)
  1013. // We use warehouse selected for each line
  1014. $result=$mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, 0, $langs->trans("ShipmentDeletedInDolibarr", $this->ref)); // Price is set to 0, because we don't want to see WAP changed
  1015. if ($result < 0)
  1016. {
  1017. $error++;$this->errors=$this->errors + $mouvS->errors;
  1018. break;
  1019. }
  1020. }
  1021. else
  1022. {
  1023. // We increment stock of batches
  1024. // We use warehouse selected for each line
  1025. foreach($lotArray as $lot)
  1026. {
  1027. $result=$mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $lot->dluo_qty, 0, $langs->trans("ShipmentDeletedInDolibarr", $this->ref), $lot->eatby, $lot->sellby, $lot->batch); // Price is set to 0, because we don't want to see WAP changed
  1028. if ($result < 0)
  1029. {
  1030. $error++;$this->errors=$this->errors + $mouvS->errors;
  1031. break;
  1032. }
  1033. }
  1034. if ($error) break; // break for loop incase of error
  1035. }
  1036. }
  1037. }
  1038. else
  1039. {
  1040. $error++;$this->errors[]="Error ".$this->db->lasterror();
  1041. }
  1042. }
  1043. // delete batch expedition line
  1044. if (! $error && $conf->productbatch->enabled)
  1045. {
  1046. if (ExpeditionLineBatch::deletefromexp($this->db,$this->id) < 0)
  1047. {
  1048. $error++;$this->errors[]="Error ".$this->db->lasterror();
  1049. }
  1050. }
  1051. if (! $error)
  1052. {
  1053. $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet";
  1054. $sql.= " WHERE fk_expedition = ".$this->id;
  1055. if ( $this->db->query($sql) )
  1056. {
  1057. // Delete linked object
  1058. $res = $this->deleteObjectLinked();
  1059. if ($res < 0) $error++;
  1060. if (! $error)
  1061. {
  1062. $sql = "DELETE FROM ".MAIN_DB_PREFIX."expedition";
  1063. $sql.= " WHERE rowid = ".$this->id;
  1064. if ($this->db->query($sql))
  1065. {
  1066. // Call trigger
  1067. $result=$this->call_trigger('SHIPPING_DELETE',$user);
  1068. if ($result < 0) { $error++; }
  1069. // End call triggers
  1070. if (! empty($this->origin) && $this->origin_id > 0)
  1071. {
  1072. $this->fetch_origin();
  1073. $origin=$this->origin;
  1074. if ($this->$origin->statut == Commande::STATUS_SHIPMENTONPROCESS) // If order source of shipment is "shipment in progress"
  1075. {
  1076. // Check if there is no more shipment. If not, we can move back status of order to "validated" instead of "shipment in progress"
  1077. $this->$origin->loadExpeditions();
  1078. //var_dump($this->$origin->expeditions);exit;
  1079. if (count($this->$origin->expeditions) <= 0)
  1080. {
  1081. $this->$origin->setStatut(Commande::STATUS_VALIDATED);
  1082. }
  1083. }
  1084. }
  1085. if (! $error)
  1086. {
  1087. $this->db->commit();
  1088. // We delete PDFs
  1089. $ref = dol_sanitizeFileName($this->ref);
  1090. if (! empty($conf->expedition->dir_output))
  1091. {
  1092. $dir = $conf->expedition->dir_output . '/sending/' . $ref ;
  1093. $file = $dir . '/' . $ref . '.pdf';
  1094. if (file_exists($file))
  1095. {
  1096. if (! dol_delete_file($file))
  1097. {
  1098. return 0;
  1099. }
  1100. }
  1101. if (file_exists($dir))
  1102. {
  1103. if (!dol_delete_dir_recursive($dir))
  1104. {
  1105. $this->error=$langs->trans("ErrorCanNotDeleteDir",$dir);
  1106. return 0;
  1107. }
  1108. }
  1109. }
  1110. return 1;
  1111. }
  1112. else
  1113. {
  1114. $this->db->rollback();
  1115. return -1;
  1116. }
  1117. }
  1118. else
  1119. {
  1120. $this->error=$this->db->lasterror()." - sql=$sql";
  1121. $this->db->rollback();
  1122. return -3;
  1123. }
  1124. }
  1125. else
  1126. {
  1127. $this->error=$this->db->lasterror()." - sql=$sql";
  1128. $this->db->rollback();
  1129. return -2;
  1130. }
  1131. }
  1132. else
  1133. {
  1134. $this->error=$this->db->lasterror()." - sql=$sql";
  1135. $this->db->rollback();
  1136. return -1;
  1137. }
  1138. }
  1139. else
  1140. {
  1141. $this->db->rollback();
  1142. return -1;
  1143. }
  1144. }
  1145. /**
  1146. * Load lines
  1147. *
  1148. * @return int >0 if OK, Otherwise if KO
  1149. */
  1150. function fetch_lines()
  1151. {
  1152. global $conf, $mysoc;
  1153. // TODO: recuperer les champs du document associe a part
  1154. $sql = "SELECT cd.rowid, cd.fk_product, cd.label as custom_label, cd.description, cd.qty as qty_asked, cd.product_type";
  1155. $sql.= ", cd.total_ht, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.total_tva";
  1156. $sql.= ", cd.tva_tx, cd.localtax1_tx, cd.localtax2_tx, cd.price, cd.subprice, cd.remise_percent";
  1157. $sql.= ", ed.rowid as line_id, ed.qty as qty_shipped, ed.fk_origin_line, ed.fk_entrepot";
  1158. $sql.= ", p.ref as product_ref, p.label as product_label, p.fk_product_type";
  1159. $sql.= ", p.weight, p.weight_units, p.length, p.length_units, p.surface, p.surface_units, p.volume, p.volume_units, p.tobatch as product_tobatch";
  1160. $sql.= " FROM (".MAIN_DB_PREFIX."expeditiondet as ed,";
  1161. $sql.= " ".MAIN_DB_PREFIX."commandedet as cd)";
  1162. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = cd.fk_product";
  1163. $sql.= " WHERE ed.fk_expedition = ".$this->id;
  1164. $sql.= " AND ed.fk_origin_line = cd.rowid";
  1165. $sql.= " ORDER BY cd.rang, ed.fk_origin_line";
  1166. dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
  1167. $resql = $this->db->query($sql);
  1168. if ($resql)
  1169. {
  1170. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1171. $num = $this->db->num_rows($resql);
  1172. $i = 0;
  1173. $lineindex = 0;
  1174. $originline = 0;
  1175. $this->total_ht = 0;
  1176. $this->total_tva = 0;
  1177. $this->total_ttc = 0;
  1178. $this->total_localtax1 = 0;
  1179. $this->total_localtax2 = 0;
  1180. while ($i < $num)
  1181. {
  1182. $obj = $this->db->fetch_object($resql);
  1183. if ($originline == $obj->fk_origin_line) {
  1184. $line->entrepot_id = 0; // entrepod_id in details_entrepot
  1185. $line->qty_shipped += $obj->qty_shipped;
  1186. } else {
  1187. $line = new ExpeditionLigne($this->db);
  1188. $line->entrepot_id = $obj->fk_entrepot;
  1189. $line->qty_shipped = $obj->qty_shipped;
  1190. }
  1191. $detail_entrepot = new stdClass;
  1192. $detail_entrepot->entrepot_id = $obj->fk_entrepot;
  1193. $detail_entrepot->qty_shipped = $obj->qty_shipped;
  1194. $line->details_entrepot[] = $detail_entrepot;
  1195. $line->line_id = $obj->line_id;
  1196. $line->rowid = $obj->line_id; // TODO deprecated
  1197. $line->id = $obj->line_id;
  1198. $line->fk_origin_line = $obj->fk_origin_line;
  1199. $line->origin_line_id = $obj->fk_origin_line; // TODO deprecated
  1200. $line->product_type = $obj->product_type;
  1201. $line->fk_product = $obj->fk_product;
  1202. $line->fk_product_type = $obj->fk_product_type;
  1203. $line->ref = $obj->product_ref; // TODO deprecated
  1204. $line->product_ref = $obj->product_ref;
  1205. $line->product_label = $obj->product_label;
  1206. $line->libelle = $obj->product_label; // TODO deprecated
  1207. $line->product_tobatch = $obj->product_tobatch;
  1208. $line->label = $obj->custom_label;
  1209. $line->description = $obj->description;
  1210. $line->qty_asked = $obj->qty_asked;
  1211. $line->weight = $obj->weight;
  1212. $line->weight_units = $obj->weight_units;
  1213. $line->length = $obj->length;
  1214. $line->length_units = $obj->length_units;
  1215. $line->surface = $obj->surface;
  1216. $line->surface_units = $obj->surface_units;
  1217. $line->volume = $obj->volume;
  1218. $line->volume_units = $obj->volume_units;
  1219. // For invoicing
  1220. $tabprice = calcul_price_total($obj->qty_shipped, $obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->fk_product_type, $mysoc); // We force type to 0
  1221. $line->desc = $obj->description; // We need ->desc because some code into CommonObject use desc (property defined for other elements)
  1222. $line->qty = $line->qty_shipped;
  1223. $line->total_ht = $tabprice[0];
  1224. $line->total_localtax1 = $tabprice[9];
  1225. $line->total_localtax2 = $tabprice[10];
  1226. $line->total_ttc = $tabprice[2];
  1227. $line->total_tva = $tabprice[1];
  1228. $line->tva_tx = $obj->tva_tx;
  1229. $line->localtax1_tx = $obj->localtax1_tx;
  1230. $line->localtax2_tx = $obj->localtax2_tx;
  1231. $line->price = $obj->price;
  1232. $line->subprice = $obj->subprice;
  1233. $line->remise_percent = $obj->remise_percent;
  1234. $this->total_ht+= $tabprice[0];
  1235. $this->total_tva+= $tabprice[1];
  1236. $this->total_ttc+= $tabprice[2];
  1237. $this->total_localtax1+= $tabprice[9];
  1238. $this->total_localtax2+= $tabprice[10];
  1239. if ($originline != $obj->fk_origin_line)
  1240. {
  1241. $line->detail_batch = array();
  1242. }
  1243. // Eat-by date
  1244. if (! empty($conf->productbatch->enabled) && $obj->line_id > 0)
  1245. {
  1246. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php';
  1247. $newdetailbatch = ExpeditionLineBatch::fetchAll($this->db,$obj->line_id);
  1248. if (is_array($newdetailbatch))
  1249. {
  1250. if ($originline != $obj->fk_origin_line)
  1251. {
  1252. $line->detail_batch = $newdetailbatch;
  1253. }
  1254. else
  1255. {
  1256. $line->detail_batch = array_merge($line->detail_batch, $newdetailbatch);
  1257. }
  1258. }
  1259. }
  1260. if ($originline != $obj->fk_origin_line)
  1261. {
  1262. $this->lines[$lineindex] = $line;
  1263. $lineindex++;
  1264. }
  1265. else
  1266. {
  1267. $line->total_ht += $tabprice[0];
  1268. $line->total_localtax1 += $tabprice[9];
  1269. $line->total_localtax2 += $tabprice[10];
  1270. $line->total_ttc += $tabprice[2];
  1271. $line->total_tva += $tabprice[1];
  1272. }
  1273. $i++;
  1274. $originline = $obj->fk_origin_line;
  1275. }
  1276. $this->db->free($resql);
  1277. return 1;
  1278. }
  1279. else
  1280. {
  1281. $this->error=$this->db->error();
  1282. return -3;
  1283. }
  1284. }
  1285. /**
  1286. * Return clicable link of object (with eventually picto)
  1287. *
  1288. * @param int $withpicto Add picto into link
  1289. * @param int $option Where point the link
  1290. * @param int $max Max length to show
  1291. * @param int $short Use short labels
  1292. * @return string String with URL
  1293. */
  1294. function getNomUrl($withpicto=0,$option=0,$max=0,$short=0)
  1295. {
  1296. global $langs;
  1297. $result='';
  1298. $label = '<u>' . $langs->trans("ShowSending") . '</u>';
  1299. if (! empty($this->ref))
  1300. $label .= '<br><b>' . $langs->trans('Ref') . ':</b> '.$this->ref;
  1301. $url = DOL_URL_ROOT.'/expedition/card.php?id='.$this->id;
  1302. if ($short) return $url;
  1303. $linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
  1304. $linkend='</a>';
  1305. $picto='sending';
  1306. if ($withpicto) $result.=($linkstart.img_object($label, $picto, 'class="classfortooltip"').$linkend);
  1307. if ($withpicto && $withpicto != 2) $result.=' ';
  1308. $result.=$linkstart.$this->ref.$linkend;
  1309. return $result;
  1310. }
  1311. /**
  1312. * Return status label
  1313. *
  1314. * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
  1315. * @return string Libelle
  1316. */
  1317. function getLibStatut($mode=0)
  1318. {
  1319. return $this->LibStatut($this->statut,$mode);
  1320. }
  1321. /**
  1322. * Return label of a status
  1323. *
  1324. * @param int $statut Id statut
  1325. * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
  1326. * @return string Label of status
  1327. */
  1328. function LibStatut($statut,$mode)
  1329. {
  1330. global $langs;
  1331. if ($mode==0)
  1332. {
  1333. if ($statut==0) return $langs->trans($this->statuts[$statut]);
  1334. if ($statut==1) return $langs->trans($this->statuts[$statut]);
  1335. if ($statut==2) return $langs->trans($this->statuts[$statut]);
  1336. }
  1337. if ($mode==1)
  1338. {
  1339. if ($statut==0) return $langs->trans('StatusSendingDraftShort');
  1340. if ($statut==1) return $langs->trans('StatusSendingValidatedShort');
  1341. if ($statut==2) return $langs->trans('StatusSendingProcessedShort');
  1342. }
  1343. if ($mode == 3)
  1344. {
  1345. if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0');
  1346. if ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut4');
  1347. if ($statut==2) return img_picto($langs->trans('StatusSendingProcessed'),'statut6');
  1348. }
  1349. if ($mode == 4)
  1350. {
  1351. if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]);
  1352. if ($statut==1) return img_picto($langs->trans($this->statuts[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]);
  1353. if ($statut==2) return img_picto($langs->trans('StatusSendingProcessed'),'statut6').' '.$langs->trans('StatusSendingProcessed');
  1354. }
  1355. if ($mode == 5)
  1356. {
  1357. if ($statut==0) return $langs->trans('StatusSendingDraftShort').' '.img_picto($langs->trans($this->statuts[$statut]),'statut0');
  1358. if ($statut==1) return $langs->trans('StatusSendingValidatedShort').' '.img_picto($langs->trans($this->statuts[$statut]),'statut4');
  1359. if ($statut==2) return $langs->trans('StatusSendingProcessedShort').' '.img_picto($langs->trans('StatusSendingProcessedShort'),'statut6');
  1360. }
  1361. }
  1362. /**
  1363. * Initialise an instance with random values.
  1364. * Used to build previews or test instances.
  1365. * id must be 0 if object instance is a specimen.
  1366. *
  1367. * @return void
  1368. */
  1369. function initAsSpecimen()
  1370. {
  1371. global $langs;
  1372. $now=dol_now();
  1373. dol_syslog(get_class($this)."::initAsSpecimen");
  1374. // Load array of products prodids
  1375. $num_prods = 0;
  1376. $prodids = array();
  1377. $sql = "SELECT rowid";
  1378. $sql.= " FROM ".MAIN_DB_PREFIX."product";
  1379. $sql.= " WHERE entity IN (".getEntity('product', 1).")";
  1380. $resql = $this->db->query($sql);
  1381. if ($resql)
  1382. {
  1383. $num_prods = $this->db->num_rows($resql);
  1384. $i = 0;
  1385. while ($i < $num_prods)
  1386. {
  1387. $i++;
  1388. $row = $this->db->fetch_row($resql);
  1389. $prodids[$i] = $row[0];
  1390. }
  1391. }
  1392. $order=new Commande($this->db);
  1393. $order->initAsSpecimen();
  1394. // Initialise parametres
  1395. $this->id=0;
  1396. $this->ref = 'SPECIMEN';
  1397. $this->specimen=1;
  1398. $this->statut = 1;
  1399. $this->livraison_id = 0;
  1400. $this->date = $now;
  1401. $this->date_creation = $now;
  1402. $this->date_valid = $now;
  1403. $this->date_delivery = $now;
  1404. $this->date_expedition = $now + 24*3600;
  1405. $this->entrepot_id = 0;
  1406. $this->fk_delivery_address = 0;
  1407. $this->socid = 1;
  1408. $this->commande_id = 0;
  1409. $this->commande = $order;
  1410. $this->origin_id = 1;
  1411. $this->origin = 'commande';
  1412. $this->note_private = 'Private note';
  1413. $this->note_public = 'Public note';
  1414. $nbp = 5;
  1415. $xnbp = 0;
  1416. while ($xnbp < $nbp)
  1417. {
  1418. $line=new ExpeditionLigne($this->db);
  1419. $line->desc=$langs->trans("Description")." ".$xnbp;
  1420. $line->libelle=$langs->trans("Description")." ".$xnbp;
  1421. $line->qty=10;
  1422. $line->qty_asked=5;
  1423. $line->qty_shipped=4;
  1424. $line->fk_product=$this->commande->lines[$xnbp]->fk_product;
  1425. $this->lines[]=$line;
  1426. $xnbp++;
  1427. }
  1428. }
  1429. /**
  1430. * Set the planned delivery date
  1431. *
  1432. * @param User $user Objet utilisateur qui modifie
  1433. * @param timestamp $date_livraison Date de livraison
  1434. * @return int <0 if KO, >0 if OK
  1435. */
  1436. function set_date_livraison($user, $date_livraison)
  1437. {
  1438. if ($user->rights->expedition->creer)
  1439. {
  1440. $sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
  1441. $sql.= " SET date_delivery = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null');
  1442. $sql.= " WHERE rowid = ".$this->id;
  1443. dol_syslog(get_class($this)."::set_date_livraison", LOG_DEBUG);
  1444. $resql=$this->db->query($sql);
  1445. if ($resql)
  1446. {
  1447. $this->date_delivery = $date_livraison;
  1448. return 1;
  1449. }
  1450. else
  1451. {
  1452. $this->error=$this->db->error();
  1453. return -1;
  1454. }
  1455. }
  1456. else
  1457. {
  1458. return -2;
  1459. }
  1460. }
  1461. /**
  1462. * Fetch deliveries method and return an array. Load array this->meths(rowid=>label).
  1463. *
  1464. * @return void
  1465. */
  1466. function fetch_delivery_methods()
  1467. {
  1468. global $langs;
  1469. $this->meths = array();
  1470. $sql = "SELECT em.rowid, em.code, em.libelle";
  1471. $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
  1472. $sql.= " WHERE em.active = 1";
  1473. $sql.= " ORDER BY em.libelle ASC";
  1474. $resql = $this->db->query($sql);
  1475. if ($resql)
  1476. {
  1477. while ($obj = $this->db->fetch_object($resql))
  1478. {
  1479. $label=$langs->trans('SendingMethod'.$obj->code);
  1480. $this->meths[$obj->rowid] = ($label != 'SendingMethod'.$obj->code?$label:$obj->libelle);
  1481. }
  1482. }
  1483. }
  1484. /**
  1485. * Fetch all deliveries method and return an array. Load array this->listmeths.
  1486. *
  1487. * @param id $id only this carrier, all if none
  1488. * @return void
  1489. */
  1490. function list_delivery_methods($id='')
  1491. {
  1492. global $langs;
  1493. $this->listmeths = array();
  1494. $i=0;
  1495. $sql = "SELECT em.rowid, em.code, em.libelle, em.description, em.tracking, em.active";
  1496. $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
  1497. if ($id!='') $sql.= " WHERE em.rowid=".$id;
  1498. $resql = $this->db->query($sql);
  1499. if ($resql)
  1500. {
  1501. while ($obj = $this->db->fetch_object($resql))
  1502. {
  1503. $this->listmeths[$i]['rowid'] = $obj->rowid;
  1504. $this->listmeths[$i]['code'] = $obj->code;
  1505. $label=$langs->trans('SendingMethod'.$obj->code);
  1506. $this->listmeths[$i]['libelle'] = ($label != 'SendingMethod'.$obj->code?$label:$obj->libelle);
  1507. $this->listmeths[$i]['description'] = $obj->description;
  1508. $this->listmeths[$i]['tracking'] = $obj->tracking;
  1509. $this->listmeths[$i]['active'] = $obj->active;
  1510. $i++;
  1511. }
  1512. }
  1513. }
  1514. /**
  1515. * Update/create delivery method.
  1516. *
  1517. * @param string $id id method to activate
  1518. *
  1519. * @return void
  1520. */
  1521. function update_delivery_method($id='')
  1522. {
  1523. if ($id=='')
  1524. {
  1525. $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_shipment_mode (code, libelle, description, tracking)";
  1526. $sql.=" VALUES ('".$this->update['code']."','".$this->update['libelle']."','".$this->update['description']."','".$this->update['tracking']."')";
  1527. $resql = $this->db->query($sql);
  1528. }
  1529. else
  1530. {
  1531. $sql = "UPDATE ".MAIN_DB_PREFIX."c_shipment_mode SET";
  1532. $sql.= " code='".$this->update['code']."'";
  1533. $sql.= ",libelle='".$this->update['libelle']."'";
  1534. $sql.= ",description='".$this->update['description']."'";
  1535. $sql.= ",tracking='".$this->update['tracking']."'";
  1536. $sql.= " WHERE rowid=".$id;
  1537. $resql = $this->db->query($sql);
  1538. }
  1539. if ($resql < 0) dol_print_error($this->db,'');
  1540. }
  1541. /**
  1542. * Activate delivery method.
  1543. *
  1544. * @param id $id id method to activate
  1545. *
  1546. * @return void
  1547. */
  1548. function activ_delivery_method($id)
  1549. {
  1550. $sql = 'UPDATE '.MAIN_DB_PREFIX.'c_shipment_mode SET active=1';
  1551. $sql.= ' WHERE rowid='.$id;
  1552. $resql = $this->db->query($sql);
  1553. }
  1554. /**
  1555. * DesActivate delivery method.
  1556. *
  1557. * @param id $id id method to desactivate
  1558. *
  1559. * @return void
  1560. */
  1561. function disable_delivery_method($id)
  1562. {
  1563. $sql = 'UPDATE '.MAIN_DB_PREFIX.'c_shipment_mode SET active=0';
  1564. $sql.= ' WHERE rowid='.$id;
  1565. $resql = $this->db->query($sql);
  1566. }
  1567. /**
  1568. * Forge an set tracking url
  1569. *
  1570. * @param string $value Value
  1571. * @return void
  1572. */
  1573. function GetUrlTrackingStatus($value='')
  1574. {
  1575. if (! empty($this->shipping_method_id))
  1576. {
  1577. $sql = "SELECT em.code, em.tracking";
  1578. $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
  1579. $sql.= " WHERE em.rowid = ".$this->shipping_method_id;
  1580. $resql = $this->db->query($sql);
  1581. if ($resql)
  1582. {
  1583. if ($obj = $this->db->fetch_object($resql))
  1584. {
  1585. $tracking = $obj->tracking;
  1586. }
  1587. }
  1588. }
  1589. if (!empty($tracking) && !empty($value))
  1590. {
  1591. $url = str_replace('{TRACKID}', $value, $tracking);
  1592. $this->tracking_url = sprintf('<a target="_blank" href="%s">'.($value?$value:'url').'</a>',$url,$url);
  1593. }
  1594. else
  1595. {
  1596. $this->tracking_url = $value;
  1597. }
  1598. }
  1599. /**
  1600. * Classify the shipping as closed.
  1601. *
  1602. * @return int <0 if KO, >0 if OK
  1603. */
  1604. function setClosed()
  1605. {
  1606. global $conf,$langs,$user;
  1607. $error=0;
  1608. $this->db->begin();
  1609. $sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET fk_statut='.self::STATUS_CLOSED;
  1610. $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0';
  1611. $resql=$this->db->query($sql);
  1612. if ($resql)
  1613. {
  1614. // Set order billed if 100% of order is shipped (qty in shipment lines match qty in order lines)
  1615. if ($this->origin == 'commande' && $this->origin_id > 0)
  1616. {
  1617. $order = new Commande($this->db);
  1618. $order->fetch($this->origin_id);
  1619. $order->loadExpeditions(self::STATUS_CLOSED); // Fill $order->expeditions = array(orderlineid => qty)
  1620. $shipments_match_order = 1;
  1621. foreach($order->lines as $line)
  1622. {
  1623. $lineid = $line->id;
  1624. $qty = $line->qty;
  1625. if (($line->product_type == 0 || ! empty($conf->global->STOCK_SUPPORTS_SERVICES)) && $order->expeditions[$lineid] != $qty)
  1626. {
  1627. $shipments_match_order = 0;
  1628. $text='Qty for order line id '.$lineid.' is '.$qty.'. However in the shipments with status Expedition::STATUS_CLOSED='.self::STATUS_CLOSED.' we have qty = '.$order->expeditions[$lineid].', so we can t close order';
  1629. dol_syslog($text);
  1630. break;
  1631. }
  1632. }
  1633. if ($shipments_match_order)
  1634. {
  1635. dol_syslog("Qty for the ".count($order->lines)." lines of order have same value for shipments with status Expedition::STATUS_CLOSED=".self::STATUS_CLOSED.', so we close order');
  1636. $order->cloture($user);
  1637. }
  1638. }
  1639. $this->statut=self::STATUS_CLOSED;
  1640. // If stock increment is done on closing
  1641. if (! $error && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE))
  1642. {
  1643. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1644. $langs->load("agenda");
  1645. // Loop on each product line to add a stock movement
  1646. // TODO possibilite d'expedier a partir d'une propale ou autre origine ?
  1647. $sql = "SELECT cd.fk_product, cd.subprice,";
  1648. $sql.= " ed.rowid, ed.qty, ed.fk_entrepot,";
  1649. $sql.= " edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
  1650. $sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
  1651. $sql.= " ".MAIN_DB_PREFIX."expeditiondet as ed";
  1652. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
  1653. $sql.= " WHERE ed.fk_expedition = ".$this->id;
  1654. $sql.= " AND cd.rowid = ed.fk_origin_line";
  1655. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  1656. $resql=$this->db->query($sql);
  1657. if ($resql)
  1658. {
  1659. $cpt = $this->db->num_rows($resql);
  1660. for ($i = 0; $i < $cpt; $i++)
  1661. {
  1662. $obj = $this->db->fetch_object($resql);
  1663. if (empty($obj->edbrowid))
  1664. {
  1665. $qty = $obj->qty;
  1666. }
  1667. else
  1668. {
  1669. $qty = $obj->edbqty;
  1670. }
  1671. if ($qty <= 0) continue;
  1672. dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
  1673. $mouvS = new MouvementStock($this->db);
  1674. $mouvS->origin = &$this;
  1675. if (empty($obj->edbrowid))
  1676. {
  1677. // line without batch detail
  1678. // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
  1679. $result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentClassifyClosedInDolibarr",$numref));
  1680. if ($result < 0) {
  1681. $this->error = $mouvS->error;
  1682. $this->errors = $mouvS->errors;
  1683. $error++; break;
  1684. }
  1685. }
  1686. else
  1687. {
  1688. // line with batch detail
  1689. // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
  1690. $result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentClassifyClosedInDolibarr",$numref), '', $obj->eatby, $obj->sellby, $obj->batch, $obj->fk_origin_stock);
  1691. if ($result < 0) {
  1692. $this->error = $mouvS->error;
  1693. $this->errors = $mouvS->errors;
  1694. $error++; break;
  1695. }
  1696. }
  1697. }
  1698. }
  1699. else
  1700. {
  1701. $this->error=$this->db->lasterror();
  1702. $error++;
  1703. }
  1704. }
  1705. // Call trigger
  1706. if (! $error)
  1707. {
  1708. $result=$this->call_trigger('SHIPPING_CLOSED',$user);
  1709. if ($result < 0) {
  1710. $error++;
  1711. }
  1712. }
  1713. }
  1714. else
  1715. {
  1716. dol_print_error($this->db);
  1717. $error++;
  1718. }
  1719. if (! $error)
  1720. {
  1721. $this->db->commit();
  1722. return 1;
  1723. }
  1724. else
  1725. {
  1726. $this->db->rollback();
  1727. return -1;
  1728. }
  1729. }
  1730. /**
  1731. * Classify the shipping as invoiced (used when WORKFLOW_BILL_ON_SHIPMENT is on)
  1732. *
  1733. * @return int <0 if ko, >0 if ok
  1734. */
  1735. function set_billed()
  1736. {
  1737. $error=0;
  1738. $this->db->begin();
  1739. $sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET fk_statut=2, billed=1'; // TODO Update only billed
  1740. $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0';
  1741. $resql=$this->db->query($sql);
  1742. if ($resql)
  1743. {
  1744. $this->statut=2;
  1745. $this->billed=1;
  1746. // Call trigger
  1747. $result=$this->call_trigger('SHIPPING_BILLED',$user);
  1748. if ($result < 0) {
  1749. $error++;
  1750. }
  1751. } else {
  1752. $error++;
  1753. $this->errors[]=$this->db->lasterror;
  1754. }
  1755. if (empty($error)) {
  1756. $this->db->commit();
  1757. return 1;
  1758. }
  1759. else
  1760. {
  1761. $this->db->rollback();
  1762. return -1;
  1763. }
  1764. }
  1765. /**
  1766. * Classify the shipping as validated/opened
  1767. *
  1768. * @return int <0 if ko, >0 if ok
  1769. */
  1770. function reOpen()
  1771. {
  1772. global $conf,$langs,$user;
  1773. $error=0;
  1774. $this->db->begin();
  1775. $sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET fk_statut=1';
  1776. $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0';
  1777. $resql=$this->db->query($sql);
  1778. if ($resql)
  1779. {
  1780. $this->statut=1;
  1781. $this->billed=0;
  1782. // If stock increment is done on closing
  1783. if (! $error && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE))
  1784. {
  1785. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1786. $langs->load("agenda");
  1787. // Loop on each product line to add a stock movement
  1788. // TODO possibilite d'expedier a partir d'une propale ou autre origine
  1789. $sql = "SELECT cd.fk_product, cd.subprice,";
  1790. $sql.= " ed.rowid, ed.qty, ed.fk_entrepot,";
  1791. $sql.= " edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
  1792. $sql.= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
  1793. $sql.= " ".MAIN_DB_PREFIX."expeditiondet as ed";
  1794. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
  1795. $sql.= " WHERE ed.fk_expedition = ".$this->id;
  1796. $sql.= " AND cd.rowid = ed.fk_origin_line";
  1797. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  1798. $resql=$this->db->query($sql);
  1799. if ($resql)
  1800. {
  1801. $cpt = $this->db->num_rows($resql);
  1802. for ($i = 0; $i < $cpt; $i++)
  1803. {
  1804. $obj = $this->db->fetch_object($resql);
  1805. if (empty($obj->edbrowid))
  1806. {
  1807. $qty = $obj->qty;
  1808. }
  1809. else
  1810. {
  1811. $qty = $obj->edbqty;
  1812. }
  1813. if ($qty <= 0) continue;
  1814. dol_syslog(get_class($this)."::reopen expedition movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
  1815. //var_dump($this->lines[$i]);
  1816. $mouvS = new MouvementStock($this->db);
  1817. $mouvS->origin = &$this;
  1818. if (empty($obj->edbrowid))
  1819. {
  1820. // line without batch detail
  1821. // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
  1822. $result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ShipmentUnClassifyCloseddInDolibarr",$numref));
  1823. if ($result < 0) {
  1824. $this->error = $mouvS->error;
  1825. $this->errors = $mouvS->errors;
  1826. $error++; break;
  1827. }
  1828. }
  1829. else
  1830. {
  1831. // line with batch detail
  1832. // We decrement stock of product (and sub-products) -> update table llx_product_stock (key of this table is fk_product+fk_entrepot) and add a movement record
  1833. $result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ShipmentUnClassifyCloseddInDolibarr",$numref), '', $obj->eatby, $obj->sellby, $obj->batch, $obj->fk_origin_stock);
  1834. if ($result < 0) {
  1835. $this->error = $mouvS->error;
  1836. $this->errors = $mouvS->errors;
  1837. $error++; break;
  1838. }
  1839. }
  1840. }
  1841. }
  1842. else
  1843. {
  1844. $this->error=$this->db->lasterror();
  1845. $error++;
  1846. }
  1847. }
  1848. if (! $error)
  1849. {
  1850. // Call trigger
  1851. $result=$this->call_trigger('SHIPPING_REOPEN',$user);
  1852. if ($result < 0) {
  1853. $error++;
  1854. }
  1855. }
  1856. } else {
  1857. $error++;
  1858. $this->errors[]=$this->db->lasterror();
  1859. }
  1860. if (! $error)
  1861. {
  1862. $this->db->commit();
  1863. return 1;
  1864. }
  1865. else
  1866. {
  1867. $this->db->rollback();
  1868. return -1;
  1869. }
  1870. }
  1871. /**
  1872. * Create a document onto disk according to template module.
  1873. *
  1874. * @param string $modele Force the model to using ('' to not force)
  1875. * @param Translate $outputlangs object lang to use for translations
  1876. * @param int $hidedetails Hide details of lines
  1877. * @param int $hidedesc Hide description
  1878. * @param int $hideref Hide ref
  1879. * @return int 0 if KO, 1 if OK
  1880. */
  1881. public function generateDocument($modele, $outputlangs,$hidedetails=0, $hidedesc=0, $hideref=0)
  1882. {
  1883. global $conf,$langs;
  1884. $langs->load("sendings");
  1885. // Sets the model on the model name to use
  1886. if (! dol_strlen($modele))
  1887. {
  1888. if (! empty($conf->global->EXPEDITION_ADDON_PDF))
  1889. {
  1890. $modele = $conf->global->EXPEDITION_ADDON_PDF;
  1891. }
  1892. else
  1893. {
  1894. $modele = 'rouget';
  1895. }
  1896. }
  1897. $modelpath = "core/modules/expedition/doc/";
  1898. $this->fetch_origin();
  1899. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1900. }
  1901. /**
  1902. * Function used to replace a thirdparty id with another one.
  1903. *
  1904. * @param DoliDB $db Database handler
  1905. * @param int $origin_id Old thirdparty id
  1906. * @param int $dest_id New thirdparty id
  1907. * @return bool
  1908. */
  1909. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  1910. {
  1911. $tables = array(
  1912. 'expedition'
  1913. );
  1914. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  1915. }
  1916. }
  1917. /**
  1918. * Classe de gestion des lignes de bons d'expedition
  1919. */
  1920. class ExpeditionLigne extends CommonObjectLine
  1921. {
  1922. var $db;
  1923. // From llx_expeditiondet
  1924. var $qty;
  1925. var $qty_shipped;
  1926. var $fk_product;
  1927. var $detail_batch;
  1928. // From llx_commandedet or llx_propaldet
  1929. var $qty_asked;
  1930. public $product_ref;
  1931. public $product_label;
  1932. public $product_desc;
  1933. // Invoicing
  1934. var $remise_percent;
  1935. var $total_ht; // Total net of tax
  1936. var $total_ttc; // Total with tax
  1937. var $total_tva; // Total VAT
  1938. var $total_localtax1; // Total Local tax 1
  1939. var $total_localtax2; // Total Local tax 2
  1940. public $element='expeditiondet';
  1941. public $table_element='expeditiondet';
  1942. public $fk_origin_line;
  1943. // Deprecated
  1944. /**
  1945. * @deprecated
  1946. * @see fk_origin_line
  1947. */
  1948. var $origin_line_id;
  1949. /**
  1950. * @deprecated
  1951. * @see product_ref
  1952. */
  1953. var $ref;
  1954. /**
  1955. * @deprecated
  1956. * @see product_label
  1957. */
  1958. var $libelle;
  1959. /**
  1960. * Constructor
  1961. *
  1962. * @param DoliDB $db Database handler
  1963. */
  1964. function __construct($db)
  1965. {
  1966. $this->db=$db;
  1967. }
  1968. }