dolibarr 25.0.0-alpha
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 $this->subscription->fetchObjectLinked();
79
80 return $this->_cleanObjectDatas($this->subscription);
81 }
82
103 public function index($sortfield = "dateadh", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
104 {
105 $obj_ret = array();
106
107 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'lire')) {
108 throw new RestException(403);
109 }
110
111 $sql = "SELECT t.rowid";
112 $sql .= " FROM ".MAIN_DB_PREFIX."subscription as t";
113 // llx_subscription carries no entity column, the entity of a subscription is the one of its member,
114 // so the restriction goes through llx_adherent, as adherents/subscription/list.php does.
115 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."adherent as d ON d.rowid = t.fk_adherent";
116 $sql .= ' WHERE d.entity IN ('.getEntity('adherent').')';
117 // Add sql filters
118 if ($sqlfilters) {
119 $errormessage = '';
120 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
121 if ($errormessage) {
122 throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
123 }
124 }
125
126 //this query will return total orders with the filters given
127 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
128
129 $sql .= $this->db->order($sortfield, $sortorder);
130 if ($limit) {
131 if ($page < 0) {
132 $page = 0;
133 }
134 $offset = $limit * $page;
135
136 $sql .= $this->db->plimit($limit + 1, $offset);
137 }
138
139 $result = $this->db->query($sql);
140 if ($result) {
141 $i = 0;
142 $num = $this->db->num_rows($result);
143 $min = min($num, ($limit <= 0 ? $num : $limit));
144 while ($i < $min) {
145 $obj = $this->db->fetch_object($result);
146 $subscription = new Subscription($this->db);
147 if ($subscription->fetch($obj->rowid)) {
148 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($subscription), $properties);
149 }
150 $i++;
151 }
152 } else {
153 throw new RestException(503, 'Error when retrieve subscription list : '.$this->db->lasterror());
154 }
155
156 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
157 if ($pagination_data) {
158 $totalsResult = $this->db->query($sqlTotals);
159 $total = $this->db->fetch_object($totalsResult)->total;
160
161 $tmp = $obj_ret;
162 $obj_ret = [];
163
164 $obj_ret['data'] = $tmp;
165 $obj_ret['pagination'] = [
166 'total' => (int) $total,
167 'page' => $page, //count starts from 0
168 'page_count' => ceil((int) $total / $limit),
169 'limit' => $limit
170 ];
171 }
172
173 return $obj_ret;
174 }
175
187 public function post($request_data = null)
188 {
189 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'creer')) {
190 throw new RestException(403);
191 }
192 // Check mandatory fields
193 $result = $this->_validate($request_data);
194
195 $subscription = new Subscription($this->db);
196 foreach ($request_data as $field => $value) {
197 if ($field === 'caller') {
198 // 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
199 $subscription->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
200 continue;
201 }
202
203 $subscription->$field = $this->_checkValForAPI($field, $value, $subscription);
204 }
205 if ($subscription->create(DolibarrApiAccess::$user) < 0) {
206 throw new RestException(500, 'Error when creating subscription', array_merge(array($subscription->error), $subscription->errors));
207 }
208 return $subscription->id;
209 }
210
224 public function put($id, $request_data = null)
225 {
226 if (!DolibarrApiAccess::$user->hasRight('adherent', 'creer')) {
227 throw new RestException(403);
228 }
229
230 $subscription = new Subscription($this->db);
231 $result = $subscription->fetch($id);
232 if (!$result) {
233 throw new RestException(404, 'Subscription not found');
234 }
235
236 foreach ($request_data as $field => $value) {
237 if ($field == 'id') {
238 continue;
239 }
240 if ($field === 'caller') {
241 // 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
242 $subscription->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
243 continue;
244 }
245
246 if ($field == 'array_options' && is_array($value)) {
247 foreach ($value as $index => $val) {
248 $subscription->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $subscription);
249 }
250 continue;
251 }
252 $subscription->$field = $this->_checkValForAPI($field, $value, $subscription);
253 }
254
255 if ($subscription->update(DolibarrApiAccess::$user) > 0) {
256 return $this->get($id);
257 } else {
258 throw new RestException(500, 'Error when updating contribution: '.$subscription->errorsToString());
259 }
260 }
261
275 public function delete($id)
276 {
277 // The right to delete a subscription comes with the right to create one.
278 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'creer')) {
279 throw new RestException(403);
280 }
281 $subscription = new Subscription($this->db);
282 $result = $subscription->fetch($id);
283 if (!$result) {
284 throw new RestException(404, 'Subscription not found');
285 }
286
287 $res = $subscription->delete(DolibarrApiAccess::$user);
288 if ($res < 0) {
289 throw new RestException(500, "Can't delete, error occurs");
290 } elseif ($res == 0) {
291 throw new RestException(409, "No subscription whas deleted");
292 }
293
294 return array(
295 'success' => array(
296 'code' => 200,
297 'message' => 'Subscription deleted'
298 )
299 );
300 }
301
310 private function _validate($data)
311 {
312 $subscription = array();
313 foreach (Subscriptions::$FIELDS as $field) {
314 if (!isset($data[$field])) {
315 throw new RestException(400, "$field field missing");
316 }
317 $subscription[$field] = $data[$field];
318 }
319 return $subscription;
320 }
321}
$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.
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:
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.