dolibarr 24.0.2
api_subscriptions.class.php
1<?php
2/* Copyright (C) 2016 Xebax Christy <xebax@wanadoo.fr>
3 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
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
19use Luracast\Restler\RestException;
20
21require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
22
30{
34 public static $FIELDS = array(
35 'fk_adherent',
36 'dateh',
37 'datef',
38 'amount',
39 );
40
44 public $subscription;
45
49 public function __construct()
50 {
51 global $db, $conf;
52 $this->db = $db;
53 $this->subscription = new Subscription($this->db);
54 }
55
67 public function get($id)
68 {
69 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'lire')) {
70 throw new RestException(403);
71 }
72
73 $result = $this->subscription->fetch($id);
74 if (!$result) {
75 throw new RestException(404, 'Subscription not found');
76 }
77
78 // A subscription has no entity, the entity is the one of its member
79 if (!DolibarrApi::_checkAccessToResource('adherent', $this->subscription->fk_adherent)) {
80 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
81 }
82
83 $this->subscription->fetchObjectLinked();
84
85 return $this->_cleanObjectDatas($this->subscription);
86 }
87
108 public function index($sortfield = "dateadh", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
109 {
110 $obj_ret = array();
111
112 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'lire')) {
113 throw new RestException(403);
114 }
115
116 $sql = "SELECT t.rowid";
117 $sql .= " FROM ".MAIN_DB_PREFIX."subscription as t";
118 // llx_subscription carries no entity column, the entity of a subscription is the one of its member,
119 // so the restriction goes through llx_adherent, as adherents/subscription/list.php does.
120 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."adherent as d ON d.rowid = t.fk_adherent";
121 $sql .= ' WHERE d.entity IN ('.getEntity('adherent').')';
122 // Add sql filters
123 if ($sqlfilters) {
124 $errormessage = '';
125 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
126 if ($errormessage) {
127 throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
128 }
129 }
130
131 //this query will return total orders with the filters given
132 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
133
134 $sql .= $this->db->order($sortfield, $sortorder);
135 if ($limit) {
136 if ($page < 0) {
137 $page = 0;
138 }
139 $offset = $limit * $page;
140
141 $sql .= $this->db->plimit($limit + 1, $offset);
142 }
143
144 $result = $this->db->query($sql);
145 if ($result) {
146 $i = 0;
147 $num = $this->db->num_rows($result);
148 $min = min($num, ($limit <= 0 ? $num : $limit));
149 while ($i < $min) {
150 $obj = $this->db->fetch_object($result);
151 $subscription = new Subscription($this->db);
152 if ($subscription->fetch($obj->rowid)) {
153 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($subscription), $properties);
154 }
155 $i++;
156 }
157 } else {
158 throw new RestException(503, 'Error when retrieve subscription list : '.$this->db->lasterror());
159 }
160
161 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
162 if ($pagination_data) {
163 $totalsResult = $this->db->query($sqlTotals);
164 $total = $this->db->fetch_object($totalsResult)->total;
165
166 $tmp = $obj_ret;
167 $obj_ret = [];
168
169 $obj_ret['data'] = $tmp;
170 $obj_ret['pagination'] = [
171 'total' => (int) $total,
172 'page' => $page, //count starts from 0
173 'page_count' => ceil((int) $total / $limit),
174 'limit' => $limit
175 ];
176 }
177
178 return $obj_ret;
179 }
180
192 public function post($request_data = null)
193 {
194 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'creer')) {
195 throw new RestException(403);
196 }
197 // Check mandatory fields
198 $result = $this->_validate($request_data);
199
200 // The member of the new subscription must be a member of an entity the user can access
201 if (!empty($request_data['fk_adherent']) && !DolibarrApi::_checkAccessToResource('adherent', (int) $request_data['fk_adherent'])) {
202 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
203 }
204
205 $subscription = new Subscription($this->db);
206 foreach ($request_data as $field => $value) {
207 if ($field === 'caller') {
208 // 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 with the caller
209 $subscription->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
210 continue;
211 }
212
213 $subscription->$field = $this->_checkValForAPI($field, $value, $subscription);
214 }
215 if ($subscription->create(DolibarrApiAccess::$user) < 0) {
216 throw new RestException(500, 'Error when creating subscription', array_merge(array($subscription->error), $subscription->errors));
217 }
218 return $subscription->id;
219 }
220
234 public function put($id, $request_data = null)
235 {
236 if (!DolibarrApiAccess::$user->hasRight('adherent', 'creer')) {
237 throw new RestException(403);
238 }
239
240 $subscription = new Subscription($this->db);
241 $result = $subscription->fetch($id);
242 if (!$result) {
243 throw new RestException(404, 'Subscription not found');
244 }
245
246 // A subscription has no entity, the entity is the one of its member
247 if (!DolibarrApi::_checkAccessToResource('adherent', $subscription->fk_adherent)) {
248 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
249 }
250
251 foreach ($request_data as $field => $value) {
252 if ($field == 'id') {
253 continue;
254 }
255 if ($field === 'caller') {
256 // 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 with the caller
257 $subscription->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
258 continue;
259 }
260
261 if ($field == 'array_options' && is_array($value)) {
262 foreach ($value as $index => $val) {
263 $subscription->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $subscription);
264 }
265 continue;
266 }
267 $subscription->$field = $this->_checkValForAPI($field, $value, $subscription);
268 }
269
270 if ($subscription->update(DolibarrApiAccess::$user) > 0) {
271 return $this->get($id);
272 } else {
273 throw new RestException(500, 'Error when updating contribution: '.$subscription->error);
274 }
275 }
276
290 public function delete($id)
291 {
292 // The right to delete a subscription comes with the right to create one.
293 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'creer')) {
294 throw new RestException(403);
295 }
296 $subscription = new Subscription($this->db);
297 $result = $subscription->fetch($id);
298 if (!$result) {
299 throw new RestException(404, 'Subscription not found');
300 }
301
302 // A subscription has no entity, the entity is the one of its member
303 if (!DolibarrApi::_checkAccessToResource('adherent', $subscription->fk_adherent)) {
304 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
305 }
306
307 $res = $subscription->delete(DolibarrApiAccess::$user);
308 if ($res < 0) {
309 throw new RestException(500, "Can't delete, error occurs");
310 } elseif ($res == 0) {
311 throw new RestException(409, "No subscription whas deleted");
312 }
313
314 return array(
315 'success' => array(
316 'code' => 200,
317 'message' => 'Subscription deleted'
318 )
319 );
320 }
321
330 private function _validate($data)
331 {
332 $subscription = array();
333 foreach (Subscriptions::$FIELDS as $field) {
334 if (!isset($data[$field])) {
335 throw new RestException(400, "$field field missing");
336 }
337 $subscription[$field] = $data[$field];
338 }
339 return $subscription;
340 }
341}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
Class for API REST v1.
Definition api.class.php:35
_checkValExtrafieldsForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_cleanObjectDatas($object)
Clean sensitive object data @phpstan-template T.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $parenttableforentity='')
Check access by user to a given resource.
Class to manage subscriptions of foundation members.
_validate($data)
Validate fields before creating an object.
post($request_data=null)
Create subscription object.
index($sortfield="dateadh", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='', $pagination_data=false)
List subscriptions.
put($id, $request_data=null)
Update subscription.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.