reception.class.php 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033
  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-2022 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 .= ", ".(is_null($this->weight) ? "NULL" : ((double) $this->weight));
  234. $sql .= ", ".(is_null($this->trueDepth) ? "NULL" : ((double) $this->trueDepth));
  235. $sql .= ", ".(is_null($this->trueWidth) ? "NULL" : ((double) $this->trueWidth));
  236. $sql .= ", ".(is_null($this->trueHeight) ? "NULL" : ((double) $this->trueHeight));
  237. $sql .= ", ".(is_null($this->weight_units) ? "NULL" : ((double) $this->weight_units));
  238. $sql .= ", ".(is_null($this->size_units) ? "NULL" : ((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, cd.remise_percent,";
  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. $mouvS->setOrigin($this->element, $this->id);
  502. // get unit price with discount
  503. $up_ht_disc = $obj->subprice;
  504. if (!empty($obj->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) {
  505. $up_ht_disc = price2num($up_ht_disc * (100 - $obj->remise_percent) / 100, 'MU');
  506. }
  507. if (empty($obj->batch)) {
  508. // line without batch detail
  509. // 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.
  510. $inventorycode = '';
  511. if (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION || $conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
  512. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->cost_price, $langs->trans("ReceptionValidatedInDolibarr", $numref), '', '', '', '', 0, $inventorycode);
  513. } else {
  514. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $up_ht_disc, $langs->trans("ReceptionValidatedInDolibarr", $numref), '', '', '', '', 0, $inventorycode);
  515. }
  516. if ($result < 0) {
  517. $error++;
  518. $this->errors[] = $mouvS->error;
  519. $this->errors = array_merge($this->errors, $mouvS->errors);
  520. break;
  521. }
  522. } else {
  523. // line with batch detail
  524. // 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.
  525. // Note: ->fk_origin_stock = id into table llx_product_batch (may be rename into llx_product_stock_batch in another version)
  526. $inventorycode = '';
  527. if (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION || $conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
  528. $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);
  529. } else {
  530. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $up_ht_disc, $langs->trans("ReceptionValidatedInDolibarr", $numref), $this->db->jdate($obj->eatby), $this->db->jdate($obj->sellby), $obj->batch, '', 0, $inventorycode);
  531. }
  532. if ($result < 0) {
  533. $error++;
  534. $this->errors[] = $mouvS->error;
  535. $this->errors = array_merge($this->errors, $mouvS->errors);
  536. break;
  537. }
  538. }
  539. }
  540. } else {
  541. $this->db->rollback();
  542. $this->error = $this->db->error();
  543. return -2;
  544. }
  545. }
  546. // Change status of order to "reception in process" or "totally received"
  547. $status = $this->getStatusDispatch();
  548. if ($status < 0) {
  549. $error++;
  550. } else {
  551. $trigger_key = '';
  552. if ($status == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) {
  553. $ret = $this->commandeFournisseur->Livraison($user, dol_now(), 'tot', '');
  554. if ($ret < 0) {
  555. $error++;
  556. $this->errors = array_merge($this->errors, $this->commandeFournisseur->errors);
  557. }
  558. } else {
  559. $ret = $this->setStatut($status, $this->origin_id, 'commande_fournisseur', $trigger_key);
  560. if ($ret < 0) {
  561. $error++;
  562. }
  563. }
  564. }
  565. if (!$error && !$notrigger) {
  566. // Call trigger
  567. $result = $this->call_trigger('RECEPTION_VALIDATE', $user);
  568. if ($result < 0) {
  569. $error++;
  570. }
  571. // End call triggers
  572. }
  573. if (!$error) {
  574. $this->oldref = $this->ref;
  575. // Rename directory if dir was a temporary ref
  576. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  577. // Now we rename also files into index
  578. $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)."'";
  579. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'reception/".$this->db->escape($this->ref)."' AND entity = ".((int) $conf->entity);
  580. $resql = $this->db->query($sql);
  581. if (!$resql) {
  582. $error++; $this->error = $this->db->lasterror();
  583. }
  584. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  585. $oldref = dol_sanitizeFileName($this->ref);
  586. $newref = dol_sanitizeFileName($numref);
  587. $dirsource = $conf->reception->dir_output.'/'.$oldref;
  588. $dirdest = $conf->reception->dir_output.'/'.$newref;
  589. if (!$error && file_exists($dirsource)) {
  590. dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
  591. if (@rename($dirsource, $dirdest)) {
  592. dol_syslog("Rename ok");
  593. // Rename docs starting with $oldref with $newref
  594. $listoffiles = dol_dir_list($conf->reception->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  595. foreach ($listoffiles as $fileentry) {
  596. $dirsource = $fileentry['name'];
  597. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  598. $dirsource = $fileentry['path'].'/'.$dirsource;
  599. $dirdest = $fileentry['path'].'/'.$dirdest;
  600. @rename($dirsource, $dirdest);
  601. }
  602. }
  603. }
  604. }
  605. }
  606. // Set new ref and current status
  607. if (!$error) {
  608. $this->ref = $numref;
  609. $this->statut = 1;
  610. }
  611. if (!$error) {
  612. $this->db->commit();
  613. return 1;
  614. } else {
  615. foreach ($this->errors as $errmsg) {
  616. dol_syslog(get_class($this)."::valid ".$errmsg, LOG_ERR);
  617. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  618. }
  619. $this->db->rollback();
  620. return -1 * $error;
  621. }
  622. }
  623. /**
  624. * Get status from all dispatched lines
  625. *
  626. * @return int <0 if KO, Status of reception if OK
  627. */
  628. public function getStatusDispatch()
  629. {
  630. global $conf;
  631. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  632. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
  633. $status = CommandeFournisseur::STATUS_RECEIVED_PARTIALLY;
  634. if (!empty($this->origin) && $this->origin_id > 0 && ($this->origin == 'order_supplier' || $this->origin == 'commandeFournisseur')) {
  635. if (empty($this->commandeFournisseur)) {
  636. $this->fetch_origin();
  637. if (empty($this->commandeFournisseur->lines)) {
  638. $res = $this->commandeFournisseur->fetch_lines();
  639. if ($res < 0) return $res;
  640. }
  641. }
  642. $qty_received = array();
  643. $qty_wished = array();
  644. $supplierorderdispatch = new CommandeFournisseurDispatch($this->db);
  645. $filter = array('t.fk_commande'=>$this->origin_id);
  646. if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) {
  647. $filter['t.status'] = 1; // Restrict to lines with status validated
  648. }
  649. $ret = $supplierorderdispatch->fetchAll('', '', 0, 0, $filter);
  650. if ($ret < 0) {
  651. $this->error = $supplierorderdispatch->error;
  652. $this->errors = $supplierorderdispatch->errors;
  653. return $ret;
  654. } else {
  655. // build array with quantity received by product in all supplier orders (origin)
  656. foreach ($supplierorderdispatch->lines as $dispatch_line) {
  657. $qty_received[$dispatch_line->fk_product] += $dispatch_line->qty;
  658. }
  659. // qty wished in order supplier (origin)
  660. foreach ($this->commandeFournisseur->lines as $origin_line) {
  661. // exclude lines not qualified for reception
  662. if (empty($conf->global->STOCK_SUPPORTS_SERVICES) && $origin_line->product_type > 0) {
  663. continue;
  664. }
  665. $qty_wished[$origin_line->fk_product] += $origin_line->qty;
  666. }
  667. // compare array
  668. $diff_array = array_diff_assoc($qty_received, $qty_wished); // Warning: $diff_array is done only on common keys.
  669. $keys_in_wished_not_in_received = array_diff(array_keys($qty_wished), array_keys($qty_received));
  670. $keys_in_received_not_in_wished = array_diff(array_keys($qty_received), array_keys($qty_wished));
  671. if (count($diff_array) == 0 && count($keys_in_wished_not_in_received) == 0 && count($keys_in_received_not_in_wished) == 0) { // no diff => mean everything is received
  672. $status = CommandeFournisseur::STATUS_RECEIVED_COMPLETELY;
  673. } elseif (!empty($conf->global->SUPPLIER_ORDER_MORE_THAN_WISHED)) {
  674. // set totally received if more products received than ordered
  675. $close = 0;
  676. if (count($diff_array) > 0) {
  677. // there are some difference between the two arrays
  678. // scan the array of results
  679. foreach ($diff_array as $key => $value) {
  680. // if the quantity delivered is greater or equal to ordered quantity
  681. if ($qty_received[$key] >= $qty_wished[$key]) {
  682. $close++;
  683. }
  684. }
  685. }
  686. if ($close == count($diff_array)) {
  687. // all the products are received equal or more than the ordered quantity
  688. $status = CommandeFournisseur::STATUS_RECEIVED_COMPLETELY;
  689. }
  690. }
  691. }
  692. }
  693. return $status;
  694. }
  695. /**
  696. * Add an reception line.
  697. * If STOCK_WAREHOUSE_NOT_REQUIRED_FOR_RECEPTIONS is set, you can add a reception line, with no stock source defined
  698. * If STOCK_MUST_BE_ENOUGH_FOR_RECEPTION is not set, you can add a reception line, even if not enough into stock
  699. *
  700. * @param int $entrepot_id Id of warehouse
  701. * @param int $id Id of source line (supplier order line)
  702. * @param int $qty Quantity
  703. * @param array $array_options extrafields array
  704. * @param string $comment Comment for stock movement
  705. * @param integer $eatby eat-by date
  706. * @param integer $sellby sell-by date
  707. * @param string $batch Lot number
  708. * @param double $cost_price Line cost
  709. * @return int <0 if KO, index of line if OK
  710. */
  711. public function addline($entrepot_id, $id, $qty, $array_options = 0, $comment = '', $eatby = '', $sellby = '', $batch = '', $cost_price = 0)
  712. {
  713. global $conf, $langs, $user;
  714. $num = count($this->lines);
  715. $line = new CommandeFournisseurDispatch($this->db);
  716. $line->fk_entrepot = $entrepot_id;
  717. $line->fk_commandefourndet = $id;
  718. $line->qty = $qty;
  719. $supplierorderline = new CommandeFournisseurLigne($this->db);
  720. $result = $supplierorderline->fetch($id);
  721. if ($result <= 0) {
  722. $this->error = $supplierorderline->error;
  723. $this->errors = $supplierorderline->errors;
  724. return -1;
  725. }
  726. $fk_product = 0;
  727. if (!empty($conf->stock->enabled) && !empty($supplierorderline->fk_product)) {
  728. $fk_product = $supplierorderline->fk_product;
  729. if (!($entrepot_id > 0) && empty($conf->global->STOCK_WAREHOUSE_NOT_REQUIRED_FOR_RECEPTIONS)) {
  730. $langs->load("errors");
  731. $this->error = $langs->trans("ErrorWarehouseRequiredIntoReceptionLine");
  732. return -1;
  733. }
  734. }
  735. // extrafields
  736. $line->array_options = $supplierorderline->array_options;
  737. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) {
  738. foreach ($array_options as $key => $value) {
  739. $line->array_options[$key] = $value;
  740. }
  741. }
  742. $line->fk_product = $fk_product;
  743. $line->fk_commande = $supplierorderline->fk_commande;
  744. $line->fk_user = $user->id;
  745. $line->comment = $comment;
  746. $line->batch = $batch;
  747. $line->eatby = $eatby;
  748. $line->sellby = $sellby;
  749. $line->status = 1;
  750. $line->cost_price = $cost_price;
  751. $line->fk_reception = $this->id;
  752. $this->lines[$num] = $line;
  753. return $num;
  754. }
  755. /**
  756. * Update database
  757. *
  758. * @param User $user User that modify
  759. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  760. * @return int <0 if KO, >0 if OK
  761. */
  762. public function update($user = null, $notrigger = 0)
  763. {
  764. global $conf;
  765. $error = 0;
  766. // Clean parameters
  767. if (isset($this->ref)) {
  768. $this->ref = trim($this->ref);
  769. }
  770. if (isset($this->entity)) {
  771. $this->entity = trim($this->entity);
  772. }
  773. if (isset($this->ref_supplier)) {
  774. $this->ref_supplier = trim($this->ref_supplier);
  775. }
  776. if (isset($this->socid)) {
  777. $this->socid = trim($this->socid);
  778. }
  779. if (isset($this->fk_user_author)) {
  780. $this->fk_user_author = trim($this->fk_user_author);
  781. }
  782. if (isset($this->fk_user_valid)) {
  783. $this->fk_user_valid = trim($this->fk_user_valid);
  784. }
  785. if (isset($this->shipping_method_id)) {
  786. $this->shipping_method_id = trim($this->shipping_method_id);
  787. }
  788. if (isset($this->tracking_number)) {
  789. $this->tracking_number = trim($this->tracking_number);
  790. }
  791. if (isset($this->statut)) {
  792. $this->statut = (int) $this->statut;
  793. }
  794. if (isset($this->trueDepth)) {
  795. $this->trueDepth = trim($this->trueDepth);
  796. }
  797. if (isset($this->trueWidth)) {
  798. $this->trueWidth = trim($this->trueWidth);
  799. }
  800. if (isset($this->trueHeight)) {
  801. $this->trueHeight = trim($this->trueHeight);
  802. }
  803. if (isset($this->size_units)) {
  804. $this->size_units = trim($this->size_units);
  805. }
  806. if (isset($this->weight_units)) {
  807. $this->weight_units = trim($this->weight_units);
  808. }
  809. if (isset($this->trueWeight)) {
  810. $this->weight = trim($this->trueWeight);
  811. }
  812. if (isset($this->note_private)) {
  813. $this->note_private = trim($this->note_private);
  814. }
  815. if (isset($this->note_public)) {
  816. $this->note_public = trim($this->note_public);
  817. }
  818. if (isset($this->model_pdf)) {
  819. $this->model_pdf = trim($this->model_pdf);
  820. }
  821. // Check parameters
  822. // Put here code to add control on parameters values
  823. // Update request
  824. $sql = "UPDATE ".MAIN_DB_PREFIX."reception SET";
  825. $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
  826. $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
  827. $sql .= " fk_soc=".(isset($this->socid) ? $this->socid : "null").",";
  828. $sql .= " date_creation=".(dol_strlen($this->date_creation) != 0 ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
  829. $sql .= " fk_user_author=".(isset($this->fk_user_author) ? $this->fk_user_author : "null").",";
  830. $sql .= " date_valid=".(dol_strlen($this->date_valid) != 0 ? "'".$this->db->idate($this->date_valid)."'" : 'null').",";
  831. $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->fk_user_valid : "null").",";
  832. $sql .= " date_reception=".(dol_strlen($this->date_reception) != 0 ? "'".$this->db->idate($this->date_reception)."'" : 'null').",";
  833. $sql .= " date_delivery=".(dol_strlen($this->date_delivery) != 0 ? "'".$this->db->idate($this->date_delivery)."'" : 'null').",";
  834. $sql .= " fk_shipping_method=".((isset($this->shipping_method_id) && $this->shipping_method_id > 0) ? $this->shipping_method_id : "null").",";
  835. $sql .= " tracking_number=".(isset($this->tracking_number) ? "'".$this->db->escape($this->tracking_number)."'" : "null").",";
  836. $sql .= " fk_statut=".(isset($this->statut) ? $this->statut : "null").",";
  837. $sql .= " height=".(($this->trueHeight != '') ? $this->trueHeight : "null").",";
  838. $sql .= " width=".(($this->trueWidth != '') ? $this->trueWidth : "null").",";
  839. $sql .= " size_units=".(isset($this->size_units) ? $this->size_units : "null").",";
  840. $sql .= " size=".(($this->trueDepth != '') ? $this->trueDepth : "null").",";
  841. $sql .= " weight_units=".(isset($this->weight_units) ? $this->weight_units : "null").",";
  842. $sql .= " weight=".(($this->trueWeight != '') ? $this->trueWeight : "null").",";
  843. $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
  844. $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
  845. $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
  846. $sql .= " entity = ".((int) $conf->entity);
  847. $sql .= " WHERE rowid=".((int) $this->id);
  848. $this->db->begin();
  849. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  850. $resql = $this->db->query($sql);
  851. if (!$resql) {
  852. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  853. }
  854. if (!$error) {
  855. if (!$notrigger) {
  856. // Call trigger
  857. $result = $this->call_trigger('RECEPTION_MODIFY', $user);
  858. if ($result < 0) {
  859. $error++;
  860. }
  861. // End call triggers
  862. }
  863. }
  864. // Commit or rollback
  865. if ($error) {
  866. foreach ($this->errors as $errmsg) {
  867. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  868. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  869. }
  870. $this->db->rollback();
  871. return -1 * $error;
  872. } else {
  873. $this->db->commit();
  874. return 1;
  875. }
  876. }
  877. /**
  878. * Delete reception.
  879. *
  880. * @param User $user Object user
  881. * @return int >0 if OK, 0 if deletion done but failed to delete files, <0 if KO
  882. */
  883. public function delete(User $user)
  884. {
  885. global $conf, $langs, $user;
  886. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  887. $error = 0;
  888. $this->error = '';
  889. $this->db->begin();
  890. // Stock control
  891. if ($conf->stock->enabled && $conf->global->STOCK_CALCULATE_ON_RECEPTION && $this->statut > 0) {
  892. require_once DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php";
  893. $langs->load("agenda");
  894. // Loop on each product line to add a stock movement
  895. $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";
  896. $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
  897. $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as ed";
  898. $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
  899. $sql .= " AND cd.rowid = ed.fk_commandefourndet";
  900. dol_syslog(get_class($this)."::delete select details", LOG_DEBUG);
  901. $resql = $this->db->query($sql);
  902. if ($resql) {
  903. $cpt = $this->db->num_rows($resql);
  904. for ($i = 0; $i < $cpt; $i++) {
  905. dol_syslog(get_class($this)."::delete movement index ".$i);
  906. $obj = $this->db->fetch_object($resql);
  907. $mouvS = new MouvementStock($this->db);
  908. // we do not log origin because it will be deleted
  909. $mouvS->origin = null;
  910. $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
  911. }
  912. } else {
  913. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  914. }
  915. }
  916. if (!$error) {
  917. $main = MAIN_DB_PREFIX.'commande_fournisseur_dispatch';
  918. $ef = $main."_extrafields";
  919. $sqlef = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_reception = ".((int) $this->id).")";
  920. $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur_dispatch";
  921. $sql .= " WHERE fk_reception = ".((int) $this->id);
  922. if ($this->db->query($sqlef) && $this->db->query($sql)) {
  923. // Delete linked object
  924. $res = $this->deleteObjectLinked();
  925. if ($res < 0) {
  926. $error++;
  927. }
  928. if (!$error) {
  929. $sql = "DELETE FROM ".MAIN_DB_PREFIX."reception";
  930. $sql .= " WHERE rowid = ".((int) $this->id);
  931. if ($this->db->query($sql)) {
  932. // Call trigger
  933. $result = $this->call_trigger('RECEPTION_DELETE', $user);
  934. if ($result < 0) {
  935. $error++;
  936. }
  937. // End call triggers
  938. if (!empty($this->origin) && $this->origin_id > 0) {
  939. $this->fetch_origin();
  940. $origin = $this->origin;
  941. if ($this->$origin->statut == 4) { // If order source of reception is "partially received"
  942. // Check if there is no more reception. If not, we can move back status of order to "validated" instead of "reception in progress"
  943. $this->$origin->loadReceptions();
  944. //var_dump($this->$origin->receptions);exit;
  945. if (count($this->$origin->receptions) <= 0) {
  946. $this->$origin->setStatut(3); // ordered
  947. }
  948. }
  949. }
  950. if (!$error) {
  951. $this->db->commit();
  952. // We delete PDFs
  953. $ref = dol_sanitizeFileName($this->ref);
  954. if (!empty($conf->reception->dir_output)) {
  955. $dir = $conf->reception->dir_output.'/'.$ref;
  956. $file = $dir.'/'.$ref.'.pdf';
  957. if (file_exists($file)) {
  958. if (!dol_delete_file($file)) {
  959. return 0;
  960. }
  961. }
  962. if (file_exists($dir)) {
  963. if (!dol_delete_dir_recursive($dir)) {
  964. $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
  965. return 0;
  966. }
  967. }
  968. }
  969. return 1;
  970. } else {
  971. $this->db->rollback();
  972. return -1;
  973. }
  974. } else {
  975. $this->error = $this->db->lasterror()." - sql=$sql";
  976. $this->db->rollback();
  977. return -3;
  978. }
  979. } else {
  980. $this->error = $this->db->lasterror()." - sql=$sql";
  981. $this->db->rollback();
  982. return -2;
  983. }
  984. } else {
  985. $this->error = $this->db->lasterror()." - sql=$sql";
  986. $this->db->rollback();
  987. return -1;
  988. }
  989. } else {
  990. $this->db->rollback();
  991. return -1;
  992. }
  993. }
  994. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  995. /**
  996. * Load lines
  997. *
  998. * @return int >0 if OK, Otherwise if KO
  999. */
  1000. public function fetch_lines()
  1001. {
  1002. // phpcs:enable
  1003. $this->lines = array();
  1004. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
  1005. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."commande_fournisseur_dispatch WHERE fk_reception = ".((int) $this->id);
  1006. $resql = $this->db->query($sql);
  1007. if (!empty($resql)) {
  1008. while ($obj = $this->db->fetch_object($resql)) {
  1009. $line = new CommandeFournisseurDispatch($this->db);
  1010. $line->fetch($obj->rowid);
  1011. $line->fetch_product();
  1012. $sql_commfourndet = 'SELECT qty, ref, label, description, tva_tx, vat_src_code, subprice, multicurrency_subprice, remise_percent';
  1013. $sql_commfourndet .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet';
  1014. $sql_commfourndet .= ' WHERE rowid = '.((int) $line->fk_commandefourndet);
  1015. $sql_commfourndet .= ' ORDER BY rang';
  1016. $resql_commfourndet = $this->db->query($sql_commfourndet);
  1017. if (!empty($resql_commfourndet)) {
  1018. $obj = $this->db->fetch_object($resql_commfourndet);
  1019. $line->qty_asked = $obj->qty;
  1020. $line->description = $obj->description;
  1021. $line->desc = $obj->description;
  1022. $line->tva_tx = $obj->tva_tx;
  1023. $line->vat_src_code = $obj->vat_src_code;
  1024. $line->subprice = $obj->subprice;
  1025. $line->multicurrency_subprice = $obj->multicurrency_subprice;
  1026. $line->remise_percent = $obj->remise_percent;
  1027. $line->label = !empty($obj->label) ? $obj->label : $line->product->label;
  1028. $line->ref_supplier = $obj->ref;
  1029. } else {
  1030. $line->qty_asked = 0;
  1031. $line->description = '';
  1032. $line->desc = '';
  1033. $line->label = $obj->label;
  1034. }
  1035. $pu_ht = ($line->subprice * $line->qty) * (100 - $line->remise_percent) / 100;
  1036. $tva = $pu_ht * $line->tva_tx / 100;
  1037. $this->total_ht += $pu_ht;
  1038. $this->total_tva += $pu_ht * $line->tva_tx / 100;
  1039. $this->total_ttc += $pu_ht + $tva;
  1040. $this->lines[] = $line;
  1041. }
  1042. return 1;
  1043. } else {
  1044. return -1;
  1045. }
  1046. }
  1047. /**
  1048. * Return clicable link of object (with eventually picto)
  1049. *
  1050. * @param int $withpicto Add picto into link
  1051. * @param int $option Where point the link
  1052. * @param int $max Max length to show
  1053. * @param int $short Use short labels
  1054. * @param int $notooltip 1=No tooltip
  1055. * @return string String with URL
  1056. */
  1057. public function getNomUrl($withpicto = 0, $option = 0, $max = 0, $short = 0, $notooltip = 0)
  1058. {
  1059. global $conf, $langs, $hookmanager;
  1060. $result = '';
  1061. $label = img_picto('', $this->picto).' <u>'.$langs->trans("Reception").'</u>';
  1062. $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1063. $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.($this->ref_supplier ? $this->ref_supplier : '');
  1064. $url = DOL_URL_ROOT.'/reception/card.php?id='.$this->id;
  1065. if ($short) {
  1066. return $url;
  1067. }
  1068. $linkclose = '';
  1069. if (empty($notooltip)) {
  1070. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1071. $label = $langs->trans("Reception");
  1072. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1073. }
  1074. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1075. $linkclose .= ' class="classfortooltip"';
  1076. }
  1077. $linkstart = '<a href="'.$url.'"';
  1078. $linkstart .= $linkclose.'>';
  1079. $linkend = '</a>';
  1080. if ($withpicto) {
  1081. $result .= ($linkstart.img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).$linkend);
  1082. }
  1083. if ($withpicto && $withpicto != 2) {
  1084. $result .= ' ';
  1085. }
  1086. $result .= $linkstart.$this->ref.$linkend;
  1087. global $action;
  1088. $hookmanager->initHooks(array($this->element . 'dao'));
  1089. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1090. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1091. if ($reshook > 0) {
  1092. $result = $hookmanager->resPrint;
  1093. } else {
  1094. $result .= $hookmanager->resPrint;
  1095. }
  1096. return $result;
  1097. }
  1098. /**
  1099. * Return status label
  1100. *
  1101. * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
  1102. * @return string Libelle
  1103. */
  1104. public function getLibStatut($mode = 0)
  1105. {
  1106. return $this->LibStatut($this->statut, $mode);
  1107. }
  1108. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1109. /**
  1110. * Return label of a status
  1111. *
  1112. * @param int $status Id status
  1113. * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto
  1114. * @return string Label of status
  1115. */
  1116. public function LibStatut($status, $mode)
  1117. {
  1118. // phpcs:enable
  1119. global $langs;
  1120. $labelStatus = $langs->transnoentitiesnoconv($this->statuts[$status]);
  1121. $labelStatusShort = $langs->transnoentitiesnoconv($this->statutshorts[$status]);
  1122. $statusType = 'status'.$status;
  1123. if ($status == self::STATUS_VALIDATED) {
  1124. $statusType = 'status4';
  1125. }
  1126. if ($status == self::STATUS_CLOSED) {
  1127. $statusType = 'status6';
  1128. }
  1129. return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
  1130. }
  1131. /**
  1132. * Initialise an instance with random values.
  1133. * Used to build previews or test instances.
  1134. * id must be 0 if object instance is a specimen.
  1135. *
  1136. * @return void
  1137. */
  1138. public function initAsSpecimen()
  1139. {
  1140. global $langs;
  1141. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  1142. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php';
  1143. $now = dol_now();
  1144. dol_syslog(get_class($this)."::initAsSpecimen");
  1145. // Load array of products prodids
  1146. $num_prods = 0;
  1147. $prodids = array();
  1148. $sql = "SELECT rowid";
  1149. $sql .= " FROM ".MAIN_DB_PREFIX."product";
  1150. $sql .= " WHERE entity IN (".getEntity('product').")";
  1151. $sql .= $this->db->plimit(100);
  1152. $resql = $this->db->query($sql);
  1153. if ($resql) {
  1154. $num_prods = $this->db->num_rows($resql);
  1155. $i = 0;
  1156. while ($i < $num_prods) {
  1157. $i++;
  1158. $row = $this->db->fetch_row($resql);
  1159. $prodids[$i] = $row[0];
  1160. }
  1161. }
  1162. $order = new CommandeFournisseur($this->db);
  1163. $order->initAsSpecimen();
  1164. // Initialise parametres
  1165. $this->id = 0;
  1166. $this->ref = 'SPECIMEN';
  1167. $this->specimen = 1;
  1168. $this->statut = 1;
  1169. $this->livraison_id = 0;
  1170. $this->date = $now;
  1171. $this->date_creation = $now;
  1172. $this->date_valid = $now;
  1173. $this->date_delivery = $now;
  1174. $this->date_reception = $now + 24 * 3600;
  1175. $this->entrepot_id = 0;
  1176. $this->socid = 1;
  1177. $this->commande_id = 0;
  1178. $this->commande = $order;
  1179. $this->origin_id = 1;
  1180. $this->origin = 'commande';
  1181. $this->note_private = 'Private note';
  1182. $this->note_public = 'Public note';
  1183. $nbp = 5;
  1184. $xnbp = 0;
  1185. while ($xnbp < $nbp) {
  1186. $line = new CommandeFournisseurDispatch($this->db);
  1187. $line->desc = $langs->trans("Description")." ".$xnbp;
  1188. $line->libelle = $langs->trans("Description")." ".$xnbp;
  1189. $line->qty = 10;
  1190. $line->fk_product = $this->commande->lines[$xnbp]->fk_product;
  1191. $this->lines[] = $line;
  1192. $xnbp++;
  1193. }
  1194. }
  1195. /**
  1196. * Set the planned delivery date
  1197. *
  1198. * @param User $user Objet utilisateur qui modifie
  1199. * @param integer $delivery_date Delivery date
  1200. * @return int <0 if KO, >0 if OK
  1201. */
  1202. public function setDeliveryDate($user, $delivery_date)
  1203. {
  1204. // phpcs:enable
  1205. if ($user->rights->reception->creer) {
  1206. $sql = "UPDATE ".MAIN_DB_PREFIX."reception";
  1207. $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
  1208. $sql .= " WHERE rowid = ".((int) $this->id);
  1209. dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG);
  1210. $resql = $this->db->query($sql);
  1211. if ($resql) {
  1212. $this->date_delivery = $delivery_date;
  1213. return 1;
  1214. } else {
  1215. $this->error = $this->db->error();
  1216. return -1;
  1217. }
  1218. } else {
  1219. return -2;
  1220. }
  1221. }
  1222. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1223. /**
  1224. * Fetch deliveries method and return an array. Load array this->meths(rowid=>label).
  1225. *
  1226. * @return void
  1227. */
  1228. public function fetch_delivery_methods()
  1229. {
  1230. // phpcs:enable
  1231. global $langs;
  1232. $this->meths = array();
  1233. $sql = "SELECT em.rowid, em.code, em.libelle";
  1234. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
  1235. $sql .= " WHERE em.active = 1";
  1236. $sql .= " ORDER BY em.libelle ASC";
  1237. $resql = $this->db->query($sql);
  1238. if ($resql) {
  1239. while ($obj = $this->db->fetch_object($resql)) {
  1240. $label = $langs->trans('ReceptionMethod'.$obj->code);
  1241. $this->meths[$obj->rowid] = ($label != 'ReceptionMethod'.$obj->code ? $label : $obj->libelle);
  1242. }
  1243. }
  1244. }
  1245. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1246. /**
  1247. * Fetch all deliveries method and return an array. Load array this->listmeths.
  1248. *
  1249. * @param int $id only this carrier, all if none
  1250. * @return void
  1251. */
  1252. public function list_delivery_methods($id = '')
  1253. {
  1254. // phpcs:enable
  1255. global $langs;
  1256. $this->listmeths = array();
  1257. $i = 0;
  1258. $sql = "SELECT em.rowid, em.code, em.libelle, em.description, em.tracking, em.active";
  1259. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
  1260. if ($id != '') {
  1261. $sql .= " WHERE em.rowid = ".((int) $id);
  1262. }
  1263. $resql = $this->db->query($sql);
  1264. if ($resql) {
  1265. while ($obj = $this->db->fetch_object($resql)) {
  1266. $this->listmeths[$i]['rowid'] = $obj->rowid;
  1267. $this->listmeths[$i]['code'] = $obj->code;
  1268. $label = $langs->trans('ReceptionMethod'.$obj->code);
  1269. $this->listmeths[$i]['libelle'] = ($label != 'ReceptionMethod'.$obj->code ? $label : $obj->libelle);
  1270. $this->listmeths[$i]['description'] = $obj->description;
  1271. $this->listmeths[$i]['tracking'] = $obj->tracking;
  1272. $this->listmeths[$i]['active'] = $obj->active;
  1273. $i++;
  1274. }
  1275. }
  1276. }
  1277. /**
  1278. * Forge an set tracking url
  1279. *
  1280. * @param string $value Value
  1281. * @return void
  1282. */
  1283. public function getUrlTrackingStatus($value = '')
  1284. {
  1285. if (!empty($this->shipping_method_id)) {
  1286. $sql = "SELECT em.code, em.tracking";
  1287. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as em";
  1288. $sql .= " WHERE em.rowid = ".((int) $this->shipping_method_id);
  1289. $resql = $this->db->query($sql);
  1290. if ($resql) {
  1291. if ($obj = $this->db->fetch_object($resql)) {
  1292. $tracking = $obj->tracking;
  1293. }
  1294. }
  1295. }
  1296. if (!empty($tracking) && !empty($value)) {
  1297. $url = str_replace('{TRACKID}', $value, $tracking);
  1298. $this->tracking_url = sprintf('<a target="_blank" rel="noopener noreferrer" href="%s">'.($value ? $value : 'url').'</a>', $url, $url);
  1299. } else {
  1300. $this->tracking_url = $value;
  1301. }
  1302. }
  1303. /**
  1304. * Classify the reception as closed (this record also the stock movement)
  1305. *
  1306. * @return int <0 if KO, >0 if OK
  1307. */
  1308. public function setClosed()
  1309. {
  1310. global $conf, $langs, $user;
  1311. $error = 0;
  1312. $this->db->begin();
  1313. $sql = 'UPDATE '.MAIN_DB_PREFIX.'reception SET fk_statut='.self::STATUS_CLOSED;
  1314. $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > 0';
  1315. $resql = $this->db->query($sql);
  1316. if ($resql) {
  1317. // Set order billed if 100% of order is received (qty in reception lines match qty in order lines)
  1318. if ($this->origin == 'order_supplier' && $this->origin_id > 0) {
  1319. $order = new CommandeFournisseur($this->db);
  1320. $order->fetch($this->origin_id);
  1321. $order->loadReceptions(self::STATUS_CLOSED); // Fill $order->receptions = array(orderlineid => qty)
  1322. $receptions_match_order = 1;
  1323. foreach ($order->lines as $line) {
  1324. $lineid = $line->id;
  1325. $qty = $line->qty;
  1326. if (($line->product_type == 0 || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) && $order->receptions[$lineid] < $qty) {
  1327. $receptions_match_order = 0;
  1328. $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';
  1329. dol_syslog($text);
  1330. break;
  1331. }
  1332. }
  1333. if ($receptions_match_order) {
  1334. 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');
  1335. $order->Livraison($user, dol_now(), 'tot', 'Reception '.$this->ref);
  1336. }
  1337. }
  1338. $this->statut = self::STATUS_CLOSED;
  1339. // If stock increment is done on closing
  1340. if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
  1341. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1342. $langs->load("agenda");
  1343. // Loop on each product line to add a stock movement
  1344. // TODO possibilite de receptionner a partir d'une propale ou autre origine ?
  1345. $sql = "SELECT cd.fk_product, cd.subprice,";
  1346. $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
  1347. $sql .= " ed.eatby, ed.sellby, ed.batch";
  1348. $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
  1349. $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as ed";
  1350. $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
  1351. $sql .= " AND cd.rowid = ed.fk_commandefourndet";
  1352. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  1353. $resql = $this->db->query($sql);
  1354. if ($resql) {
  1355. $cpt = $this->db->num_rows($resql);
  1356. for ($i = 0; $i < $cpt; $i++) {
  1357. $obj = $this->db->fetch_object($resql);
  1358. $qty = $obj->qty;
  1359. if ($qty <= 0) {
  1360. continue;
  1361. }
  1362. dol_syslog(get_class($this)."::valid movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
  1363. $mouvS = new MouvementStock($this->db);
  1364. $mouvS->origin = &$this;
  1365. $mouvS->setOrigin($this->element, $this->id);
  1366. if (empty($obj->batch)) {
  1367. // line without batch detail
  1368. // 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
  1369. $inventorycode = '';
  1370. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, $qty, $obj->subprice, $langs->trans("ReceptionClassifyClosedInDolibarr", $this->ref), '', '', '', '', 0, $inventorycode);
  1371. if ($result < 0) {
  1372. $this->error = $mouvS->error;
  1373. $this->errors = $mouvS->errors;
  1374. $error++; break;
  1375. }
  1376. } else {
  1377. // line with batch detail
  1378. // 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
  1379. $inventorycode = '';
  1380. $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);
  1381. if ($result < 0) {
  1382. $this->error = $mouvS->error;
  1383. $this->errors = $mouvS->errors;
  1384. $error++; break;
  1385. }
  1386. }
  1387. }
  1388. } else {
  1389. $this->error = $this->db->lasterror();
  1390. $error++;
  1391. }
  1392. }
  1393. // Call trigger
  1394. if (!$error) {
  1395. $result = $this->call_trigger('RECEPTION_CLOSED', $user);
  1396. if ($result < 0) {
  1397. $error++;
  1398. }
  1399. }
  1400. } else {
  1401. dol_print_error($this->db);
  1402. $error++;
  1403. }
  1404. if (!$error) {
  1405. $this->db->commit();
  1406. return 1;
  1407. } else {
  1408. $this->db->rollback();
  1409. return -1;
  1410. }
  1411. }
  1412. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1413. /**
  1414. * Classify the reception as invoiced (used when WORKFLOW_BILL_ON_RECEPTION is on)
  1415. *
  1416. * @deprecated
  1417. * @see setBilled()
  1418. * @return int <0 if ko, >0 if ok
  1419. */
  1420. public function set_billed()
  1421. {
  1422. // phpcs:enable
  1423. dol_syslog(get_class($this)."::set_billed is deprecated, use setBilled instead", LOG_NOTICE);
  1424. return $this->setBilled();
  1425. }
  1426. /**
  1427. * Classify the reception as invoiced (used when WORKFLOW_BILL_ON_RECEPTION is on)
  1428. *
  1429. * @return int <0 if ko, >0 if ok
  1430. */
  1431. public function setBilled()
  1432. {
  1433. global $user;
  1434. $error = 0;
  1435. $this->db->begin();
  1436. $this->setClosed();
  1437. $sql = 'UPDATE '.MAIN_DB_PREFIX.'reception SET billed=1';
  1438. $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > 0';
  1439. $resql = $this->db->query($sql);
  1440. if ($resql) {
  1441. $this->statut = 2;
  1442. $this->billed = 1;
  1443. // Call trigger
  1444. $result = $this->call_trigger('RECEPTION_BILLED', $user);
  1445. if ($result < 0) {
  1446. $error++;
  1447. }
  1448. } else {
  1449. $error++;
  1450. $this->errors[] = $this->db->lasterror;
  1451. }
  1452. if (empty($error)) {
  1453. $this->db->commit();
  1454. return 1;
  1455. } else {
  1456. $this->db->rollback();
  1457. return -1;
  1458. }
  1459. }
  1460. /**
  1461. * Classify the reception as validated/opened
  1462. *
  1463. * @return int <0 if ko, >0 if ok
  1464. */
  1465. public function reOpen()
  1466. {
  1467. global $conf, $langs, $user;
  1468. $error = 0;
  1469. $this->db->begin();
  1470. $sql = 'UPDATE '.MAIN_DB_PREFIX.'reception SET fk_statut=1, billed=0';
  1471. $sql .= " WHERE rowid = ".((int) $this->id).' AND fk_statut > 0';
  1472. $resql = $this->db->query($sql);
  1473. if ($resql) {
  1474. $this->statut = 1;
  1475. $this->billed = 0;
  1476. // If stock increment is done on closing
  1477. if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
  1478. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1479. $numref = $this->ref;
  1480. $langs->load("agenda");
  1481. // Loop on each product line to add a stock movement
  1482. // TODO possibilite de receptionner a partir d'une propale ou autre origine
  1483. $sql = "SELECT ed.fk_product, cd.subprice,";
  1484. $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
  1485. $sql .= " ed.eatby, ed.sellby, ed.batch";
  1486. $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
  1487. $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as ed";
  1488. $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
  1489. $sql .= " AND cd.rowid = ed.fk_commandefourndet";
  1490. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  1491. $resql = $this->db->query($sql);
  1492. if ($resql) {
  1493. $cpt = $this->db->num_rows($resql);
  1494. for ($i = 0; $i < $cpt; $i++) {
  1495. $obj = $this->db->fetch_object($resql);
  1496. $qty = $obj->qty;
  1497. if ($qty <= 0) {
  1498. continue;
  1499. }
  1500. dol_syslog(get_class($this)."::reopen reception movement index ".$i." ed.rowid=".$obj->rowid);
  1501. //var_dump($this->lines[$i]);
  1502. $mouvS = new MouvementStock($this->db);
  1503. $mouvS->origin = &$this;
  1504. $mouvS->setOrigin($this->element, $this->id);
  1505. if (empty($obj->batch)) {
  1506. // line without batch detail
  1507. // 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
  1508. $inventorycode = '';
  1509. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ReceptionUnClassifyCloseddInDolibarr", $numref), '', '', '', '', 0, $inventorycode);
  1510. if ($result < 0) {
  1511. $this->error = $mouvS->error;
  1512. $this->errors = $mouvS->errors;
  1513. $error++; break;
  1514. }
  1515. } else {
  1516. // line with batch detail
  1517. // 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
  1518. $inventorycode = '';
  1519. $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);
  1520. if ($result < 0) {
  1521. $this->error = $mouvS->error;
  1522. $this->errors = $mouvS->errors;
  1523. $error++; break;
  1524. }
  1525. }
  1526. }
  1527. } else {
  1528. $this->error = $this->db->lasterror();
  1529. $error++;
  1530. }
  1531. }
  1532. if (!$error) {
  1533. // Call trigger
  1534. $result = $this->call_trigger('RECEPTION_REOPEN', $user);
  1535. if ($result < 0) {
  1536. $error++;
  1537. }
  1538. }
  1539. if (!$error && $this->origin == 'order_supplier') {
  1540. $commande = new CommandeFournisseur($this->db);
  1541. $commande->fetch($this->origin_id);
  1542. $result = $commande->setStatus($user, 4);
  1543. if ($result < 0) {
  1544. $error++;
  1545. $this->error = $commande->error;
  1546. $this->errors = $commande->errors;
  1547. }
  1548. }
  1549. } else {
  1550. $error++;
  1551. $this->errors[] = $this->db->lasterror();
  1552. }
  1553. if (!$error) {
  1554. $this->db->commit();
  1555. return 1;
  1556. } else {
  1557. $this->db->rollback();
  1558. return -1;
  1559. }
  1560. }
  1561. /**
  1562. * Set draft status
  1563. *
  1564. * @param User $user Object user that modify
  1565. * @return int <0 if KO, >0 if OK
  1566. */
  1567. public function setDraft($user)
  1568. {
  1569. // phpcs:enable
  1570. global $conf, $langs;
  1571. $error = 0;
  1572. // Protection
  1573. if ($this->statut <= self::STATUS_DRAFT) {
  1574. return 0;
  1575. }
  1576. if (!((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->creer))
  1577. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->reception->reception_advance->validate)))) {
  1578. $this->error = 'Permission denied';
  1579. return -1;
  1580. }
  1581. $this->db->begin();
  1582. $sql = "UPDATE ".MAIN_DB_PREFIX."reception";
  1583. $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
  1584. $sql .= " WHERE rowid = ".((int) $this->id);
  1585. dol_syslog(__METHOD__, LOG_DEBUG);
  1586. if ($this->db->query($sql)) {
  1587. // If stock increment is done on closing
  1588. if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION)) {
  1589. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1590. $langs->load("agenda");
  1591. // Loop on each product line to add a stock movement
  1592. // TODO possibilite de receptionner a partir d'une propale ou autre origine
  1593. $sql = "SELECT cd.fk_product, cd.subprice,";
  1594. $sql .= " ed.rowid, ed.qty, ed.fk_entrepot,";
  1595. $sql .= " ed.eatby, ed.sellby, ed.batch";
  1596. $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd,";
  1597. $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as ed";
  1598. $sql .= " WHERE ed.fk_reception = ".((int) $this->id);
  1599. $sql .= " AND cd.rowid = ed.fk_commandefourndet";
  1600. dol_syslog(get_class($this)."::valid select details", LOG_DEBUG);
  1601. $resql = $this->db->query($sql);
  1602. if ($resql) {
  1603. $cpt = $this->db->num_rows($resql);
  1604. for ($i = 0; $i < $cpt; $i++) {
  1605. $obj = $this->db->fetch_object($resql);
  1606. $qty = $obj->qty;
  1607. if ($qty <= 0) {
  1608. continue;
  1609. }
  1610. dol_syslog(get_class($this)."::reopen reception movement index ".$i." ed.rowid=".$obj->rowid." edb.rowid=".$obj->edbrowid);
  1611. //var_dump($this->lines[$i]);
  1612. $mouvS = new MouvementStock($this->db);
  1613. $mouvS->origin = &$this;
  1614. $mouvS->setOrigin($this->element, $this->id);
  1615. if (empty($obj->batch)) {
  1616. // line without batch detail
  1617. // 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
  1618. $inventorycode = '';
  1619. $result = $mouvS->reception($user, $obj->fk_product, $obj->fk_entrepot, -$qty, $obj->subprice, $langs->trans("ReceptionBackToDraftInDolibarr", $this->ref), '', '', '', '', 0, $inventorycode);
  1620. if ($result < 0) {
  1621. $this->error = $mouvS->error;
  1622. $this->errors = $mouvS->errors;
  1623. $error++;
  1624. break;
  1625. }
  1626. } else {
  1627. // line with batch detail
  1628. // 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
  1629. $inventorycode = '';
  1630. $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);
  1631. if ($result < 0) {
  1632. $this->error = $mouvS->error;
  1633. $this->errors = $mouvS->errors;
  1634. $error++; break;
  1635. }
  1636. }
  1637. }
  1638. } else {
  1639. $this->error = $this->db->lasterror();
  1640. $error++;
  1641. }
  1642. }
  1643. if (!$error) {
  1644. // Call trigger
  1645. $result = $this->call_trigger('RECEPTION_UNVALIDATE', $user);
  1646. if ($result < 0) {
  1647. $error++;
  1648. }
  1649. }
  1650. if ($this->origin == 'order_supplier') {
  1651. if (!empty($this->origin) && $this->origin_id > 0) {
  1652. $this->fetch_origin();
  1653. $origin = $this->origin;
  1654. if ($this->$origin->statut == 4) { // If order source of reception is "partially received"
  1655. // Check if there is no more reception validated.
  1656. $this->$origin->fetchObjectLinked();
  1657. $setStatut = 1;
  1658. if (!empty($this->$origin->linkedObjects['reception'])) {
  1659. foreach ($this->$origin->linkedObjects['reception'] as $rcption) {
  1660. if ($rcption->statut > 0) {
  1661. $setStatut = 0;
  1662. break;
  1663. }
  1664. }
  1665. //var_dump($this->$origin->receptions);exit;
  1666. if ($setStatut) {
  1667. $this->$origin->setStatut(3); // ordered
  1668. }
  1669. }
  1670. }
  1671. }
  1672. }
  1673. if (!$error) {
  1674. $this->statut = self::STATUS_DRAFT;
  1675. $this->db->commit();
  1676. return 1;
  1677. } else {
  1678. $this->db->rollback();
  1679. return -1;
  1680. }
  1681. } else {
  1682. $this->error = $this->db->error();
  1683. $this->db->rollback();
  1684. return -1;
  1685. }
  1686. }
  1687. /**
  1688. * Create a document onto disk according to template module.
  1689. *
  1690. * @param string $modele Force the model to using ('' to not force)
  1691. * @param Translate $outputlangs object lang to use for translations
  1692. * @param int $hidedetails Hide details of lines
  1693. * @param int $hidedesc Hide description
  1694. * @param int $hideref Hide ref
  1695. * @return int 0 if KO, 1 if OK
  1696. */
  1697. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
  1698. {
  1699. global $conf, $langs;
  1700. $langs->load("receptions");
  1701. if (!dol_strlen($modele)) {
  1702. $modele = 'squille';
  1703. if ($this->model_pdf) {
  1704. $modele = $this->model_pdf;
  1705. } elseif (!empty($conf->global->RECEPTION_ADDON_PDF)) {
  1706. $modele = $conf->global->RECEPTION_ADDON_PDF;
  1707. }
  1708. }
  1709. $modelpath = "core/modules/reception/doc/";
  1710. $this->fetch_origin();
  1711. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1712. }
  1713. /**
  1714. * Function used to replace a thirdparty id with another one.
  1715. *
  1716. * @param DoliDB $db Database handler
  1717. * @param int $origin_id Old thirdparty id
  1718. * @param int $dest_id New thirdparty id
  1719. * @return bool
  1720. */
  1721. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  1722. {
  1723. $tables = array('reception');
  1724. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  1725. }
  1726. /**
  1727. * Function used to replace a product id with another one.
  1728. *
  1729. * @param DoliDB $db Database handler
  1730. * @param int $origin_id Old product id
  1731. * @param int $dest_id New product id
  1732. * @return bool
  1733. */
  1734. public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
  1735. {
  1736. $tables = array(
  1737. 'commande_fournisseur_dispatch'
  1738. );
  1739. return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
  1740. }
  1741. }