reception.class.php 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952
  1. <?php
  2. /* Copyright (C) 2003-2008 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.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-2017 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-2020 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 Quentin Vial-Gouteyron <quentin.vial-gouteyron@atm-consulting.fr>
  14. *
  15. * This program is free software; you can redistribute it and/or modify
  16. * it under the terms of the GNU General Public License as published by
  17. * the Free Software Foundation; either version 3 of the License, or
  18. * (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU General Public License
  26. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  27. */
  28. /**
  29. * \file htdocs/reception/class/reception.class.php
  30. * \ingroup reception
  31. * \brief Fichier de la classe de gestion des receptions
  32. */
  33. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  34. require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
  35. require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
  36. if (!empty($conf->propal->enabled)) {
  37. require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  38. }
  39. if (!empty($conf->commande->enabled)) {
  40. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  41. }
  42. /**
  43. * Class to manage receptions
  44. */
  45. class Reception extends CommonObject
  46. {
  47. use CommonIncoterm;
  48. /**
  49. * @var string element name
  50. */
  51. public $element = "reception";
  52. /**
  53. * @var string Fieldname with ID of parent key if this field has a parent
  54. */
  55. public $fk_element = "fk_reception";
  56. public $table_element = "reception";
  57. public $table_element_line = "commande_fournisseur_dispatch";
  58. public $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  59. /**
  60. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  61. */
  62. public $picto = 'dollyrevert';
  63. public $socid;
  64. public $ref_supplier;
  65. /**
  66. * @var int Ref int
  67. * @deprecated
  68. */
  69. public $ref_int;
  70. public $brouillon;
  71. public $entrepot_id;
  72. public $tracking_number;
  73. public $tracking_url;
  74. public $billed;
  75. public $model_pdf;
  76. public $trueWeight;
  77. public $weight_units;
  78. public $trueWidth;
  79. public $width_units;
  80. public $trueHeight;
  81. public $height_units;
  82. public $trueDepth;
  83. public $depth_units;
  84. // A denormalized value
  85. public $trueSize;
  86. public $date_delivery; // Date delivery planed
  87. /**
  88. * @var integer|string Effective delivery date
  89. */
  90. public $date_reception;
  91. /**
  92. * @var integer|string date_creation
  93. */
  94. public $date_creation;
  95. /**
  96. * @var integer|string date_validation
  97. */
  98. public $date_valid;
  99. public $meths;
  100. public $listmeths; // List of carriers
  101. public $lines = array();
  102. const STATUS_DRAFT = 0;
  103. const STATUS_VALIDATED = 1;
  104. const STATUS_CLOSED = 2;
  105. /**
  106. * Constructor
  107. *
  108. * @param DoliDB $db Database handler
  109. */
  110. public function __construct($db)
  111. {
  112. $this->db = $db;
  113. // List of long language codes for status
  114. $this->statuts = array();
  115. $this->statuts[-1] = 'StatusReceptionCanceled';
  116. $this->statuts[0] = 'StatusReceptionDraft';
  117. // product to receive if stock increase is on close or already received if stock increase is on validation
  118. $this->statuts[1] = 'StatusReceptionValidated';
  119. if (getDolGlobalInt("STOCK_CALCULATE_ON_RECEPTION")) {
  120. $this->statuts[1] = 'StatusReceptionValidatedReceived';
  121. }
  122. if (getDolGlobalInt("STOCK_CALCULATE_ON_RECEPTION_CLOSE")) {
  123. $this->statuts[1] = 'StatusReceptionValidatedToReceive';
  124. }
  125. $this->statuts[2] = 'StatusReceptionProcessed';
  126. // List of short language codes for status
  127. $this->statutshorts = array();
  128. $this->statutshorts[-1] = 'StatusReceptionCanceledShort';
  129. $this->statutshorts[0] = 'StatusReceptionDraftShort';
  130. $this->statutshorts[1] = 'StatusReceptionValidatedShort';
  131. $this->statutshorts[2] = 'StatusReceptionProcessedShort';
  132. }
  133. /**
  134. * Return next contract ref
  135. *
  136. * @param Societe $soc Thirdparty object
  137. * @return string Free reference for contract
  138. */
  139. public function getNextNumRef($soc)
  140. {
  141. global $langs, $conf;
  142. $langs->load("receptions");
  143. if (!empty($conf->global->RECEPTION_ADDON_NUMBER)) {
  144. $mybool = false;
  145. $file = $conf->global->RECEPTION_ADDON_NUMBER.".php";
  146. $classname = $conf->global->RECEPTION_ADDON_NUMBER;
  147. // Include file with class
  148. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  149. foreach ($dirmodels as $reldir) {
  150. $dir = dol_buildpath($reldir."core/modules/reception/");
  151. // Load file with numbering class (if found)
  152. $mybool |= @include_once $dir.$file;
  153. }
  154. if (!$mybool) {
  155. dol_print_error('', "Failed to include file ".$file);
  156. return '';
  157. }
  158. $obj = new $classname();
  159. $numref = "";
  160. $numref = $obj->getNextValue($soc, $this);
  161. if ($numref != "") {
  162. return $numref;
  163. } else {
  164. dol_print_error($this->db, get_class($this)."::getNextNumRef ".$obj->error);
  165. return "";
  166. }
  167. } else {
  168. print $langs->trans("Error")." ".$langs->trans("Error_RECEPTION_ADDON_NUMBER_NotDefined");
  169. return "";
  170. }
  171. }
  172. /**
  173. * Create reception en base
  174. *
  175. * @param User $user Objet du user qui cree
  176. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  177. * @return int <0 si erreur, id reception creee si ok
  178. */
  179. public function create($user, $notrigger = 0)
  180. {
  181. global $conf, $hookmanager;
  182. $now = dol_now();
  183. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  184. $error = 0;
  185. // Clean parameters
  186. $this->brouillon = 1;
  187. $this->tracking_number = dol_sanitizeFileName($this->tracking_number);
  188. if (empty($this->fk_project)) {
  189. $this->fk_project = 0;
  190. }
  191. if (empty($this->weight_units)) {
  192. $this->weight_units = 0;
  193. }
  194. if (empty($this->size_units)) {
  195. $this->size_units = 0;
  196. }
  197. $this->user = $user;
  198. $this->db->begin();
  199. $sql = "INSERT INTO ".MAIN_DB_PREFIX."reception (";
  200. $sql .= "ref";
  201. $sql .= ", entity";
  202. $sql .= ", ref_supplier";
  203. $sql .= ", date_creation";
  204. $sql .= ", fk_user_author";
  205. $sql .= ", date_reception";
  206. $sql .= ", date_delivery";
  207. $sql .= ", fk_soc";
  208. $sql .= ", fk_projet";
  209. $sql .= ", fk_shipping_method";
  210. $sql .= ", tracking_number";
  211. $sql .= ", weight";
  212. $sql .= ", size";
  213. $sql .= ", width";
  214. $sql .= ", height";
  215. $sql .= ", weight_units";
  216. $sql .= ", size_units";
  217. $sql .= ", note_private";
  218. $sql .= ", note_public";
  219. $sql .= ", model_pdf";
  220. $sql .= ", fk_incoterms, location_incoterms";
  221. $sql .= ") VALUES (";
  222. $sql .= "'(PROV)'";
  223. $sql .= ", ".((int) $conf->entity);
  224. $sql .= ", ".($this->ref_supplier ? "'".$this->db->escape($this->ref_supplier)."'" : "null");
  225. $sql .= ", '".$this->db->idate($now)."'";
  226. $sql .= ", ".((int) $user->id);
  227. $sql .= ", ".($this->date_reception > 0 ? "'".$this->db->idate($this->date_reception)."'" : "null");
  228. $sql .= ", ".($this->date_delivery > 0 ? "'".$this->db->idate($this->date_delivery)."'" : "null");
  229. $sql .= ", ".((int) $this->socid);
  230. $sql .= ", ".((int) $this->fk_project);
  231. $sql .= ", ".($this->shipping_method_id > 0 ? ((int) $this->shipping_method_id) : "null");
  232. $sql .= ", '".$this->db->escape($this->tracking_number)."'";
  233. $sql .= ", ".((double) $this->weight);
  234. $sql .= ", ".((double) $this->sizeS); // TODO Should use this->trueDepth
  235. $sql .= ", ".((double) $this->sizeW); // TODO Should use this->trueWidth
  236. $sql .= ", ".((double) $this->sizeH); // TODO Should use this->trueHeight
  237. $sql .= ", ".((double) $this->weight_units);
  238. $sql .= ", ".((double) $this->size_units);
  239. $sql .= ", ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
  240. $sql .= ", ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
  241. $sql .= ", ".(!empty($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
  242. $sql .= ", ".(int) $this->fk_incoterms;
  243. $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
  244. $sql .= ")";
  245. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  246. $resql = $this->db->query($sql);
  247. if ($resql) {
  248. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."reception");
  249. $sql = "UPDATE ".MAIN_DB_PREFIX."reception";
  250. $sql .= " SET ref = '(PROV".$this->id.")'";
  251. $sql .= " WHERE rowid = ".((int) $this->id);
  252. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  253. if ($this->db->query($sql)) {
  254. // Insert of lines
  255. $num = count($this->lines);
  256. for ($i = 0; $i < $num; $i++) {
  257. $this->lines[$i]->fk_reception = $this->id;
  258. if (!$this->lines[$i]->create($user) > 0) {
  259. $error++;
  260. }
  261. }
  262. if (!$error && $this->id && $this->origin_id) {
  263. $ret = $this->add_object_linked();
  264. if (!$ret) {
  265. $error++;
  266. }
  267. }
  268. // Create extrafields
  269. if (!$error) {
  270. $result = $this->insertExtraFields();
  271. if ($result < 0) {
  272. $error++;
  273. }
  274. }
  275. if (!$error && !$notrigger) {
  276. // Call trigger
  277. $result = $this->call_trigger('RECEPTION_CREATE', $user);
  278. if ($result < 0) {
  279. $error++;
  280. }
  281. // End call triggers
  282. }
  283. if (!$error) {
  284. $this->db->commit();
  285. return $this->id;
  286. } else {
  287. foreach ($this->errors as $errmsg) {
  288. dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
  289. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  290. }
  291. $this->db->rollback();
  292. return -1 * $error;
  293. }
  294. } else {
  295. $error++;
  296. $this->error = $this->db->lasterror()." - sql=$sql";
  297. $this->db->rollback();
  298. return -2;
  299. }
  300. } else {
  301. $error++;
  302. $this->error = $this->db->error()." - sql=$sql";
  303. $this->db->rollback();
  304. return -1;
  305. }
  306. }
  307. /**
  308. * Get object and lines from database
  309. *
  310. * @param int $id Id of object to load
  311. * @param string $ref Ref of object
  312. * @param string $ref_ext External reference of object
  313. * @param string $notused Internal reference of other object
  314. * @return int >0 if OK, 0 if not found, <0 if KO
  315. */
  316. public function fetch($id, $ref = '', $ref_ext = '', $notused = '')
  317. {
  318. global $conf;
  319. // Check parameters
  320. if (empty($id) && empty($ref) && empty($ref_ext)) {
  321. return -1;
  322. }
  323. $sql = "SELECT e.rowid, e.ref, e.fk_soc as socid, e.date_creation, e.ref_supplier, e.ref_ext, e.fk_user_author, e.fk_statut";
  324. $sql .= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height";
  325. $sql .= ", e.date_reception as date_reception, e.model_pdf, e.date_delivery";
  326. $sql .= ", e.fk_shipping_method, e.tracking_number";
  327. $sql .= ", el.fk_source as origin_id, el.sourcetype as origin";
  328. $sql .= ", e.note_private, e.note_public";
  329. $sql .= ', e.fk_incoterms, e.location_incoterms';
  330. $sql .= ', i.libelle as label_incoterms';
  331. $sql .= " FROM ".MAIN_DB_PREFIX."reception as e";
  332. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = e.rowid AND el.targettype = '".$this->db->escape($this->element)."'";
  333. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON e.fk_incoterms = i.rowid';
  334. $sql .= " WHERE e.entity IN (".getEntity('reception').")";
  335. if ($id) {
  336. $sql .= " AND e.rowid=".((int) $id);
  337. }
  338. if ($ref) {
  339. $sql .= " AND e.ref='".$this->db->escape($ref)."'";
  340. }
  341. if ($ref_ext) {
  342. $sql .= " AND e.ref_ext='".$this->db->escape($ref_ext)."'";
  343. }
  344. if ($notused) {
  345. $sql .= " AND e.ref_int='".$this->db->escape($notused)."'";
  346. }
  347. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  348. $result = $this->db->query($sql);
  349. if ($result) {
  350. if ($this->db->num_rows($result)) {
  351. $obj = $this->db->fetch_object($result);
  352. $this->id = $obj->rowid;
  353. $this->ref = $obj->ref;
  354. $this->socid = $obj->socid;
  355. $this->ref_supplier = $obj->ref_supplier;
  356. $this->ref_ext = $obj->ref_ext;
  357. $this->statut = $obj->fk_statut;
  358. $this->user_author_id = $obj->fk_user_author;
  359. $this->date_creation = $this->db->jdate($obj->date_creation);
  360. $this->date = $this->db->jdate($obj->date_reception); // TODO deprecated
  361. $this->date_reception = $this->db->jdate($obj->date_reception); // TODO deprecated
  362. $this->date_reception = $this->db->jdate($obj->date_reception); // Date real
  363. $this->date_delivery = $this->db->jdate($obj->date_delivery); // Date planed
  364. $this->model_pdf = $obj->model_pdf;
  365. $this->modelpdf = $obj->model_pdf; // deprecated
  366. $this->shipping_method_id = $obj->fk_shipping_method;
  367. $this->tracking_number = $obj->tracking_number;
  368. $this->origin = ($obj->origin ? $obj->origin : 'commande'); // For compatibility
  369. $this->origin_id = $obj->origin_id;
  370. $this->billed = ($obj->fk_statut == 2 ? 1 : 0);
  371. $this->trueWeight = $obj->weight;
  372. $this->weight_units = $obj->weight_units;
  373. $this->trueWidth = $obj->width;
  374. $this->width_units = $obj->size_units;
  375. $this->trueHeight = $obj->height;
  376. $this->height_units = $obj->size_units;
  377. $this->trueDepth = $obj->size;
  378. $this->depth_units = $obj->size_units;
  379. $this->note_public = $obj->note_public;
  380. $this->note_private = $obj->note_private;
  381. // A denormalized value
  382. $this->trueSize = $obj->size."x".$obj->width."x".$obj->height;
  383. $this->size_units = $obj->size_units;
  384. //Incoterms
  385. $this->fk_incoterms = $obj->fk_incoterms;
  386. $this->location_incoterms = $obj->location_incoterms;
  387. $this->label_incoterms = $obj->label_incoterms;
  388. $this->db->free($result);
  389. if ($this->statut == 0) {
  390. $this->brouillon = 1;
  391. }
  392. $file = $conf->reception->dir_output."/".get_exdir($this->id, 2, 0, 0, $this, 'reception')."/".$this->id.".pdf";
  393. $this->pdf_filename = $file;
  394. // Tracking url
  395. $this->getUrlTrackingStatus($obj->tracking_number);
  396. /*
  397. * Thirdparty
  398. */
  399. $result = $this->fetch_thirdparty();
  400. // Retrieve all extrafields for reception
  401. // fetch optionals attributes and labels
  402. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  403. $extrafields = new ExtraFields($this->db);
  404. $extrafields->fetch_name_optionals_label($this->table_element, true);
  405. $this->fetch_optionals();
  406. /*
  407. * Lines
  408. */
  409. $result = $this->fetch_lines();
  410. if ($result < 0) {
  411. return -3;
  412. }
  413. return 1;
  414. } else {
  415. dol_syslog(get_class($this).'::Fetch no reception found', LOG_ERR);
  416. $this->error = 'Delivery with id '.$id.' not found';
  417. return 0;
  418. }
  419. } else {
  420. $this->error = $this->db->error();
  421. return -1;
  422. }
  423. }
  424. /**
  425. * Validate object and update stock if option enabled
  426. *
  427. * @param User $user Object user that validate
  428. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  429. * @return int <0 if OK, >0 if KO
  430. */
  431. public function valid($user, $notrigger = 0)
  432. {
  433. global $conf, $langs;
  434. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  435. dol_syslog(get_class($this)."::valid");
  436. // Protection
  437. if ($this->statut) {
  438. dol_syslog(get_class($this)."::valid no draft status", LOG_WARNING);
  439. return 0;
  440. }
  441. if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->creer))
  442. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->reception_advance->validate)))) {
  443. $this->error = 'Permission denied';
  444. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  445. return -1;
  446. }
  447. $this->db->begin();
  448. $error = 0;
  449. // Define new ref
  450. $soc = new Societe($this->db);
  451. $soc->fetch($this->socid);
  452. // Define new ref
  453. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  454. $numref = $this->getNextNumRef($soc);
  455. } else {
  456. $numref = $this->ref;
  457. }
  458. $this->newref = dol_sanitizeFileName($numref);
  459. $now = dol_now();
  460. // Validate
  461. $sql = "UPDATE ".MAIN_DB_PREFIX."reception SET";
  462. $sql .= " ref='".$this->db->escape($numref)."'";
  463. $sql .= ", fk_statut = 1";
  464. $sql .= ", date_valid = '".$this->db->idate($now)."'";
  465. $sql .= ", fk_user_valid = ".$user->id;
  466. $sql .= " WHERE rowid = ".((int) $this->id);
  467. dol_syslog(get_class($this)."::valid update reception", LOG_DEBUG);
  468. $resql = $this->db->query($sql);
  469. if (!$resql) {
  470. $this->error = $this->db->lasterror();
  471. $error++;
  472. }
  473. // If stock increment is done on reception (recommanded choice)
  474. if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)) {
  475. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  476. $langs->load("agenda");
  477. // Loop on each product line to add a stock movement
  478. // TODO in future, reception lines may not be linked to order line
  479. $sql = "SELECT cd.fk_product, cd.subprice,";
  480. $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
  481. $sql .= " ed.eatby, ed.sellby, ed.batch,";
  482. $sql .= " ed.cost_price";
  483. $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
  484. $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as ed";
  485. $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
  486. $sql .= " AND cd.rowid = ed.fk_commandefourndet";
  487. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  488. $resql = $this->db->query($sql);
  489. if ($resql) {
  490. $cpt = $this->db->num_rows($resql);
  491. for ($i = 0; $i < $cpt; $i++) {
  492. $obj = $this->db->fetch_object($resql);
  493. $qty = $obj->qty;
  494. if ($qty <= 0) {
  495. continue;
  496. }
  497. dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
  498. //var_dump($this->lines[$i]);
  499. $mouvS = new MouvementStock($this->db);
  500. $mouvS->origin = &$this;
  501. if (empty($obj->batch)) {
  502. // line without batch detail
  503. // 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.
  504. $inventorycode = '';
  505. if (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION || $conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
  506. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionValidatedInDolibarr", $numref), '', '', '', '', 0, $inventorycode);
  507. } else {
  508. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ReceptionValidatedInDolibarr", $numref), '', '', '', '', 0, $inventorycode);
  509. }
  510. if ($result < 0) {
  511. $error++;
  512. $this->errors[] = $mouvS->error;
  513. $this->errors = array_merge($this->errors, $mouvS->errors);
  514. break;
  515. }
  516. } else {
  517. // line with batch detail
  518. // 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.
  519. // Note: ->fk_origin_stock = id into table llx_product_batch (may be rename into llx_product_stock_batch in another version)
  520. $inventorycode = '';
  521. if (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION || $conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
  522. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionValidatedInDolibarr", $numref), $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, '', 0, $inventorycode);
  523. } else {
  524. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ReceptionValidatedInDolibarr", $numref), $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, '', 0, $inventorycode);
  525. }
  526. if ($result < 0) {
  527. $error++;
  528. $this->errors[] = $mouvS->error;
  529. $this->errors = array_merge($this->errors, $mouvS->errors);
  530. break;
  531. }
  532. }
  533. }
  534. } else {
  535. $this->db->rollback();
  536. $this->error = $this->db->error();
  537. return -2;
  538. }
  539. }
  540. // Change status of order to "reception in process"
  541. $ret = $this->setStatut(4, $this->origin_id, 'commande_fournisseur');
  542. if (!$ret) {
  543. $error++;
  544. }
  545. if (!$error && !$notrigger) {
  546. // Call trigger
  547. $result = $this->call_trigger('RECEPTION_VALIDATE', $user);
  548. if ($result < 0) {
  549. $error++;
  550. }
  551. // End call triggers
  552. }
  553. if (!$error) {
  554. $this->oldref = $this->ref;
  555. // Rename directory if dir was a temporary ref
  556. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  557. // Now we rename also files into index
  558. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'reception/".$this->db->escape($this->newref)."'";
  559. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'reception/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  560. $resql = $this->db->query($sql);
  561. if (!$resql) {
  562. $error++; $this->error = $this->db->lasterror();
  563. }
  564. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  565. $oldref = dol_sanitizeFileName($this->ref);
  566. $newref = dol_sanitizeFileName($numref);
  567. $dirsource = $conf->reception->dir_output.'/'.$oldref;
  568. $dirdest = $conf->reception->dir_output.'/'.$newref;
  569. if (!$error && file_exists($dirsource)) {
  570. dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
  571. if (@rename($dirsource, $dirdest)) {
  572. dol_syslog("Rename ok");
  573. // Rename docs starting with $oldref with $newref
  574. $listoffiles = dol_dir_list($conf->reception->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  575. foreach ($listoffiles as $fileentry) {
  576. $dirsource = $fileentry['name'];
  577. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  578. $dirsource = $fileentry['path'].'/'.$dirsource;
  579. $dirdest = $fileentry['path'].'/'.$dirdest;
  580. @rename($dirsource, $dirdest);
  581. }
  582. }
  583. }
  584. }
  585. }
  586. // Set new ref and current status
  587. if (!$error) {
  588. $this->ref = $numref;
  589. $this->statut = 1;
  590. }
  591. if (!$error) {
  592. $this->db->commit();
  593. return 1;
  594. } else {
  595. foreach ($this->errors as $errmsg) {
  596. dol_syslog(get_class($this)."::valid ".$errmsg, LOG_ERR);
  597. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  598. }
  599. $this->db->rollback();
  600. return -1 * $error;
  601. }
  602. }
  603. /**
  604. * Add an reception line.
  605. * If STOCK_WAREHOUSE_NOT_REQUIRED_FOR_RECEPTIONS is set, you can add a reception line, with no stock source defined
  606. * If STOCK_MUST_BE_ENOUGH_FOR_RECEPTION is not set, you can add a reception line, even if not enough into stock
  607. *
  608. * @param int $entrepot_id Id of warehouse
  609. * @param int $id Id of source line (supplier order line)
  610. * @param int $qty Quantity
  611. * @param array $array_options extrafields array
  612. * @param string $comment Comment for stock movement
  613. * @param integer $eatby eat-by date
  614. * @param integer $sellby sell-by date
  615. * @param string $batch Lot number
  616. * @param double $cost_price Line cost
  617. * @return int <0 if KO, index of line if OK
  618. */
  619. public function addline($entrepot_id, $id, $qty, $array_options = 0, $comment = '', $eatby = '', $sellby = '', $batch = '', $cost_price = 0)
  620. {
  621. global $conf, $langs, $user;
  622. $num = count($this->lines);
  623. $line = new CommandeFournisseurDispatch($this->db);
  624. $line->fk_entrepot = $entrepot_id;
  625. $line->fk_commandefourndet = $id;
  626. $line->qty = $qty;
  627. $supplierorderline = new CommandeFournisseurLigne($this->db);
  628. $supplierorderline->fetch($id);
  629. if (!empty($conf->stock->enabled) && !empty($supplierorderline->fk_product)) {
  630. $fk_product = $supplierorderline->fk_product;
  631. if (!($entrepot_id > 0) && empty($conf->global->STOCK_WAREHOUSE_NOT_REQUIRED_FOR_RECEPTIONS)) {
  632. $langs->load("errors");
  633. $this->error = $langs->trans("ErrorWarehouseRequiredIntoReceptionLine");
  634. return -1;
  635. }
  636. }
  637. // extrafields
  638. $line->array_options = $supplierorderline->array_options;
  639. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) {
  640. foreach ($array_options as $key => $value) {
  641. $line->array_options[$key] = $value;
  642. }
  643. }
  644. $line->fk_product = $fk_product;
  645. $line->fk_commande = $supplierorderline->fk_commande;
  646. $line->fk_user = $user->id;
  647. $line->comment = $comment;
  648. $line->batch = $batch;
  649. $line->eatby = $eatby;
  650. $line->sellby = $sellby;
  651. $line->status = 1;
  652. $line->cost_price = $cost_price;
  653. $line->fk_reception = $this->id;
  654. $this->lines[$num] = $line;
  655. return $num;
  656. }
  657. /**
  658. * Update database
  659. *
  660. * @param User $user User that modify
  661. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  662. * @return int <0 if KO, >0 if OK
  663. */
  664. public function update($user = null, $notrigger = 0)
  665. {
  666. global $conf;
  667. $error = 0;
  668. // Clean parameters
  669. if (isset($this->ref)) {
  670. $this->ref = trim($this->ref);
  671. }
  672. if (isset($this->entity)) {
  673. $this->entity = trim($this->entity);
  674. }
  675. if (isset($this->ref_supplier)) {
  676. $this->ref_supplier = trim($this->ref_supplier);
  677. }
  678. if (isset($this->socid)) {
  679. $this->socid = trim($this->socid);
  680. }
  681. if (isset($this->fk_user_author)) {
  682. $this->fk_user_author = trim($this->fk_user_author);
  683. }
  684. if (isset($this->fk_user_valid)) {
  685. $this->fk_user_valid = trim($this->fk_user_valid);
  686. }
  687. if (isset($this->shipping_method_id)) {
  688. $this->shipping_method_id = trim($this->shipping_method_id);
  689. }
  690. if (isset($this->tracking_number)) {
  691. $this->tracking_number = trim($this->tracking_number);
  692. }
  693. if (isset($this->statut)) {
  694. $this->statut = (int) $this->statut;
  695. }
  696. if (isset($this->trueDepth)) {
  697. $this->trueDepth = trim($this->trueDepth);
  698. }
  699. if (isset($this->trueWidth)) {
  700. $this->trueWidth = trim($this->trueWidth);
  701. }
  702. if (isset($this->trueHeight)) {
  703. $this->trueHeight = trim($this->trueHeight);
  704. }
  705. if (isset($this->size_units)) {
  706. $this->size_units = trim($this->size_units);
  707. }
  708. if (isset($this->weight_units)) {
  709. $this->weight_units = trim($this->weight_units);
  710. }
  711. if (isset($this->trueWeight)) {
  712. $this->weight = trim($this->trueWeight);
  713. }
  714. if (isset($this->note_private)) {
  715. $this->note_private = trim($this->note_private);
  716. }
  717. if (isset($this->note_public)) {
  718. $this->note_public = trim($this->note_public);
  719. }
  720. if (isset($this->model_pdf)) {
  721. $this->model_pdf = trim($this->model_pdf);
  722. }
  723. // Check parameters
  724. // Put here code to add control on parameters values
  725. // Update request
  726. $sql = "UPDATE ".MAIN_DB_PREFIX."reception SET";
  727. $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
  728. $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
  729. $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
  730. $sql .= " date_creation=".(dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
  731. $sql .= " fk_user_author=".(isset($this->fk_user_author) ? $this->fk_user_author : "null").",";
  732. $sql .= " date_valid=".(dol_strlen($this->date_valid) != 0 ? "'".$this->db->idate($this->date_valid)."'" : 'null').",";
  733. $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->fk_user_valid : "null").",";
  734. $sql .= " date_reception=".(dol_strlen($this->date_reception) != 0 ? "'".$this->db->idate($this->date_reception)."'" : 'null').",";
  735. $sql .= " date_delivery=".(dol_strlen($this->date_delivery) != 0 ? "'".$this->db->idate($this->date_delivery)."'" : 'null').",";
  736. $sql .= " fk_shipping_method=".((isset($this->shipping_method_id) && $this->shipping_method_id > 0) ? $this->shipping_method_id : "null").",";
  737. $sql .= " tracking_number=".(isset($this->tracking_number) ? "'".$this->db->escape($this->tracking_number)."'" : "null").",";
  738. $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
  739. $sql .= " height=".(($this->trueHeight != '') ? $this->trueHeight : "null").",";
  740. $sql .= " width=".(($this->trueWidth != '') ? $this->trueWidth : "null").",";
  741. $sql .= " size_units=".(isset($this->size_units) ? $this->size_units : "null").",";
  742. $sql .= " size=".(($this->trueDepth != '') ? $this->trueDepth : "null").",";
  743. $sql .= " weight_units=".(isset($this->weight_units) ? $this->weight_units : "null").",";
  744. $sql .= " weight=".(($this->trueWeight != '') ? $this->trueWeight : "null").",";
  745. $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
  746. $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
  747. $sql .= " model_pdf=".(isset($this->modelpdf) ? "'".$this->db->escape($this->modelpdf)."'" : "null").",";
  748. $sql .= " entity=".$conf->entity;
  749. $sql .= " WHERE rowid=".((int) $this->id);
  750. $this->db->begin();
  751. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  752. $resql = $this->db->query($sql);
  753. if (!$resql) {
  754. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  755. }
  756. if (!$error) {
  757. if (!$notrigger) {
  758. // Call trigger
  759. $result = $this->call_trigger('RECEPTION_MODIFY', $user);
  760. if ($result < 0) {
  761. $error++;
  762. }
  763. // End call triggers
  764. }
  765. }
  766. // Commit or rollback
  767. if ($error) {
  768. foreach ($this->errors as $errmsg) {
  769. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  770. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  771. }
  772. $this->db->rollback();
  773. return -1 * $error;
  774. } else {
  775. $this->db->commit();
  776. return 1;
  777. }
  778. }
  779. /**
  780. * Delete reception.
  781. *
  782. * @param User $user Object user
  783. * @return int >0 if OK, 0 if deletion done but failed to delete files, <0 if KO
  784. */
  785. public function delete(User $user)
  786. {
  787. global $conf, $langs, $user;
  788. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  789. $error = 0;
  790. $this->error = '';
  791. $this->db->begin();
  792. // Stock control
  793. if ($conf->stock->enabled && $conf->global->STOCK_CALCULATE_ON_RECEPTION && $this->statut > 0) {
  794. require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php";
  795. $langs->load("agenda");
  796. // Loop on each product line to add a stock movement
  797. $sql = "SELECT cd.fk_product, cd.subprice, ed.qty, ed.fk_entrepot, ed.eatby, ed.sellby, ed.batch, ed.rowid as commande_fournisseur_dispatch_id";
  798. $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
  799. $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as ed";
  800. $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
  801. $sql .= " AND cd.rowid = ed.fk_commandefourndet";
  802. dol_syslog(get_class($this)."::delete select details", LOG_DEBUG);
  803. $resql = $this->db->query($sql);
  804. if ($resql) {
  805. $cpt = $this->db->num_rows($resql);
  806. for ($i = 0; $i < $cpt; $i++) {
  807. dol_syslog(get_class($this)."::delete movement index ".$i);
  808. $obj = $this->db->fetch_object($resql);
  809. $mouvS = new MouvementStock($this->db);
  810. // we do not log origin because it will be deleted
  811. $mouvS->origin = null;
  812. $result = $mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, 0, $langs->trans("ReceptionDeletedInDolibarr", $this->ref), '', $obj->eatby, $obj->sellby, $obj->batch); // Price is set to 0, because we don't want to see WAP changed
  813. }
  814. } else {
  815. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  816. }
  817. }
  818. if (!$error) {
  819. $main = MAIN_DB_PREFIX.'commande_fournisseur_dispatch';
  820. $ef = $main."_extrafields";
  821. $sqlef = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_reception = ".((int) $this->id).")";
  822. $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur_dispatch";
  823. $sql .= " WHERE fk_reception = ".((int) $this->id);
  824. if ($this->db->query($sqlef) && $this->db->query($sql)) {
  825. // Delete linked object
  826. $res = $this->deleteObjectLinked();
  827. if ($res < 0) {
  828. $error++;
  829. }
  830. if (!$error) {
  831. $sql = "DELETE FROM ".MAIN_DB_PREFIX."reception";
  832. $sql .= " WHERE rowid = ".((int) $this->id);
  833. if ($this->db->query($sql)) {
  834. // Call trigger
  835. $result = $this->call_trigger('RECEPTION_DELETE', $user);
  836. if ($result < 0) {
  837. $error++;
  838. }
  839. // End call triggers
  840. if (!empty($this->origin) && $this->origin_id > 0) {
  841. $this->fetch_origin();
  842. $origin = $this->origin;
  843. if ($this->$origin->statut == 4) { // If order source of reception is "partially received"
  844. // Check if there is no more reception. If not, we can move back status of order to "validated" instead of "reception in progress"
  845. $this->$origin->loadReceptions();
  846. //var_dump($this->$origin->receptions);exit;
  847. if (count($this->$origin->receptions) <= 0) {
  848. $this->$origin->setStatut(3); // ordered
  849. }
  850. }
  851. }
  852. if (!$error) {
  853. $this->db->commit();
  854. // We delete PDFs
  855. $ref = dol_sanitizeFileName($this->ref);
  856. if (!empty($conf->reception->dir_output)) {
  857. $dir = $conf->reception->dir_output.'/'.$ref;
  858. $file = $dir.'/'.$ref.'.pdf';
  859. if (file_exists($file)) {
  860. if (!dol_delete_file($file)) {
  861. return 0;
  862. }
  863. }
  864. if (file_exists($dir)) {
  865. if (!dol_delete_dir_recursive($dir)) {
  866. $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
  867. return 0;
  868. }
  869. }
  870. }
  871. return 1;
  872. } else {
  873. $this->db->rollback();
  874. return -1;
  875. }
  876. } else {
  877. $this->error = $this->db->lasterror()." - sql=$sql";
  878. $this->db->rollback();
  879. return -3;
  880. }
  881. } else {
  882. $this->error = $this->db->lasterror()." - sql=$sql";
  883. $this->db->rollback();
  884. return -2;
  885. }
  886. } else {
  887. $this->error = $this->db->lasterror()." - sql=$sql";
  888. $this->db->rollback();
  889. return -1;
  890. }
  891. } else {
  892. $this->db->rollback();
  893. return -1;
  894. }
  895. }
  896. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  897. /**
  898. * Load lines
  899. *
  900. * @return int >0 if OK, Otherwise if KO
  901. */
  902. public function fetch_lines()
  903. {
  904. // phpcs:enable
  905. dol_include_once('/fourn/class/fournisseur.commande.dispatch.class.php');
  906. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur_dispatch WHERE fk_reception = ".((int) $this->id);
  907. $resql = $this->db->query($sql);
  908. if (!empty($resql)) {
  909. $this->lines = array();
  910. while ($obj = $this->db->fetch_object($resql)) {
  911. $line = new CommandeFournisseurDispatch($this->db);
  912. $line->fetch($obj->rowid);
  913. $line->fetch_product();
  914. $sql_commfourndet = 'SELECT qty, ref, label, description, tva_tx, vat_src_code, subprice, multicurrency_subprice, remise_percent';
  915. $sql_commfourndet .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet';
  916. $sql_commfourndet .= ' WHERE rowid = '.((int) $line->fk_commandefourndet);
  917. $resql_commfourndet = $this->db->query($sql_commfourndet);
  918. if (!empty($resql_commfourndet)) {
  919. $obj = $this->db->fetch_object($resql_commfourndet);
  920. $line->qty_asked = $obj->qty;
  921. $line->description = $obj->description;
  922. $line->desc = $obj->description;
  923. $line->tva_tx = $obj->tva_tx;
  924. $line->vat_src_code = $obj->vat_src_code;
  925. $line->subprice = $obj->subprice;
  926. $line->multicurrency_subprice = $obj->multicurrency_subprice;
  927. $line->remise_percent = $obj->remise_percent;
  928. $line->label = !empty($obj->label) ? $obj->label : $line->product->label;
  929. $line->ref_supplier = $obj->ref;
  930. } else {
  931. $line->qty_asked = 0;
  932. $line->description = '';
  933. $line->desc = '';
  934. $line->label = $obj->label;
  935. }
  936. $pu_ht = ($line->subprice * $line->qty) * (100 - $line->remise_percent) / 100;
  937. $tva = $pu_ht * $line->tva_tx / 100;
  938. $this->total_ht += $pu_ht;
  939. $this->total_tva += $pu_ht * $line->tva_tx / 100;
  940. $this->total_ttc += $pu_ht + $tva;
  941. $this->lines[] = $line;
  942. }
  943. return 1;
  944. } else {
  945. return -1;
  946. }
  947. }
  948. /**
  949. * Return clicable link of object (with eventually picto)
  950. *
  951. * @param int $withpicto Add picto into link
  952. * @param int $option Where point the link
  953. * @param int $max Max length to show
  954. * @param int $short Use short labels
  955. * @param int $notooltip 1=No tooltip
  956. * @return string String with URL
  957. */
  958. public function getNomUrl($withpicto = 0, $option = 0, $max = 0, $short = 0, $notooltip = 0)
  959. {
  960. global $conf, $langs;
  961. $result = '';
  962. $label = img_picto('', $this->picto).' <u>'.$langs->trans("Reception").'</u>';
  963. $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  964. $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.($this->ref_supplier ? $this->ref_supplier : '');
  965. $url = DOL_URL_ROOT.'/reception/card.php?id='.$this->id;
  966. if ($short) {
  967. return $url;
  968. }
  969. $linkclose = '';
  970. if (empty($notooltip)) {
  971. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  972. $label = $langs->trans("Reception");
  973. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  974. }
  975. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  976. $linkclose .= ' class="classfortooltip"';
  977. }
  978. $linkstart = '<a href="'.$url.'"';
  979. $linkstart .= $linkclose.'>';
  980. $linkend = '</a>';
  981. if ($withpicto) {
  982. $result .= ($linkstart.img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend);
  983. }
  984. if ($withpicto && $withpicto != 2) {
  985. $result .= ' ';
  986. }
  987. $result .= $linkstart.$this->ref.$linkend;
  988. return $result;
  989. }
  990. /**
  991. * Return status label
  992. *
  993. * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
  994. * @return string Libelle
  995. */
  996. public function getLibStatut($mode = 0)
  997. {
  998. return $this->LibStatut($this->statut, $mode);
  999. }
  1000. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1001. /**
  1002. * Return label of a status
  1003. *
  1004. * @param int $status Id status
  1005. * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
  1006. * @return string Label of status
  1007. */
  1008. public function LibStatut($status, $mode)
  1009. {
  1010. // phpcs:enable
  1011. global $langs;
  1012. $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]);
  1013. $labelStatusShort = $langs->transnoentitiesnoconv($this->statutshorts[$status]);
  1014. $statusType = 'status'.$status;
  1015. if ($status == self::STATUS_VALIDATED) {
  1016. $statusType = 'status4';
  1017. }
  1018. if ($status == self::STATUS_CLOSED) {
  1019. $statusType = 'status6';
  1020. }
  1021. return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
  1022. }
  1023. /**
  1024. * Initialise an instance with random values.
  1025. * Used to build previews or test instances.
  1026. * id must be 0 if object instance is a specimen.
  1027. *
  1028. * @return void
  1029. */
  1030. public function initAsSpecimen()
  1031. {
  1032. global $langs;
  1033. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  1034. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
  1035. $now = dol_now();
  1036. dol_syslog(get_class($this)."::initAsSpecimen");
  1037. // Load array of products prodids
  1038. $num_prods = 0;
  1039. $prodids = array();
  1040. $sql = "SELECT rowid";
  1041. $sql .= " FROM ".MAIN_DB_PREFIX."product";
  1042. $sql .= " WHERE entity IN (".getEntity('product').")";
  1043. $sql .= $this->db->plimit(100);
  1044. $resql = $this->db->query($sql);
  1045. if ($resql) {
  1046. $num_prods = $this->db->num_rows($resql);
  1047. $i = 0;
  1048. while ($i < $num_prods) {
  1049. $i++;
  1050. $row = $this->db->fetch_row($resql);
  1051. $prodids[$i] = $row[0];
  1052. }
  1053. }
  1054. $order = new CommandeFournisseur($this->db);
  1055. $order->initAsSpecimen();
  1056. // Initialise parametres
  1057. $this->id = 0;
  1058. $this->ref = 'SPECIMEN';
  1059. $this->specimen = 1;
  1060. $this->statut = 1;
  1061. $this->livraison_id = 0;
  1062. $this->date = $now;
  1063. $this->date_creation = $now;
  1064. $this->date_valid = $now;
  1065. $this->date_delivery = $now;
  1066. $this->date_reception = $now + 24 * 3600;
  1067. $this->entrepot_id = 0;
  1068. $this->socid = 1;
  1069. $this->commande_id = 0;
  1070. $this->commande = $order;
  1071. $this->origin_id = 1;
  1072. $this->origin = 'commande';
  1073. $this->note_private = 'Private note';
  1074. $this->note_public = 'Public note';
  1075. $nbp = 5;
  1076. $xnbp = 0;
  1077. while ($xnbp < $nbp) {
  1078. $line = new CommandeFournisseurDispatch($this->db);
  1079. $line->desc = $langs->trans("Description")." ".$xnbp;
  1080. $line->libelle = $langs->trans("Description")." ".$xnbp;
  1081. $line->qty = 10;
  1082. $line->fk_product = $this->commande->lines[$xnbp]->fk_product;
  1083. $this->lines[] = $line;
  1084. $xnbp++;
  1085. }
  1086. }
  1087. /**
  1088. * Set the planned delivery date
  1089. *
  1090. * @param User $user Objet utilisateur qui modifie
  1091. * @param integer $delivery_date Delivery date
  1092. * @return int <0 if KO, >0 if OK
  1093. */
  1094. public function setDeliveryDate($user, $delivery_date)
  1095. {
  1096. // phpcs:enable
  1097. if ($user->rights->reception->creer) {
  1098. $sql = "UPDATE ".MAIN_DB_PREFIX."reception";
  1099. $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
  1100. $sql .= " WHERE rowid = ".((int) $this->id);
  1101. dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG);
  1102. $resql = $this->db->query($sql);
  1103. if ($resql) {
  1104. $this->date_delivery = $delivery_date;
  1105. return 1;
  1106. } else {
  1107. $this->error = $this->db->error();
  1108. return -1;
  1109. }
  1110. } else {
  1111. return -2;
  1112. }
  1113. }
  1114. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1115. /**
  1116. * Fetch deliveries method and return an array. Load array this->meths(rowid=>label).
  1117. *
  1118. * @return void
  1119. */
  1120. public function fetch_delivery_methods()
  1121. {
  1122. // phpcs:enable
  1123. global $langs;
  1124. $this->meths = array();
  1125. $sql = "SELECT em.rowid, em.code, em.libelle";
  1126. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
  1127. $sql .= " WHERE em.active = 1";
  1128. $sql .= " ORDER BY em.libelle ASC";
  1129. $resql = $this->db->query($sql);
  1130. if ($resql) {
  1131. while ($obj = $this->db->fetch_object($resql)) {
  1132. $label = $langs->trans('ReceptionMethod'.$obj->code);
  1133. $this->meths[$obj->rowid] = ($label != 'ReceptionMethod'.$obj->code ? $label : $obj->libelle);
  1134. }
  1135. }
  1136. }
  1137. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1138. /**
  1139. * Fetch all deliveries method and return an array. Load array this->listmeths.
  1140. *
  1141. * @param int $id only this carrier, all if none
  1142. * @return void
  1143. */
  1144. public function list_delivery_methods($id = '')
  1145. {
  1146. // phpcs:enable
  1147. global $langs;
  1148. $this->listmeths = array();
  1149. $i = 0;
  1150. $sql = "SELECT em.rowid, em.code, em.libelle, em.description, em.tracking, em.active";
  1151. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
  1152. if ($id != '') {
  1153. $sql .= " WHERE em.rowid = ".((int) $id);
  1154. }
  1155. $resql = $this->db->query($sql);
  1156. if ($resql) {
  1157. while ($obj = $this->db->fetch_object($resql)) {
  1158. $this->listmeths[$i]['rowid'] = $obj->rowid;
  1159. $this->listmeths[$i]['code'] = $obj->code;
  1160. $label = $langs->trans('ReceptionMethod'.$obj->code);
  1161. $this->listmeths[$i]['libelle'] = ($label != 'ReceptionMethod'.$obj->code ? $label : $obj->libelle);
  1162. $this->listmeths[$i]['description'] = $obj->description;
  1163. $this->listmeths[$i]['tracking'] = $obj->tracking;
  1164. $this->listmeths[$i]['active'] = $obj->active;
  1165. $i++;
  1166. }
  1167. }
  1168. }
  1169. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1170. /**
  1171. * Update/create delivery method.
  1172. *
  1173. * @param string $id id method to activate
  1174. *
  1175. * @return void
  1176. */
  1177. public function update_delivery_method($id = '')
  1178. {
  1179. // phpcs:enable
  1180. if ($id == '') {
  1181. $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_shipment_mode (code, libelle, description, tracking)";
  1182. $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'])."')";
  1183. $resql = $this->db->query($sql);
  1184. } else {
  1185. $sql = "UPDATE ".MAIN_DB_PREFIX."c_shipment_mode SET";
  1186. $sql .= " code='".$this->db->escape($this->update['code'])."'";
  1187. $sql .= ",libelle='".$this->db->escape($this->update['libelle'])."'";
  1188. $sql .= ",description='".$this->db->escape($this->update['description'])."'";
  1189. $sql .= ",tracking='".$this->db->escape($this->update['tracking'])."'";
  1190. $sql .= " WHERE rowid=".((int) $id);
  1191. $resql = $this->db->query($sql);
  1192. }
  1193. if ($resql < 0) {
  1194. dol_print_error($this->db, '');
  1195. }
  1196. }
  1197. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1198. /**
  1199. * Activate delivery method.
  1200. *
  1201. * @param int $id id method to activate
  1202. *
  1203. * @return void
  1204. */
  1205. public function activ_delivery_method($id)
  1206. {
  1207. // phpcs:enable
  1208. $sql = 'UPDATE '.MAIN_DB_PREFIX.'c_shipment_mode SET active=1';
  1209. $sql .= ' WHERE rowid='.$id;
  1210. $resql = $this->db->query($sql);
  1211. }
  1212. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1213. /**
  1214. * DesActivate delivery method.
  1215. *
  1216. * @param int $id id method to desactivate
  1217. *
  1218. * @return void
  1219. */
  1220. public function disable_delivery_method($id)
  1221. {
  1222. // phpcs:enable
  1223. $sql = 'UPDATE '.MAIN_DB_PREFIX.'c_shipment_mode SET active=0';
  1224. $sql .= ' WHERE rowid='.$id;
  1225. $resql = $this->db->query($sql);
  1226. }
  1227. /**
  1228. * Forge an set tracking url
  1229. *
  1230. * @param string $value Value
  1231. * @return void
  1232. */
  1233. public function getUrlTrackingStatus($value = '')
  1234. {
  1235. if (!empty($this->shipping_method_id)) {
  1236. $sql = "SELECT em.code, em.tracking";
  1237. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
  1238. $sql .= " WHERE em.rowid = ".((int) $this->shipping_method_id);
  1239. $resql = $this->db->query($sql);
  1240. if ($resql) {
  1241. if ($obj = $this->db->fetch_object($resql)) {
  1242. $tracking = $obj->tracking;
  1243. }
  1244. }
  1245. }
  1246. if (!empty($tracking) && !empty($value)) {
  1247. $url = str_replace('{TRACKID}', $value, $tracking);
  1248. $this->tracking_url = sprintf('<a target="_blank" rel="noopener noreferrer" href="%s">'.($value ? $value : 'url').'</a>', $url, $url);
  1249. } else {
  1250. $this->tracking_url = $value;
  1251. }
  1252. }
  1253. /**
  1254. * Classify the reception as closed (this record also the stock movement)
  1255. *
  1256. * @return int <0 if KO, >0 if OK
  1257. */
  1258. public function setClosed()
  1259. {
  1260. global $conf, $langs, $user;
  1261. $error = 0;
  1262. $this->db->begin();
  1263. $sql = 'UPDATE '.MAIN_DB_PREFIX.'reception SET fk_statut='.self::STATUS_CLOSED;
  1264. $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > 0';
  1265. $resql = $this->db->query($sql);
  1266. if ($resql) {
  1267. // Set order billed if 100% of order is received (qty in reception lines match qty in order lines)
  1268. if ($this->origin == 'order_supplier' && $this->origin_id > 0) {
  1269. $order = new CommandeFournisseur($this->db);
  1270. $order->fetch($this->origin_id);
  1271. $order->loadReceptions(self::STATUS_CLOSED); // Fill $order->receptions = array(orderlineid => qty)
  1272. $receptions_match_order = 1;
  1273. foreach ($order->lines as $line) {
  1274. $lineid = $line->id;
  1275. $qty = $line->qty;
  1276. if (($line->product_type == 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) && $order->receptions[$lineid] < $qty) {
  1277. $receptions_match_order = 0;
  1278. $text = 'Qty for order line id '.$lineid.' is '.$qty.'. However in the receptions with status Reception::STATUS_CLOSED='.self::STATUS_CLOSED.' we have qty = '.$order->receptions[$lineid].', so we can t close order';
  1279. dol_syslog($text);
  1280. break;
  1281. }
  1282. }
  1283. if ($receptions_match_order) {
  1284. dol_syslog("Qty for the ".count($order->lines)." lines of order have same value for receptions with status Reception::STATUS_CLOSED=".self::STATUS_CLOSED.', so we close order');
  1285. $order->Livraison($user, dol_now(), 'tot', 'Reception '.$this->ref);
  1286. }
  1287. }
  1288. $this->statut = self::STATUS_CLOSED;
  1289. // If stock increment is done on closing
  1290. if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
  1291. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1292. $langs->load("agenda");
  1293. // Loop on each product line to add a stock movement
  1294. // TODO possibilite de receptionner a partir d'une propale ou autre origine ?
  1295. $sql = "SELECT cd.fk_product, cd.subprice,";
  1296. $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
  1297. $sql .= " ed.eatby, ed.sellby, ed.batch";
  1298. $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
  1299. $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as ed";
  1300. $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
  1301. $sql .= " AND cd.rowid = ed.fk_commandefourndet";
  1302. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  1303. $resql = $this->db->query($sql);
  1304. if ($resql) {
  1305. $cpt = $this->db->num_rows($resql);
  1306. for ($i = 0; $i < $cpt; $i++) {
  1307. $obj = $this->db->fetch_object($resql);
  1308. $qty = $obj->qty;
  1309. if ($qty <= 0) {
  1310. continue;
  1311. }
  1312. dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
  1313. $mouvS = new MouvementStock($this->db);
  1314. $mouvS->origin = &$this;
  1315. if (empty($obj->batch)) {
  1316. // line without batch detail
  1317. // 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
  1318. $inventorycode = '';
  1319. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ReceptionClassifyClosedInDolibarr", $this->ref), '', '', '', '', 0, $inventorycode);
  1320. if ($result < 0) {
  1321. $this->error = $mouvS->error;
  1322. $this->errors = $mouvS->errors;
  1323. $error++; break;
  1324. }
  1325. } else {
  1326. // line with batch detail
  1327. // 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
  1328. $inventorycode = '';
  1329. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ReceptionClassifyClosedInDolibarr", $this->ref), $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, '', 0, $inventorycode);
  1330. if ($result < 0) {
  1331. $this->error = $mouvS->error;
  1332. $this->errors = $mouvS->errors;
  1333. $error++; break;
  1334. }
  1335. }
  1336. }
  1337. } else {
  1338. $this->error = $this->db->lasterror();
  1339. $error++;
  1340. }
  1341. }
  1342. // Call trigger
  1343. if (!$error) {
  1344. $result = $this->call_trigger('RECEPTION_CLOSED', $user);
  1345. if ($result < 0) {
  1346. $error++;
  1347. }
  1348. }
  1349. } else {
  1350. dol_print_error($this->db);
  1351. $error++;
  1352. }
  1353. if (!$error) {
  1354. $this->db->commit();
  1355. return 1;
  1356. } else {
  1357. $this->db->rollback();
  1358. return -1;
  1359. }
  1360. }
  1361. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1362. /**
  1363. * Classify the reception as invoiced (used when WORKFLOW_BILL_ON_RECEPTION is on)
  1364. *
  1365. * @deprecated
  1366. * @see setBilled()
  1367. * @return int <0 if ko, >0 if ok
  1368. */
  1369. public function set_billed()
  1370. {
  1371. // phpcs:enable
  1372. dol_syslog(get_class($this)."::set_billed is deprecated, use setBilled instead", LOG_NOTICE);
  1373. return $this->setBilled();
  1374. }
  1375. /**
  1376. * Classify the reception as invoiced (used when WORKFLOW_BILL_ON_RECEPTION is on)
  1377. *
  1378. * @return int <0 if ko, >0 if ok
  1379. */
  1380. public function setBilled()
  1381. {
  1382. global $user;
  1383. $error = 0;
  1384. $this->db->begin();
  1385. $this->setClosed();
  1386. $sql = 'UPDATE '.MAIN_DB_PREFIX.'reception SET billed=1';
  1387. $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > 0';
  1388. $resql = $this->db->query($sql);
  1389. if ($resql) {
  1390. $this->statut = 2;
  1391. $this->billed = 1;
  1392. // Call trigger
  1393. $result = $this->call_trigger('RECEPTION_BILLED', $user);
  1394. if ($result < 0) {
  1395. $error++;
  1396. }
  1397. } else {
  1398. $error++;
  1399. $this->errors[] = $this->db->lasterror;
  1400. }
  1401. if (empty($error)) {
  1402. $this->db->commit();
  1403. return 1;
  1404. } else {
  1405. $this->db->rollback();
  1406. return -1;
  1407. }
  1408. }
  1409. /**
  1410. * Classify the reception as validated/opened
  1411. *
  1412. * @return int <0 if ko, >0 if ok
  1413. */
  1414. public function reOpen()
  1415. {
  1416. global $conf, $langs, $user;
  1417. $error = 0;
  1418. $this->db->begin();
  1419. $sql = 'UPDATE '.MAIN_DB_PREFIX.'reception SET fk_statut=1, billed=0';
  1420. $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > 0';
  1421. $resql = $this->db->query($sql);
  1422. if ($resql) {
  1423. $this->statut = 1;
  1424. $this->billed = 0;
  1425. // If stock increment is done on closing
  1426. if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
  1427. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1428. $numref = $this->ref;
  1429. $langs->load("agenda");
  1430. // Loop on each product line to add a stock movement
  1431. // TODO possibilite de receptionner a partir d'une propale ou autre origine
  1432. $sql = "SELECT ed.fk_product, cd.subprice,";
  1433. $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
  1434. $sql .= " ed.eatby, ed.sellby, ed.batch";
  1435. $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
  1436. $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as ed";
  1437. $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
  1438. $sql .= " AND cd.rowid = ed.fk_commandefourndet";
  1439. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  1440. $resql = $this->db->query($sql);
  1441. if ($resql) {
  1442. $cpt = $this->db->num_rows($resql);
  1443. for ($i = 0; $i < $cpt; $i++) {
  1444. $obj = $this->db->fetch_object($resql);
  1445. $qty = $obj->qty;
  1446. if ($qty <= 0) {
  1447. continue;
  1448. }
  1449. dol_syslog(get_class($this)."::reopen reception movement index ".$i." ed.rowid=".$obj->rowid);
  1450. //var_dump($this->lines[$i]);
  1451. $mouvS = new MouvementStock($this->db);
  1452. $mouvS->origin = &$this;
  1453. if (empty($obj->batch)) {
  1454. // line without batch detail
  1455. // 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
  1456. $inventorycode = '';
  1457. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ReceptionUnClassifyCloseddInDolibarr", $numref), '', '', '', '', 0, $inventorycode);
  1458. if ($result < 0) {
  1459. $this->error = $mouvS->error;
  1460. $this->errors = $mouvS->errors;
  1461. $error++; break;
  1462. }
  1463. } else {
  1464. // line with batch detail
  1465. // 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
  1466. $inventorycode = '';
  1467. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ReceptionUnClassifyCloseddInDolibarr", $numref), $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, '', $obj->fk_origin_stock, $inventorycode);
  1468. if ($result < 0) {
  1469. $this->error = $mouvS->error;
  1470. $this->errors = $mouvS->errors;
  1471. $error++; break;
  1472. }
  1473. }
  1474. }
  1475. } else {
  1476. $this->error = $this->db->lasterror();
  1477. $error++;
  1478. }
  1479. }
  1480. if (!$error) {
  1481. // Call trigger
  1482. $result = $this->call_trigger('RECEPTION_REOPEN', $user);
  1483. if ($result < 0) {
  1484. $error++;
  1485. }
  1486. }
  1487. if (!$error && $this->origin == 'order_supplier') {
  1488. $commande = new CommandeFournisseur($this->db);
  1489. $commande->fetch($this->origin_id);
  1490. $result = $commande->setStatus($user, 4);
  1491. if ($result < 0) {
  1492. $error++;
  1493. $this->error = $commande->error;
  1494. $this->errors = $commande->errors;
  1495. }
  1496. }
  1497. } else {
  1498. $error++;
  1499. $this->errors[] = $this->db->lasterror();
  1500. }
  1501. if (!$error) {
  1502. $this->db->commit();
  1503. return 1;
  1504. } else {
  1505. $this->db->rollback();
  1506. return -1;
  1507. }
  1508. }
  1509. /**
  1510. * Set draft status
  1511. *
  1512. * @param User $user Object user that modify
  1513. * @return int <0 if KO, >0 if OK
  1514. */
  1515. public function setDraft($user)
  1516. {
  1517. // phpcs:enable
  1518. global $conf, $langs;
  1519. $error = 0;
  1520. // Protection
  1521. if ($this->statut <= self::STATUS_DRAFT) {
  1522. return 0;
  1523. }
  1524. if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->creer))
  1525. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->reception_advance->validate)))) {
  1526. $this->error = 'Permission denied';
  1527. return -1;
  1528. }
  1529. $this->db->begin();
  1530. $sql = "UPDATE ".MAIN_DB_PREFIX."reception";
  1531. $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
  1532. $sql .= " WHERE rowid = ".((int) $this->id);
  1533. dol_syslog(__METHOD__, LOG_DEBUG);
  1534. if ($this->db->query($sql)) {
  1535. // If stock increment is done on closing
  1536. if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)) {
  1537. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1538. $langs->load("agenda");
  1539. // Loop on each product line to add a stock movement
  1540. // TODO possibilite de receptionner a partir d'une propale ou autre origine
  1541. $sql = "SELECT cd.fk_product, cd.subprice,";
  1542. $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
  1543. $sql .= " ed.eatby, ed.sellby, ed.batch";
  1544. $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
  1545. $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as ed";
  1546. $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
  1547. $sql .= " AND cd.rowid = ed.fk_commandefourndet";
  1548. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  1549. $resql = $this->db->query($sql);
  1550. if ($resql) {
  1551. $cpt = $this->db->num_rows($resql);
  1552. for ($i = 0; $i < $cpt; $i++) {
  1553. $obj = $this->db->fetch_object($resql);
  1554. $qty = $obj->qty;
  1555. if ($qty <= 0) {
  1556. continue;
  1557. }
  1558. dol_syslog(get_class($this)."::reopen reception movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
  1559. //var_dump($this->lines[$i]);
  1560. $mouvS = new MouvementStock($this->db);
  1561. $mouvS->origin = &$this;
  1562. if (empty($obj->batch)) {
  1563. // line without batch detail
  1564. // 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
  1565. $inventorycode = '';
  1566. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ReceptionBackToDraftInDolibarr", $this->ref), '', '', '', '', 0, $inventorycode);
  1567. if ($result < 0) {
  1568. $this->error = $mouvS->error;
  1569. $this->errors = $mouvS->errors;
  1570. $error++;
  1571. break;
  1572. }
  1573. } else {
  1574. // line with batch detail
  1575. // 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
  1576. $inventorycode = '';
  1577. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ReceptionBackToDraftInDolibarr", $this->ref), $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, '', 0, $inventorycode);
  1578. if ($result < 0) {
  1579. $this->error = $mouvS->error;
  1580. $this->errors = $mouvS->errors;
  1581. $error++; break;
  1582. }
  1583. }
  1584. }
  1585. } else {
  1586. $this->error = $this->db->lasterror();
  1587. $error++;
  1588. }
  1589. }
  1590. if (!$error) {
  1591. // Call trigger
  1592. $result = $this->call_trigger('RECEPTION_UNVALIDATE', $user);
  1593. if ($result < 0) {
  1594. $error++;
  1595. }
  1596. }
  1597. if ($this->origin == 'order_supplier') {
  1598. if (!empty($this->origin) && $this->origin_id > 0) {
  1599. $this->fetch_origin();
  1600. $origin = $this->origin;
  1601. if ($this->$origin->statut == 4) { // If order source of reception is "partially received"
  1602. // Check if there is no more reception validated.
  1603. $this->$origin->fetchObjectLinked();
  1604. $setStatut = 1;
  1605. if (!empty($this->$origin->linkedObjects['reception'])) {
  1606. foreach ($this->$origin->linkedObjects['reception'] as $rcption) {
  1607. if ($rcption->statut > 0) {
  1608. $setStatut = 0;
  1609. break;
  1610. }
  1611. }
  1612. //var_dump($this->$origin->receptions);exit;
  1613. if ($setStatut) {
  1614. $this->$origin->setStatut(3); // ordered
  1615. }
  1616. }
  1617. }
  1618. }
  1619. }
  1620. if (!$error) {
  1621. $this->statut = self::STATUS_DRAFT;
  1622. $this->db->commit();
  1623. return 1;
  1624. } else {
  1625. $this->db->rollback();
  1626. return -1;
  1627. }
  1628. } else {
  1629. $this->error = $this->db->error();
  1630. $this->db->rollback();
  1631. return -1;
  1632. }
  1633. }
  1634. /**
  1635. * Create a document onto disk according to template module.
  1636. *
  1637. * @param string $modele Force the model to using ('' to not force)
  1638. * @param Translate $outputlangs object lang to use for translations
  1639. * @param int $hidedetails Hide details of lines
  1640. * @param int $hidedesc Hide description
  1641. * @param int $hideref Hide ref
  1642. * @return int 0 if KO, 1 if OK
  1643. */
  1644. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
  1645. {
  1646. global $conf, $langs;
  1647. $langs->load("receptions");
  1648. if (!dol_strlen($modele)) {
  1649. $modele = 'squille';
  1650. if ($this->model_pdf) {
  1651. $modele = $this->model_pdf;
  1652. } elseif (!empty($conf->global->RECEPTION_ADDON_PDF)) {
  1653. $modele = $conf->global->RECEPTION_ADDON_PDF;
  1654. }
  1655. }
  1656. $modelpath = "core/modules/reception/doc/";
  1657. $this->fetch_origin();
  1658. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1659. }
  1660. /**
  1661. * Function used to replace a thirdparty id with another one.
  1662. *
  1663. * @param DoliDB $db Database handler
  1664. * @param int $origin_id Old thirdparty id
  1665. * @param int $dest_id New thirdparty id
  1666. * @return bool
  1667. */
  1668. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  1669. {
  1670. $tables = array('reception');
  1671. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  1672. }
  1673. }