dolibarr 22.0.5
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 global $conf;
111
112 $obj_ret = array();
113
114 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'lire')) {
115 throw new RestException(403);
116 }
117
118 $sql = "SELECT rowid";
119 $sql .= " FROM ".MAIN_DB_PREFIX."subscription as t";
120 $sql .= ' WHERE 1 = 1';
121 // Add sql filters
122 if ($sqlfilters) {
123 $errormessage = '';
124 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
125 if ($errormessage) {
126 throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
127 }
128 }
129
130 //this query will return total orders with the filters given
131 $sqlTotals = str_replace('SELECT rowid', 'SELECT count(rowid) as total', $sql);
132
133 $sql .= $this->db->order($sortfield, $sortorder);
134 if ($limit) {
135 if ($page < 0) {
136 $page = 0;
137 }
138 $offset = $limit * $page;
139
140 $sql .= $this->db->plimit($limit + 1, $offset);
141 }
142
143 $result = $this->db->query($sql);
144 if ($result) {
145 $i = 0;
146 $num = $this->db->num_rows($result);
147 while ($i < min($limit, $num)) {
148 $obj = $this->db->fetch_object($result);
149 $subscription = new Subscription($this->db);
150 if ($subscription->fetch($obj->rowid)) {
151 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($subscription), $properties);
152 }
153 $i++;
154 }
155 } else {
156 throw new RestException(503, 'Error when retrieve subscription list : '.$this->db->lasterror());
157 }
158
159 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
160 if ($pagination_data) {
161 $totalsResult = $this->db->query($sqlTotals);
162 $total = $this->db->fetch_object($totalsResult)->total;
163
164 $tmp = $obj_ret;
165 $obj_ret = [];
166
167 $obj_ret['data'] = $tmp;
168 $obj_ret['pagination'] = [
169 'total' => (int) $total,
170 'page' => $page, //count starts from 0
171 'page_count' => ceil((int) $total / $limit),
172 'limit' => $limit
173 ];
174 }
175
176 return $obj_ret;
177 }
178
190 public function post($request_data = null)
191 {
192 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'creer')) {
193 throw new RestException(403);
194 }
195 // Check mandatory fields
196 $result = $this->_validate($request_data);
197
198 // The member of the new subscription must be a member of an entity the user can access
199 if (!empty($request_data['fk_adherent']) && !DolibarrApi::_checkAccessToResource('adherent', (int) $request_data['fk_adherent'])) {
200 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
201 }
202
203 $subscription = new Subscription($this->db);
204 foreach ($request_data as $field => $value) {
205 if ($field === 'caller') {
206 // 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
207 $subscription->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
208 continue;
209 }
210
211 $subscription->$field = $this->_checkValForAPI($field, $value, $subscription);
212 }
213 if ($subscription->create(DolibarrApiAccess::$user) < 0) {
214 throw new RestException(500, 'Error when creating subscription', array_merge(array($subscription->error), $subscription->errors));
215 }
216 return $subscription->id;
217 }
218
232 public function put($id, $request_data = null)
233 {
234 if (!DolibarrApiAccess::$user->hasRight('adherent', 'creer')) {
235 throw new RestException(403);
236 }
237
238 $subscription = new Subscription($this->db);
239 $result = $subscription->fetch($id);
240 if (!$result) {
241 throw new RestException(404, 'Subscription not found');
242 }
243
244 // A subscription has no entity, the entity is the one of its member
245 if (!DolibarrApi::_checkAccessToResource('adherent', $subscription->fk_adherent)) {
246 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
247 }
248
249 foreach ($request_data as $field => $value) {
250 if ($field == 'id') {
251 continue;
252 }
253 if ($field === 'caller') {
254 // 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
255 $subscription->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
256 continue;
257 }
258
259 if ($field == 'array_options' && is_array($value)) {
260 foreach ($value as $index => $val) {
261 $subscription->array_options[$index] = $this->_checkValForAPI($field, $val, $subscription);
262 }
263 continue;
264 }
265 $subscription->$field = $this->_checkValForAPI($field, $value, $subscription);
266 }
267
268 if ($subscription->update(DolibarrApiAccess::$user) > 0) {
269 return $this->get($id);
270 } else {
271 throw new RestException(500, 'Error when updating contribution: '.$subscription->error);
272 }
273 }
274
288 public function delete($id)
289 {
290 // The right to delete a subscription comes with the right to create one.
291 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'creer')) {
292 throw new RestException(403);
293 }
294 $subscription = new Subscription($this->db);
295 $result = $subscription->fetch($id);
296 if (!$result) {
297 throw new RestException(404, 'Subscription not found');
298 }
299
300 // A subscription has no entity, the entity is the one of its member
301 if (!DolibarrApi::_checkAccessToResource('adherent', $subscription->fk_adherent)) {
302 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
303 }
304
305 $res = $subscription->delete(DolibarrApiAccess::$user);
306 if ($res < 0) {
307 throw new RestException(500, "Can't delete, error occurs");
308 } elseif ($res == 0) {
309 throw new RestException(409, "No subscription whas deleted");
310 }
311
312 return array(
313 'success' => array(
314 'code' => 200,
315 'message' => 'Subscription deleted'
316 )
317 );
318 }
319
328 private function _validate($data)
329 {
330 $subscription = array();
331 foreach (Subscriptions::$FIELDS as $field) {
332 if (!isset($data[$field])) {
333 throw new RestException(400, "$field field missing");
334 }
335 $subscription[$field] = $data[$field];
336 }
337 return $subscription;
338 }
339}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
Class for API REST v1.
Definition api.class.php:33
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:98
_cleanObjectDatas($object)
Clean sensitive object data @phpstan-template T of Object.
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.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79