dolibarr 21.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 *
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.'/don/class/don.class.php';
22
30{
34 public static $FIELDS = array(
35 'amount'
36 );
37
41 public $don;
42
46 public function __construct()
47 {
48 global $db, $conf;
49 $this->db = $db;
50 $this->don = new Don($this->db);
51 }
52
63 public function get($id)
64 {
65 if (!DolibarrApiAccess::$user->hasRight('don', 'lire')) {
66 throw new RestException(403);
67 }
68
69 $result = $this->don->fetch($id);
70 if (!$result) {
71 throw new RestException(404, 'Donation not found');
72 }
73
74 if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
75 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
76 }
77
78 // Add external contacts ids
79 //$this->don->contacts_ids = $this->don->liste_contact(-1,'external',1);
80 //$this->don->fetchObjectLinked();
81 return $this->_cleanObjectDatas($this->don);
82 }
83
101 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
102 {
103 if (!DolibarrApiAccess::$user->hasRight('don', 'lire')) {
104 throw new RestException(403);
105 }
106
107 $obj_ret = array();
108
109 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
110 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
111
112 $sql = "SELECT t.rowid";
113 if ((!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids)) {
114 $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)
115 }
116 $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
117
118 $sql .= ' WHERE t.entity IN ('.getEntity('don').')';
119 if ((!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids)) {
120 $sql .= " AND t.fk_soc = sc.fk_soc";
121 }
122 if ($thirdparty_ids) {
123 $sql .= " AND t.fk_soc = ".((int) $thirdparty_ids)." ";
124 }
125
126 // Add sql filters
127 if ($sqlfilters) {
128 $errormessage = '';
129 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
130 if ($errormessage) {
131 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
132 }
133 }
134
135 //this query will return total orders with the filters given
136 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
137
138 $sql .= $this->db->order($sortfield, $sortorder);
139 if ($limit) {
140 if ($page < 0) {
141 $page = 0;
142 }
143 $offset = $limit * $page;
144
145 $sql .= $this->db->plimit($limit + 1, $offset);
146 }
147
148 dol_syslog("API Rest request");
149 $result = $this->db->query($sql);
150
151 if ($result) {
152 $num = $this->db->num_rows($result);
153 $min = min($num, ($limit <= 0 ? $num : $limit));
154 $i = 0;
155 while ($i < $min) {
156 $obj = $this->db->fetch_object($result);
157 $don_static = new Don($this->db);
158 if ($don_static->fetch($obj->rowid)) {
159 // Add external contacts ids
160 //$don_static->contacts_ids = $don_static->liste_contact(-1, 'external', 1);
161 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($don_static), $properties);
162 }
163 $i++;
164 }
165 } else {
166 throw new RestException(503, 'Error when retrieve donation list : '.$this->db->lasterror());
167 }
168
169 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
170 if ($pagination_data) {
171 $totalsResult = $this->db->query($sqlTotals);
172 $total = $this->db->fetch_object($totalsResult)->total;
173
174 $tmp = $obj_ret;
175 $obj_ret = [];
176
177 $obj_ret['data'] = $tmp;
178 $obj_ret['pagination'] = [
179 'total' => (int) $total,
180 'page' => $page, //count starts from 0
181 'page_count' => ceil((int) $total / $limit),
182 'limit' => $limit
183 ];
184 }
185
186 return $obj_ret;
187 }
188
195 public function post($request_data = null)
196 {
197 if (!DolibarrApiAccess::$user->hasRight('don', 'creer')) {
198 throw new RestException(403, "Insuffisant rights");
199 }
200
201 // Check mandatory fields
202 $result = $this->_validate($request_data);
203
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 $this->don->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
208 continue;
209 }
210
211 $this->don->$field = $this->_checkValForAPI($field, $value, $this->don);
212 }
213 /*if (isset($request_data["lines"])) {
214 $lines = array();
215 foreach ($request_data["lines"] as $line) {
216 array_push($lines, (object) $line);
217 }
218 $this->don->lines = $lines;
219 }*/
220
221 if ($this->don->create(DolibarrApiAccess::$user) < 0) {
222 throw new RestException(500, "Error creating donation", array_merge(array($this->don->error), $this->don->errors));
223 }
224
225 return $this->don->id;
226 }
227
235 public function put($id, $request_data = null)
236 {
237 if (!DolibarrApiAccess::$user->hasRight('don', 'creer')) {
238 throw new RestException(403);
239 }
240
241 $result = $this->don->fetch($id);
242 if (!$result) {
243 throw new RestException(404, 'Donation not found');
244 }
245
246 if (!DolibarrApi::_checkAccessToResource('donation', $this->don->id)) {
247 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
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 $this->don->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
256 continue;
257 }
258
259 $this->don->$field = $this->_checkValForAPI($field, $value, $this->don);
260 }
261
262 if ($this->don->update(DolibarrApiAccess::$user) > 0) {
263 return $this->get($id);
264 } else {
265 throw new RestException(500, $this->don->error);
266 }
267 }
268
275 public function delete($id)
276 {
277 if (!DolibarrApiAccess::$user->hasRight('don', 'supprimer')) {
278 throw new RestException(403);
279 }
280
281 $result = $this->don->fetch($id);
282 if (!$result) {
283 throw new RestException(404, 'Donation not found');
284 }
285
286 if (!DolibarrApi::_checkAccessToResource('donation', $this->don->id)) {
287 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
288 }
289
290 if (!$this->don->delete(DolibarrApiAccess::$user)) {
291 throw new RestException(500, 'Error when delete donation : '.$this->don->error);
292 }
293
294 return array(
295 'success' => array(
296 'code' => 200,
297 'message' => 'Donation deleted'
298 )
299 );
300 }
301
324 public function validate($id, $idwarehouse = 0, $notrigger = 0)
325 {
326 if (!DolibarrApiAccess::$user->hasRight('don', 'creer')) {
327 throw new RestException(403);
328 }
329
330 $result = $this->don->fetch($id);
331 if (!$result) {
332 throw new RestException(404, 'Donation not found');
333 }
334
335 if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) {
336 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
337 }
338
339 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
340 $result = $this->don->valid_promesse($id, DolibarrApiAccess::$user->id, $notrigger);
341 if ($result == 0) {
342 throw new RestException(304, 'Error nothing done. May be object is already validated');
343 }
344 if ($result < 0) {
345 throw new RestException(500, 'Error when validating Order: '.$this->don->error);
346 }
347 $result = $this->don->fetch($id);
348 if (!$result) {
349 throw new RestException(404, 'Order 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 $this->don->fetchObjectLinked();
357
358 return $this->_cleanObjectDatas($this->don);
359 }
360
361 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
368 protected function _cleanObjectDatas($object)
369 {
370 // phpcs:enable
371 $object = parent::_cleanObjectDatas($object);
372
373 unset($object->note);
374 unset($object->address);
375 unset($object->barcode_type);
376 unset($object->barcode_type_code);
377 unset($object->barcode_type_label);
378 unset($object->barcode_type_coder);
379
380 return $object;
381 }
382
390 private function _validate($data)
391 {
392 $don = array();
393 foreach (Donations::$FIELDS as $field) {
394 if (!isset($data[$field])) {
395 throw new RestException(400, $field." field missing");
396 }
397 $don[$field] = $data[$field];
398 }
399 return $don;
400 }
401}
$id
Definition account.php:39
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
Class for API REST v1.
Definition api.class.php:30
_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:82
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.