reception.class.php 60 KB

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