dolibarr 22.0.5
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 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20use Luracast\Restler\RestException;
21
22require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
23
31{
35 public static $FIELDS = array(
36 'amount'
37 );
38
42 public $don;
43
47 public function __construct()
48 {
49 global $db, $conf;
50 $this->db = $db;
51 $this->don = new Don($this->db);
52 }
53
64 public function get($id)
65 {
66 if (!DolibarrApiAccess::$user->hasRight('don', 'lire')) {
67 throw new RestException(403);
68 }
69
70 $result = $this->don->fetch($id);
71 if (!$result) {
72 throw new RestException(404, 'Donation not found');
73 }
74
75 if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
76 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
77 }
78
79 // Add external contacts ids
80 //$this->don->contacts_ids = $this->don->liste_contact(-1,'external',1);
81 //$this->don->fetchObjectLinked();
82 return $this->_cleanObjectDatas($this->don);
83 }
84
104 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
105 {
106 if (!DolibarrApiAccess::$user->hasRight('don', 'lire')) {
107 throw new RestException(403);
108 }
109
110 $obj_ret = array();
111
112 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
113 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
114
115 $sql = "SELECT t.rowid";
116 if ((!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids)) {
117 $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)
118 }
119 $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
120
121 $sql .= ' WHERE t.entity IN ('.getEntity('don').')';
122 if ((!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids)) {
123 $sql .= " AND t.fk_soc = sc.fk_soc";
124 }
125 if ($thirdparty_ids) {
126 $sql .= " AND t.fk_soc = ".((int) $thirdparty_ids)." ";
127 }
128
129 // Add sql filters
130 if ($sqlfilters) {
131 $errormessage = '';
132 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
133 if ($errormessage) {
134 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
135 }
136 }
137
138 //this query will return total orders with the filters given
139 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
140
141 $sql .= $this->db->order($sortfield, $sortorder);
142 if ($limit) {
143 if ($page < 0) {
144 $page = 0;
145 }
146 $offset = $limit * $page;
147
148 $sql .= $this->db->plimit($limit + 1, $offset);
149 }
150
151 dol_syslog("API Rest request");
152 $result = $this->db->query($sql);
153
154 if ($result) {
155 $num = $this->db->num_rows($result);
156 $min = min($num, ($limit <= 0 ? $num : $limit));
157 $i = 0;
158 while ($i < $min) {
159 $obj = $this->db->fetch_object($result);
160 $don_static = new Don($this->db);
161 if ($don_static->fetch($obj->rowid)) {
162 // Add external contacts ids
163 //$don_static->contacts_ids = $don_static->liste_contact(-1, 'external', 1);
164 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($don_static), $properties);
165 }
166 $i++;
167 }
168 } else {
169 throw new RestException(503, 'Error when retrieve donation list : '.$this->db->lasterror());
170 }
171
172 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
173 if ($pagination_data) {
174 $totalsResult = $this->db->query($sqlTotals);
175 $total = $this->db->fetch_object($totalsResult)->total;
176
177 $tmp = $obj_ret;
178 $obj_ret = [];
179
180 $obj_ret['data'] = $tmp;
181 $obj_ret['pagination'] = [
182 'total' => (int) $total,
183 'page' => $page, //count starts from 0
184 'page_count' => ceil((int) $total / $limit),
185 'limit' => $limit
186 ];
187 }
188
189 return $obj_ret;
190 }
191
200 public function post($request_data = null)
201 {
202 if (!DolibarrApiAccess::$user->hasRight('don', 'creer')) {
203 throw new RestException(403, "Insuffisant rights");
204 }
205
206 // Check mandatory fields
207 $result = $this->_validate($request_data);
208
209 foreach ($request_data as $field => $value) {
210 if ($field === 'caller') {
211 // 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
212 $this->don->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
213 continue;
214 }
215
216 $this->don->$field = $this->_checkValForAPI($field, $value, $this->don);
217 }
218 /*if (isset($request_data["lines"])) {
219 $lines = array();
220 foreach ($request_data["lines"] as $line) {
221 array_push($lines, (object) $line);
222 }
223 $this->don->lines = $lines;
224 }*/
225
226 if ($this->don->create(DolibarrApiAccess::$user) < 0) {
227 throw new RestException(500, "Error creating donation", array_merge(array($this->don->error), $this->don->errors));
228 }
229
230 return $this->don->id;
231 }
232
242 public function put($id, $request_data = null)
243 {
244 if (!DolibarrApiAccess::$user->hasRight('don', 'creer')) {
245 throw new RestException(403);
246 }
247
248 $result = $this->don->fetch($id);
249 if (!$result) {
250 throw new RestException(404, 'Donation not found');
251 }
252
253 if (!DolibarrApi::_checkAccessToResource('donation', $this->don->id)) {
254 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
255 }
256 foreach ($request_data as $field => $value) {
257 if ($field == 'id') {
258 continue;
259 }
260 if ($field === 'caller') {
261 // 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
262 $this->don->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
263 continue;
264 }
265
266 if ($field == 'array_options' && is_array($value)) {
267 foreach ($value as $index => $val) {
268 $this->don->array_options[$index] = $this->_checkValForAPI($field, $val, $this->don);
269 }
270 continue;
271 }
272
273 $this->don->$field = $this->_checkValForAPI($field, $value, $this->don);
274 }
275
276 if ($this->don->update(DolibarrApiAccess::$user) > 0) {
277 return $this->get($id);
278 } else {
279 throw new RestException(500, $this->don->error);
280 }
281 }
282
291 public function delete($id)
292 {
293 if (!DolibarrApiAccess::$user->hasRight('don', 'supprimer')) {
294 throw new RestException(403);
295 }
296
297 $result = $this->don->fetch($id);
298 if (!$result) {
299 throw new RestException(404, 'Donation not found');
300 }
301
302 if (!DolibarrApi::_checkAccessToResource('donation', $this->don->id)) {
303 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
304 }
305
306 if (!$this->don->delete(DolibarrApiAccess::$user)) {
307 throw new RestException(500, 'Error when delete donation : '.$this->don->error);
308 }
309
310 return array(
311 'success' => array(
312 'code' => 200,
313 'message' => 'Donation deleted'
314 )
315 );
316 }
317
340 public function validate($id, $idwarehouse = 0, $notrigger = 0)
341 {
342 if (!DolibarrApiAccess::$user->hasRight('don', 'creer')) {
343 throw new RestException(403);
344 }
345
346 $result = $this->don->fetch($id);
347 if (!$result) {
348 throw new RestException(404, 'Donation not found');
349 }
350
351 if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
352 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
353 }
354
355 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
356 $result = $this->don->valid_promesse($id, DolibarrApiAccess::$user->id, $notrigger);
357 if ($result == 0) {
358 throw new RestException(304, 'Error nothing done. May be object is already validated');
359 }
360 if ($result < 0) {
361 throw new RestException(500, 'Error when validating Order: '.$this->don->error);
362 }
363 $result = $this->don->fetch($id);
364 if (!$result) {
365 throw new RestException(404, 'Order not found');
366 }
367
368 if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
369 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
370 }
371
372 $this->don->fetchObjectLinked();
373
374 return $this->_cleanObjectDatas($this->don);
375 }
376
377 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
384 protected function _cleanObjectDatas($object)
385 {
386 // phpcs:enable
387 $object = parent::_cleanObjectDatas($object);
388
389 unset($object->note);
390 unset($object->address);
391 unset($object->barcode_type);
392 unset($object->barcode_type_code);
393 unset($object->barcode_type_label);
394 unset($object->barcode_type_coder);
395
396 return $object;
397 }
398
406 private function _validate($data)
407 {
408 if ($data === null) {
409 $data = array();
410 }
411 $don = array();
412 foreach (Donations::$FIELDS as $field) {
413 if (!isset($data[$field])) {
414 throw new RestException(400, $field." field missing");
415 }
416 $don[$field] = $data[$field];
417 }
418 return $don;
419 }
420}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
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.
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79