api_projects.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. <?php
  2. /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  3. * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use Luracast\Restler\RestException;
  19. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  20. require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
  21. /**
  22. * API class for projects
  23. *
  24. * @access protected
  25. * @class DolibarrApiAccess {@requires user,external}
  26. */
  27. class Projects extends DolibarrApi
  28. {
  29. /**
  30. * @var array $FIELDS Mandatory fields, checked when create and update object
  31. */
  32. public static $FIELDS = array(
  33. 'ref',
  34. 'title'
  35. );
  36. /**
  37. * @var Project $project {@type Project}
  38. */
  39. public $project;
  40. /**
  41. * Constructor
  42. */
  43. public function __construct()
  44. {
  45. global $db, $conf;
  46. $this->db = $db;
  47. $this->project = new Project($this->db);
  48. $this->task = new Task($this->db);
  49. }
  50. /**
  51. * Get properties of a project object
  52. *
  53. * Return an array with project informations
  54. *
  55. * @param int $id ID of project
  56. * @return array|mixed data without useless information
  57. *
  58. * @throws RestException
  59. */
  60. public function get($id)
  61. {
  62. if (!DolibarrApiAccess::$user->rights->projet->lire) {
  63. throw new RestException(401);
  64. }
  65. $result = $this->project->fetch($id);
  66. if (!$result) {
  67. throw new RestException(404, 'Project not found');
  68. }
  69. if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
  70. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  71. }
  72. $this->project->fetchObjectLinked();
  73. return $this->_cleanObjectDatas($this->project);
  74. }
  75. /**
  76. * List projects
  77. *
  78. * Get a list of projects
  79. *
  80. * @param string $sortfield Sort field
  81. * @param string $sortorder Sort order
  82. * @param int $limit Limit for list
  83. * @param int $page Page number
  84. * @param string $thirdparty_ids Thirdparty ids to filter projects of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
  85. * @param int $category Use this param to filter list by category
  86. * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  87. * @return array Array of project objects
  88. */
  89. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '')
  90. {
  91. global $db, $conf;
  92. if (!DolibarrApiAccess::$user->rights->projet->lire) {
  93. throw new RestException(401);
  94. }
  95. $obj_ret = array();
  96. // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
  97. $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
  98. // If the internal user must only see his customers, force searching by him
  99. $search_sale = 0;
  100. if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) {
  101. $search_sale = DolibarrApiAccess::$user->id;
  102. }
  103. $sql = "SELECT t.rowid";
  104. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  105. $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
  106. }
  107. $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
  108. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_extrafields AS ef ON ef.fk_object = t.rowid"; // So we will be able to filter on extrafields
  109. if ($category > 0) {
  110. $sql .= ", ".MAIN_DB_PREFIX."categorie_project as c";
  111. }
  112. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  113. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
  114. }
  115. $sql .= ' WHERE t.entity IN ('.getEntity('project').')';
  116. if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
  117. $sql .= " AND t.fk_soc = sc.fk_soc";
  118. }
  119. if ($socids) {
  120. $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
  121. }
  122. if ($search_sale > 0) {
  123. $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
  124. }
  125. // Insert sale filter
  126. if ($search_sale > 0) {
  127. $sql .= " AND sc.fk_user = ".((int) $search_sale);
  128. }
  129. // Select projects of given category
  130. if ($category > 0) {
  131. $sql .= " AND c.fk_categorie = ".((int) $category)." AND c.fk_project = t.rowid ";
  132. }
  133. // Add sql filters
  134. if ($sqlfilters) {
  135. $errormessage = '';
  136. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
  137. if ($errormessage) {
  138. throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
  139. }
  140. }
  141. $sql .= $this->db->order($sortfield, $sortorder);
  142. if ($limit) {
  143. if ($page < 0) {
  144. $page = 0;
  145. }
  146. $offset = $limit * $page;
  147. $sql .= $this->db->plimit($limit + 1, $offset);
  148. }
  149. dol_syslog("API Rest request");
  150. $result = $this->db->query($sql);
  151. if ($result) {
  152. $num = $this->db->num_rows($result);
  153. $min = min($num, ($limit <= 0 ? $num : $limit));
  154. $i = 0;
  155. while ($i < $min) {
  156. $obj = $this->db->fetch_object($result);
  157. $project_static = new Project($this->db);
  158. if ($project_static->fetch($obj->rowid)) {
  159. $obj_ret[] = $this->_cleanObjectDatas($project_static);
  160. }
  161. $i++;
  162. }
  163. } else {
  164. throw new RestException(503, 'Error when retrieve project list : '.$this->db->lasterror());
  165. }
  166. if (!count($obj_ret)) {
  167. throw new RestException(404, 'No project found');
  168. }
  169. return $obj_ret;
  170. }
  171. /**
  172. * Create project object
  173. *
  174. * @param array $request_data Request data
  175. * @return int ID of project
  176. */
  177. public function post($request_data = null)
  178. {
  179. if (!DolibarrApiAccess::$user->rights->projet->creer) {
  180. throw new RestException(401, "Insuffisant rights");
  181. }
  182. // Check mandatory fields
  183. $result = $this->_validate($request_data);
  184. foreach ($request_data as $field => $value) {
  185. $this->project->$field = $value;
  186. }
  187. /*if (isset($request_data["lines"])) {
  188. $lines = array();
  189. foreach ($request_data["lines"] as $line) {
  190. array_push($lines, (object) $line);
  191. }
  192. $this->project->lines = $lines;
  193. }*/
  194. if ($this->project->create(DolibarrApiAccess::$user) < 0) {
  195. throw new RestException(500, "Error creating project", array_merge(array($this->project->error), $this->project->errors));
  196. }
  197. return $this->project->id;
  198. }
  199. /**
  200. * Get tasks of a project.
  201. * See also API /tasks
  202. *
  203. * @param int $id Id of project
  204. * @param int $includetimespent 0=Return only list of tasks. 1=Include a summary of time spent, 2=Include details of time spent lines
  205. * @return int
  206. *
  207. * @url GET {id}/tasks
  208. */
  209. public function getLines($id, $includetimespent = 0)
  210. {
  211. if (!DolibarrApiAccess::$user->rights->projet->lire) {
  212. throw new RestException(401);
  213. }
  214. $result = $this->project->fetch($id);
  215. if (!$result) {
  216. throw new RestException(404, 'Project not found');
  217. }
  218. if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
  219. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  220. }
  221. $this->project->getLinesArray(DolibarrApiAccess::$user);
  222. $result = array();
  223. foreach ($this->project->lines as $line) { // $line is a task
  224. if ($includetimespent == 1) {
  225. $timespent = $line->getSummaryOfTimeSpent(0);
  226. }
  227. if ($includetimespent == 2) {
  228. $timespent = $line->fetchTimeSpentOnTask();
  229. }
  230. array_push($result, $this->_cleanObjectDatas($line));
  231. }
  232. return $result;
  233. }
  234. /**
  235. * Get roles a user is assigned to a project with
  236. *
  237. * @param int $id Id of project
  238. * @param int $userid Id of user (0 = connected user)
  239. *
  240. * @url GET {id}/roles
  241. *
  242. * @return int
  243. */
  244. public function getRoles($id, $userid = 0)
  245. {
  246. global $db;
  247. if (!DolibarrApiAccess::$user->rights->projet->lire) {
  248. throw new RestException(401);
  249. }
  250. $result = $this->project->fetch($id);
  251. if (!$result) {
  252. throw new RestException(404, 'Project not found');
  253. }
  254. if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
  255. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  256. }
  257. require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
  258. $taskstatic = new Task($this->db);
  259. $userp = DolibarrApiAccess::$user;
  260. if ($userid > 0) {
  261. $userp = new User($this->db);
  262. $userp->fetch($userid);
  263. }
  264. $this->project->roles = $taskstatic->getUserRolesForProjectsOrTasks($userp, 0, $id, 0);
  265. $result = array();
  266. foreach ($this->project->roles as $line) {
  267. array_push($result, $this->_cleanObjectDatas($line));
  268. }
  269. return $result;
  270. }
  271. /**
  272. * Add a task to given project
  273. *
  274. * @param int $id Id of project to update
  275. * @param array $request_data Projectline data
  276. *
  277. * @url POST {id}/tasks
  278. *
  279. * @return int
  280. */
  281. /*
  282. public function postLine($id, $request_data = null)
  283. {
  284. if(! DolibarrApiAccess::$user->rights->projet->creer) {
  285. throw new RestException(401);
  286. }
  287. $result = $this->project->fetch($id);
  288. if( ! $result ) {
  289. throw new RestException(404, 'Project not found');
  290. }
  291. if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
  292. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  293. }
  294. $request_data = (object) $request_data;
  295. $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
  296. $updateRes = $this->project->addline(
  297. $request_data->desc,
  298. $request_data->subprice,
  299. $request_data->qty,
  300. $request_data->tva_tx,
  301. $request_data->localtax1_tx,
  302. $request_data->localtax2_tx,
  303. $request_data->fk_product,
  304. $request_data->remise_percent,
  305. $request_data->info_bits,
  306. $request_data->fk_remise_except,
  307. 'HT',
  308. 0,
  309. $request_data->date_start,
  310. $request_data->date_end,
  311. $request_data->product_type,
  312. $request_data->rang,
  313. $request_data->special_code,
  314. $fk_parent_line,
  315. $request_data->fk_fournprice,
  316. $request_data->pa_ht,
  317. $request_data->label,
  318. $request_data->array_options,
  319. $request_data->fk_unit,
  320. $this->element,
  321. $request_data->id
  322. );
  323. if ($updateRes > 0) {
  324. return $updateRes;
  325. }
  326. return false;
  327. }
  328. */
  329. /**
  330. * Update a task to given project
  331. *
  332. * @param int $id Id of project to update
  333. * @param int $taskid Id of task to update
  334. * @param array $request_data Projectline data
  335. *
  336. * @url PUT {id}/tasks/{taskid}
  337. *
  338. * @return object
  339. */
  340. /*
  341. public function putLine($id, $lineid, $request_data = null)
  342. {
  343. if(! DolibarrApiAccess::$user->rights->projet->creer) {
  344. throw new RestException(401);
  345. }
  346. $result = $this->project->fetch($id);
  347. if( ! $result ) {
  348. throw new RestException(404, 'Project not found');
  349. }
  350. if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
  351. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  352. }
  353. $request_data = (object) $request_data;
  354. $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
  355. $updateRes = $this->project->updateline(
  356. $lineid,
  357. $request_data->desc,
  358. $request_data->subprice,
  359. $request_data->qty,
  360. $request_data->remise_percent,
  361. $request_data->tva_tx,
  362. $request_data->localtax1_tx,
  363. $request_data->localtax2_tx,
  364. 'HT',
  365. $request_data->info_bits,
  366. $request_data->date_start,
  367. $request_data->date_end,
  368. $request_data->product_type,
  369. $request_data->fk_parent_line,
  370. 0,
  371. $request_data->fk_fournprice,
  372. $request_data->pa_ht,
  373. $request_data->label,
  374. $request_data->special_code,
  375. $request_data->array_options,
  376. $request_data->fk_unit
  377. );
  378. if ($updateRes > 0) {
  379. $result = $this->get($id);
  380. unset($result->line);
  381. return $this->_cleanObjectDatas($result);
  382. }
  383. return false;
  384. }*/
  385. /**
  386. * Update project general fields (won't touch lines of project)
  387. *
  388. * @param int $id Id of project to update
  389. * @param array $request_data Datas
  390. *
  391. * @return int
  392. */
  393. public function put($id, $request_data = null)
  394. {
  395. if (!DolibarrApiAccess::$user->rights->projet->creer) {
  396. throw new RestException(401);
  397. }
  398. $result = $this->project->fetch($id);
  399. if ($result <= 0) {
  400. throw new RestException(404, 'Project not found');
  401. }
  402. if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
  403. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  404. }
  405. foreach ($request_data as $field => $value) {
  406. if ($field == 'id') {
  407. continue;
  408. }
  409. $this->project->$field = $value;
  410. }
  411. if ($this->project->update(DolibarrApiAccess::$user) >= 0) {
  412. return $this->get($id);
  413. } else {
  414. throw new RestException(500, $this->project->error);
  415. }
  416. }
  417. /**
  418. * Delete project
  419. *
  420. * @param int $id Project ID
  421. *
  422. * @return array
  423. */
  424. public function delete($id)
  425. {
  426. if (!DolibarrApiAccess::$user->rights->projet->supprimer) {
  427. throw new RestException(401);
  428. }
  429. $result = $this->project->fetch($id);
  430. if (!$result) {
  431. throw new RestException(404, 'Project not found');
  432. }
  433. if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
  434. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  435. }
  436. if (!$this->project->delete(DolibarrApiAccess::$user)) {
  437. throw new RestException(500, 'Error when delete project : '.$this->project->error);
  438. }
  439. return array(
  440. 'success' => array(
  441. 'code' => 200,
  442. 'message' => 'Project deleted'
  443. )
  444. );
  445. }
  446. /**
  447. * Validate a project.
  448. * You can test this API with the following input message
  449. * { "notrigger": 0 }
  450. *
  451. * @param int $id Project ID
  452. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  453. *
  454. * @url POST {id}/validate
  455. *
  456. * @return array
  457. * FIXME An error 403 is returned if the request has an empty body.
  458. * Error message: "Forbidden: Content type `text/plain` is not supported."
  459. * Workaround: send this in the body
  460. * {
  461. * "notrigger": 0
  462. * }
  463. */
  464. public function validate($id, $notrigger = 0)
  465. {
  466. if (!DolibarrApiAccess::$user->rights->projet->creer) {
  467. throw new RestException(401);
  468. }
  469. $result = $this->project->fetch($id);
  470. if (!$result) {
  471. throw new RestException(404, 'Project not found');
  472. }
  473. if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
  474. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  475. }
  476. $result = $this->project->setValid(DolibarrApiAccess::$user, $notrigger);
  477. if ($result == 0) {
  478. throw new RestException(304, 'Error nothing done. May be object is already validated');
  479. }
  480. if ($result < 0) {
  481. throw new RestException(500, 'Error when validating Project: '.$this->project->error);
  482. }
  483. return array(
  484. 'success' => array(
  485. 'code' => 200,
  486. 'message' => 'Project validated'
  487. )
  488. );
  489. }
  490. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  491. /**
  492. * Clean sensible object datas
  493. *
  494. * @param Object $object Object to clean
  495. * @return Object Object with cleaned properties
  496. */
  497. protected function _cleanObjectDatas($object)
  498. {
  499. // phpcs:enable
  500. $object = parent::_cleanObjectDatas($object);
  501. unset($object->datec);
  502. unset($object->datem);
  503. unset($object->barcode_type);
  504. unset($object->barcode_type_code);
  505. unset($object->barcode_type_label);
  506. unset($object->barcode_type_coder);
  507. unset($object->cond_reglement_id);
  508. unset($object->cond_reglement);
  509. unset($object->fk_delivery_address);
  510. unset($object->shipping_method_id);
  511. unset($object->fk_account);
  512. unset($object->note);
  513. unset($object->fk_incoterms);
  514. unset($object->label_incoterms);
  515. unset($object->location_incoterms);
  516. unset($object->name);
  517. unset($object->lastname);
  518. unset($object->firstname);
  519. unset($object->civility_id);
  520. unset($object->mode_reglement_id);
  521. unset($object->country);
  522. unset($object->country_id);
  523. unset($object->country_code);
  524. unset($object->weekWorkLoad);
  525. unset($object->weekWorkLoad);
  526. //unset($object->lines); // for task we use timespent_lines, but for project we use lines
  527. unset($object->total_ht);
  528. unset($object->total_tva);
  529. unset($object->total_localtax1);
  530. unset($object->total_localtax2);
  531. unset($object->total_ttc);
  532. unset($object->comments);
  533. return $object;
  534. }
  535. /**
  536. * Validate fields before create or update object
  537. *
  538. * @param array $data Array with data to verify
  539. * @return array
  540. * @throws RestException
  541. */
  542. private function _validate($data)
  543. {
  544. $object = array();
  545. foreach (self::$FIELDS as $field) {
  546. if (!isset($data[$field])) {
  547. throw new RestException(400, "$field field missing");
  548. }
  549. $object[$field] = $data[$field];
  550. }
  551. return $object;
  552. }
  553. // TODO
  554. // getSummaryOfTimeSpent
  555. }