expedition.class.php 91 KB

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