expedition.class.php 93 KB

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