expedition.class.php 93 KB

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