reception.class.php 64 KB

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