dolibarr 23.0.3
api_donations.class.php
1<?php
2/* Copyright (C) 2019 Thibault FOUCART <support@ptibogxiv.net>
3 * Copyright (C) 2019 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2025 Frédéric France <frederic.france@free.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
21use Luracast\Restler\RestException;
22
23require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
24
32{
36 public static $FIELDS = array(
37 'amount'
38 );
39
43 public $don;
44
48 public function __construct()
49 {
50 global $db, $conf;
51 $this->db = $db;
52 $this->don = new Don($this->db);
53 }
54
65 public function get($id)
66 {
67 if (!DolibarrApiAccess::$user->hasRight('don', 'lire')) {
68 throw new RestException(403);
69 }
70
71 $result = $this->don->fetch($id);
72 if (!$result) {
73 throw new RestException(404, 'Donation not found');
74 }
75
76 if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
77 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
78 }
79
80 // Add external contacts ids
81 //$this->don->contacts_ids = $this->don->liste_contact(-1,'external',1);
82 //$this->don->fetchObjectLinked();
83 return $this->_cleanObjectDatas($this->don);
84 }
85
105 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
106 {
107 if (!DolibarrApiAccess::$user->hasRight('don', 'lire')) {
108 throw new RestException(403);
109 }
110
111 $obj_ret = array();
112
113 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
114 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
115
116 $sql = "SELECT t.rowid";
117 if ((!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids)) {
118 $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)
119 }
120 $sql .= " FROM ".MAIN_DB_PREFIX."don AS t LEFT JOIN ".MAIN_DB_PREFIX."don_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
121
122 $sql .= ' WHERE t.entity IN ('.getEntity('don').')';
123 if ((!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids)) {
124 $sql .= " AND t.fk_soc = sc.fk_soc";
125 }
126 if ($thirdparty_ids) {
127 $sql .= " AND t.fk_soc = ".((int) $thirdparty_ids)." ";
128 }
129
130 // Add sql filters
131 if ($sqlfilters) {
132 $errormessage = '';
133 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
134 if ($errormessage) {
135 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
136 }
137 }
138
139 //this query will return total orders with the filters given
140 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
141
142 $sql .= $this->db->order($sortfield, $sortorder);
143 if ($limit) {
144 if ($page < 0) {
145 $page = 0;
146 }
147 $offset = $limit * $page;
148
149 $sql .= $this->db->plimit($limit + 1, $offset);
150 }
151
152 dol_syslog("API Rest request");
153 $result = $this->db->query($sql);
154
155 if ($result) {
156 $num = $this->db->num_rows($result);
157 $min = min($num, ($limit <= 0 ? $num : $limit));
158 $i = 0;
159 while ($i < $min) {
160 $obj = $this->db->fetch_object($result);
161 $don_static = new Don($this->db);
162 if ($don_static->fetch($obj->rowid)) {
163 // Add external contacts ids
164 //$don_static->contacts_ids = $don_static->liste_contact(-1, 'external', 1);
165 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($don_static), $properties);
166 }
167 $i++;
168 }
169 } else {
170 throw new RestException(503, 'Error when retrieve donation list : '.$this->db->lasterror());
171 }
172
173 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
174 if ($pagination_data) {
175 $totalsResult = $this->db->query($sqlTotals);
176 $total = $this->db->fetch_object($totalsResult)->total;
177
178 $tmp = $obj_ret;
179 $obj_ret = [];
180
181 $obj_ret['data'] = $tmp;
182 $obj_ret['pagination'] = [
183 'total' => (int) $total,
184 'page' => $page, //count starts from 0
185 'page_count' => ceil((int) $total / $limit),
186 'limit' => $limit
187 ];
188 }
189
190 return $obj_ret;
191 }
192
201 public function post($request_data = null)
202 {
203 if (!DolibarrApiAccess::$user->hasRight('don', 'creer')) {
204 throw new RestException(403, "Insufficiant rights");
205 }
206
207 // Check mandatory fields
208 $result = $this->_validate($request_data);
209
210 foreach ($request_data as $field => $value) {
211 if ($field === 'caller') {
212 // 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
213 $this->don->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
214 continue;
215 }
216
217 $this->don->$field = $this->_checkValForAPI($field, $value, $this->don);
218 }
219 /*if (isset($request_data["lines"])) {
220 $lines = array();
221 foreach ($request_data["lines"] as $line) {
222 array_push($lines, (object) $line);
223 }
224 $this->don->lines = $lines;
225 }*/
226
227 if ($this->don->create(DolibarrApiAccess::$user) < 0) {
228 throw new RestException(500, "Error creating donation", array_merge(array($this->don->error), $this->don->errors));
229 }
230
231 return $this->don->id;
232 }
233
243 public function put($id, $request_data = null)
244 {
245 if (!DolibarrApiAccess::$user->hasRight('don', 'creer')) {
246 throw new RestException(403);
247 }
248
249 $result = $this->don->fetch($id);
250 if (!$result) {
251 throw new RestException(404, 'Donation not found');
252 }
253
254 if (!DolibarrApi::_checkAccessToResource('donation', $this->don->id)) {
255 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
256 }
257 foreach ($request_data as $field => $value) {
258 if ($field == 'id') {
259 continue;
260 }
261 if ($field === 'caller') {
262 // 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
263 $this->don->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
264 continue;
265 }
266
267 if ($field == 'array_options' && is_array($value)) {
268 foreach ($value as $index => $val) {
269 $this->don->array_options[$index] = $this->_checkValForAPI($field, $val, $this->don);
270 }
271 continue;
272 }
273
274 $this->don->$field = $this->_checkValForAPI($field, $value, $this->don);
275 }
276
277 if ($this->don->update(DolibarrApiAccess::$user) > 0) {
278 return $this->get($id);
279 } else {
280 throw new RestException(500, $this->don->error);
281 }
282 }
283
292 public function delete($id)
293 {
294 if (!DolibarrApiAccess::$user->hasRight('don', 'supprimer')) {
295 throw new RestException(403);
296 }
297
298 $result = $this->don->fetch($id);
299 if (!$result) {
300 throw new RestException(404, 'Donation not found');
301 }
302
303 if (!DolibarrApi::_checkAccessToResource('donation', $this->don->id)) {
304 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
305 }
306
307 if (!$this->don->delete(DolibarrApiAccess::$user)) {
308 throw new RestException(500, 'Error when delete donation : '.$this->don->error);
309 }
310
311 return array(
312 'success' => array(
313 'code' => 200,
314 'message' => 'Donation deleted'
315 )
316 );
317 }
318
341 public function validate($id, $idwarehouse = 0, $notrigger = 0)
342 {
343 if (!DolibarrApiAccess::$user->hasRight('don', 'creer')) {
344 throw new RestException(403);
345 }
346
347 $result = $this->don->fetch($id);
348 if (!$result) {
349 throw new RestException(404, 'Donation not found');
350 }
351
352 if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
353 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
354 }
355
356 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
357 $result = $this->don->valid_promesse($id, DolibarrApiAccess::$user->id, $notrigger);
358 if ($result == 0) {
359 throw new RestException(304, 'Error nothing done. May be object is already validated');
360 }
361 if ($result < 0) {
362 throw new RestException(500, 'Error when validating Order: '.$this->don->error);
363 }
364 $result = $this->don->fetch($id);
365 if (!$result) {
366 throw new RestException(404, 'Order not found');
367 }
368
369 // test already done
370 // if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
371 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
372 // }
373
374 $this->don->fetchObjectLinked();
375
376 return $this->_cleanObjectDatas($this->don);
377 }
378
379 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
389 protected function _cleanObjectDatas($object)
390 {
391 // phpcs:enable
392 $object = parent::_cleanObjectDatas($object);
393
394 unset($object->note);
395 unset($object->address);
396 unset($object->barcode_type);
397 unset($object->barcode_type_code);
398 unset($object->barcode_type_label);
399 unset($object->barcode_type_coder);
400
401 return $object;
402 }
403
411 private function _validate($data)
412 {
413 if ($data === null) {
414 $data = array();
415 }
416 $don = array();
417 foreach (Donations::$FIELDS as $field) {
418 if (!isset($data[$field])) {
419 throw new RestException(400, $field." field missing");
420 }
421 $don[$field] = $data[$field];
422 }
423 return $don;
424 }
425}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
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
Class to manage donations.
Definition don.class.php:41
validate($id, $idwarehouse=0, $notrigger=0)
Validate an donation.
post($request_data=null)
Create donation object.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
put($id, $request_data=null)
Update order general fields (won't touch lines of order)
__construct()
Constructor.
_validate($data)
Validate fields before create or update object.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $sqlfilters='', $properties='', $pagination_data=false)
List donations.
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.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.