expedition.class.php 92 KB

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