dolibarr 25.0.0-alpha
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
99 public function getPayments($id)
100 {
101 if (!DolibarrApiAccess::$user->hasRight('don', 'lire')) {
102 throw new RestException(403);
103 }
104 if (empty($id)) {
105 throw new RestException(400, 'Donation ID is mandatory');
106 }
107
108 $result = $this->don->fetch($id);
109 if ($result < 0) {
110 throw new RestException(503, 'Error when retrieving donation: '.$this->don->error);
111 }
112 if (empty($this->don->id)) {
113 throw new RestException(404, 'Donation not found');
114 }
115
116 if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
117 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
118 }
119
120 $sql = "SELECT pd.rowid, pd.datep, pd.amount, pd.fk_bank, pd.num_payment";
121 $sql .= " FROM ".MAIN_DB_PREFIX."payment_donation AS pd";
122 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."don AS d ON d.rowid = pd.fk_donation";
123 $sql .= " WHERE pd.fk_donation = ".((int) $id);
124 $sql .= " AND d.entity IN (".getEntity('donation').")";
125 $sql .= " ORDER BY pd.datep ASC, pd.rowid ASC";
126
127 $resql = $this->db->query($sql);
128 if (!$resql) {
129 throw new RestException(503, 'Error when retrieving donation payments: '.$this->db->lasterror());
130 }
131
132 $payments = array();
133 while ($obj = $this->db->fetch_object($resql)) {
134 $payments[] = array(
135 'rowid' => (int) $obj->rowid,
136 'datep' => $this->db->jdate($obj->datep),
137 'amount' => (float) $obj->amount,
138 'fk_bank' => (int) $obj->fk_bank,
139 'num_payment' => $obj->num_payment
140 );
141 }
142 $this->db->free($resql);
143
144 return $payments;
145 }
146
166 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
167 {
168 if (!DolibarrApiAccess::$user->hasRight('don', 'lire')) {
169 throw new RestException(403);
170 }
171
172 $obj_ret = array();
173
174 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
175 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
176
177 $sql = "SELECT t.rowid";
178 if ((!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids)) {
179 $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)
180 }
181 $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
182
183 $sql .= ' WHERE t.entity IN ('.getEntity('don').')';
184 if ((!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids)) {
185 $sql .= " AND t.fk_soc = sc.fk_soc";
186 }
187 if ($thirdparty_ids) {
188 $sql .= " AND t.fk_soc = ".((int) $thirdparty_ids)." ";
189 }
190
191 // Add sql filters
192 if ($sqlfilters) {
193 $errormessage = '';
194 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
195 if ($errormessage) {
196 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
197 }
198 }
199
200 //this query will return total orders with the filters given
201 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
202
203 $sql .= $this->db->order($sortfield, $sortorder);
204 if ($limit) {
205 if ($page < 0) {
206 $page = 0;
207 }
208 $offset = $limit * $page;
209
210 $sql .= $this->db->plimit($limit + 1, $offset);
211 }
212
213 dol_syslog("API Rest request");
214 $result = $this->db->query($sql);
215
216 if ($result) {
217 $num = $this->db->num_rows($result);
218 $min = min($num, ($limit <= 0 ? $num : $limit));
219 $i = 0;
220 while ($i < $min) {
221 $obj = $this->db->fetch_object($result);
222 $don_static = new Don($this->db);
223 if ($don_static->fetch($obj->rowid)) {
224 // Add external contacts ids
225 //$don_static->contacts_ids = $don_static->liste_contact(-1, 'external', 1);
226 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($don_static), $properties);
227 }
228 $i++;
229 }
230 } else {
231 throw new RestException(503, 'Error when retrieve donation list : '.$this->db->lasterror());
232 }
233
234 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
235 if ($pagination_data) {
236 $totalsResult = $this->db->query($sqlTotals);
237 $total = $this->db->fetch_object($totalsResult)->total;
238
239 $tmp = $obj_ret;
240 $obj_ret = [];
241
242 $obj_ret['data'] = $tmp;
243 $obj_ret['pagination'] = [
244 'total' => (int) $total,
245 'page' => $page, //count starts from 0
246 'page_count' => ceil((int) $total / $limit),
247 'limit' => $limit
248 ];
249 }
250
251 return $obj_ret;
252 }
253
262 public function post($request_data = null)
263 {
264 if (!DolibarrApiAccess::$user->hasRight('don', 'creer')) {
265 throw new RestException(403, "Insufficiant rights");
266 }
267
268 // Check mandatory fields
269 $result = $this->_validate($request_data);
270
271 foreach ($request_data as $field => $value) {
272 if ($field === 'caller') {
273 // 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
274 $this->don->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
275 continue;
276 }
277
278 $this->don->$field = $this->_checkValForAPI($field, $value, $this->don);
279 }
280 /*if (isset($request_data["lines"])) {
281 $lines = array();
282 foreach ($request_data["lines"] as $line) {
283 array_push($lines, (object) $line);
284 }
285 $this->don->lines = $lines;
286 }*/
287
288 if ($this->don->create(DolibarrApiAccess::$user) < 0) {
289 throw new RestException(500, "Error creating donation", array_merge(array($this->don->error), $this->don->errors));
290 }
291
292 return $this->don->id;
293 }
294
304 public function put($id, $request_data = null)
305 {
306 if (!DolibarrApiAccess::$user->hasRight('don', 'creer')) {
307 throw new RestException(403);
308 }
309
310 $result = $this->don->fetch($id);
311 if (!$result) {
312 throw new RestException(404, 'Donation not found');
313 }
314
315 if (!DolibarrApi::_checkAccessToResource('donation', $this->don->id)) {
316 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
317 }
318 foreach ($request_data as $field => $value) {
319 if ($field == 'id') {
320 continue;
321 }
322 if ($field === 'caller') {
323 // 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
324 $this->don->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
325 continue;
326 }
327
328 if ($field == 'array_options' && is_array($value)) {
329 foreach ($value as $index => $val) {
330 $this->don->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->don);
331 }
332 continue;
333 }
334
335 $this->don->$field = $this->_checkValForAPI($field, $value, $this->don);
336 }
337
338 if ($this->don->update(DolibarrApiAccess::$user) > 0) {
339 return $this->get($id);
340 } else {
341 throw new RestException(500, $this->don->errorsToString());
342 }
343 }
344
353 public function delete($id)
354 {
355 if (!DolibarrApiAccess::$user->hasRight('don', 'supprimer')) {
356 throw new RestException(403);
357 }
358
359 $result = $this->don->fetch($id);
360 if (!$result) {
361 throw new RestException(404, 'Donation not found');
362 }
363
364 if (!DolibarrApi::_checkAccessToResource('donation', $this->don->id)) {
365 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
366 }
367
368 if (!$this->don->delete(DolibarrApiAccess::$user)) {
369 throw new RestException(500, 'Error when delete donation : '.$this->don->errorsToString());
370 }
371
372 return array(
373 'success' => array(
374 'code' => 200,
375 'message' => 'Donation deleted'
376 )
377 );
378 }
379
402 public function validate($id, $idwarehouse = 0, $notrigger = 0)
403 {
404 if (!DolibarrApiAccess::$user->hasRight('don', 'creer')) {
405 throw new RestException(403);
406 }
407
408 $result = $this->don->fetch($id);
409 if (!$result) {
410 throw new RestException(404, 'Donation not found');
411 }
412
413 if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
414 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
415 }
416
417 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
418 $result = $this->don->valid_promesse($id, DolibarrApiAccess::$user->id, $notrigger);
419 if ($result == 0) {
420 throw new RestException(304, 'Error nothing done. May be object is already validated');
421 }
422 if ($result < 0) {
423 throw new RestException(500, 'Error when validating Order: '.$this->don->errorsToString());
424 }
425 $result = $this->don->fetch($id);
426 if (!$result) {
427 throw new RestException(404, 'Order not found');
428 }
429
430 // test already done
431 // if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
432 // throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
433 // }
434
435 $this->don->fetchObjectLinked();
436
437 return $this->_cleanObjectDatas($this->don);
438 }
439
440 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
450 protected function _cleanObjectDatas($object)
451 {
452 // phpcs:enable
453 $object = parent::_cleanObjectDatas($object);
454
455 unset($object->note);
456 unset($object->address);
457 unset($object->barcode_type);
458 unset($object->barcode_type_code);
459 unset($object->barcode_type_label);
460 unset($object->barcode_type_coder);
461
462 return $object;
463 }
464
472 private function _validate($data)
473 {
474 if ($data === null) {
475 $data = array();
476 }
477 $don = array();
478 foreach (Donations::$FIELDS as $field) {
479 if (!isset($data[$field])) {
480 throw new RestException(400, $field." field missing");
481 }
482 $don[$field] = $data[$field];
483 }
484 return $don;
485 }
486}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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.
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 donations.
Definition don.class.php:42
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)
getPayments($id)
Get list of payments of a given donation.
__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, $forbiddenfields=array())
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.