dolibarr 25.0.0-alpha
api_agendaevents.class.php
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2025 William Mead <william@m34d.com>
6 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22use Luracast\Restler\RestException;
23
24require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
25require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
26
27
37{
41 public static $FIELDS = array(
42 'userownerid',
43 'type_code'
44 );
45
49 public $actioncomm;
50
51
55 public function __construct()
56 {
57 global $db, $conf;
58 $this->db = $db;
59 $this->actioncomm = new ActionComm($this->db);
60 }
61
74 public function get($id)
75 {
76 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'read')) {
77 throw new RestException(403, "Insufficient rights to read an event");
78 }
79 if ($id === 0) {
80 $result = $this->actioncomm->initAsSpecimen();
81 } else {
82 $result = $this->actioncomm->fetch($id);
83 if ($result) {
84 $this->actioncomm->fetch_optionals();
85 $this->actioncomm->fetchObjectLinked();
86 }
87 }
88 if (!$result) {
89 throw new RestException(404, 'Agenda Events not found');
90 }
91
92 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'read') && $this->actioncomm->userownerid != DolibarrApiAccess::$user->id) {
93 throw new RestException(403, 'Insufficient rights to read event of this owner id. Your id is '.DolibarrApiAccess::$user->id);
94 }
95
96 if (!DolibarrApi::_checkAccessToResource('agenda', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
97 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
98 }
99 return $this->_cleanObjectDatas($this->actioncomm);
100 }
101
124 public function index($sortfield = "t.id", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
125 {
126 global $db, $conf;
127
128 $obj_ret = array();
129
130 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'read')) {
131 throw new RestException(403, "Insufficient rights to read events");
132 }
133
134 // case of external user
135 $socid = DolibarrApiAccess::$user->socid ?: 0;
136
137 // If the internal user must only see his customers, force searching by him
138 $search_sale = 0;
139 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
140 $search_sale = DolibarrApiAccess::$user->id;
141 }
142 if (!isModEnabled('societe')) {
143 $search_sale = 0; // If module thirdparty not enabled, sale representative is something that does not exists
144 }
145
146 $sql = "SELECT t.id";
147 $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm AS t";
148 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_extrafields AS ef ON (ef.fk_object = t.id)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
149 $sql .= ' WHERE t.entity IN ('.getEntity('agenda').')';
150 if ($user_ids) {
151 $sql .= " AND t.fk_user_action IN (".$this->db->sanitize($user_ids).")";
152 }
153 if ($socid > 0) {
154 $sql .= " AND t.fk_soc = ".((int) $socid);
155 }
156 // Search on sale representative
157 if ($search_sale && $search_sale != '-1') {
158 if ($search_sale == -2) {
159 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', 0, 1);
160 } elseif ($search_sale > 0) {
161 $sql .= " AND (t.fk_soc IS NULL OR ".getSalesRepresentativeSqlFilter('t.fk_soc', (int) $search_sale).")";
162 }
163 }
164 // Add sql filters
165 if ($sqlfilters) {
166 $errormessage = '';
167 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
168 if ($errormessage) {
169 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
170 }
171 }
172
173 //this query will return total orders with the filters given
174 $sqlTotals = str_replace('SELECT t.id', 'SELECT count(t.id) as total', $sql);
175
176 $sql .= $this->db->order($sortfield, $sortorder);
177 if ($limit) {
178 if ($page < 0) {
179 $page = 0;
180 }
181 $offset = $limit * $page;
182
183 $sql .= $this->db->plimit($limit + 1, $offset);
184 }
185
186 $result = $this->db->query($sql);
187
188 if ($result) {
189 $i = 0;
190 $num = $this->db->num_rows($result);
191 $min = min($num, ($limit <= 0 ? $num : $limit));
192 while ($i < $min) {
193 $obj = $this->db->fetch_object($result);
194 $actioncomm_static = new ActionComm($this->db);
195 if ($actioncomm_static->fetch($obj->id)) {
196 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($actioncomm_static), $properties);
197 }
198 $i++;
199 }
200 } else {
201 throw new RestException(503, 'Error when retrieve Agenda Event list : '.$this->db->lasterror());
202 }
203
204 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
205 if ($pagination_data) {
206 $totalsResult = $this->db->query($sqlTotals);
207 $total = $this->db->fetch_object($totalsResult)->total;
208
209 $tmp = $obj_ret;
210 $obj_ret = [];
211
212 $obj_ret['data'] = $tmp;
213 $obj_ret['pagination'] = [
214 'total' => (int) $total,
215 'page' => $page, //count starts from 0
216 'page_count' => (int) ceil((int) $total / $limit),
217 'limit' => $limit
218 ];
219 }
220
221 return $obj_ret;
222 }
223
236 public function post($request_data = null)
237 {
238 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'create')) {
239 throw new RestException(403, "Insufficient rights to create your Agenda Event");
240 }
241 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'create') && DolibarrApiAccess::$user->id != $request_data['userownerid']) {
242 throw new RestException(403, "Insufficient rights to create an Agenda Event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
243 }
244
245 // Check mandatory fields
246 $result = $this->_validate($request_data);
247
248 foreach ($request_data as $field => $value) {
249 if ($field === 'caller') {
250 // 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
251 $this->actioncomm->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
252 continue;
253 }
254
255 $this->actioncomm->$field = $this->_checkValForAPI($field, $value, $this->actioncomm);
256 }
257 /*if (isset($request_data["lines"])) {
258 $lines = array();
259 foreach ($request_data["lines"] as $line) {
260 array_push($lines, (object) $line);
261 }
262 $this->expensereport->lines = $lines;
263 }*/
264
265 if ($this->actioncomm->create(DolibarrApiAccess::$user) < 0) {
266 throw new RestException(500, "Error creating event", array_merge(array($this->actioncomm->error), $this->actioncomm->errors));
267 }
268
269 return $this->actioncomm->id;
270 }
271
272
286 public function put($id, $request_data = null)
287 {
288 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'create')) {
289 throw new RestException(403, "Insufficient rights to create your Agenda Event");
290 }
291 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'create') && DolibarrApiAccess::$user->id != $request_data['userownerid']) {
292 throw new RestException(403, "Insufficient rights to create an Agenda Event for owner id ".$request_data['userownerid'].' Your id is '.DolibarrApiAccess::$user->id);
293 }
294
295 $result = $this->actioncomm->fetch($id);
296 if ($result) {
297 $this->actioncomm->fetch_optionals();
298 $this->actioncomm->fetch_userassigned();
299 $this->actioncomm->oldcopy = clone $this->actioncomm; // @phan-suppress-current-line PhanTypeMismatchProperty
300 }
301 if (!$result) {
302 throw new RestException(404, 'actioncomm not found');
303 }
304
305 if (!DolibarrApi::_checkAccessToResource('actioncomm', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
306 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
307 }
308 foreach ($request_data as $field => $value) {
309 if ($field == 'id') {
310 continue;
311 }
312 if ($field === 'caller') {
313 // 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
314 $this->actioncomm->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
315 continue;
316 }
317
318 if ($field == 'array_options' && is_array($value)) {
319 foreach ($value as $index => $val) {
320 $this->actioncomm->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->actioncomm);
321 }
322 continue;
323 }
324 $this->actioncomm->$field = $this->_checkValForAPI($field, $value, $this->actioncomm);
325 }
326
327 if ($this->actioncomm->update(DolibarrApiAccess::$user, 1) > 0) {
328 return $this->get($id);
329 }
330
331 return false;
332 }
333
347 public function delete($id)
348 {
349 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'delete')) {
350 throw new RestException(403, "Insufficient rights to delete your Agenda Event");
351 }
352
353 $result = $this->actioncomm->fetch($id);
354 if ($result) {
355 $this->actioncomm->fetch_optionals();
356 $this->actioncomm->fetch_userassigned();
357 $this->actioncomm->oldcopy = clone $this->actioncomm; // @phan-suppress-current-line PhanTypeMismatchProperty
358 }
359
360 if (!DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'delete') && DolibarrApiAccess::$user->id != $this->actioncomm->userownerid) {
361 throw new RestException(403, "Insufficient rights to delete an Agenda Event of owner id ".$this->actioncomm->userownerid.' Your id is '.DolibarrApiAccess::$user->id);
362 }
363
364 if (!$result) {
365 throw new RestException(404, 'Agenda Event not found');
366 }
367
368 if (!DolibarrApi::_checkAccessToResource('actioncomm', $this->actioncomm->id, 'actioncomm', '', 'fk_soc', 'id')) {
369 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
370 }
371
372 if (!$this->actioncomm->delete(DolibarrApiAccess::$user)) {
373 throw new RestException(500, 'Error when delete Agenda Event : '.$this->actioncomm->error);
374 }
375
376 return array(
377 'success' => array(
378 'code' => 200,
379 'message' => 'Agenda Event deleted'
380 )
381 );
382 }
383
391 private function _validate($data)
392 {
393 if ($data === null) {
394 $data = array();
395 }
396 $event = array();
397 foreach (AgendaEvents::$FIELDS as $field) {
398 if (!isset($data[$field])) {
399 throw new RestException(400, "$field field missing");
400 }
401 $event[$field] = $data[$field];
402 }
403 return $event;
404 }
405
406 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
416 protected function _cleanObjectDatas($object)
417 {
418 // phpcs:enable
419 $object = parent::_cleanObjectDatas($object);
420
421 unset($object->note); // already in note_private or note_public
422 unset($object->usermod);
423 unset($object->libelle);
424 unset($object->context);
425 unset($object->canvas);
426 unset($object->contact);
427 unset($object->contact_id);
428 unset($object->thirdparty);
429 unset($object->user);
430 unset($object->origin);
431 unset($object->origin_id);
432 unset($object->ref_ext);
433 unset($object->statut);
434 unset($object->state_code);
435 unset($object->state_id);
436 unset($object->state);
437 unset($object->region);
438 unset($object->region_code);
439 unset($object->country);
440 unset($object->country_id);
441 unset($object->country_code);
442 unset($object->barcode_type);
443 unset($object->barcode_type_code);
444 unset($object->barcode_type_label);
445 unset($object->barcode_type_coder);
446 unset($object->mode_reglement_id);
447 unset($object->cond_reglement_id);
448 unset($object->cond_reglement);
449 unset($object->fk_delivery_address);
450 unset($object->shipping_method_id);
451 unset($object->fk_account);
452 unset($object->total_ht);
453 unset($object->total_tva);
454 unset($object->total_localtax1);
455 unset($object->total_localtax2);
456 unset($object->total_ttc);
457 unset($object->fk_incoterms);
458 unset($object->label_incoterms);
459 unset($object->location_incoterms);
460 unset($object->name);
461 unset($object->lastname);
462 unset($object->firstname);
463 unset($object->civility_id);
464 unset($object->contact);
465 unset($object->societe);
466 unset($object->demand_reason_id);
467 unset($object->transport_mode_id);
468 unset($object->region_id);
469 unset($object->actions);
470 unset($object->lines);
471
472 return $object;
473 }
474}
$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 to manage agenda events (actions)
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
_validate($data)
Validate fields before create or update object.
__construct()
Constructor.
put($id, $request_data=null)
Update an agenda event.
index($sortfield="t.id", $sortorder='ASC', $limit=100, $page=0, $user_ids='', $sqlfilters='', $properties='', $pagination_data=false)
List agenda events.
post($request_data=null)
Create an agenda event.
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.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.
isModEnabled($module)
Is Dolibarr module enabled.