expedition.class.php 93 KB

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