delivery.class.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  1. <?php
  2. /* Copyright (C) 2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2006-2007 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
  6. * Copyright (C) 2011-2018 Philippe Grand <philippe.grand@atoo-net.com>
  7. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  8. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  9. *
  10. * This program is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  22. */
  23. /**
  24. * \file htdocs/delivery/class/delivery.class.php
  25. * \ingroup delivery
  26. * \brief Delivery Order Management Class File
  27. */
  28. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  29. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  30. require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
  31. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  32. if (!empty($conf->propal->enabled)) {
  33. require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  34. }
  35. if (!empty($conf->commande->enabled)) {
  36. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  37. }
  38. /**
  39. * Class to manage receptions
  40. */
  41. class Delivery extends CommonObject
  42. {
  43. use CommonIncoterm;
  44. /**
  45. * @var string ID to identify managed object
  46. */
  47. public $element = "delivery";
  48. /**
  49. * @var string Field with ID of parent key if this field has a parent
  50. */
  51. public $fk_element = "fk_delivery";
  52. /**
  53. * @var string Name of table without prefix where object is stored
  54. */
  55. public $table_element = "delivery";
  56. /**
  57. * @var string Name of subtable line
  58. */
  59. public $table_element_line = "deliverydet";
  60. /**
  61. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  62. */
  63. public $picto = 'sending';
  64. /**
  65. * @var int draft status
  66. */
  67. public $draft;
  68. /**
  69. * @var int thirdparty id
  70. */
  71. public $socid;
  72. /**
  73. * @var string ref custome
  74. */
  75. public $ref_customer;
  76. /**
  77. * @var integer|string Date really received
  78. */
  79. public $date_delivery;
  80. /**
  81. * @var integer|string date_creation
  82. */
  83. public $date_creation;
  84. /**
  85. * @var integer|string date_valid
  86. */
  87. public $date_valid;
  88. /**
  89. * @var string model pdf
  90. */
  91. public $model_pdf;
  92. public $commande_id;
  93. public $lines = array();
  94. /**
  95. * Constructor
  96. *
  97. * @param DoliDB $db Database handler
  98. */
  99. public function __construct($db)
  100. {
  101. $this->db = $db;
  102. // List of short language codes for status
  103. $this->statuts[-1] = 'StatusDeliveryCanceled';
  104. $this->statuts[0] = 'StatusDeliveryDraft';
  105. $this->statuts[1] = 'StatusDeliveryValidated';
  106. }
  107. /**
  108. * Create delivery receipt in database
  109. *
  110. * @param User $user Objet du user qui cree
  111. * @return int <0 si erreur, id delivery cree si ok
  112. */
  113. public function create($user)
  114. {
  115. global $conf;
  116. dol_syslog("Delivery::create");
  117. if (empty($this->model_pdf)) {
  118. $this->model_pdf = $conf->global->DELIVERY_ADDON_PDF;
  119. }
  120. $error = 0;
  121. $now = dol_now();
  122. /* Delivery note as draft On positionne en mode draft le bon de livraison */
  123. $this->draft = 1;
  124. $this->user = $user;
  125. $this->db->begin();
  126. $sql = "INSERT INTO ".MAIN_DB_PREFIX."delivery (";
  127. $sql .= "ref";
  128. $sql .= ", entity";
  129. $sql .= ", fk_soc";
  130. $sql .= ", ref_customer";
  131. $sql .= ", date_creation";
  132. $sql .= ", fk_user_author";
  133. $sql .= ", date_delivery";
  134. $sql .= ", fk_address";
  135. $sql .= ", note_private";
  136. $sql .= ", note_public";
  137. $sql .= ", model_pdf";
  138. $sql .= ", fk_incoterms, location_incoterms";
  139. $sql .= ") VALUES (";
  140. $sql .= "'(PROV)'";
  141. $sql .= ", ".((int) $conf->entity);
  142. $sql .= ", ".((int) $this->socid);
  143. $sql .= ", '".$this->db->escape($this->ref_customer)."'";
  144. $sql .= ", '".$this->db->idate($now)."'";
  145. $sql .= ", ".((int) $user->id);
  146. $sql .= ", ".($this->date_delivery ? "'".$this->db->idate($this->date_delivery)."'" : "null");
  147. $sql .= ", ".($this->fk_delivery_address > 0 ? $this->fk_delivery_address : "null");
  148. $sql .= ", ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
  149. $sql .= ", ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
  150. $sql .= ", ".(!empty($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
  151. $sql .= ", ".(int) $this->fk_incoterms;
  152. $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
  153. $sql .= ")";
  154. dol_syslog("Delivery::create", LOG_DEBUG);
  155. $resql = $this->db->query($sql);
  156. if ($resql) {
  157. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."delivery");
  158. $numref = "(PROV".$this->id.")";
  159. $sql = "UPDATE ".MAIN_DB_PREFIX."delivery ";
  160. $sql .= "SET ref = '".$this->db->escape($numref)."'";
  161. $sql .= " WHERE rowid = ".((int) $this->id);
  162. dol_syslog("Delivery::create", LOG_DEBUG);
  163. $resql = $this->db->query($sql);
  164. if ($resql) {
  165. if (!$conf->expedition_bon->enabled) {
  166. $commande = new Commande($this->db);
  167. $commande->id = $this->commande_id;
  168. $commande->fetch_lines();
  169. }
  170. /*
  171. * Inserting products into the database
  172. */
  173. $num = count($this->lines);
  174. for ($i = 0; $i < $num; $i++) {
  175. $origin_id = $this->lines[$i]->origin_line_id;
  176. if (!$origin_id) {
  177. $origin_id = $this->lines[$i]->commande_ligne_id; // For backward compatibility
  178. }
  179. if (!$this->create_line($origin_id, $this->lines[$i]->qty, $this->lines[$i]->fk_product, $this->lines[$i]->description, $this->lines[$i]->array_options)) {
  180. $error++;
  181. }
  182. }
  183. if (!$error && $this->id && $this->origin_id) {
  184. $ret = $this->add_object_linked();
  185. if (!$ret) {
  186. $error++;
  187. }
  188. if (!$conf->expedition_bon->enabled) {
  189. // TODO standardize status uniformiser les statuts
  190. $ret = $this->setStatut(2, $this->origin_id, $this->origin);
  191. if (!$ret) {
  192. $error++;
  193. }
  194. }
  195. }
  196. if (!$error) {
  197. $this->db->commit();
  198. return $this->id;
  199. } else {
  200. $error++;
  201. $this->error = $this->db->lasterror()." - sql=".$this->db->lastqueryerror;
  202. $this->db->rollback();
  203. return -3;
  204. }
  205. } else {
  206. $error++;
  207. $this->error = $this->db->lasterror()." - sql=".$this->db->lastqueryerror;
  208. $this->db->rollback();
  209. return -2;
  210. }
  211. } else {
  212. $error++;
  213. $this->error = $this->db->lasterror()." - sql=".$this->db->lastqueryerror;
  214. $this->db->rollback();
  215. return -1;
  216. }
  217. }
  218. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  219. /**
  220. * Create a line
  221. *
  222. * @param string $origin_id Id of order
  223. * @param string $qty Quantity
  224. * @param string $fk_product Id of predefined product
  225. * @param string $description Description
  226. * @param array $array_options Array options
  227. * @return int <0 if KO, >0 if OK
  228. */
  229. public function create_line($origin_id, $qty, $fk_product, $description, $array_options = null)
  230. {
  231. // phpcs:enable
  232. $error = 0;
  233. $idprod = $fk_product;
  234. $j = 0;
  235. $sql = "INSERT INTO ".MAIN_DB_PREFIX."deliverydet (fk_delivery, fk_origin_line,";
  236. $sql .= " fk_product, description, qty)";
  237. $sql .= " VALUES (".$this->id.",".((int) $origin_id).",";
  238. $sql .= " ".($idprod > 0 ? ((int) $idprod) : "null").",";
  239. $sql .= " ".($description ? "'".$this->db->escape($description)."'" : "null").",";
  240. $sql .= (price2num($qty, 'MS')).")";
  241. dol_syslog(get_class($this)."::create_line", LOG_DEBUG);
  242. if (!$this->db->query($sql)) {
  243. $error++;
  244. }
  245. $id = $this->db->last_insert_id(MAIN_DB_PREFIX."deliverydet");
  246. if (is_array($array_options) && count($array_options) > 0) {
  247. $line = new DeliveryLine($this->db);
  248. $line->id = $id;
  249. $line->array_options = $array_options;
  250. $result = $line->insertExtraFields();
  251. }
  252. if ($error == 0) {
  253. return 1;
  254. }
  255. }
  256. /**
  257. * Load a delivery receipt
  258. *
  259. * @param int $id Id of object to load
  260. * @return integer
  261. */
  262. public function fetch($id)
  263. {
  264. global $conf;
  265. $sql = "SELECT l.rowid, l.fk_soc, l.date_creation, l.date_valid, l.ref, l.ref_customer, l.fk_user_author,";
  266. $sql .= " l.total_ht, l.fk_statut, l.fk_user_valid, l.note_private, l.note_public";
  267. $sql .= ", l.date_delivery, l.fk_address, l.model_pdf";
  268. $sql .= ", el.fk_source as origin_id, el.sourcetype as origin";
  269. $sql .= ', l.fk_incoterms, l.location_incoterms';
  270. $sql .= ", i.libelle as label_incoterms";
  271. $sql .= " FROM ".MAIN_DB_PREFIX."delivery as l";
  272. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = l.rowid AND el.targettype = '".$this->db->escape($this->element)."'";
  273. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON l.fk_incoterms = i.rowid';
  274. $sql .= " WHERE l.rowid = ".((int) $id);
  275. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  276. $result = $this->db->query($sql);
  277. if ($result) {
  278. if ($this->db->num_rows($result)) {
  279. $obj = $this->db->fetch_object($result);
  280. $this->id = $obj->rowid;
  281. $this->date_delivery = $this->db->jdate($obj->date_delivery);
  282. $this->date_creation = $this->db->jdate($obj->date_creation);
  283. $this->date_valid = $this->db->jdate($obj->date_valid);
  284. $this->ref = $obj->ref;
  285. $this->ref_customer = $obj->ref_customer;
  286. $this->socid = $obj->fk_soc;
  287. $this->statut = $obj->fk_statut;
  288. $this->user_author_id = $obj->fk_user_author;
  289. $this->user_valid_id = $obj->fk_user_valid;
  290. $this->fk_delivery_address = $obj->fk_address;
  291. $this->note = $obj->note_private; //TODO deprecated
  292. $this->note_private = $obj->note_private;
  293. $this->note_public = $obj->note_public;
  294. $this->model_pdf = $obj->model_pdf;
  295. $this->modelpdf = $obj->model_pdf; // deprecated
  296. $this->origin = $obj->origin; // May be 'shipping'
  297. $this->origin_id = $obj->origin_id; // May be id of shipping
  298. //Incoterms
  299. $this->fk_incoterms = $obj->fk_incoterms;
  300. $this->location_incoterms = $obj->location_incoterms;
  301. $this->label_incoterms = $obj->label_incoterms;
  302. $this->db->free($result);
  303. if ($this->statut == 0) {
  304. $this->draft = 1;
  305. }
  306. // Retrieve all extrafields
  307. // fetch optionals attributes and labels
  308. $this->fetch_optionals();
  309. // Load lines
  310. $result = $this->fetch_lines();
  311. if ($result < 0) {
  312. return -3;
  313. }
  314. return 1;
  315. } else {
  316. $this->error = 'Delivery with id '.$id.' not found sql='.$sql;
  317. dol_syslog(get_class($this).'::fetch Error '.$this->error, LOG_ERR);
  318. return -2;
  319. }
  320. } else {
  321. $this->error = $this->db->error();
  322. return -1;
  323. }
  324. }
  325. /**
  326. * Validate object and update stock if option enabled
  327. *
  328. * @param User $user Object user that validate
  329. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  330. * @return int
  331. */
  332. public function valid($user, $notrigger = 0)
  333. {
  334. global $conf, $langs;
  335. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  336. dol_syslog(get_class($this)."::valid begin");
  337. $this->db->begin();
  338. $error = 0;
  339. if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery->creer))
  340. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->expedition->delivery_advance->validate))) {
  341. if (!empty($conf->global->DELIVERY_ADDON_NUMBER)) {
  342. // Setting the command numbering module name
  343. $modName = $conf->global->DELIVERY_ADDON_NUMBER;
  344. if (is_readable(DOL_DOCUMENT_ROOT.'/core/modules/delivery/'.$modName.'.php')) {
  345. require_once DOL_DOCUMENT_ROOT.'/core/modules/delivery/'.$modName.'.php';
  346. $now = dol_now();
  347. // Retrieving the new reference
  348. $objMod = new $modName($this->db);
  349. $soc = new Societe($this->db);
  350. $soc->fetch($this->socid);
  351. if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
  352. $numref = $objMod->delivery_get_num($soc, $this);
  353. } else {
  354. $numref = $this->ref;
  355. }
  356. $this->newref = dol_sanitizeFileName($numref);
  357. // Test if is not already in valid status. If so, we stop to avoid decrementing the stock twice.
  358. $sql = "SELECT ref";
  359. $sql .= " FROM ".MAIN_DB_PREFIX."delivery";
  360. $sql .= " WHERE ref = '".$this->db->escape($numref)."'";
  361. $sql .= " AND fk_statut <> 0";
  362. $sql .= " AND entity = ".((int) $conf->entity);
  363. $resql = $this->db->query($sql);
  364. if ($resql) {
  365. $num = $this->db->num_rows($resql);
  366. if ($num > 0) {
  367. return 0;
  368. }
  369. }
  370. $sql = "UPDATE ".MAIN_DB_PREFIX."delivery SET";
  371. $sql .= " ref='".$this->db->escape($numref)."'";
  372. $sql .= ", fk_statut = 1";
  373. $sql .= ", date_valid = '".$this->db->idate($now)."'";
  374. $sql .= ", fk_user_valid = ".$user->id;
  375. $sql .= " WHERE rowid = ".((int) $this->id);
  376. $sql .= " AND fk_statut = 0";
  377. $resql = $this->db->query($sql);
  378. if (!$resql) {
  379. dol_print_error($this->db);
  380. $this->error = $this->db->lasterror();
  381. $error++;
  382. }
  383. if (!$error && !$notrigger) {
  384. // Call trigger
  385. $result = $this->call_trigger('DELIVERY_VALIDATE', $user);
  386. if ($result < 0) {
  387. $error++;
  388. }
  389. // End call triggers
  390. }
  391. if (!$error) {
  392. $this->oldref = $this->ref;
  393. // Rename directory if dir was a temporary ref
  394. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  395. // Now we rename also files into index
  396. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expedition/receipt/".$this->db->escape($this->newref)."'";
  397. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expedition/receipt/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
  398. $resql = $this->db->query($sql);
  399. if (!$resql) {
  400. $error++; $this->error = $this->db->lasterror();
  401. }
  402. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  403. $oldref = dol_sanitizeFileName($this->ref);
  404. $newref = dol_sanitizeFileName($numref);
  405. $dirsource = $conf->expedition->dir_output.'/receipt/'.$oldref;
  406. $dirdest = $conf->expedition->dir_output.'/receipt/'.$newref;
  407. if (!$error && file_exists($dirsource)) {
  408. dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest);
  409. if (@rename($dirsource, $dirdest)) {
  410. dol_syslog("Rename ok");
  411. // Rename docs starting with $oldref with $newref
  412. $listoffiles = dol_dir_list($conf->expedition->dir_output.'/receipt/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  413. foreach ($listoffiles as $fileentry) {
  414. $dirsource = $fileentry['name'];
  415. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  416. $dirsource = $fileentry['path'].'/'.$dirsource;
  417. $dirdest = $fileentry['path'].'/'.$dirdest;
  418. @rename($dirsource, $dirdest);
  419. }
  420. }
  421. }
  422. }
  423. // Set new ref and current status
  424. if (!$error) {
  425. $this->ref = $numref;
  426. $this->statut = 1;
  427. }
  428. dol_syslog(get_class($this)."::valid ok");
  429. }
  430. if (!$error) {
  431. $this->db->commit();
  432. return 1;
  433. } else {
  434. $this->db->rollback();
  435. return -1;
  436. }
  437. }
  438. }
  439. } else {
  440. $this->error = "Non autorise";
  441. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  442. return -1;
  443. }
  444. }
  445. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  446. /**
  447. * Creating the delivery slip from an existing shipment
  448. *
  449. * @param User $user User who creates
  450. * @param int $sending_id Id of the expedition that serves as a model
  451. * @return integer
  452. */
  453. public function create_from_sending($user, $sending_id)
  454. {
  455. // phpcs:enable
  456. global $conf;
  457. $expedition = new Expedition($this->db);
  458. $result = $expedition->fetch($sending_id);
  459. $this->lines = array();
  460. $num = count($expedition->lines);
  461. for ($i = 0; $i < $num; $i++) {
  462. $line = new DeliveryLine($this->db);
  463. $line->origin_line_id = $expedition->lines[$i]->origin_line_id;
  464. $line->label = $expedition->lines[$i]->label;
  465. $line->description = $expedition->lines[$i]->description;
  466. $line->qty = $expedition->lines[$i]->qty_shipped;
  467. $line->fk_product = $expedition->lines[$i]->fk_product;
  468. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($expedition->lines[$i]->array_options) && count($expedition->lines[$i]->array_options) > 0) { // For avoid conflicts if trigger used
  469. $line->array_options = $expedition->lines[$i]->array_options;
  470. }
  471. $this->lines[$i] = $line;
  472. }
  473. $this->origin = $expedition->element;
  474. $this->origin_id = $expedition->id;
  475. $this->note_private = $expedition->note_private;
  476. $this->note_public = $expedition->note_public;
  477. $this->fk_project = $expedition->fk_project;
  478. $this->date_delivery = $expedition->date_delivery;
  479. $this->fk_delivery_address = $expedition->fk_delivery_address;
  480. $this->socid = $expedition->socid;
  481. $this->ref_customer = $expedition->ref_customer;
  482. //Incoterms
  483. $this->fk_incoterms = $expedition->fk_incoterms;
  484. $this->location_incoterms = $expedition->location_incoterms;
  485. return $this->create($user);
  486. }
  487. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  488. /**
  489. * Update a livraison line (only extrafields)
  490. *
  491. * @param int $id Id of line (livraison line)
  492. * @param array $array_options extrafields array
  493. * @return int <0 if KO, >0 if OK
  494. */
  495. public function update_line($id, $array_options = 0)
  496. {
  497. // phpcs:enable
  498. global $conf;
  499. $error = 0;
  500. if ($id > 0 && !$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
  501. $line = new DeliveryLine($this->db);
  502. $line->array_options = $array_options;
  503. $line->id = $id;
  504. $result = $line->insertExtraFields();
  505. if ($result < 0) {
  506. $this->error[] = $line->error;
  507. $error++;
  508. }
  509. }
  510. if (!$error) {
  511. return 1;
  512. } else {
  513. return -1;
  514. }
  515. }
  516. /**
  517. * Add line
  518. *
  519. * @param int $origin_id Origin id
  520. * @param int $qty Qty
  521. * @param array $array_options Array options
  522. * @return void
  523. */
  524. public function addline($origin_id, $qty, $array_options = null)
  525. {
  526. global $conf;
  527. $num = count($this->lines);
  528. $line = new DeliveryLine($this->db);
  529. $line->origin_id = $origin_id;
  530. $line->qty = $qty;
  531. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
  532. $line->array_options = $array_options;
  533. }
  534. $this->lines[$num] = $line;
  535. }
  536. /**
  537. * Delete line
  538. *
  539. * @param int $lineid Line id
  540. * @return integer|null
  541. */
  542. public function deleteline($lineid)
  543. {
  544. if ($this->statut == 0) {
  545. $sql = "DELETE FROM ".MAIN_DB_PREFIX."commandedet";
  546. $sql .= " WHERE rowid = ".((int) $lineid);
  547. if ($this->db->query($sql)) {
  548. $this->update_price();
  549. return 1;
  550. } else {
  551. return 0;
  552. }
  553. }
  554. }
  555. /**
  556. * Delete object
  557. *
  558. * @return integer
  559. */
  560. public function delete()
  561. {
  562. global $conf, $langs, $user;
  563. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  564. $this->db->begin();
  565. $error = 0;
  566. $sql = "DELETE FROM ".MAIN_DB_PREFIX."deliverydet";
  567. $sql .= " WHERE fk_delivery = ".((int) $this->id);
  568. if ($this->db->query($sql)) {
  569. // Delete linked object
  570. $res = $this->deleteObjectLinked();
  571. if ($res < 0) {
  572. $error++;
  573. }
  574. if (!$error) {
  575. $sql = "DELETE FROM ".MAIN_DB_PREFIX."delivery";
  576. $sql .= " WHERE rowid = ".((int) $this->id);
  577. if ($this->db->query($sql)) {
  578. $this->db->commit();
  579. // Deleting pdf folder's draft On efface le repertoire de pdf provisoire
  580. $ref = dol_sanitizeFileName($this->ref);
  581. if (!empty($conf->expedition->dir_output)) {
  582. $dir = $conf->expedition->dir_output.'/receipt/'.$ref;
  583. $file = $dir.'/'.$ref.'.pdf';
  584. if (file_exists($file)) {
  585. if (!dol_delete_file($file)) {
  586. return 0;
  587. }
  588. }
  589. if (file_exists($dir)) {
  590. if (!dol_delete_dir($dir)) {
  591. $this->error = $langs->trans("ErrorCanNotDeleteDir", $dir);
  592. return 0;
  593. }
  594. }
  595. }
  596. // Call trigger
  597. $result = $this->call_trigger('DELIVERY_DELETE', $user);
  598. if ($result < 0) {
  599. $this->db->rollback();
  600. return -4;
  601. }
  602. // End call triggers
  603. return 1;
  604. } else {
  605. $this->error = $this->db->lasterror()." - sql=$sql";
  606. $this->db->rollback();
  607. return -3;
  608. }
  609. } else {
  610. $this->error = $this->db->lasterror()." - sql=$sql";
  611. $this->db->rollback();
  612. return -2;
  613. }
  614. } else {
  615. $this->error = $this->db->lasterror()." - sql=$sql";
  616. $this->db->rollback();
  617. return -1;
  618. }
  619. }
  620. /**
  621. * Return clicable name (with picto eventually)
  622. *
  623. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  624. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  625. * @return string Chaine avec URL
  626. */
  627. public function getNomUrl($withpicto = 0, $save_lastsearch_value = -1)
  628. {
  629. global $langs, $hookmanager;
  630. $result = '';
  631. $label = img_picto('', $this->picto).' <u>'.$langs->trans("ShowReceiving").'</u>:<br>';
  632. $label .= '<b>'.$langs->trans("Status").'</b>: '.$this->ref;
  633. $url = DOL_URL_ROOT.'/delivery/card.php?id='.$this->id;
  634. //if ($option !== 'nolink')
  635. //{
  636. // Add param to save lastsearch_values or not
  637. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  638. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  639. $add_save_lastsearch_values = 1;
  640. }
  641. if ($add_save_lastsearch_values) {
  642. $url .= '&save_lastsearch_values=1';
  643. }
  644. //}
  645. $linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
  646. $linkend = '</a>';
  647. if ($withpicto) {
  648. $result .= ($linkstart.img_object($label, $this->picto, 'class="classfortooltip"').$linkend);
  649. }
  650. if ($withpicto && $withpicto != 2) {
  651. $result .= ' ';
  652. }
  653. $result .= $linkstart.$this->ref.$linkend;
  654. global $action;
  655. $hookmanager->initHooks(array($this->element . 'dao'));
  656. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  657. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  658. if ($reshook > 0) {
  659. $result = $hookmanager->resPrint;
  660. } else {
  661. $result .= $hookmanager->resPrint;
  662. }
  663. return $result;
  664. }
  665. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  666. /**
  667. * Load lines insto $this->lines.
  668. *
  669. * @return int <0 if KO, >0 if OK
  670. */
  671. public function fetch_lines()
  672. {
  673. // phpcs:enable
  674. $this->lines = array();
  675. $sql = "SELECT ld.rowid, ld.fk_product, ld.description, ld.subprice, ld.total_ht, ld.qty as qty_shipped, ld.fk_origin_line, ";
  676. $sql .= " cd.qty as qty_asked, cd.label as custom_label, cd.fk_unit,";
  677. $sql .= " p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc,";
  678. $sql .= " p.weight, p.weight_units, p.width, p.width_units, p.length, p.length_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units, p.tobatch as product_tobatch";
  679. $sql .= " FROM ".MAIN_DB_PREFIX."commandedet as cd, ".MAIN_DB_PREFIX."deliverydet as ld";
  680. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on p.rowid = ld.fk_product";
  681. $sql .= " WHERE ld.fk_origin_line = cd.rowid";
  682. $sql .= " AND ld.fk_delivery = ".((int) $this->id);
  683. dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
  684. $resql = $this->db->query($sql);
  685. if ($resql) {
  686. $num = $this->db->num_rows($resql);
  687. $i = 0;
  688. while ($i < $num) {
  689. $obj = $this->db->fetch_object($resql);
  690. $line = new DeliveryLine($this->db);
  691. $line->id = $obj->rowid;
  692. $line->label = $obj->custom_label;
  693. $line->description = $obj->description;
  694. $line->fk_product = $obj->fk_product;
  695. $line->qty_asked = $obj->qty_asked;
  696. $line->qty_shipped = $obj->qty_shipped;
  697. $line->ref = $obj->product_ref; // deprecated
  698. $line->libelle = $obj->product_label; // deprecated
  699. $line->product_label = $obj->product_label; // Product label
  700. $line->product_ref = $obj->product_ref; // Product ref
  701. $line->product_desc = $obj->product_desc; // Product description
  702. $line->product_type = $obj->fk_product_type;
  703. $line->fk_origin_line = $obj->fk_origin_line;
  704. $line->price = $obj->price;
  705. $line->total_ht = $obj->total_ht;
  706. // units
  707. $line->weight = $obj->weight;
  708. $line->weight_units = $obj->weight_units;
  709. $line->width = $obj->width;
  710. $line->width_units = $obj->width_units;
  711. $line->height = $obj->height;
  712. $line->height_units = $obj->height_units;
  713. $line->length = $obj->length;
  714. $line->length_units = $obj->length_units;
  715. $line->surface = $obj->surface;
  716. $line->surface_units = $obj->surface_units;
  717. $line->volume = $obj->volume;
  718. $line->volume_units = $obj->volume_units;
  719. $line->fk_unit = $obj->fk_unit;
  720. $line->fetch_optionals();
  721. $this->lines[$i] = $line;
  722. $i++;
  723. }
  724. $this->db->free($resql);
  725. return 1;
  726. } else {
  727. return -1;
  728. }
  729. }
  730. /**
  731. * Retourne le libelle du statut d'une expedition
  732. *
  733. * @param int $mode Mode
  734. * @return string Label
  735. */
  736. public function getLibStatut($mode = 0)
  737. {
  738. return $this->LibStatut($this->statut, $mode);
  739. }
  740. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  741. /**
  742. * Renvoi le libelle d'un statut donne
  743. *
  744. * @param int $status Id status
  745. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  746. * @return string Label
  747. */
  748. public function LibStatut($status, $mode)
  749. {
  750. // phpcs:enable
  751. global $langs;
  752. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  753. global $langs;
  754. //$langs->load("mymodule");
  755. $this->labelStatus[-1] = $langs->transnoentitiesnoconv('StatusDeliveryCanceled');
  756. $this->labelStatus[0] = $langs->transnoentitiesnoconv('StatusDeliveryDraft');
  757. $this->labelStatus[1] = $langs->transnoentitiesnoconv('StatusDeliveryValidated');
  758. $this->labelStatusShort[-1] = $langs->transnoentitiesnoconv('StatusDeliveryCanceled');
  759. $this->labelStatusShort[0] = $langs->transnoentitiesnoconv('StatusDeliveryDraft');
  760. $this->labelStatusShort[1] = $langs->transnoentitiesnoconv('StatusDeliveryValidated');
  761. }
  762. $statusType = 'status0';
  763. if ($status == -1) {
  764. $statusType = 'status5';
  765. }
  766. if ($status == 1) {
  767. $statusType = 'status4';
  768. }
  769. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  770. }
  771. /**
  772. * Initialise an instance with random values.
  773. * Used to build previews or test instances.
  774. * id must be 0 if object instance is a specimen.
  775. *
  776. * @return void
  777. */
  778. public function initAsSpecimen()
  779. {
  780. global $user, $langs, $conf;
  781. $now = dol_now();
  782. // Load array of products prodids
  783. $num_prods = 0;
  784. $prodids = array();
  785. $sql = "SELECT rowid";
  786. $sql .= " FROM ".MAIN_DB_PREFIX."product";
  787. $sql .= " WHERE entity IN (".getEntity('product').")";
  788. $sql .= " AND tosell = 1";
  789. $sql .= $this->db->plimit(100);
  790. $resql = $this->db->query($sql);
  791. if ($resql) {
  792. $num_prods = $this->db->num_rows($resql);
  793. $i = 0;
  794. while ($i < $num_prods) {
  795. $i++;
  796. $row = $this->db->fetch_row($resql);
  797. $prodids[$i] = $row[0];
  798. }
  799. }
  800. // Initialise parametres
  801. $this->id = 0;
  802. $this->ref = 'SPECIMEN';
  803. $this->specimen = 1;
  804. $this->socid = 1;
  805. $this->date_delivery = $now;
  806. $this->note_public = 'Public note';
  807. $this->note_private = 'Private note';
  808. $i = 0;
  809. $line = new DeliveryLine($this->db);
  810. $line->fk_product = $prodids[0];
  811. $line->qty_asked = 10;
  812. $line->qty_shipped = 9;
  813. $line->ref = 'REFPROD';
  814. $line->label = 'Specimen';
  815. $line->description = 'Description';
  816. $line->price = 100;
  817. $line->total_ht = 100;
  818. $this->lines[$i] = $line;
  819. }
  820. /**
  821. * Renvoie la quantite de produit restante a livrer pour une commande
  822. *
  823. * @return array Product remaining to be delivered
  824. * TODO use new function
  825. */
  826. public function getRemainingDelivered()
  827. {
  828. global $langs;
  829. // Get the linked object
  830. $this->fetchObjectLinked('', '', $this->id, $this->element);
  831. //var_dump($this->linkedObjectsIds);
  832. // Get the product ref and qty in source
  833. $sqlSourceLine = "SELECT st.rowid, st.description, st.qty";
  834. $sqlSourceLine .= ", p.ref, p.label";
  835. $sqlSourceLine .= " FROM ".MAIN_DB_PREFIX.$this->linkedObjectsIds[0]['type']."det as st";
  836. $sqlSourceLine .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON st.fk_product = p.rowid";
  837. $sqlSourceLine .= " WHERE fk_".$this->linked_object[0]['type']." = ".((int) $this->linked_object[0]['linkid']);
  838. $resultSourceLine = $this->db->query($sqlSourceLine);
  839. if ($resultSourceLine) {
  840. $num_lines = $this->db->num_rows($resultSourceLine);
  841. $i = 0;
  842. $array = array();
  843. while ($i < $num_lines) {
  844. $objSourceLine = $this->db->fetch_object($resultSourceLine);
  845. // Get lines of sources alread delivered
  846. $sql = "SELECT ld.fk_origin_line, sum(ld.qty) as qty";
  847. $sql .= " FROM ".MAIN_DB_PREFIX."deliverydet as ld, ".MAIN_DB_PREFIX."delivery as l,";
  848. $sql .= " ".MAIN_DB_PREFIX.$this->linked_object[0]['type']." as c";
  849. $sql .= ", ".MAIN_DB_PREFIX.$this->linked_object[0]['type']."det as cd";
  850. $sql .= " WHERE ld.fk_delivery = l.rowid";
  851. $sql .= " AND ld.fk_origin_line = cd.rowid";
  852. $sql .= " AND cd.fk_".$this->linked_object[0]['type']." = c.rowid";
  853. $sql .= " AND cd.fk_".$this->linked_object[0]['type']." = ".((int) $this->linked_object[0]['linkid']);
  854. $sql .= " AND ld.fk_origin_line = ".((int) $objSourceLine->rowid);
  855. $sql .= " GROUP BY ld.fk_origin_line";
  856. $result = $this->db->query($sql);
  857. $row = $this->db->fetch_row($result);
  858. if ($objSourceLine->qty - $row[1] > 0) {
  859. if ($row[0] == $objSourceLine->rowid) {
  860. $array[$i]['qty'] = $objSourceLine->qty - $row[1];
  861. } else {
  862. $array[$i]['qty'] = $objSourceLine->qty;
  863. }
  864. $array[$i]['ref'] = $objSourceLine->ref;
  865. $array[$i]['label'] = $objSourceLine->label ? $objSourceLine->label : $objSourceLine->description;
  866. } elseif ($objSourceLine->qty - $row[1] < 0) {
  867. $array[$i]['qty'] = $objSourceLine->qty - $row[1]." Erreur livraison !";
  868. $array[$i]['ref'] = $objSourceLine->ref;
  869. $array[$i]['label'] = $objSourceLine->label ? $objSourceLine->label : $objSourceLine->description;
  870. }
  871. $i++;
  872. }
  873. return $array;
  874. } else {
  875. $this->error = $this->db->error()." - sql=$sqlSourceLine";
  876. return -1;
  877. }
  878. }
  879. /**
  880. * Set the planned delivery date
  881. *
  882. * @param User $user Objet utilisateur qui modifie
  883. * @param integer $delivery_date Delivery date
  884. * @return int <0 if KO, >0 if OK
  885. */
  886. public function setDeliveryDate($user, $delivery_date)
  887. {
  888. if ($user->rights->expedition->creer) {
  889. $sql = "UPDATE ".MAIN_DB_PREFIX."delivery";
  890. $sql .= " SET date_delivery = ".($delivery_date ? "'".$this->db->idate($delivery_date)."'" : 'null');
  891. $sql .= " WHERE rowid = ".((int) $this->id);
  892. dol_syslog(get_class($this)."::setDeliveryDate", LOG_DEBUG);
  893. $resql = $this->db->query($sql);
  894. if ($resql) {
  895. $this->date_delivery = $delivery_date;
  896. return 1;
  897. } else {
  898. $this->error = $this->db->error();
  899. return -1;
  900. }
  901. } else {
  902. return -2;
  903. }
  904. }
  905. /**
  906. * Create object on disk
  907. *
  908. * @param string $modele force le modele a utiliser ('' to not force)
  909. * @param Translate $outputlangs Object langs to use for output
  910. * @param int $hidedetails Hide details of lines
  911. * @param int $hidedesc Hide description
  912. * @param int $hideref Hide ref
  913. * @return int 0 if KO, 1 if OK
  914. */
  915. public function generateDocument($modele, $outputlangs = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
  916. {
  917. global $conf, $user, $langs;
  918. $langs->load("deliveries");
  919. $outputlangs->load("products");
  920. if (!dol_strlen($modele)) {
  921. $modele = 'typhon';
  922. if ($this->model_pdf) {
  923. $modele = $this->model_pdf;
  924. } elseif (!empty($conf->global->DELIVERY_ADDON_PDF)) {
  925. $modele = $conf->global->DELIVERY_ADDON_PDF;
  926. }
  927. }
  928. $modelpath = "core/modules/delivery/doc/";
  929. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  930. }
  931. /**
  932. * Function used to replace a thirdparty id with another one.
  933. *
  934. * @param DoliDB $db Database handler
  935. * @param int $origin_id Old thirdparty id
  936. * @param int $dest_id New thirdparty id
  937. * @return bool
  938. */
  939. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  940. {
  941. $tables = array(
  942. 'delivery'
  943. );
  944. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  945. }
  946. /**
  947. * Function used to replace a product id with another one.
  948. *
  949. * @param DoliDB $db Database handler
  950. * @param int $origin_id Old product id
  951. * @param int $dest_id New product id
  952. * @return bool
  953. */
  954. public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
  955. {
  956. $tables = array(
  957. 'deliverydet'
  958. );
  959. return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
  960. }
  961. }
  962. /**
  963. * Management class of delivery note lines
  964. */
  965. class DeliveryLine extends CommonObjectLine
  966. {
  967. /**
  968. * @var DoliDB Database handler.
  969. */
  970. public $db;
  971. /**
  972. * @var string ID to identify managed object
  973. */
  974. public $element = 'deliverydet';
  975. /**
  976. * @var string Name of table without prefix where object is stored
  977. */
  978. public $table_element = 'deliverydet';
  979. /**
  980. * @var string delivery note lines label
  981. */
  982. public $label;
  983. /**
  984. * @var string product description
  985. */
  986. public $description;
  987. /**
  988. * @deprecated
  989. * @see $product_ref
  990. */
  991. public $ref;
  992. /**
  993. * @deprecated
  994. * @see product_label;
  995. */
  996. public $libelle;
  997. // From llx_expeditiondet
  998. public $qty;
  999. public $qty_asked;
  1000. public $qty_shipped;
  1001. public $fk_product;
  1002. public $product_desc;
  1003. public $product_type;
  1004. public $product_ref;
  1005. public $product_label;
  1006. public $fk_origin_line;
  1007. public $origin_id;
  1008. public $price;
  1009. public $origin_line_id;
  1010. /**
  1011. * Constructor
  1012. *
  1013. * @param DoliDB $db Database handler
  1014. */
  1015. public function __construct($db)
  1016. {
  1017. $this->db = $db;
  1018. }
  1019. }