delivery.class.php 34 KB

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