reception.class.php 65 KB

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