api_members.class.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. <?php
  2. /* Copyright (C) 2016 Xebax Christy <xebax@wanadoo.fr>
  3. * Copyright (C) 2017 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2020 Thibault FOUCART<support@ptibogxiv.net>
  5. * Copyright (C) 2020 Frédéric France <frederic.france@netlogic.fr>
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. use Luracast\Restler\RestException;
  21. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  22. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  23. require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
  24. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  25. /**
  26. * API class for members
  27. *
  28. * @access protected
  29. * @class DolibarrApiAccess {@requires user,external}
  30. */
  31. class Members extends DolibarrApi
  32. {
  33. /**
  34. * @var array $FIELDS Mandatory fields, checked when create and update object
  35. */
  36. public static $FIELDS = array(
  37. 'morphy',
  38. 'typeid'
  39. );
  40. /**
  41. * Constructor
  42. */
  43. public function __construct()
  44. {
  45. global $db, $conf;
  46. $this->db = $db;
  47. }
  48. /**
  49. * Get properties of a member object
  50. *
  51. * Return an array with member informations
  52. *
  53. * @param int $id ID of member
  54. * @return Object Object with cleaned properties
  55. *
  56. * @throws RestException
  57. */
  58. public function get($id)
  59. {
  60. if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
  61. throw new RestException(401);
  62. }
  63. $member = new Adherent($this->db);
  64. if ($id == 0) {
  65. $result = $member->initAsSpecimen();
  66. } else {
  67. $result = $member->fetch($id);
  68. }
  69. if (!$result) {
  70. throw new RestException(404, 'member not found');
  71. }
  72. if (!DolibarrApi::_checkAccessToResource('adherent', $member->id) && $id > 0) {
  73. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  74. }
  75. return $this->_cleanObjectDatas($member);
  76. }
  77. /**
  78. * Get properties of a member object by linked thirdparty
  79. *
  80. * Return an array with member informations
  81. *
  82. * @param int $thirdparty ID of third party
  83. *
  84. * @return Object Data without useless information
  85. *
  86. * @url GET thirdparty/{thirdparty}
  87. *
  88. * @throws RestException 401
  89. * @throws RestException 404
  90. */
  91. public function getByThirdparty($thirdparty)
  92. {
  93. if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
  94. throw new RestException(401);
  95. }
  96. $member = new Adherent($this->db);
  97. $result = $member->fetch('', '', $thirdparty);
  98. if (!$result) {
  99. throw new RestException(404, 'member not found');
  100. }
  101. if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
  102. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  103. }
  104. return $this->_cleanObjectDatas($member);
  105. }
  106. /**
  107. * Get properties of a member object by linked thirdparty email
  108. *
  109. * Return an array with member informations
  110. *
  111. * @param string $email Email of third party
  112. *
  113. * @return Object Data without useless information
  114. *
  115. * @url GET thirdparty/email/{email}
  116. *
  117. * @throws RestException 401
  118. * @throws RestException 404
  119. */
  120. public function getByThirdpartyEmail($email)
  121. {
  122. if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
  123. throw new RestException(401);
  124. }
  125. $thirdparty = new Societe($this->db);
  126. $result = $thirdparty->fetch('', '', '', '', '', '', '', '', '', '', $email);
  127. if (!$result) {
  128. throw new RestException(404, 'thirdparty not found');
  129. }
  130. $member = new Adherent($this->db);
  131. $result = $member->fetch('', '', $thirdparty->id);
  132. if (!$result) {
  133. throw new RestException(404, 'member not found');
  134. }
  135. if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
  136. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  137. }
  138. return $this->_cleanObjectDatas($member);
  139. }
  140. /**
  141. * Get properties of a member object by linked thirdparty barcode
  142. *
  143. * Return an array with member informations
  144. *
  145. * @param string $barcode Barcode of third party
  146. *
  147. * @return Object Data without useless information
  148. *
  149. * @url GET thirdparty/barcode/{barcode}
  150. *
  151. * @throws RestException 401
  152. * @throws RestException 404
  153. */
  154. public function getByThirdpartyBarcode($barcode)
  155. {
  156. if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
  157. throw new RestException(401);
  158. }
  159. $thirdparty = new Societe($this->db);
  160. $result = $thirdparty->fetch('', '', '', $barcode);
  161. if (!$result) {
  162. throw new RestException(404, 'thirdparty not found');
  163. }
  164. $member = new Adherent($this->db);
  165. $result = $member->fetch('', '', $thirdparty->id);
  166. if (!$result) {
  167. throw new RestException(404, 'member not found');
  168. }
  169. if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
  170. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  171. }
  172. return $this->_cleanObjectDatas($member);
  173. }
  174. /**
  175. * List members
  176. *
  177. * Get a list of members
  178. *
  179. * @param string $sortfield Sort field
  180. * @param string $sortorder Sort order
  181. * @param int $limit Limit for list
  182. * @param int $page Page number
  183. * @param string $typeid ID of the type of member
  184. * @param int $category Use this param to filter list by category
  185. * @param string $sqlfilters Other criteria to filter answers separated by a comma.
  186. * Example: "(t.ref:like:'SO-%') and ((t.date_creation:<:'20160101') or (t.nature:is:NULL))"
  187. * @param string $properties Restrict the data returned to theses properties. Ignored if empty. Comma separated list of properties names
  188. * @return array Array of member objects
  189. *
  190. * @throws RestException
  191. */
  192. public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $typeid = '', $category = 0, $sqlfilters = '', $properties = '')
  193. {
  194. global $db, $conf;
  195. $obj_ret = array();
  196. if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
  197. throw new RestException(401);
  198. }
  199. $sql = "SELECT t.rowid";
  200. $sql .= " FROM ".MAIN_DB_PREFIX."adherent AS t LEFT JOIN ".MAIN_DB_PREFIX."adherent_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call
  201. if ($category > 0) {
  202. $sql .= ", ".MAIN_DB_PREFIX."categorie_member as c";
  203. }
  204. $sql .= ' WHERE t.entity IN ('.getEntity('adherent').')';
  205. if (!empty($typeid)) {
  206. $sql .= ' AND t.fk_adherent_type='.((int) $typeid);
  207. }
  208. // Select members of given category
  209. if ($category > 0) {
  210. $sql .= " AND c.fk_categorie = ".((int) $category);
  211. $sql .= " AND c.fk_member = t.rowid";
  212. }
  213. // Add sql filters
  214. if ($sqlfilters) {
  215. $errormessage = '';
  216. $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
  217. if ($errormessage) {
  218. throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
  219. }
  220. }
  221. $sql .= $this->db->order($sortfield, $sortorder);
  222. if ($limit) {
  223. if ($page < 0) {
  224. $page = 0;
  225. }
  226. $offset = $limit * $page;
  227. $sql .= $this->db->plimit($limit + 1, $offset);
  228. }
  229. $result = $this->db->query($sql);
  230. if ($result) {
  231. $i = 0;
  232. $num = $this->db->num_rows($result);
  233. $min = min($num, ($limit <= 0 ? $num : $limit));
  234. while ($i < $min) {
  235. $obj = $this->db->fetch_object($result);
  236. $member = new Adherent($this->db);
  237. if ($member->fetch($obj->rowid)) {
  238. $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($member), $properties);
  239. }
  240. $i++;
  241. }
  242. } else {
  243. throw new RestException(503, 'Error when retrieve member list : '.$this->db->lasterror());
  244. }
  245. return $obj_ret;
  246. }
  247. /**
  248. * Create member object
  249. *
  250. * @param array $request_data Request data
  251. * @return int ID of member
  252. */
  253. public function post($request_data = null)
  254. {
  255. if (!DolibarrApiAccess::$user->hasRight('adherent', 'creer')) {
  256. throw new RestException(401);
  257. }
  258. // Check mandatory fields
  259. $result = $this->_validate($request_data);
  260. $member = new Adherent($this->db);
  261. foreach ($request_data as $field => $value) {
  262. if ($field === 'caller') {
  263. // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller
  264. $member->context['caller'] = $request_data['caller'];
  265. continue;
  266. }
  267. $member->$field = $value;
  268. }
  269. if ($member->create(DolibarrApiAccess::$user) < 0) {
  270. throw new RestException(500, 'Error creating member', array_merge(array($member->error), $member->errors));
  271. }
  272. return $member->id;
  273. }
  274. /**
  275. * Update member
  276. *
  277. * @param int $id ID of member to update
  278. * @param array $request_data Datas
  279. * @return Object Updated object
  280. */
  281. public function put($id, $request_data = null)
  282. {
  283. if (!DolibarrApiAccess::$user->hasRight('adherent', 'creer')) {
  284. throw new RestException(401);
  285. }
  286. $member = new Adherent($this->db);
  287. $result = $member->fetch($id);
  288. if (!$result) {
  289. throw new RestException(404, 'member not found');
  290. }
  291. if (!DolibarrApi::_checkAccessToResource('member', $member->id)) {
  292. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  293. }
  294. foreach ($request_data as $field => $value) {
  295. if ($field == 'id') {
  296. continue;
  297. }
  298. if ($field === 'caller') {
  299. // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller
  300. $member->context['caller'] = $request_data['caller'];
  301. continue;
  302. }
  303. // Process the status separately because it must be updated using
  304. // the validate(), resiliate() and exclude() methods of the class Adherent.
  305. if ($field == 'statut') {
  306. if ($value == '0') {
  307. $result = $member->resiliate(DolibarrApiAccess::$user);
  308. if ($result < 0) {
  309. throw new RestException(500, 'Error when resiliating member: '.$member->error);
  310. }
  311. } elseif ($value == '1') {
  312. $result = $member->validate(DolibarrApiAccess::$user);
  313. if ($result < 0) {
  314. throw new RestException(500, 'Error when validating member: '.$member->error);
  315. }
  316. } elseif ($value == '-2') {
  317. $result = $member->exclude(DolibarrApiAccess::$user);
  318. if ($result < 0) {
  319. throw new RestException(500, 'Error when excluding member: '.$member->error);
  320. }
  321. }
  322. } else {
  323. $member->$field = $value;
  324. }
  325. }
  326. // If there is no error, update() returns the number of affected rows
  327. // so if the update is a no op, the return value is zero.
  328. if ($member->update(DolibarrApiAccess::$user) >= 0) {
  329. return $this->get($id);
  330. } else {
  331. throw new RestException(500, 'Error when updating member: '.$member->error);
  332. }
  333. }
  334. /**
  335. * Delete member
  336. *
  337. * @param int $id member ID
  338. * @return array
  339. */
  340. public function delete($id)
  341. {
  342. if (!DolibarrApiAccess::$user->hasRight('adherent', 'supprimer')) {
  343. throw new RestException(401);
  344. }
  345. $member = new Adherent($this->db);
  346. $result = $member->fetch($id);
  347. if (!$result) {
  348. throw new RestException(404, 'member not found');
  349. }
  350. if (!DolibarrApi::_checkAccessToResource('member', $member->id)) {
  351. throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
  352. }
  353. $res = $member->delete($member->id, DolibarrApiAccess::$user);
  354. if ($res < 0) {
  355. throw new RestException(500, "Can't delete, error occurs");
  356. } elseif ($res == 0) {
  357. throw new RestException(409, "Can't delete, that product is probably used");
  358. }
  359. return array(
  360. 'success' => array(
  361. 'code' => 200,
  362. 'message' => 'Member deleted'
  363. )
  364. );
  365. }
  366. /**
  367. * Validate fields before creating an object
  368. *
  369. * @param array|null $data Data to validate
  370. * @return array
  371. *
  372. * @throws RestException
  373. */
  374. private function _validate($data)
  375. {
  376. $member = array();
  377. foreach (Members::$FIELDS as $field) {
  378. if (!isset($data[$field])) {
  379. throw new RestException(400, "$field field missing");
  380. }
  381. $member[$field] = $data[$field];
  382. }
  383. return $member;
  384. }
  385. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  386. /**
  387. * Clean sensible object datas
  388. *
  389. * @param Object $object Object to clean
  390. * @return Object Object with cleaned properties
  391. */
  392. protected function _cleanObjectDatas($object)
  393. {
  394. // phpcs:enable
  395. $object = parent::_cleanObjectDatas($object);
  396. // Remove the subscriptions because they are handled as a subresource.
  397. unset($object->subscriptions);
  398. unset($object->fk_incoterms);
  399. unset($object->label_incoterms);
  400. unset($object->location_incoterms);
  401. unset($object->fk_delivery_address);
  402. unset($object->shipping_method_id);
  403. unset($object->total_ht);
  404. unset($object->total_ttc);
  405. unset($object->total_tva);
  406. unset($object->total_localtax1);
  407. unset($object->total_localtax2);
  408. return $object;
  409. }
  410. /**
  411. * List subscriptions of a member
  412. *
  413. * Get a list of subscriptions
  414. *
  415. * @param int $id ID of member
  416. * @return array Array of subscription objects
  417. *
  418. * @throws RestException
  419. *
  420. * @url GET {id}/subscriptions
  421. */
  422. public function getSubscriptions($id)
  423. {
  424. $obj_ret = array();
  425. if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'lire')) {
  426. throw new RestException(401);
  427. }
  428. $member = new Adherent($this->db);
  429. $result = $member->fetch($id);
  430. if (!$result) {
  431. throw new RestException(404, 'member not found');
  432. }
  433. $obj_ret = array();
  434. foreach ($member->subscriptions as $subscription) {
  435. $obj_ret[] = $this->_cleanObjectDatas($subscription);
  436. }
  437. return $obj_ret;
  438. }
  439. /**
  440. * Add a subscription for a member
  441. *
  442. * @param int $id ID of member
  443. * @param string $start_date Start date {@from body} {@type timestamp}
  444. * @param string $end_date End date {@from body} {@type timestamp}
  445. * @param float $amount Amount (may be 0) {@from body}
  446. * @param string $label Label {@from body}
  447. * @return int ID of subscription
  448. *
  449. * @url POST {id}/subscriptions
  450. */
  451. public function createSubscription($id, $start_date, $end_date, $amount, $label = '')
  452. {
  453. if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'creer')) {
  454. throw new RestException(401);
  455. }
  456. $member = new Adherent($this->db);
  457. $result = $member->fetch($id);
  458. if (!$result) {
  459. throw new RestException(404, 'member not found');
  460. }
  461. return $member->subscription($start_date, $amount, 0, '', $label, '', '', '', $end_date);
  462. }
  463. /**
  464. * Get categories for a member
  465. *
  466. * @param int $id ID of member
  467. * @param string $sortfield Sort field
  468. * @param string $sortorder Sort order
  469. * @param int $limit Limit for list
  470. * @param int $page Page number
  471. *
  472. * @return mixed
  473. *
  474. * @url GET {id}/categories
  475. */
  476. public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
  477. {
  478. if (!DolibarrApiAccess::$user->rights->categorie->lire) {
  479. throw new RestException(401);
  480. }
  481. $categories = new Categorie($this->db);
  482. $result = $categories->getListForItem($id, 'member', $sortfield, $sortorder, $limit, $page);
  483. if ($result < 0) {
  484. throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
  485. }
  486. return $result;
  487. }
  488. }