reception.class.php 65 KB

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