expedition.class.php 91 KB

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