expedition.class.php 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080
  1. <?php
  2. /* Copyright (C) 2003-2008 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.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-2020 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-2017 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. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  14. * Copyright (C) 2018-2020 Frédéric France <frederic.france@netlogic.fr>
  15. * Copyright (C) 2020 Lenin Rivas <lenin@leninrivas.com>
  16. *
  17. * This program is free software; you can redistribute it and/or modify
  18. * it under the terms of the GNU General Public License as published by
  19. * the Free Software Foundation; either version 3 of the License, or
  20. * (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU General Public License
  28. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  29. */
  30. /**
  31. * \file htdocs/expedition/class/expedition.class.php
  32. * \ingroup expedition
  33. * \brief Fichier de la classe de gestion des expeditions
  34. */
  35. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  36. require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
  37. require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
  38. if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  39. if (!empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  40. if (!empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php';
  41. /**
  42. * Class to manage shipments
  43. */
  44. class Expedition extends CommonObject
  45. {
  46. use CommonIncoterm;
  47. /**
  48. * @var string ID to identify managed object
  49. */
  50. public $element = "shipping";
  51. /**
  52. * @var string Field with ID of parent key if this field has a parent
  53. */
  54. public $fk_element = "fk_expedition";
  55. /**
  56. * @var string Name of table without prefix where object is stored
  57. */
  58. public $table_element = "expedition";
  59. /**
  60. * @var string Name of subtable line
  61. */
  62. public $table_element_line = "expeditiondet";
  63. /**
  64. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  65. * @var int
  66. */
  67. public $ismultientitymanaged = 1;
  68. /**
  69. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  70. */
  71. public $picto = 'dolly';
  72. public $socid;
  73. /**
  74. * @var string Customer ref
  75. * @deprecated
  76. * @see $ref_customer
  77. */
  78. public $ref_client;
  79. /**
  80. * @var string Customer ref
  81. */
  82. public $ref_customer;
  83. /**
  84. * @var string internal ref
  85. * @deprecated
  86. */
  87. public $ref_int;
  88. public $brouillon;
  89. /**
  90. * @var int warehouse id
  91. */
  92. public $entrepot_id;
  93. /**
  94. * @var string Tracking number
  95. */
  96. public $tracking_number;
  97. /**
  98. * @var string Tracking url
  99. */
  100. public $tracking_url;
  101. public $billed;
  102. /**
  103. * @var string name of pdf model
  104. */
  105. public $model_pdf;
  106. public $trueWeight;
  107. public $weight_units;
  108. public $trueWidth;
  109. public $width_units;
  110. public $trueHeight;
  111. public $height_units;
  112. public $trueDepth;
  113. public $depth_units;
  114. // A denormalized value
  115. public $trueSize;
  116. /**
  117. * @var integer|string Date delivery planed
  118. */
  119. public $date_delivery;
  120. /**
  121. * @deprecated
  122. * @see $date_shipping
  123. */
  124. public $date;
  125. /**
  126. * @deprecated
  127. * @see $date_shipping
  128. */
  129. public $date_expedition;
  130. /**
  131. * Effective delivery date
  132. * @var integer|string
  133. */
  134. public $date_shipping;
  135. /**
  136. * @var integer|string date_creation
  137. */
  138. public $date_creation;
  139. /**
  140. * @var integer|string date_valid
  141. */
  142. public $date_valid;
  143. public $meths;
  144. public $listmeths; // List of carriers
  145. public $lines = array();
  146. /**
  147. * Draft status
  148. */
  149. const STATUS_DRAFT = 0;
  150. /**
  151. * Validated status
  152. */
  153. const STATUS_VALIDATED = 1;
  154. /**
  155. * Closed status
  156. */
  157. const STATUS_CLOSED = 2;
  158. /**
  159. * Canceled status
  160. */
  161. const STATUS_CANCELED = -1;
  162. /**
  163. * Constructor
  164. *
  165. * @param DoliDB $db Database handler
  166. */
  167. public function __construct($db)
  168. {
  169. global $conf;
  170. $this->db = $db;
  171. // List of long language codes for status
  172. $this->statuts = array();
  173. $this->statuts[-1] = 'StatusSendingCanceled';
  174. $this->statuts[0] = 'StatusSendingDraft';
  175. $this->statuts[1] = 'StatusSendingValidated';
  176. $this->statuts[2] = 'StatusSendingProcessed';
  177. // List of short language codes for status
  178. $this->statutshorts = array();
  179. $this->statutshorts[-1] = 'StatusSendingCanceledShort';
  180. $this->statutshorts[0] = 'StatusSendingDraftShort';
  181. $this->statutshorts[1] = 'StatusSendingValidatedShort';
  182. $this->statutshorts[2] = 'StatusSendingProcessedShort';
  183. }
  184. /**
  185. * Return next contract ref
  186. *
  187. * @param Societe $soc Thirdparty object
  188. * @return string Free reference for contract
  189. */
  190. public function getNextNumRef($soc)
  191. {
  192. global $langs, $conf;
  193. $langs->load("sendings");
  194. if (!empty($conf->global->EXPEDITION_ADDON_NUMBER))
  195. {
  196. $mybool = false;
  197. $file = $conf->global->EXPEDITION_ADDON_NUMBER.".php";
  198. $classname = $conf->global->EXPEDITION_ADDON_NUMBER;
  199. // Include file with class
  200. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  201. foreach ($dirmodels as $reldir) {
  202. $dir = dol_buildpath($reldir."core/modules/expedition/");
  203. // Load file with numbering class (if found)
  204. $mybool |= @include_once $dir.$file;
  205. }
  206. if (!$mybool)
  207. {
  208. dol_print_error('', "Failed to include file ".$file);
  209. return '';
  210. }
  211. $obj = new $classname();
  212. $numref = "";
  213. $numref = $obj->getNextValue($soc, $this);
  214. if ($numref != "")
  215. {
  216. return $numref;
  217. } else {
  218. dol_print_error($this->db, get_class($this)."::getNextNumRef ".$obj->error);
  219. return "";
  220. }
  221. } else {
  222. print $langs->trans("Error")." ".$langs->trans("Error_EXPEDITION_ADDON_NUMBER_NotDefined");
  223. return "";
  224. }
  225. }
  226. /**
  227. * Create expedition en base
  228. *
  229. * @param User $user Objet du user qui cree
  230. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  231. * @return int <0 si erreur, id expedition creee si ok
  232. */
  233. public function create($user, $notrigger = 0)
  234. {
  235. global $conf, $hookmanager;
  236. $now = dol_now();
  237. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  238. $error = 0;
  239. // Clean parameters
  240. $this->brouillon = 1;
  241. $this->tracking_number = dol_sanitizeFileName($this->tracking_number);
  242. if (empty($this->fk_project)) $this->fk_project = 0;
  243. $this->user = $user;
  244. $this->db->begin();
  245. $sql = "INSERT INTO ".MAIN_DB_PREFIX."expedition (";
  246. $sql .= "ref";
  247. $sql .= ", entity";
  248. $sql .= ", ref_customer";
  249. $sql .= ", ref_int";
  250. $sql .= ", ref_ext";
  251. $sql .= ", date_creation";
  252. $sql .= ", fk_user_author";
  253. $sql .= ", date_expedition";
  254. $sql .= ", date_delivery";
  255. $sql .= ", fk_soc";
  256. $sql .= ", fk_projet";
  257. $sql .= ", fk_address";
  258. $sql .= ", fk_shipping_method";
  259. $sql .= ", tracking_number";
  260. $sql .= ", weight";
  261. $sql .= ", size";
  262. $sql .= ", width";
  263. $sql .= ", height";
  264. $sql .= ", weight_units";
  265. $sql .= ", size_units";
  266. $sql .= ", note_private";
  267. $sql .= ", note_public";
  268. $sql .= ", model_pdf";
  269. $sql .= ", fk_incoterms, location_incoterms";
  270. $sql .= ") VALUES (";
  271. $sql .= "'(PROV)'";
  272. $sql .= ", ".$conf->entity;
  273. $sql .= ", ".($this->ref_customer ? "'".$this->db->escape($this->ref_customer)."'" : "null");
  274. $sql .= ", ".($this->ref_int ? "'".$this->db->escape($this->ref_int)."'" : "null");
  275. $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
  276. $sql .= ", '".$this->db->idate($now)."'";
  277. $sql .= ", ".$user->id;
  278. $sql .= ", ".($this->date_expedition > 0 ? "'".$this->db->idate($this->date_expedition)."'" : "null");
  279. $sql .= ", ".($this->date_delivery > 0 ? "'".$this->db->idate($this->date_delivery)."'" : "null");
  280. $sql .= ", ".$this->socid;
  281. $sql .= ", ".$this->fk_project;
  282. $sql .= ", ".($this->fk_delivery_address > 0 ? $this->fk_delivery_address : "null");
  283. $sql .= ", ".($this->shipping_method_id > 0 ? $this->shipping_method_id : "null");
  284. $sql .= ", '".$this->db->escape($this->tracking_number)."'";
  285. $sql .= ", ".(is_numeric($this->weight) ? $this->weight : 'NULL');
  286. $sql .= ", ".(is_numeric($this->sizeS) ? $this->sizeS : 'NULL'); // TODO Should use this->trueDepth
  287. $sql .= ", ".(is_numeric($this->sizeW) ? $this->sizeW : 'NULL'); // TODO Should use this->trueWidth
  288. $sql .= ", ".(is_numeric($this->sizeH) ? $this->sizeH : 'NULL'); // TODO Should use this->trueHeight
  289. $sql .= ", ".($this->weight_units != '' ? (int) $this->weight_units : 'NULL');
  290. $sql .= ", ".($this->size_units != '' ? (int) $this->size_units : 'NULL');
  291. $sql .= ", ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
  292. $sql .= ", ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
  293. $sql .= ", ".(!empty($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
  294. $sql .= ", ".(int) $this->fk_incoterms;
  295. $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
  296. $sql .= ")";
  297. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  298. $resql = $this->db->query($sql);
  299. if ($resql)
  300. {
  301. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."expedition");
  302. $sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
  303. $sql .= " SET ref = '(PROV".$this->id.")'";
  304. $sql .= " WHERE rowid = ".$this->id;
  305. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  306. if ($this->db->query($sql))
  307. {
  308. // Insert of lines
  309. $num = count($this->lines);
  310. for ($i = 0; $i < $num; $i++)
  311. {
  312. if (!isset($this->lines[$i]->detail_batch))
  313. { // no batch management
  314. if (!$this->create_line($this->lines[$i]->entrepot_id, $this->lines[$i]->origin_line_id, $this->lines[$i]->qty, $this->lines[$i]->rang, $this->lines[$i]->array_options) > 0)
  315. {
  316. $error++;
  317. }
  318. } else { // with batch management
  319. if (!$this->create_line_batch($this->lines[$i], $this->lines[$i]->array_options) > 0)
  320. {
  321. $error++;
  322. }
  323. }
  324. }
  325. if (!$error && $this->id && $this->origin_id)
  326. {
  327. $ret = $this->add_object_linked();
  328. if (!$ret)
  329. {
  330. $error++;
  331. }
  332. }
  333. // Actions on extra fields
  334. if (!$error)
  335. {
  336. $result = $this->insertExtraFields();
  337. if ($result < 0)
  338. {
  339. $error++;
  340. }
  341. }
  342. if (!$error && !$notrigger)
  343. {
  344. // Call trigger
  345. $result = $this->call_trigger('SHIPPING_CREATE', $user);
  346. if ($result < 0) { $error++; }
  347. // End call triggers
  348. if (!$error)
  349. {
  350. $this->db->commit();
  351. return $this->id;
  352. } else {
  353. foreach ($this->errors as $errmsg)
  354. {
  355. dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
  356. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  357. }
  358. $this->db->rollback();
  359. return -1 * $error;
  360. }
  361. } else {
  362. $error++;
  363. $this->error = $this->db->lasterror()." - sql=$sql";
  364. $this->db->rollback();
  365. return -3;
  366. }
  367. } else {
  368. $error++;
  369. $this->error = $this->db->lasterror()." - sql=$sql";
  370. $this->db->rollback();
  371. return -2;
  372. }
  373. } else {
  374. $error++;
  375. $this->error = $this->db->error()." - sql=$sql";
  376. $this->db->rollback();
  377. return -1;
  378. }
  379. }
  380. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  381. /**
  382. * Create a expedition line
  383. *
  384. * @param int $entrepot_id Id of warehouse
  385. * @param int $origin_line_id Id of source line
  386. * @param int $qty Quantity
  387. * @param int $rang Rang
  388. * @param array $array_options extrafields array
  389. * @return int <0 if KO, line_id if OK
  390. */
  391. public function create_line($entrepot_id, $origin_line_id, $qty, $rang = 0, $array_options = 0)
  392. {
  393. //phpcs:enable
  394. global $user;
  395. $expeditionline = new ExpeditionLigne($this->db);
  396. $expeditionline->fk_expedition = $this->id;
  397. $expeditionline->entrepot_id = $entrepot_id;
  398. $expeditionline->fk_origin_line = $origin_line_id;
  399. $expeditionline->qty = $qty;
  400. $expeditionline->rang = $rang;
  401. $expeditionline->array_options = $array_options;
  402. if (($lineId = $expeditionline->insert($user)) < 0)
  403. {
  404. $this->errors[] = $expeditionline->error;
  405. }
  406. return $lineId;
  407. }
  408. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  409. /**
  410. * Create the detail (eat-by date) of the expedition line
  411. *
  412. * @param object $line_ext full line informations
  413. * @param array $array_options extrafields array
  414. * @return int <0 if KO, >0 if OK
  415. */
  416. public function create_line_batch($line_ext, $array_options = 0)
  417. {
  418. // phpcs:enable
  419. $error = 0;
  420. $stockLocationQty = array(); // associated array with batch qty in stock location
  421. $tab = $line_ext->detail_batch;
  422. // create stockLocation Qty array
  423. foreach ($tab as $detbatch)
  424. {
  425. if ($detbatch->entrepot_id)
  426. {
  427. $stockLocationQty[$detbatch->entrepot_id] += $detbatch->qty;
  428. }
  429. }
  430. // create shipment lines
  431. foreach ($stockLocationQty as $stockLocation => $qty)
  432. {
  433. if (($line_id = $this->create_line($stockLocation, $line_ext->origin_line_id, $qty, $line_ext->rang, $array_options)) < 0)
  434. {
  435. $error++;
  436. } else {
  437. // create shipment batch lines for stockLocation
  438. foreach ($tab as $detbatch)
  439. {
  440. if ($detbatch->entrepot_id == $stockLocation) {
  441. if (!($detbatch->create($line_id) > 0)) // Create an expeditionlinebatch
  442. {
  443. $error++;
  444. }
  445. }
  446. }
  447. }
  448. }
  449. if (!$error) return 1;
  450. else return -1;
  451. }
  452. /**
  453. * Get object and lines from database
  454. *
  455. * @param int $id Id of object to load
  456. * @param string $ref Ref of object
  457. * @param string $ref_ext External reference of object
  458. * @param string $notused Internal reference of other object
  459. * @return int >0 if OK, 0 if not found, <0 if KO
  460. */
  461. public function fetch($id, $ref = '', $ref_ext = '', $notused = '')
  462. {
  463. global $conf;
  464. // Check parameters
  465. if (empty($id) && empty($ref) && empty($ref_ext)) return -1;
  466. $sql = "SELECT e.rowid, e.entity, 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, e.fk_projet as fk_project, e.billed";
  467. $sql .= ", e.date_valid";
  468. $sql .= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height";
  469. $sql .= ", e.date_expedition as date_expedition, e.model_pdf, e.fk_address, e.date_delivery";
  470. $sql .= ", e.fk_shipping_method, e.tracking_number";
  471. $sql .= ", e.note_private, e.note_public";
  472. $sql .= ', e.fk_incoterms, e.location_incoterms';
  473. $sql .= ', i.libelle as label_incoterms';
  474. $sql .= ', s.libelle as shipping_method';
  475. $sql .= ", el.fk_source as origin_id, el.sourcetype as origin";
  476. $sql .= " FROM ".MAIN_DB_PREFIX."expedition as e";
  477. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = e.rowid AND el.targettype = '".$this->db->escape($this->element)."'";
  478. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON e.fk_incoterms = i.rowid';
  479. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_shipment_mode as s ON e.fk_shipping_method = s.rowid';
  480. $sql .= " WHERE e.entity IN (".getEntity('expedition').")";
  481. if ($id) $sql .= " AND e.rowid=".$id;
  482. if ($ref) $sql .= " AND e.ref='".$this->db->escape($ref)."'";
  483. if ($ref_ext) $sql .= " AND e.ref_ext='".$this->db->escape($ref_ext)."'";
  484. if ($notused) $sql .= " AND e.ref_int='".$this->db->escape($notused)."'";
  485. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  486. $result = $this->db->query($sql);
  487. if ($result)
  488. {
  489. if ($this->db->num_rows($result))
  490. {
  491. $obj = $this->db->fetch_object($result);
  492. $this->id = $obj->rowid;
  493. $this->entity = $obj->entity;
  494. $this->ref = $obj->ref;
  495. $this->socid = $obj->socid;
  496. $this->ref_customer = $obj->ref_customer;
  497. $this->ref_ext = $obj->ref_ext;
  498. $this->ref_int = $obj->ref_int;
  499. $this->statut = $obj->fk_statut;
  500. $this->user_author_id = $obj->fk_user_author;
  501. $this->date_creation = $this->db->jdate($obj->date_creation);
  502. $this->date_valid = $this->db->jdate($obj->date_valid);
  503. $this->date = $this->db->jdate($obj->date_expedition); // TODO deprecated
  504. $this->date_expedition = $this->db->jdate($obj->date_expedition); // TODO deprecated
  505. $this->date_shipping = $this->db->jdate($obj->date_expedition); // Date real
  506. $this->date_delivery = $this->db->jdate($obj->date_delivery); // Date planed
  507. $this->fk_delivery_address = $obj->fk_address;
  508. $this->model_pdf = $obj->model_pdf;
  509. $this->modelpdf = $obj->model_pdf;
  510. $this->shipping_method_id = $obj->fk_shipping_method;
  511. $this->shipping_method = $obj->shipping_method;
  512. $this->tracking_number = $obj->tracking_number;
  513. $this->origin = ($obj->origin ? $obj->origin : 'commande'); // For compatibility
  514. $this->origin_id = $obj->origin_id;
  515. $this->billed = $obj->billed;
  516. $this->fk_project = $obj->fk_project;
  517. $this->trueWeight = $obj->weight;
  518. $this->weight_units = $obj->weight_units;
  519. $this->trueWidth = $obj->width;
  520. $this->width_units = $obj->size_units;
  521. $this->trueHeight = $obj->height;
  522. $this->height_units = $obj->size_units;
  523. $this->trueDepth = $obj->size;
  524. $this->depth_units = $obj->size_units;
  525. $this->note_public = $obj->note_public;
  526. $this->note_private = $obj->note_private;
  527. // A denormalized value
  528. $this->trueSize = $obj->size."x".$obj->width."x".$obj->height;
  529. $this->size_units = $obj->size_units;
  530. //Incoterms
  531. $this->fk_incoterms = $obj->fk_incoterms;
  532. $this->location_incoterms = $obj->location_incoterms;
  533. $this->label_incoterms = $obj->label_incoterms;
  534. $this->db->free($result);
  535. if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
  536. // Tracking url
  537. $this->getUrlTrackingStatus($obj->tracking_number);
  538. // Thirdparty
  539. $result = $this->fetch_thirdparty(); // TODO Remove this
  540. // Retrieve extrafields
  541. $this->fetch_optionals();
  542. // Fix Get multicurrency param for transmited
  543. if (!empty($conf->multicurrency->enabled))
  544. {
  545. if (!empty($this->multicurrency_code)) $this->multicurrency_code = $this->thirdparty->multicurrency_code;
  546. if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $this->multicurrency_tx = $this->thirdparty->multicurrency_tx;
  547. }
  548. /*
  549. * Lines
  550. */
  551. $result = $this->fetch_lines();
  552. if ($result < 0)
  553. {
  554. return -3;
  555. }
  556. return 1;
  557. } else {
  558. dol_syslog(get_class($this).'::Fetch no expedition found', LOG_ERR);
  559. $this->error = 'Delivery with id '.$id.' not found';
  560. return 0;
  561. }
  562. } else {
  563. $this->error = $this->db->error();
  564. return -1;
  565. }
  566. }
  567. /**
  568. * Validate object and update stock if option enabled
  569. *
  570. * @param User $user Object user that validate
  571. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  572. * @return int <0 if OK, >0 if KO
  573. */
  574. public function valid($user, $notrigger = 0)
  575. {
  576. global $conf, $langs;
  577. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  578. dol_syslog(get_class($this)."::valid");
  579. // Protection
  580. if ($this->statut)
  581. {
  582. dol_syslog(get_class($this)."::valid no draft status", LOG_WARNING);
  583. return 0;
  584. }
  585. if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->creer))
  586. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->shipping_advance->validate))))
  587. {
  588. $this->error = 'Permission denied';
  589. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  590. return -1;
  591. }
  592. $this->db->begin();
  593. $error = 0;
  594. // Define new ref
  595. $soc = new Societe($this->db);
  596. $soc->fetch($this->socid);
  597. // Class of company linked to order
  598. $result = $soc->set_as_client();
  599. // Define new ref
  600. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
  601. {
  602. $numref = $this->getNextNumRef($soc);
  603. } else {
  604. $numref = "EXP".$this->id;
  605. }
  606. $this->newref = dol_sanitizeFileName($numref);
  607. $now = dol_now();
  608. // Validate
  609. $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
  610. $sql .= " ref='".$this->db->escape($numref)."'";
  611. $sql .= ", fk_statut = 1";
  612. $sql .= ", date_valid = '".$this->db->idate($now)."'";
  613. $sql .= ", fk_user_valid = ".$user->id;
  614. $sql .= " WHERE rowid = ".$this->id;
  615. dol_syslog(get_class($this)."::valid update expedition", LOG_DEBUG);
  616. $resql = $this->db->query($sql);
  617. if (!$resql)
  618. {
  619. $this->error = $this->db->lasterror();
  620. $error++;
  621. }
  622. // If stock increment is done on sending (recommanded choice)
  623. if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT))
  624. {
  625. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  626. $langs->load("agenda");
  627. // Loop on each product line to add a stock movement
  628. $sql = "SELECT cd.fk_product, cd.subprice,";
  629. $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
  630. $sql .= " edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
  631. $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
  632. $sql .= " ".MAIN_DB_PREFIX."expeditiondet as ed";
  633. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
  634. $sql .= " WHERE ed.fk_expedition = ".$this->id;
  635. $sql .= " AND cd.rowid = ed.fk_origin_line";
  636. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  637. $resql = $this->db->query($sql);
  638. if ($resql)
  639. {
  640. $cpt = $this->db->num_rows($resql);
  641. for ($i = 0; $i < $cpt; $i++)
  642. {
  643. $obj = $this->db->fetch_object($resql);
  644. if (empty($obj->edbrowid))
  645. {
  646. $qty = $obj->qty;
  647. } else {
  648. $qty = $obj->edbqty;
  649. }
  650. if ($qty <= 0) continue;
  651. dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
  652. //var_dump($this->lines[$i]);
  653. $mouvS = new MouvementStock($this->db);
  654. $mouvS->origin = &$this;
  655. if (empty($obj->edbrowid))
  656. {
  657. // line without batch detail
  658. // 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.
  659. $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentValidatedInDolibarr", $numref));
  660. if ($result < 0) {
  661. $error++;
  662. $this->error = $mouvS->error;
  663. $this->errors = array_merge($this->errors, $mouvS->errors);
  664. break;
  665. }
  666. } else {
  667. // line with batch detail
  668. // 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.
  669. // Note: ->fk_origin_stock = id into table llx_product_batch (may be rename into llx_product_stock_batch in another version)
  670. $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentValidatedInDolibarr", $numref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, $obj->fk_origin_stock);
  671. if ($result < 0) {
  672. $error++;
  673. $this->error = $mouvS->error;
  674. $this->errors = array_merge($this->errors, $mouvS->errors);
  675. break;
  676. }
  677. }
  678. }
  679. } else {
  680. $this->db->rollback();
  681. $this->error = $this->db->error();
  682. return -2;
  683. }
  684. }
  685. // Change status of order to "shipment in process"
  686. $ret = $this->setStatut(Commande::STATUS_SHIPMENTONPROCESS, $this->origin_id, $this->origin);
  687. if (!$ret)
  688. {
  689. $error++;
  690. }
  691. if (!$error && !$notrigger)
  692. {
  693. // Call trigger
  694. $result = $this->call_trigger('SHIPPING_VALIDATE', $user);
  695. if ($result < 0) { $error++; }
  696. // End call triggers
  697. }
  698. if (!$error)
  699. {
  700. $this->oldref = $this->ref;
  701. // Rename directory if dir was a temporary ref
  702. if (preg_match('/^[\(]?PROV/i', $this->ref))
  703. {
  704. // Now we rename also files into index
  705. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expedition/sending/".$this->db->escape($this->newref)."'";
  706. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expedition/sending/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  707. $resql = $this->db->query($sql);
  708. if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
  709. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  710. $oldref = dol_sanitizeFileName($this->ref);
  711. $newref = dol_sanitizeFileName($numref);
  712. $dirsource = $conf->expedition->dir_output.'/sending/'.$oldref;
  713. $dirdest = $conf->expedition->dir_output.'/sending/'.$newref;
  714. if (!$error && file_exists($dirsource))
  715. {
  716. dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
  717. if (@rename($dirsource, $dirdest))
  718. {
  719. dol_syslog("Rename ok");
  720. // Rename docs starting with $oldref with $newref
  721. $listoffiles = dol_dir_list($conf->expedition->dir_output.'/sending/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  722. foreach ($listoffiles as $fileentry)
  723. {
  724. $dirsource = $fileentry['name'];
  725. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  726. $dirsource = $fileentry['path'].'/'.$dirsource;
  727. $dirdest = $fileentry['path'].'/'.$dirdest;
  728. @rename($dirsource, $dirdest);
  729. }
  730. }
  731. }
  732. }
  733. }
  734. // Set new ref and current status
  735. if (!$error)
  736. {
  737. $this->ref = $numref;
  738. $this->statut = self::STATUS_VALIDATED;
  739. }
  740. if (!$error)
  741. {
  742. $this->db->commit();
  743. return 1;
  744. } else {
  745. $this->db->rollback();
  746. return -1 * $error;
  747. }
  748. }
  749. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  750. /**
  751. * Create a delivery receipt from a shipment
  752. *
  753. * @param User $user User
  754. * @return int <0 if KO, >=0 if OK
  755. */
  756. public function create_delivery($user)
  757. {
  758. // phpcs:enable
  759. global $conf;
  760. if ($conf->delivery_note->enabled)
  761. {
  762. if ($this->statut == self::STATUS_VALIDATED || $this->statut == self::STATUS_CLOSED)
  763. {
  764. // Expedition validee
  765. include_once DOL_DOCUMENT_ROOT.'/delivery/class/delivery.class.php';
  766. $delivery = new Delivery($this->db);
  767. $result = $delivery->create_from_sending($user, $this->id);
  768. if ($result > 0)
  769. {
  770. return $result;
  771. } else {
  772. $this->error = $delivery->error;
  773. return $result;
  774. }
  775. } else return 0;
  776. } else return 0;
  777. }
  778. /**
  779. * Add an expedition line.
  780. * If STOCK_WAREHOUSE_NOT_REQUIRED_FOR_SHIPMENTS is set, you can add a shipment line, with no stock source defined
  781. * If STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT is not set, you can add a shipment line, even if not enough into stock
  782. *
  783. * @param int $entrepot_id Id of warehouse
  784. * @param int $id Id of source line (order line)
  785. * @param int $qty Quantity
  786. * @param array $array_options extrafields array
  787. * @return int <0 if KO, >0 if OK
  788. */
  789. public function addline($entrepot_id, $id, $qty, $array_options = 0)
  790. {
  791. global $conf, $langs;
  792. $num = count($this->lines);
  793. $line = new ExpeditionLigne($this->db);
  794. $line->entrepot_id = $entrepot_id;
  795. $line->origin_line_id = $id;
  796. $line->fk_origin_line = $id;
  797. $line->qty = $qty;
  798. $orderline = new OrderLine($this->db);
  799. $orderline->fetch($id);
  800. // Copy the rang of the order line to the expedition line
  801. $line->rang = $orderline->rang;
  802. if (!empty($conf->stock->enabled) && !empty($orderline->fk_product))
  803. {
  804. $fk_product = $orderline->fk_product;
  805. if (!($entrepot_id > 0) && empty($conf->global->STOCK_WAREHOUSE_NOT_REQUIRED_FOR_SHIPMENTS)) {
  806. $langs->load("errors");
  807. $this->error = $langs->trans("ErrorWarehouseRequiredIntoShipmentLine");
  808. return -1;
  809. }
  810. if ($conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT) {
  811. $product = new Product($this->db);
  812. $product->fetch($fk_product);
  813. // Check must be done for stock of product into warehouse if $entrepot_id defined
  814. if ($entrepot_id > 0) {
  815. $product->load_stock('warehouseopen');
  816. $product_stock = $product->stock_warehouse[$entrepot_id]->real;
  817. } else {
  818. $product_stock = $product->stock_reel;
  819. }
  820. $product_type = $product->type;
  821. if ($product_type == 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  822. $isavirtualproduct = ($product->hasFatherOrChild(1) > 0);
  823. // The product is qualified for a check of quantity (must be enough in stock to be added into shipment).
  824. if (!$isavirtualproduct || empty($conf->global->PRODUIT_SOUSPRODUITS) || ($isavirtualproduct && empty($conf->global->STOCK_EXCLUDE_VIRTUAL_PRODUCTS))) { // If STOCK_EXCLUDE_VIRTUAL_PRODUCTS is set, we do not manage stock for kits/virtual products.
  825. if ($product_stock < $qty) {
  826. $langs->load("errors");
  827. $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $product->ref);
  828. $this->errorhidden = 'ErrorStockIsNotEnoughToAddProductOnShipment';
  829. $this->db->rollback();
  830. return -3;
  831. }
  832. }
  833. }
  834. }
  835. }
  836. // If product need a batch number, we should not have called this function but addline_batch instead.
  837. if (!empty($conf->productbatch->enabled) && !empty($orderline->fk_product) && !empty($orderline->product_tobatch))
  838. {
  839. $this->error = 'ADDLINE_WAS_CALLED_INSTEAD_OF_ADDLINEBATCH';
  840. return -4;
  841. }
  842. // extrafields
  843. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) // For avoid conflicts if trigger used
  844. $line->array_options = $array_options;
  845. $this->lines[$num] = $line;
  846. }
  847. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  848. /**
  849. * Add a shipment line with batch record
  850. *
  851. * @param array $dbatch Array of value (key 'detail' -> Array, key 'qty' total quantity for line, key ix_l : original line index)
  852. * @param array $array_options extrafields array
  853. * @return int <0 if KO, >0 if OK
  854. */
  855. public function addline_batch($dbatch, $array_options = 0)
  856. {
  857. // phpcs:enable
  858. global $conf, $langs;
  859. $num = count($this->lines);
  860. if ($dbatch['qty'] > 0)
  861. {
  862. $line = new ExpeditionLigne($this->db);
  863. $tab = array();
  864. foreach ($dbatch['detail'] as $key=>$value)
  865. {
  866. if ($value['q'] > 0)
  867. {
  868. // $value['q']=qty to move
  869. // $value['id_batch']=id into llx_product_batch of record to move
  870. //var_dump($value);
  871. $linebatch = new ExpeditionLineBatch($this->db);
  872. $ret = $linebatch->fetchFromStock($value['id_batch']); // load serial, sellby, eatby
  873. if ($ret < 0)
  874. {
  875. $this->error = $linebatch->error;
  876. return -1;
  877. }
  878. $linebatch->qty = $value['q'];
  879. $tab[] = $linebatch;
  880. if ($conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT)
  881. {
  882. require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
  883. $prod_batch = new Productbatch($this->db);
  884. $prod_batch->fetch($value['id_batch']);
  885. if ($prod_batch->qty < $linebatch->qty)
  886. {
  887. $langs->load("errors");
  888. $this->errors[] = $langs->trans('ErrorStockIsNotEnoughToAddProductOnShipment', $prod_batch->fk_product);
  889. dol_syslog(get_class($this)."::addline_batch error=Product ".$prod_batch->batch.": ".$this->errorsToString(), LOG_ERR);
  890. $this->db->rollback();
  891. return -1;
  892. }
  893. }
  894. //var_dump($linebatch);
  895. }
  896. }
  897. $line->entrepot_id = $linebatch->entrepot_id;
  898. $line->origin_line_id = $dbatch['ix_l']; // deprecated
  899. $line->fk_origin_line = $dbatch['ix_l'];
  900. $line->qty = $dbatch['qty'];
  901. $line->detail_batch = $tab;
  902. // extrafields
  903. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) // For avoid conflicts if trigger used
  904. $line->array_options = $array_options;
  905. //var_dump($line);
  906. $this->lines[$num] = $line;
  907. return 1;
  908. }
  909. }
  910. /**
  911. * Update database
  912. *
  913. * @param User $user User that modify
  914. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  915. * @return int <0 if KO, >0 if OK
  916. */
  917. public function update($user = null, $notrigger = 0)
  918. {
  919. global $conf;
  920. $error = 0;
  921. // Clean parameters
  922. if (isset($this->ref)) $this->ref = trim($this->ref);
  923. if (isset($this->entity)) $this->entity = (int) $this->entity;
  924. if (isset($this->ref_customer)) $this->ref_customer = trim($this->ref_customer);
  925. if (isset($this->socid)) $this->socid = (int) $this->socid;
  926. if (isset($this->fk_user_author)) $this->fk_user_author = (int) $this->fk_user_author;
  927. if (isset($this->fk_user_valid)) $this->fk_user_valid = (int) $this->fk_user_valid;
  928. if (isset($this->fk_delivery_address)) $this->fk_delivery_address = (int) $this->fk_delivery_address;
  929. if (isset($this->shipping_method_id)) $this->shipping_method_id = (int) $this->shipping_method_id;
  930. if (isset($this->tracking_number)) $this->tracking_number = trim($this->tracking_number);
  931. if (isset($this->statut)) $this->statut = (int) $this->statut;
  932. if (isset($this->trueDepth)) $this->trueDepth = trim($this->trueDepth);
  933. if (isset($this->trueWidth)) $this->trueWidth = trim($this->trueWidth);
  934. if (isset($this->trueHeight)) $this->trueHeight = trim($this->trueHeight);
  935. if (isset($this->size_units)) $this->size_units = trim($this->size_units);
  936. if (isset($this->weight_units)) $this->weight_units = trim($this->weight_units);
  937. if (isset($this->trueWeight)) $this->weight = trim($this->trueWeight);
  938. if (isset($this->note_private)) $this->note = trim($this->note_private);
  939. if (isset($this->note_public)) $this->note = trim($this->note_public);
  940. if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf);
  941. // Check parameters
  942. // Put here code to add control on parameters values
  943. // Update request
  944. $sql = "UPDATE ".MAIN_DB_PREFIX."expedition SET";
  945. $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
  946. $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
  947. $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
  948. $sql .= " ref_customer=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
  949. $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
  950. $sql .= " date_creation=".(dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
  951. $sql .= " fk_user_author=".(isset($this->fk_user_author) ? $this->fk_user_author : "null").",";
  952. $sql .= " date_valid=".(dol_strlen($this->date_valid) != 0 ? "'".$this->db->idate($this->date_valid)."'" : 'null').",";
  953. $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->fk_user_valid : "null").",";
  954. $sql .= " date_expedition=".(dol_strlen($this->date_expedition) != 0 ? "'".$this->db->idate($this->date_expedition)."'" : 'null').",";
  955. $sql .= " date_delivery=".(dol_strlen($this->date_delivery) != 0 ? "'".$this->db->idate($this->date_delivery)."'" : 'null').",";
  956. $sql .= " fk_address=".(isset($this->fk_delivery_address) ? $this->fk_delivery_address : "null").",";
  957. $sql .= " fk_shipping_method=".((isset($this->shipping_method_id) && $this->shipping_method_id > 0) ? $this->shipping_method_id : "null").",";
  958. $sql .= " tracking_number=".(isset($this->tracking_number) ? "'".$this->db->escape($this->tracking_number)."'" : "null").",";
  959. $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
  960. $sql .= " fk_projet=".(isset($this->fk_project) ? $this->fk_project : "null").",";
  961. $sql .= " height=".(($this->trueHeight != '') ? $this->trueHeight : "null").",";
  962. $sql .= " width=".(($this->trueWidth != '') ? $this->trueWidth : "null").",";
  963. $sql .= " size_units=".(isset($this->size_units) ? $this->size_units : "null").",";
  964. $sql .= " size=".(($this->trueDepth != '') ? $this->trueDepth : "null").",";
  965. $sql .= " weight_units=".(isset($this->weight_units) ? $this->weight_units : "null").",";
  966. $sql .= " weight=".(($this->trueWeight != '') ? $this->trueWeight : "null").",";
  967. $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
  968. $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
  969. $sql .= " model_pdf=".(isset($this->modelpdf) ? "'".$this->db->escape($this->modelpdf)."'" : "null").",";
  970. $sql .= " entity=".$conf->entity;
  971. $sql .= " WHERE rowid=".$this->id;
  972. $this->db->begin();
  973. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  974. $resql = $this->db->query($sql);
  975. if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
  976. if (!$error && !$notrigger) {
  977. // Call trigger
  978. $result = $this->call_trigger('SHIPPING_MODIFY', $user);
  979. if ($result < 0) { $error++; }
  980. // End call triggers
  981. }
  982. // Commit or rollback
  983. if ($error)
  984. {
  985. foreach ($this->errors as $errmsg)
  986. {
  987. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  988. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  989. }
  990. $this->db->rollback();
  991. return -1 * $error;
  992. } else {
  993. $this->db->commit();
  994. return 1;
  995. }
  996. }
  997. /**
  998. * Cancel shipment.
  999. *
  1000. * @param int $notrigger Disable triggers
  1001. * @param bool $also_update_stock true if the stock should be increased back (false by default)
  1002. * @return int >0 if OK, 0 if deletion done but failed to delete files, <0 if KO
  1003. */
  1004. public function cancel($notrigger = 0, $also_update_stock = false)
  1005. {
  1006. global $conf, $langs, $user;
  1007. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1008. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php';
  1009. $error = 0;
  1010. $this->error = '';
  1011. $this->db->begin();
  1012. // Add a protection to refuse deleting if shipment has at least one delivery
  1013. $this->fetchObjectLinked($this->id, 'shipping', 0, 'delivery'); // Get deliveries linked to this shipment
  1014. if (count($this->linkedObjectsIds) > 0) {
  1015. $this->error = 'ErrorThereIsSomeDeliveries';
  1016. $error++;
  1017. }
  1018. if (!$error && !$notrigger) {
  1019. // Call trigger
  1020. $result = $this->call_trigger('SHIPPING_CANCEL', $user);
  1021. if ($result < 0) { $error++; }
  1022. // End call triggers
  1023. }
  1024. // Stock control
  1025. if (!$error && $conf->stock->enabled &&
  1026. (($conf->global->STOCK_CALCULATE_ON_SHIPMENT && $this->statut > self::STATUS_DRAFT) ||
  1027. ($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE && $this->statut == self::STATUS_CLOSED && $also_update_stock)))
  1028. {
  1029. require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php";
  1030. $langs->load("agenda");
  1031. // Loop on each product line to add a stock movement and delete features
  1032. $sql = "SELECT cd.fk_product, cd.subprice, ed.qty, ed.fk_entrepot, ed.rowid as expeditiondet_id";
  1033. $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
  1034. $sql .= " ".MAIN_DB_PREFIX."expeditiondet as ed";
  1035. $sql .= " WHERE ed.fk_expedition = ".$this->id;
  1036. $sql .= " AND cd.rowid = ed.fk_origin_line";
  1037. dol_syslog(get_class($this)."::delete select details", LOG_DEBUG);
  1038. $resql = $this->db->query($sql);
  1039. if ($resql)
  1040. {
  1041. $cpt = $this->db->num_rows($resql);
  1042. for ($i = 0; $i < $cpt; $i++)
  1043. {
  1044. dol_syslog(get_class($this)."::delete movement index ".$i);
  1045. $obj = $this->db->fetch_object($resql);
  1046. $mouvS = new MouvementStock($this->db);
  1047. // we do not log origin because it will be deleted
  1048. $mouvS->origin = null;
  1049. // get lot/serial
  1050. $lotArray = null;
  1051. if ($conf->productbatch->enabled)
  1052. {
  1053. $lotArray = ExpeditionLineBatch::fetchAll($this->db, $obj->expeditiondet_id);
  1054. if (!is_array($lotArray))
  1055. {
  1056. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  1057. }
  1058. }
  1059. if (empty($lotArray)) {
  1060. // no lot/serial
  1061. // We increment stock of product (and sub-products)
  1062. // We use warehouse selected for each line
  1063. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, 0, $langs->trans("ShipmentCanceledInDolibarr", $this->ref)); // Price is set to 0, because we don't want to see WAP changed
  1064. if ($result < 0)
  1065. {
  1066. $error++; $this->errors = $this->errors + $mouvS->errors;
  1067. break;
  1068. }
  1069. } else {
  1070. // We increment stock of batches
  1071. // We use warehouse selected for each line
  1072. foreach ($lotArray as $lot)
  1073. {
  1074. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $lot->qty, 0, $langs->trans("ShipmentCanceledInDolibarr", $this->ref), $lot->eatby, $lot->sellby, $lot->batch); // Price is set to 0, because we don't want to see WAP changed
  1075. if ($result < 0)
  1076. {
  1077. $error++; $this->errors = $this->errors + $mouvS->errors;
  1078. break;
  1079. }
  1080. }
  1081. if ($error) break; // break for loop incase of error
  1082. }
  1083. }
  1084. } else {
  1085. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  1086. }
  1087. }
  1088. // delete batch expedition line
  1089. if (!$error && $conf->productbatch->enabled)
  1090. {
  1091. if (ExpeditionLineBatch::deletefromexp($this->db, $this->id) < 0)
  1092. {
  1093. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  1094. }
  1095. }
  1096. if (!$error)
  1097. {
  1098. $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet";
  1099. $sql .= " WHERE fk_expedition = ".$this->id;
  1100. if ($this->db->query($sql))
  1101. {
  1102. // Delete linked object
  1103. $res = $this->deleteObjectLinked();
  1104. if ($res < 0) $error++;
  1105. // No delete expedition
  1106. if (!$error)
  1107. {
  1108. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."expedition";
  1109. $sql .= " WHERE rowid = ".$this->id;
  1110. if ($this->db->query($sql))
  1111. {
  1112. if (!empty($this->origin) && $this->origin_id > 0)
  1113. {
  1114. $this->fetch_origin();
  1115. $origin = $this->origin;
  1116. if ($this->$origin->statut == Commande::STATUS_SHIPMENTONPROCESS) // If order source of shipment is "shipment in progress"
  1117. {
  1118. // Check if there is no more shipment. If not, we can move back status of order to "validated" instead of "shipment in progress"
  1119. $this->$origin->loadExpeditions();
  1120. //var_dump($this->$origin->expeditions);exit;
  1121. if (count($this->$origin->expeditions) <= 0)
  1122. {
  1123. $this->$origin->setStatut(Commande::STATUS_VALIDATED);
  1124. }
  1125. }
  1126. }
  1127. if (!$error)
  1128. {
  1129. $this->db->commit();
  1130. // We delete PDFs
  1131. $ref = dol_sanitizeFileName($this->ref);
  1132. if (!empty($conf->expedition->dir_output))
  1133. {
  1134. $dir = $conf->expedition->dir_output.'/sending/'.$ref;
  1135. $file = $dir.'/'.$ref.'.pdf';
  1136. if (file_exists($file))
  1137. {
  1138. if (!dol_delete_file($file))
  1139. {
  1140. return 0;
  1141. }
  1142. }
  1143. if (file_exists($dir))
  1144. {
  1145. if (!dol_delete_dir_recursive($dir))
  1146. {
  1147. $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
  1148. return 0;
  1149. }
  1150. }
  1151. }
  1152. return 1;
  1153. } else {
  1154. $this->db->rollback();
  1155. return -1;
  1156. }
  1157. } else {
  1158. $this->error = $this->db->lasterror()." - sql=$sql";
  1159. $this->db->rollback();
  1160. return -3;
  1161. }
  1162. } else {
  1163. $this->error = $this->db->lasterror()." - sql=$sql";
  1164. $this->db->rollback();
  1165. return -2;
  1166. }//*/
  1167. } else {
  1168. $this->error = $this->db->lasterror()." - sql=$sql";
  1169. $this->db->rollback();
  1170. return -1;
  1171. }
  1172. } else {
  1173. $this->db->rollback();
  1174. return -1;
  1175. }
  1176. }
  1177. /**
  1178. * Delete shipment.
  1179. * Warning, do not delete a shipment if a delivery is linked to (with table llx_element_element)
  1180. *
  1181. * @param int $notrigger Disable triggers
  1182. * @param bool $also_update_stock true if the stock should be increased back (false by default)
  1183. * @return int >0 if OK, 0 if deletion done but failed to delete files, <0 if KO
  1184. */
  1185. public function delete($notrigger = 0, $also_update_stock = false)
  1186. {
  1187. global $conf, $langs, $user;
  1188. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1189. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php';
  1190. $error = 0;
  1191. $this->error = '';
  1192. $this->db->begin();
  1193. // Add a protection to refuse deleting if shipment has at least one delivery
  1194. $this->fetchObjectLinked($this->id, 'shipping', 0, 'delivery'); // Get deliveries linked to this shipment
  1195. if (count($this->linkedObjectsIds) > 0)
  1196. {
  1197. $this->error = 'ErrorThereIsSomeDeliveries';
  1198. $error++;
  1199. }
  1200. if (!$error && !$notrigger) {
  1201. // Call trigger
  1202. $result = $this->call_trigger('SHIPPING_DELETE', $user);
  1203. if ($result < 0) { $error++; }
  1204. // End call triggers
  1205. }
  1206. // Stock control
  1207. if (!$error && $conf->stock->enabled &&
  1208. (($conf->global->STOCK_CALCULATE_ON_SHIPMENT && $this->statut > self::STATUS_DRAFT) ||
  1209. ($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE && $this->statut == self::STATUS_CLOSED && $also_update_stock)))
  1210. {
  1211. require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php";
  1212. $langs->load("agenda");
  1213. // Loop on each product line to add a stock movement
  1214. $sql = "SELECT cd.fk_product, cd.subprice, ed.qty, ed.fk_entrepot, ed.rowid as expeditiondet_id";
  1215. $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
  1216. $sql .= " ".MAIN_DB_PREFIX."expeditiondet as ed";
  1217. $sql .= " WHERE ed.fk_expedition = ".$this->id;
  1218. $sql .= " AND cd.rowid = ed.fk_origin_line";
  1219. dol_syslog(get_class($this)."::delete select details", LOG_DEBUG);
  1220. $resql = $this->db->query($sql);
  1221. if ($resql)
  1222. {
  1223. $cpt = $this->db->num_rows($resql);
  1224. for ($i = 0; $i < $cpt; $i++)
  1225. {
  1226. dol_syslog(get_class($this)."::delete movement index ".$i);
  1227. $obj = $this->db->fetch_object($resql);
  1228. $mouvS = new MouvementStock($this->db);
  1229. // we do not log origin because it will be deleted
  1230. $mouvS->origin = null;
  1231. // get lot/serial
  1232. $lotArray = null;
  1233. if ($conf->productbatch->enabled)
  1234. {
  1235. $lotArray = ExpeditionLineBatch::fetchAll($this->db, $obj->expeditiondet_id);
  1236. if (!is_array($lotArray))
  1237. {
  1238. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  1239. }
  1240. }
  1241. if (empty($lotArray)) {
  1242. // no lot/serial
  1243. // We increment stock of product (and sub-products)
  1244. // We use warehouse selected for each line
  1245. $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
  1246. if ($result < 0)
  1247. {
  1248. $error++; $this->errors = $this->errors + $mouvS->errors;
  1249. break;
  1250. }
  1251. } else {
  1252. // We increment stock of batches
  1253. // We use warehouse selected for each line
  1254. foreach ($lotArray as $lot)
  1255. {
  1256. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $lot->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
  1257. if ($result < 0)
  1258. {
  1259. $error++; $this->errors = $this->errors + $mouvS->errors;
  1260. break;
  1261. }
  1262. }
  1263. if ($error) break; // break for loop incase of error
  1264. }
  1265. }
  1266. } else {
  1267. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  1268. }
  1269. }
  1270. // delete batch expedition line
  1271. if (!$error && $conf->productbatch->enabled)
  1272. {
  1273. if (ExpeditionLineBatch::deletefromexp($this->db, $this->id) < 0)
  1274. {
  1275. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  1276. }
  1277. }
  1278. if (!$error)
  1279. {
  1280. $main = MAIN_DB_PREFIX.'expeditiondet';
  1281. $ef = $main."_extrafields";
  1282. $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_expedition = ".$this->id.")";
  1283. $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet";
  1284. $sql .= " WHERE fk_expedition = ".$this->id;
  1285. if ($this->db->query($sqlef) && $this->db->query($sql))
  1286. {
  1287. // Delete linked object
  1288. $res = $this->deleteObjectLinked();
  1289. if ($res < 0) $error++;
  1290. // delete extrafields
  1291. $res = $this->deleteExtraFields();
  1292. if ($res < 0) $error++;
  1293. if (!$error)
  1294. {
  1295. $sql = "DELETE FROM ".MAIN_DB_PREFIX."expedition";
  1296. $sql .= " WHERE rowid = ".$this->id;
  1297. if ($this->db->query($sql))
  1298. {
  1299. if (!empty($this->origin) && $this->origin_id > 0)
  1300. {
  1301. $this->fetch_origin();
  1302. $origin = $this->origin;
  1303. if ($this->$origin->statut == Commande::STATUS_SHIPMENTONPROCESS) // If order source of shipment is "shipment in progress"
  1304. {
  1305. // Check if there is no more shipment. If not, we can move back status of order to "validated" instead of "shipment in progress"
  1306. $this->$origin->loadExpeditions();
  1307. //var_dump($this->$origin->expeditions);exit;
  1308. if (count($this->$origin->expeditions) <= 0)
  1309. {
  1310. $this->$origin->setStatut(Commande::STATUS_VALIDATED);
  1311. }
  1312. }
  1313. }
  1314. if (!$error)
  1315. {
  1316. $this->db->commit();
  1317. // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
  1318. $this->deleteEcmFiles();
  1319. // We delete PDFs
  1320. $ref = dol_sanitizeFileName($this->ref);
  1321. if (!empty($conf->expedition->dir_output))
  1322. {
  1323. $dir = $conf->expedition->dir_output.'/sending/'.$ref;
  1324. $file = $dir.'/'.$ref.'.pdf';
  1325. if (file_exists($file))
  1326. {
  1327. if (!dol_delete_file($file))
  1328. {
  1329. return 0;
  1330. }
  1331. }
  1332. if (file_exists($dir))
  1333. {
  1334. if (!dol_delete_dir_recursive($dir))
  1335. {
  1336. $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
  1337. return 0;
  1338. }
  1339. }
  1340. }
  1341. return 1;
  1342. } else {
  1343. $this->db->rollback();
  1344. return -1;
  1345. }
  1346. } else {
  1347. $this->error = $this->db->lasterror()." - sql=$sql";
  1348. $this->db->rollback();
  1349. return -3;
  1350. }
  1351. } else {
  1352. $this->error = $this->db->lasterror()." - sql=$sql";
  1353. $this->db->rollback();
  1354. return -2;
  1355. }
  1356. } else {
  1357. $this->error = $this->db->lasterror()." - sql=$sql";
  1358. $this->db->rollback();
  1359. return -1;
  1360. }
  1361. } else {
  1362. $this->db->rollback();
  1363. return -1;
  1364. }
  1365. }
  1366. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1367. /**
  1368. * Load lines
  1369. *
  1370. * @return int >0 if OK, Otherwise if KO
  1371. */
  1372. public function fetch_lines()
  1373. {
  1374. // phpcs:enable
  1375. global $conf, $mysoc;
  1376. // TODO: recuperer les champs du document associe a part
  1377. $this->lines = array();
  1378. $sql = "SELECT cd.rowid, cd.fk_product, cd.label as custom_label, cd.description, cd.qty as qty_asked, cd.product_type, cd.fk_unit";
  1379. $sql .= ", cd.total_ht, cd.total_localtax1, cd.total_localtax2, cd.total_ttc, cd.total_tva";
  1380. $sql .= ", cd.vat_src_code, cd.tva_tx, cd.localtax1_tx, cd.localtax2_tx, cd.localtax1_type, cd.localtax2_type, cd.info_bits, cd.price, cd.subprice, cd.remise_percent,cd.buy_price_ht as pa_ht";
  1381. $sql .= ", cd.fk_multicurrency, cd.multicurrency_code, cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc, cd.rang";
  1382. $sql .= ", ed.rowid as line_id, ed.qty as qty_shipped, ed.fk_origin_line, ed.fk_entrepot";
  1383. $sql .= ", p.ref as product_ref, p.label as product_label, p.fk_product_type";
  1384. $sql .= ", p.weight, p.weight_units, p.length, p.length_units, p.surface, p.surface_units, p.volume, p.volume_units, p.tosell as product_tosell, p.tobuy as product_tobuy, p.tobatch as product_tobatch";
  1385. $sql .= " FROM ".MAIN_DB_PREFIX."expeditiondet as ed, ".MAIN_DB_PREFIX."commandedet as cd";
  1386. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = cd.fk_product";
  1387. $sql .= " WHERE ed.fk_expedition = ".$this->id;
  1388. $sql .= " AND ed.fk_origin_line = cd.rowid";
  1389. $sql .= " ORDER BY cd.rang, ed.fk_origin_line";
  1390. dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
  1391. $resql = $this->db->query($sql);
  1392. if ($resql)
  1393. {
  1394. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1395. $num = $this->db->num_rows($resql);
  1396. $i = 0;
  1397. $lineindex = 0;
  1398. $originline = 0;
  1399. $this->total_ht = 0;
  1400. $this->total_tva = 0;
  1401. $this->total_ttc = 0;
  1402. $this->total_localtax1 = 0;
  1403. $this->total_localtax2 = 0;
  1404. $line = new ExpeditionLigne($this->db);
  1405. while ($i < $num)
  1406. {
  1407. $obj = $this->db->fetch_object($resql);
  1408. if ($originline == $obj->fk_origin_line) {
  1409. $line->entrepot_id = 0; // entrepod_id in details_entrepot
  1410. $line->qty_shipped += $obj->qty_shipped;
  1411. } else {
  1412. $line = new ExpeditionLigne($this->db);
  1413. $line->entrepot_id = $obj->fk_entrepot;
  1414. $line->qty_shipped = $obj->qty_shipped;
  1415. }
  1416. $detail_entrepot = new stdClass;
  1417. $detail_entrepot->entrepot_id = $obj->fk_entrepot;
  1418. $detail_entrepot->qty_shipped = $obj->qty_shipped;
  1419. $detail_entrepot->line_id = $obj->line_id;
  1420. $line->details_entrepot[] = $detail_entrepot;
  1421. $line->line_id = $obj->line_id;
  1422. $line->rowid = $obj->line_id; // TODO deprecated
  1423. $line->id = $obj->line_id;
  1424. $line->fk_origin = 'orderline';
  1425. $line->fk_origin_line = $obj->fk_origin_line;
  1426. $line->origin_line_id = $obj->fk_origin_line; // TODO deprecated
  1427. $line->fk_expedition = $this->id; // id of parent
  1428. $line->product_type = $obj->product_type;
  1429. $line->fk_product = $obj->fk_product;
  1430. $line->fk_product_type = $obj->fk_product_type;
  1431. $line->ref = $obj->product_ref; // TODO deprecated
  1432. $line->product_ref = $obj->product_ref;
  1433. $line->product_label = $obj->product_label;
  1434. $line->libelle = $obj->product_label; // TODO deprecated
  1435. $line->product_tosell = $obj->product_tosell;
  1436. $line->product_tobuy = $obj->product_tobuy;
  1437. $line->product_tobatch = $obj->product_tobatch;
  1438. $line->label = $obj->custom_label;
  1439. $line->description = $obj->description;
  1440. $line->qty_asked = $obj->qty_asked;
  1441. $line->rang = $obj->rang;
  1442. $line->weight = $obj->weight;
  1443. $line->weight_units = $obj->weight_units;
  1444. $line->length = $obj->length;
  1445. $line->length_units = $obj->length_units;
  1446. $line->surface = $obj->surface;
  1447. $line->surface_units = $obj->surface_units;
  1448. $line->volume = $obj->volume;
  1449. $line->volume_units = $obj->volume_units;
  1450. $line->fk_unit = $obj->fk_unit;
  1451. $line->pa_ht = $obj->pa_ht;
  1452. // Local taxes
  1453. $localtax_array = array(0=>$obj->localtax1_type, 1=>$obj->localtax1_tx, 2=>$obj->localtax2_type, 3=>$obj->localtax2_tx);
  1454. $localtax1_tx = get_localtax($obj->tva_tx, 1, $this->thirdparty);
  1455. $localtax2_tx = get_localtax($obj->tva_tx, 2, $this->thirdparty);
  1456. // For invoicing
  1457. $tabprice = calcul_price_total($obj->qty_shipped, $obj->subprice, $obj->remise_percent, $obj->tva_tx, $localtax1_tx, $localtax2_tx, 0, 'HT', $obj->info_bits, $obj->fk_product_type, $mysoc, $localtax_array); // We force type to 0
  1458. $line->desc = $obj->description; // We need ->desc because some code into CommonObject use desc (property defined for other elements)
  1459. $line->qty = $line->qty_shipped;
  1460. $line->total_ht = $tabprice[0];
  1461. $line->total_localtax1 = $tabprice[9];
  1462. $line->total_localtax2 = $tabprice[10];
  1463. $line->total_ttc = $tabprice[2];
  1464. $line->total_tva = $tabprice[1];
  1465. $line->vat_src_code = $obj->vat_src_code;
  1466. $line->tva_tx = $obj->tva_tx;
  1467. $line->localtax1_tx = $obj->localtax1_tx;
  1468. $line->localtax2_tx = $obj->localtax2_tx;
  1469. $line->info_bits = $obj->info_bits;
  1470. $line->price = $obj->price;
  1471. $line->subprice = $obj->subprice;
  1472. $line->remise_percent = $obj->remise_percent;
  1473. $this->total_ht += $tabprice[0];
  1474. $this->total_tva += $tabprice[1];
  1475. $this->total_ttc += $tabprice[2];
  1476. $this->total_localtax1 += $tabprice[9];
  1477. $this->total_localtax2 += $tabprice[10];
  1478. // Multicurrency
  1479. $this->fk_multicurrency = $obj->fk_multicurrency;
  1480. $this->multicurrency_code = $obj->multicurrency_code;
  1481. $this->multicurrency_subprice = $obj->multicurrency_subprice;
  1482. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  1483. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  1484. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  1485. if ($originline != $obj->fk_origin_line)
  1486. {
  1487. $line->detail_batch = array();
  1488. }
  1489. // Detail of batch
  1490. if (!empty($conf->productbatch->enabled) && $obj->line_id > 0 && $obj->product_tobatch > 0)
  1491. {
  1492. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php';
  1493. $newdetailbatch = ExpeditionLineBatch::fetchAll($this->db, $obj->line_id, $obj->fk_product);
  1494. if (is_array($newdetailbatch))
  1495. {
  1496. if ($originline != $obj->fk_origin_line)
  1497. {
  1498. $line->detail_batch = $newdetailbatch;
  1499. } else {
  1500. $line->detail_batch = array_merge($line->detail_batch, $newdetailbatch);
  1501. }
  1502. }
  1503. }
  1504. if ($originline != $obj->fk_origin_line)
  1505. {
  1506. $this->lines[$lineindex] = $line;
  1507. $lineindex++;
  1508. } else {
  1509. $line->total_ht += $tabprice[0];
  1510. $line->total_localtax1 += $tabprice[9];
  1511. $line->total_localtax2 += $tabprice[10];
  1512. $line->total_ttc += $tabprice[2];
  1513. $line->total_tva += $tabprice[1];
  1514. }
  1515. $line->fetch_optionals();
  1516. $i++;
  1517. $originline = $obj->fk_origin_line;
  1518. }
  1519. $this->db->free($resql);
  1520. return 1;
  1521. } else {
  1522. $this->error = $this->db->error();
  1523. return -3;
  1524. }
  1525. }
  1526. /**
  1527. * Delete detail line
  1528. *
  1529. * @param User $user User making deletion
  1530. * @param int $lineid Id of line to delete
  1531. * @return int >0 if OK, <0 if KO
  1532. */
  1533. public function deleteline($user, $lineid)
  1534. {
  1535. global $user;
  1536. if ($this->statut == self::STATUS_DRAFT)
  1537. {
  1538. $this->db->begin();
  1539. $line = new ExpeditionLigne($this->db);
  1540. // For triggers
  1541. $line->fetch($lineid);
  1542. if ($line->delete($user) > 0)
  1543. {
  1544. //$this->update_price(1);
  1545. $this->db->commit();
  1546. return 1;
  1547. } else {
  1548. $this->db->rollback();
  1549. return -1;
  1550. }
  1551. } else {
  1552. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  1553. return -2;
  1554. }
  1555. }
  1556. /**
  1557. * Return clicable link of object (with eventually picto)
  1558. *
  1559. * @param int $withpicto Add picto into link
  1560. * @param string $option Where the link point to
  1561. * @param int $max Max length to show
  1562. * @param int $short Use short labels
  1563. * @param int $notooltip 1=No tooltip
  1564. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1565. * @return string String with URL
  1566. */
  1567. public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $notooltip = 0, $save_lastsearch_value = -1)
  1568. {
  1569. global $langs, $conf;
  1570. $result = '';
  1571. $label = '<u>'.$langs->trans("Shipment").'</u>';
  1572. $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1573. $label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.($this->ref_customer ? $this->ref_customer : $this->ref_client);
  1574. $url = DOL_URL_ROOT.'/expedition/card.php?id='.$this->id;
  1575. if ($short) return $url;
  1576. if ($option !== 'nolink')
  1577. {
  1578. // Add param to save lastsearch_values or not
  1579. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1580. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
  1581. if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
  1582. }
  1583. $linkclose = '';
  1584. if (empty($notooltip))
  1585. {
  1586. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
  1587. {
  1588. $label = $langs->trans("Shipment");
  1589. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1590. }
  1591. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1592. $linkclose .= ' class="classfortooltip"';
  1593. }
  1594. $linkstart = '<a href="'.$url.'"';
  1595. $linkstart .= $linkclose.'>';
  1596. $linkend = '</a>';
  1597. $result .= $linkstart;
  1598. if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  1599. if ($withpicto != 2) $result .= $this->ref;
  1600. $result .= $linkend;
  1601. return $result;
  1602. }
  1603. /**
  1604. * Return status label
  1605. *
  1606. * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
  1607. * @return string Libelle
  1608. */
  1609. public function getLibStatut($mode = 0)
  1610. {
  1611. return $this->LibStatut($this->statut, $mode);
  1612. }
  1613. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1614. /**
  1615. * Return label of a status
  1616. *
  1617. * @param int $status Id statut
  1618. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  1619. * @return string Label of status
  1620. */
  1621. public function LibStatut($status, $mode)
  1622. {
  1623. // phpcs:enable
  1624. global $langs;
  1625. $labelStatus = $langs->trans($this->statuts[$status]);
  1626. $labelStatusShort = $langs->trans($this->statutshorts[$status]);
  1627. $statusType = 'status'.$status;
  1628. if ($status == self::STATUS_VALIDATED) $statusType = 'status4';
  1629. if ($status == self::STATUS_CLOSED) $statusType = 'status6';
  1630. if ($status == self::STATUS_CANCELED) $statusType = 'status9';
  1631. return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
  1632. }
  1633. /**
  1634. * Initialise an instance with random values.
  1635. * Used to build previews or test instances.
  1636. * id must be 0 if object instance is a specimen.
  1637. *
  1638. * @return void
  1639. */
  1640. public function initAsSpecimen()
  1641. {
  1642. global $langs;
  1643. $now = dol_now();
  1644. dol_syslog(get_class($this)."::initAsSpecimen");
  1645. // Load array of products prodids
  1646. $num_prods = 0;
  1647. $prodids = array();
  1648. $sql = "SELECT rowid";
  1649. $sql .= " FROM ".MAIN_DB_PREFIX."product";
  1650. $sql .= " WHERE entity IN (".getEntity('product').")";
  1651. $resql = $this->db->query($sql);
  1652. if ($resql)
  1653. {
  1654. $num_prods = $this->db->num_rows($resql);
  1655. $i = 0;
  1656. while ($i < $num_prods)
  1657. {
  1658. $i++;
  1659. $row = $this->db->fetch_row($resql);
  1660. $prodids[$i] = $row[0];
  1661. }
  1662. }
  1663. $order = new Commande($this->db);
  1664. $order->initAsSpecimen();
  1665. // Initialise parametres
  1666. $this->id = 0;
  1667. $this->ref = 'SPECIMEN';
  1668. $this->specimen = 1;
  1669. $this->statut = self::STATUS_VALIDATED;
  1670. $this->livraison_id = 0;
  1671. $this->date = $now;
  1672. $this->date_creation = $now;
  1673. $this->date_valid = $now;
  1674. $this->date_delivery = $now;
  1675. $this->date_expedition = $now + 24 * 3600;
  1676. $this->entrepot_id = 0;
  1677. $this->fk_delivery_address = 0;
  1678. $this->socid = 1;
  1679. $this->commande_id = 0;
  1680. $this->commande = $order;
  1681. $this->origin_id = 1;
  1682. $this->origin = 'commande';
  1683. $this->note_private = 'Private note';
  1684. $this->note_public = 'Public note';
  1685. $nbp = 5;
  1686. $xnbp = 0;
  1687. while ($xnbp < $nbp)
  1688. {
  1689. $line = new ExpeditionLigne($this->db);
  1690. $line->desc = $langs->trans("Description")." ".$xnbp;
  1691. $line->libelle = $langs->trans("Description")." ".$xnbp; // deprecated
  1692. $line->label = $langs->trans("Description")." ".$xnbp;
  1693. $line->qty = 10;
  1694. $line->qty_asked = 5;
  1695. $line->qty_shipped = 4;
  1696. $line->fk_product = $this->commande->lines[$xnbp]->fk_product;
  1697. $this->lines[] = $line;
  1698. $xnbp++;
  1699. }
  1700. }
  1701. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1702. /**
  1703. * Set delivery date
  1704. *
  1705. * @param User $user Object user that modify
  1706. * @param int $delivery_date Delivery date
  1707. * @return int <0 if ko, >0 if ok
  1708. * @deprecated Use setDeliveryDate
  1709. */
  1710. public function set_date_livraison($user, $delivery_date)
  1711. {
  1712. // phpcs:enable
  1713. return $this->setDeliveryDate($user, $delivery_date);
  1714. }
  1715. /**
  1716. * Set the planned delivery date
  1717. *
  1718. * @param User $user Objet user that modify
  1719. * @param integer $delivery_date Date of delivery
  1720. * @return int <0 if KO, >0 if OK
  1721. */
  1722. public function setDeliveryDate($user, $delivery_date)
  1723. {
  1724. if ($user->rights->expedition->creer)
  1725. {
  1726. $sql = "UPDATE ".MAIN_DB_PREFIX."expedition";
  1727. $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
  1728. $sql .= " WHERE rowid = ".$this->id;
  1729. dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG);
  1730. $resql = $this->db->query($sql);
  1731. if ($resql)
  1732. {
  1733. $this->date_delivery = $delivery_date;
  1734. return 1;
  1735. } else {
  1736. $this->error = $this->db->error();
  1737. return -1;
  1738. }
  1739. } else {
  1740. return -2;
  1741. }
  1742. }
  1743. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1744. /**
  1745. * Fetch deliveries method and return an array. Load array this->meths(rowid=>label).
  1746. *
  1747. * @return void
  1748. */
  1749. public function fetch_delivery_methods()
  1750. {
  1751. // phpcs:enable
  1752. global $langs;
  1753. $this->meths = array();
  1754. $sql = "SELECT em.rowid, em.code, em.libelle as label";
  1755. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
  1756. $sql .= " WHERE em.active = 1";
  1757. $sql .= " ORDER BY em.libelle ASC";
  1758. $resql = $this->db->query($sql);
  1759. if ($resql)
  1760. {
  1761. while ($obj = $this->db->fetch_object($resql))
  1762. {
  1763. $label = $langs->trans('SendingMethod'.$obj->code);
  1764. $this->meths[$obj->rowid] = ($label != 'SendingMethod'.$obj->code ? $label : $obj->label);
  1765. }
  1766. }
  1767. }
  1768. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1769. /**
  1770. * Fetch all deliveries method and return an array. Load array this->listmeths.
  1771. *
  1772. * @param int $id only this carrier, all if none
  1773. * @return void
  1774. */
  1775. public function list_delivery_methods($id = '')
  1776. {
  1777. // phpcs:enable
  1778. global $langs;
  1779. $this->listmeths = array();
  1780. $i = 0;
  1781. $sql = "SELECT em.rowid, em.code, em.libelle as label, em.description, em.tracking, em.active";
  1782. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
  1783. if ($id != '') $sql .= " WHERE em.rowid=".$id;
  1784. $resql = $this->db->query($sql);
  1785. if ($resql)
  1786. {
  1787. while ($obj = $this->db->fetch_object($resql))
  1788. {
  1789. $this->listmeths[$i]['rowid'] = $obj->rowid;
  1790. $this->listmeths[$i]['code'] = $obj->code;
  1791. $label = $langs->trans('SendingMethod'.$obj->code);
  1792. $this->listmeths[$i]['libelle'] = ($label != 'SendingMethod'.$obj->code ? $label : $obj->label);
  1793. $this->listmeths[$i]['description'] = $obj->description;
  1794. $this->listmeths[$i]['tracking'] = $obj->tracking;
  1795. $this->listmeths[$i]['active'] = $obj->active;
  1796. $i++;
  1797. }
  1798. }
  1799. }
  1800. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1801. /**
  1802. * Update/create delivery method.
  1803. *
  1804. * @param string $id id method to activate
  1805. *
  1806. * @return void
  1807. */
  1808. public function update_delivery_method($id = '')
  1809. {
  1810. // phpcs:enable
  1811. if ($id == '')
  1812. {
  1813. $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_shipment_mode (code, libelle, description, tracking)";
  1814. $sql .= " VALUES ('".$this->db->escape($this->update['code'])."','".$this->db->escape($this->update['libelle'])."','".$this->db->escape($this->update['description'])."','".$this->db->escape($this->update['tracking'])."')";
  1815. $resql = $this->db->query($sql);
  1816. } else {
  1817. $sql = "UPDATE ".MAIN_DB_PREFIX."c_shipment_mode SET";
  1818. $sql .= " code='".$this->db->escape($this->update['code'])."'";
  1819. $sql .= ",libelle='".$this->db->escape($this->update['libelle'])."'";
  1820. $sql .= ",description='".$this->db->escape($this->update['description'])."'";
  1821. $sql .= ",tracking='".$this->db->escape($this->update['tracking'])."'";
  1822. $sql .= " WHERE rowid=".$id;
  1823. $resql = $this->db->query($sql);
  1824. }
  1825. if ($resql < 0) dol_print_error($this->db, '');
  1826. }
  1827. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1828. /**
  1829. * Activate delivery method.
  1830. *
  1831. * @param int $id id method to activate
  1832. * @return void
  1833. */
  1834. public function activ_delivery_method($id)
  1835. {
  1836. // phpcs:enable
  1837. $sql = 'UPDATE '.MAIN_DB_PREFIX.'c_shipment_mode SET active=1';
  1838. $sql .= ' WHERE rowid='.$id;
  1839. $resql = $this->db->query($sql);
  1840. }
  1841. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1842. /**
  1843. * DesActivate delivery method.
  1844. *
  1845. * @param int $id id method to desactivate
  1846. *
  1847. * @return void
  1848. */
  1849. public function disable_delivery_method($id)
  1850. {
  1851. // phpcs:enable
  1852. $sql = 'UPDATE '.MAIN_DB_PREFIX.'c_shipment_mode SET active=0';
  1853. $sql .= ' WHERE rowid='.$id;
  1854. $resql = $this->db->query($sql);
  1855. }
  1856. /**
  1857. * Forge an set tracking url
  1858. *
  1859. * @param string $value Value
  1860. * @return void
  1861. */
  1862. public function getUrlTrackingStatus($value = '')
  1863. {
  1864. if (!empty($this->shipping_method_id))
  1865. {
  1866. $sql = "SELECT em.code, em.tracking";
  1867. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
  1868. $sql .= " WHERE em.rowid = ".$this->shipping_method_id;
  1869. $resql = $this->db->query($sql);
  1870. if ($resql)
  1871. {
  1872. if ($obj = $this->db->fetch_object($resql))
  1873. {
  1874. $tracking = $obj->tracking;
  1875. }
  1876. }
  1877. }
  1878. if (!empty($tracking) && !empty($value))
  1879. {
  1880. $url = str_replace('{TRACKID}', $value, $tracking);
  1881. $this->tracking_url = sprintf('<a target="_blank" href="%s">'.($value ? $value : 'url').'</a>', $url, $url);
  1882. } else {
  1883. $this->tracking_url = $value;
  1884. }
  1885. }
  1886. /**
  1887. * Classify the shipping as closed.
  1888. *
  1889. * @return int <0 if KO, >0 if OK
  1890. */
  1891. public function setClosed()
  1892. {
  1893. global $conf, $langs, $user;
  1894. $error = 0;
  1895. // Protection. This avoid to move stock later when we should not
  1896. if ($this->statut == self::STATUS_CLOSED)
  1897. {
  1898. return 0;
  1899. }
  1900. $this->db->begin();
  1901. $sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET fk_statut='.self::STATUS_CLOSED;
  1902. $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0';
  1903. $resql = $this->db->query($sql);
  1904. if ($resql)
  1905. {
  1906. // Set order billed if 100% of order is shipped (qty in shipment lines match qty in order lines)
  1907. if ($this->origin == 'commande' && $this->origin_id > 0)
  1908. {
  1909. $order = new Commande($this->db);
  1910. $order->fetch($this->origin_id);
  1911. $order->loadExpeditions(self::STATUS_CLOSED); // Fill $order->expeditions = array(orderlineid => qty)
  1912. $shipments_match_order = 1;
  1913. foreach ($order->lines as $line)
  1914. {
  1915. $lineid = $line->id;
  1916. $qty = $line->qty;
  1917. if (($line->product_type == 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) && $order->expeditions[$lineid] != $qty)
  1918. {
  1919. $shipments_match_order = 0;
  1920. $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';
  1921. dol_syslog($text);
  1922. break;
  1923. }
  1924. }
  1925. if ($shipments_match_order)
  1926. {
  1927. 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');
  1928. $order->cloture($user);
  1929. }
  1930. }
  1931. $this->statut = self::STATUS_CLOSED;
  1932. // If stock increment is done on closing
  1933. if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE))
  1934. {
  1935. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1936. $langs->load("agenda");
  1937. // Loop on each product line to add a stock movement
  1938. // TODO possibilite d'expedier a partir d'une propale ou autre origine ?
  1939. $sql = "SELECT cd.fk_product, cd.subprice,";
  1940. $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
  1941. $sql .= " edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
  1942. $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
  1943. $sql .= " ".MAIN_DB_PREFIX."expeditiondet as ed";
  1944. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
  1945. $sql .= " WHERE ed.fk_expedition = ".$this->id;
  1946. $sql .= " AND cd.rowid = ed.fk_origin_line";
  1947. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  1948. $resql = $this->db->query($sql);
  1949. if ($resql)
  1950. {
  1951. $cpt = $this->db->num_rows($resql);
  1952. for ($i = 0; $i < $cpt; $i++)
  1953. {
  1954. $obj = $this->db->fetch_object($resql);
  1955. if (empty($obj->edbrowid))
  1956. {
  1957. $qty = $obj->qty;
  1958. } else {
  1959. $qty = $obj->edbqty;
  1960. }
  1961. if ($qty <= 0) continue;
  1962. dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
  1963. $mouvS = new MouvementStock($this->db);
  1964. $mouvS->origin = &$this;
  1965. if (empty($obj->edbrowid))
  1966. {
  1967. // line without batch detail
  1968. // 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
  1969. $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentClassifyClosedInDolibarr", $numref));
  1970. if ($result < 0) {
  1971. $this->error = $mouvS->error;
  1972. $this->errors = $mouvS->errors;
  1973. $error++; break;
  1974. }
  1975. } else {
  1976. // line with batch detail
  1977. // 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
  1978. $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ShipmentClassifyClosedInDolibarr", $numref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, $obj->fk_origin_stock);
  1979. if ($result < 0) {
  1980. $this->error = $mouvS->error;
  1981. $this->errors = $mouvS->errors;
  1982. $error++; break;
  1983. }
  1984. }
  1985. }
  1986. } else {
  1987. $this->error = $this->db->lasterror();
  1988. $error++;
  1989. }
  1990. }
  1991. // Call trigger
  1992. if (!$error)
  1993. {
  1994. $result = $this->call_trigger('SHIPPING_CLOSED', $user);
  1995. if ($result < 0) {
  1996. $error++;
  1997. }
  1998. }
  1999. } else {
  2000. dol_print_error($this->db);
  2001. $error++;
  2002. }
  2003. if (!$error)
  2004. {
  2005. $this->db->commit();
  2006. return 1;
  2007. } else {
  2008. $this->statut = self::STATUS_VALIDATED;
  2009. $this->db->rollback();
  2010. return -1;
  2011. }
  2012. }
  2013. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2014. /**
  2015. * Classify the shipping as invoiced (used when WORKFLOW_BILL_ON_SHIPMENT is on)
  2016. *
  2017. * @return int <0 if ko, >0 if ok
  2018. */
  2019. public function set_billed()
  2020. {
  2021. // phpcs:enable
  2022. global $user;
  2023. $error = 0;
  2024. $this->db->begin();
  2025. $sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET fk_statut=2, billed=1'; // TODO Update only billed
  2026. $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0';
  2027. $resql = $this->db->query($sql);
  2028. if ($resql)
  2029. {
  2030. $this->statut = self::STATUS_CLOSED;
  2031. $this->billed = 1;
  2032. // Call trigger
  2033. $result = $this->call_trigger('SHIPPING_BILLED', $user);
  2034. if ($result < 0) {
  2035. $error++;
  2036. }
  2037. } else {
  2038. $error++;
  2039. $this->errors[] = $this->db->lasterror;
  2040. }
  2041. if (empty($error)) {
  2042. $this->db->commit();
  2043. return 1;
  2044. } else {
  2045. $this->statut = self::STATUS_VALIDATED;
  2046. $this->billed = 0;
  2047. $this->db->rollback();
  2048. return -1;
  2049. }
  2050. }
  2051. /**
  2052. * Classify the shipping as validated/opened
  2053. *
  2054. * @return int <0 if KO, 0 if already open, >0 if OK
  2055. */
  2056. public function reOpen()
  2057. {
  2058. global $conf, $langs, $user;
  2059. $error = 0;
  2060. // Protection. This avoid to move stock later when we should not
  2061. if ($this->statut == self::STATUS_VALIDATED)
  2062. {
  2063. return 0;
  2064. }
  2065. $this->db->begin();
  2066. $oldbilled = $this->billed;
  2067. $sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET fk_statut=1';
  2068. $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0';
  2069. $resql = $this->db->query($sql);
  2070. if ($resql)
  2071. {
  2072. $this->statut = self::STATUS_VALIDATED;
  2073. $this->billed = 0;
  2074. // If stock increment is done on closing
  2075. if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE))
  2076. {
  2077. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  2078. $langs->load("agenda");
  2079. // Loop on each product line to add a stock movement
  2080. // TODO possibilite d'expedier a partir d'une propale ou autre origine
  2081. $sql = "SELECT cd.fk_product, cd.subprice,";
  2082. $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
  2083. $sql .= " edb.rowid as edbrowid, edb.eatby, edb.sellby, edb.batch, edb.qty as edbqty, edb.fk_origin_stock";
  2084. $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd,";
  2085. $sql .= " ".MAIN_DB_PREFIX."expeditiondet as ed";
  2086. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet_batch as edb on edb.fk_expeditiondet = ed.rowid";
  2087. $sql .= " WHERE ed.fk_expedition = ".$this->id;
  2088. $sql .= " AND cd.rowid = ed.fk_origin_line";
  2089. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  2090. $resql = $this->db->query($sql);
  2091. if ($resql)
  2092. {
  2093. $cpt = $this->db->num_rows($resql);
  2094. for ($i = 0; $i < $cpt; $i++)
  2095. {
  2096. $obj = $this->db->fetch_object($resql);
  2097. if (empty($obj->edbrowid))
  2098. {
  2099. $qty = $obj->qty;
  2100. } else {
  2101. $qty = $obj->edbqty;
  2102. }
  2103. if ($qty <= 0) continue;
  2104. dol_syslog(get_class($this)."::reopen expedition movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
  2105. //var_dump($this->lines[$i]);
  2106. $mouvS = new MouvementStock($this->db);
  2107. $mouvS->origin = &$this;
  2108. if (empty($obj->edbrowid))
  2109. {
  2110. // line without batch detail
  2111. // 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
  2112. $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ShipmentUnClassifyCloseddInDolibarr", $numref));
  2113. if ($result < 0) {
  2114. $this->error = $mouvS->error;
  2115. $this->errors = $mouvS->errors;
  2116. $error++; break;
  2117. }
  2118. } else {
  2119. // line with batch detail
  2120. // 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
  2121. $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ShipmentUnClassifyCloseddInDolibarr", $numref), '', $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, $obj->fk_origin_stock);
  2122. if ($result < 0) {
  2123. $this->error = $mouvS->error;
  2124. $this->errors = $mouvS->errors;
  2125. $error++; break;
  2126. }
  2127. }
  2128. }
  2129. } else {
  2130. $this->error = $this->db->lasterror();
  2131. $error++;
  2132. }
  2133. }
  2134. if (!$error) {
  2135. // Call trigger
  2136. $result = $this->call_trigger('SHIPPING_REOPEN', $user);
  2137. if ($result < 0) {
  2138. $error++;
  2139. }
  2140. }
  2141. } else {
  2142. $error++;
  2143. $this->errors[] = $this->db->lasterror();
  2144. }
  2145. if (!$error)
  2146. {
  2147. $this->db->commit();
  2148. return 1;
  2149. } else {
  2150. $this->statut = self::STATUS_CLOSED;
  2151. $this->billed = $oldbilled;
  2152. $this->db->rollback();
  2153. return -1;
  2154. }
  2155. }
  2156. /**
  2157. * Create a document onto disk according to template module.
  2158. *
  2159. * @param string $modele Force the model to using ('' to not force)
  2160. * @param Translate $outputlangs object lang to use for translations
  2161. * @param int $hidedetails Hide details of lines
  2162. * @param int $hidedesc Hide description
  2163. * @param int $hideref Hide ref
  2164. * @param null|array $moreparams Array to provide more information
  2165. * @return int 0 if KO, 1 if OK
  2166. */
  2167. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  2168. {
  2169. global $conf;
  2170. $outputlangs->load("products");
  2171. if (!dol_strlen($modele)) {
  2172. $modele = 'rouget';
  2173. if (!empty($this->model_pdf)) {
  2174. $modele = $this->model_pdf;
  2175. } elseif (!empty($this->modelpdf)) { // deprecated
  2176. $modele = $this->modelpdf;
  2177. } elseif (!empty($conf->global->EXPEDITION_ADDON_PDF)) {
  2178. $modele = $conf->global->EXPEDITION_ADDON_PDF;
  2179. }
  2180. }
  2181. $modelpath = "core/modules/expedition/doc/";
  2182. $this->fetch_origin();
  2183. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  2184. }
  2185. /**
  2186. * Function used to replace a thirdparty id with another one.
  2187. *
  2188. * @param DoliDB $db Database handler
  2189. * @param int $origin_id Old thirdparty id
  2190. * @param int $dest_id New thirdparty id
  2191. * @return bool
  2192. */
  2193. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  2194. {
  2195. $tables = array(
  2196. 'expedition'
  2197. );
  2198. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  2199. }
  2200. }
  2201. /**
  2202. * Classe to manage lines of shipment
  2203. */
  2204. class ExpeditionLigne extends CommonObjectLine
  2205. {
  2206. /**
  2207. * @var string ID to identify managed object
  2208. */
  2209. public $element = 'expeditiondet';
  2210. /**
  2211. * @var string Name of table without prefix where object is stored
  2212. */
  2213. public $table_element = 'expeditiondet';
  2214. /**
  2215. * @deprecated
  2216. * @see $fk_origin_line
  2217. */
  2218. public $origin_line_id;
  2219. /**
  2220. * @var int ID
  2221. */
  2222. public $fk_origin_line;
  2223. /**
  2224. * @var int Id of shipment
  2225. */
  2226. public $fk_expedition;
  2227. /**
  2228. * @var DoliDB Database handler.
  2229. */
  2230. public $db;
  2231. /**
  2232. * @var float qty asked From llx_expeditiondet
  2233. */
  2234. public $qty;
  2235. /**
  2236. * @var float qty shipped
  2237. */
  2238. public $qty_shipped;
  2239. /**
  2240. * @var int Id of product
  2241. */
  2242. public $fk_product;
  2243. public $detail_batch;
  2244. /**
  2245. * @var int Id of warehouse
  2246. */
  2247. public $entrepot_id;
  2248. /**
  2249. * @var float qty asked From llx_commandedet or llx_propaldet
  2250. */
  2251. public $qty_asked;
  2252. /**
  2253. * @deprecated
  2254. * @see $product_ref
  2255. */
  2256. public $ref;
  2257. /**
  2258. * @var string product ref
  2259. */
  2260. public $product_ref;
  2261. /**
  2262. * @deprecated
  2263. * @see $product_label
  2264. */
  2265. public $libelle;
  2266. /**
  2267. * @var string product label
  2268. */
  2269. public $product_label;
  2270. /**
  2271. * @var string product description
  2272. * @deprecated
  2273. * @see $product_desc
  2274. */
  2275. public $desc;
  2276. /**
  2277. * @var string product description
  2278. */
  2279. public $product_desc;
  2280. /**
  2281. * @var int rang of line
  2282. */
  2283. public $rang;
  2284. /**
  2285. * @var float weight
  2286. */
  2287. public $weight;
  2288. public $weight_units;
  2289. /**
  2290. * @var float weight
  2291. */
  2292. public $length;
  2293. public $length_units;
  2294. /**
  2295. * @var float weight
  2296. */
  2297. public $surface;
  2298. public $surface_units;
  2299. /**
  2300. * @var float weight
  2301. */
  2302. public $volume;
  2303. public $volume_units;
  2304. // Invoicing
  2305. public $remise_percent;
  2306. public $tva_tx;
  2307. /**
  2308. * @var float total without tax
  2309. */
  2310. public $total_ht;
  2311. /**
  2312. * @var float total with tax
  2313. */
  2314. public $total_ttc;
  2315. /**
  2316. * @var float total vat
  2317. */
  2318. public $total_tva;
  2319. /**
  2320. * @var float total localtax 1
  2321. */
  2322. public $total_localtax1;
  2323. /**
  2324. * @var float total localtax 2
  2325. */
  2326. public $total_localtax2;
  2327. /**
  2328. * Constructor
  2329. *
  2330. * @param DoliDB $db Database handler
  2331. */
  2332. public function __construct($db)
  2333. {
  2334. $this->db = $db;
  2335. }
  2336. /**
  2337. * Load line expedition
  2338. *
  2339. * @param int $rowid Id line order
  2340. * @return int <0 if KO, >0 if OK
  2341. */
  2342. public function fetch($rowid)
  2343. {
  2344. $sql = 'SELECT ed.rowid, ed.fk_expedition, ed.fk_entrepot, ed.fk_origin_line, ed.qty, ed.rang';
  2345. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as ed';
  2346. $sql .= ' WHERE ed.rowid = '.$rowid;
  2347. $result = $this->db->query($sql);
  2348. if ($result)
  2349. {
  2350. $objp = $this->db->fetch_object($result);
  2351. $this->id = $objp->rowid;
  2352. $this->fk_expedition = $objp->fk_expedition;
  2353. $this->entrepot_id = $objp->fk_entrepot;
  2354. $this->fk_origin_line = $objp->fk_origin_line;
  2355. $this->qty = $objp->qty;
  2356. $this->rang = $objp->rang;
  2357. $this->db->free($result);
  2358. return 1;
  2359. } else {
  2360. $this->errors[] = $this->db->lasterror();
  2361. $this->error = $this->db->lasterror();
  2362. return -1;
  2363. }
  2364. }
  2365. /**
  2366. * Insert line into database
  2367. *
  2368. * @param User $user User that modify
  2369. * @param int $notrigger 1 = disable triggers
  2370. * @return int <0 if KO, line id >0 if OK
  2371. */
  2372. public function insert($user, $notrigger = 0)
  2373. {
  2374. global $langs, $conf;
  2375. $error = 0;
  2376. // Check parameters
  2377. if (empty($this->fk_expedition) || empty($this->fk_origin_line) || !is_numeric($this->qty))
  2378. {
  2379. $this->error = 'ErrorMandatoryParametersNotProvided';
  2380. return -1;
  2381. }
  2382. $this->db->begin();
  2383. if (empty($this->rang)) $this->rang = 0;
  2384. // Rank to use
  2385. $ranktouse = $this->rang;
  2386. if ($ranktouse == -1)
  2387. {
  2388. $rangmax = $this->line_max($fk_expedition);
  2389. $ranktouse = $rangmax + 1;
  2390. }
  2391. $sql = "INSERT INTO ".MAIN_DB_PREFIX."expeditiondet (";
  2392. $sql .= "fk_expedition";
  2393. $sql .= ", fk_entrepot";
  2394. $sql .= ", fk_origin_line";
  2395. $sql .= ", qty";
  2396. $sql .= ", rang";
  2397. $sql .= ") VALUES (";
  2398. $sql .= $this->fk_expedition;
  2399. $sql .= ", ".(empty($this->entrepot_id) ? 'NULL' : $this->entrepot_id);
  2400. $sql .= ", ".$this->fk_origin_line;
  2401. $sql .= ", ".$this->qty;
  2402. $sql .= ", ".$ranktouse;
  2403. $sql .= ")";
  2404. dol_syslog(get_class($this)."::insert", LOG_DEBUG);
  2405. $resql = $this->db->query($sql);
  2406. if ($resql)
  2407. {
  2408. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."expeditiondet");
  2409. if (!$error)
  2410. {
  2411. $result = $this->insertExtraFields();
  2412. if ($result < 0)
  2413. {
  2414. $error++;
  2415. }
  2416. }
  2417. if (!$error && !$notrigger)
  2418. {
  2419. // Call trigger
  2420. $result = $this->call_trigger('LINESHIPPING_INSERT', $user);
  2421. if ($result < 0)
  2422. {
  2423. $error++;
  2424. }
  2425. // End call triggers
  2426. }
  2427. if (!$error) {
  2428. $this->db->commit();
  2429. return $this->id;
  2430. }
  2431. foreach ($this->errors as $errmsg)
  2432. {
  2433. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  2434. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2435. }
  2436. $this->db->rollback();
  2437. return -1 * $error;
  2438. } else {
  2439. $error++;
  2440. }
  2441. }
  2442. /**
  2443. * Delete shipment line.
  2444. *
  2445. * @param User $user User that modify
  2446. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  2447. * @return int >0 if OK, <0 if KO
  2448. */
  2449. public function delete($user = null, $notrigger = 0)
  2450. {
  2451. global $conf;
  2452. $error = 0;
  2453. $this->db->begin();
  2454. // delete batch expedition line
  2455. if ($conf->productbatch->enabled)
  2456. {
  2457. $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch";
  2458. $sql .= " WHERE fk_expeditiondet = ".$this->id;
  2459. if (!$this->db->query($sql))
  2460. {
  2461. $this->errors[] = $this->db->lasterror()." - sql=$sql";
  2462. $error++;
  2463. }
  2464. }
  2465. $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet";
  2466. $sql .= " WHERE rowid = ".$this->id;
  2467. if (!$error && $this->db->query($sql))
  2468. {
  2469. // Remove extrafields
  2470. if (!$error)
  2471. {
  2472. $result = $this->deleteExtraFields();
  2473. if ($result < 0)
  2474. {
  2475. $this->errors[] = $this->error;
  2476. $error++;
  2477. }
  2478. }
  2479. if (!$error && !$notrigger)
  2480. {
  2481. // Call trigger
  2482. $result = $this->call_trigger('LINESHIPPING_DELETE', $user);
  2483. if ($result < 0)
  2484. {
  2485. $this->errors[] = $this->error;
  2486. $error++;
  2487. }
  2488. // End call triggers
  2489. }
  2490. } else {
  2491. $this->errors[] = $this->db->lasterror()." - sql=$sql";
  2492. $error++;
  2493. }
  2494. if (!$error) {
  2495. $this->db->commit();
  2496. return 1;
  2497. } else {
  2498. foreach ($this->errors as $errmsg)
  2499. {
  2500. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  2501. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2502. }
  2503. $this->db->rollback();
  2504. return -1 * $error;
  2505. }
  2506. }
  2507. /**
  2508. * Update a line in database
  2509. *
  2510. * @param User $user User that modify
  2511. * @param int $notrigger 1 = disable triggers
  2512. * @return int < 0 if KO, > 0 if OK
  2513. */
  2514. public function update($user = null, $notrigger = 0)
  2515. {
  2516. global $conf;
  2517. $error = 0;
  2518. dol_syslog(get_class($this)."::update id=$this->id, entrepot_id=$this->entrepot_id, product_id=$this->fk_product, qty=$this->qty");
  2519. $this->db->begin();
  2520. // Clean parameters
  2521. if (empty($this->qty)) $this->qty = 0;
  2522. $qty = price2num($this->qty);
  2523. $remainingQty = 0;
  2524. $batch = null;
  2525. $batch_id = null;
  2526. $expedition_batch_id = null;
  2527. if (is_array($this->detail_batch)) // array of ExpeditionLineBatch
  2528. {
  2529. if (count($this->detail_batch) > 1)
  2530. {
  2531. dol_syslog(get_class($this).'::update only possible for one batch', LOG_ERR);
  2532. $this->errors[] = 'ErrorBadParameters';
  2533. $error++;
  2534. } else {
  2535. $batch = $this->detail_batch[0]->batch;
  2536. $batch_id = $this->detail_batch[0]->fk_origin_stock;
  2537. $expedition_batch_id = $this->detail_batch[0]->id;
  2538. if ($this->entrepot_id != $this->detail_batch[0]->entrepot_id)
  2539. {
  2540. dol_syslog(get_class($this).'::update only possible for batch of same warehouse', LOG_ERR);
  2541. $this->errors[] = 'ErrorBadParameters';
  2542. $error++;
  2543. }
  2544. $qty = price2num($this->detail_batch[0]->qty);
  2545. }
  2546. } elseif (!empty($this->detail_batch))
  2547. {
  2548. $batch = $this->detail_batch->batch;
  2549. $batch_id = $this->detail_batch->fk_origin_stock;
  2550. $expedition_batch_id = $this->detail_batch->id;
  2551. if ($this->entrepot_id != $this->detail_batch->entrepot_id)
  2552. {
  2553. dol_syslog(get_class($this).'::update only possible for batch of same warehouse', LOG_ERR);
  2554. $this->errors[] = 'ErrorBadParameters';
  2555. $error++;
  2556. }
  2557. $qty = price2num($this->detail_batch->qty);
  2558. }
  2559. // check parameters
  2560. if (!isset($this->id) || !isset($this->entrepot_id))
  2561. {
  2562. dol_syslog(get_class($this).'::update missing line id and/or warehouse id', LOG_ERR);
  2563. $this->errors[] = 'ErrorMandatoryParametersNotProvided';
  2564. $error++;
  2565. return -1;
  2566. }
  2567. // update lot
  2568. if (!empty($batch) && $conf->productbatch->enabled)
  2569. {
  2570. dol_syslog(get_class($this)."::update expedition batch id=$expedition_batch_id, batch_id=$batch_id, batch=$batch");
  2571. if (empty($batch_id) || empty($this->fk_product)) {
  2572. dol_syslog(get_class($this).'::update missing fk_origin_stock (batch_id) and/or fk_product', LOG_ERR);
  2573. $this->errors[] = 'ErrorMandatoryParametersNotProvided';
  2574. $error++;
  2575. }
  2576. // fetch remaining lot qty
  2577. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php';
  2578. if (!$error && ($lotArray = ExpeditionLineBatch::fetchAll($this->db, $this->id)) < 0)
  2579. {
  2580. $this->errors[] = $this->db->lasterror()." - ExpeditionLineBatch::fetchAll";
  2581. $error++;
  2582. } else {
  2583. // caculate new total line qty
  2584. foreach ($lotArray as $lot)
  2585. {
  2586. if ($expedition_batch_id != $lot->id)
  2587. {
  2588. $remainingQty += $lot->qty;
  2589. }
  2590. }
  2591. $qty += $remainingQty;
  2592. //fetch lot details
  2593. // fetch from product_lot
  2594. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
  2595. $lot = new Productlot($this->db);
  2596. if ($lot->fetch(0, $this->fk_product, $batch) < 0)
  2597. {
  2598. $this->errors[] = $lot->errors;
  2599. $error++;
  2600. }
  2601. if (!$error && !empty($expedition_batch_id))
  2602. {
  2603. // delete lot expedition line
  2604. $sql = "DELETE FROM ".MAIN_DB_PREFIX."expeditiondet_batch";
  2605. $sql .= " WHERE fk_expeditiondet = ".$this->id;
  2606. $sql .= " AND rowid = ".$expedition_batch_id;
  2607. if (!$this->db->query($sql))
  2608. {
  2609. $this->errors[] = $this->db->lasterror()." - sql=$sql";
  2610. $error++;
  2611. }
  2612. }
  2613. if (!$error && $this->detail_batch->qty > 0)
  2614. {
  2615. // create lot expedition line
  2616. if (isset($lot->id))
  2617. {
  2618. $shipmentLot = new ExpeditionLineBatch($this->db);
  2619. $shipmentLot->batch = $lot->batch;
  2620. $shipmentLot->eatby = $lot->eatby;
  2621. $shipmentLot->sellby = $lot->sellby;
  2622. $shipmentLot->entrepot_id = $this->detail_batch->entrepot_id;
  2623. $shipmentLot->qty = $this->detail_batch->qty;
  2624. $shipmentLot->fk_origin_stock = $batch_id;
  2625. if ($shipmentLot->create($this->id) < 0)
  2626. {
  2627. $this->errors[] = $shipmentLot->errors;
  2628. $error++;
  2629. }
  2630. }
  2631. }
  2632. }
  2633. }
  2634. if (!$error)
  2635. {
  2636. // update line
  2637. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
  2638. $sql .= " fk_entrepot = ".($this->entrepot_id > 0 ? $this->entrepot_id : 'null');
  2639. $sql .= " , qty = ".$qty;
  2640. $sql .= " WHERE rowid = ".$this->id;
  2641. if (!$this->db->query($sql))
  2642. {
  2643. $this->errors[] = $this->db->lasterror()." - sql=$sql";
  2644. $error++;
  2645. }
  2646. }
  2647. if (!$error)
  2648. {
  2649. if (!$error)
  2650. {
  2651. $result = $this->insertExtraFields();
  2652. if ($result < 0)
  2653. {
  2654. $this->errors[] = $this->error;
  2655. $error++;
  2656. }
  2657. }
  2658. }
  2659. if (!$error && !$notrigger)
  2660. {
  2661. // Call trigger
  2662. $result = $this->call_trigger('LINESHIPPING_UPDATE', $user);
  2663. if ($result < 0)
  2664. {
  2665. $this->errors[] = $this->error;
  2666. $error++;
  2667. }
  2668. // End call triggers
  2669. }
  2670. if (!$error) {
  2671. $this->db->commit();
  2672. return 1;
  2673. } else {
  2674. foreach ($this->errors as $errmsg)
  2675. {
  2676. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  2677. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  2678. }
  2679. $this->db->rollback();
  2680. return -1 * $error;
  2681. }
  2682. }
  2683. }