dolibarr 21.0.0-alpha
api_tickets.class.php
1<?php
2/* Copyright (C) 2016 Jean-François Ferry <hello@librethic.io>
3 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
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
19 use Luracast\Restler\RestException;
20
21require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
22require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
23
24
31class Tickets extends DolibarrApi
32{
36 public static $FIELDS = array(
37 'subject',
38 'message'
39 );
40
44 public static $FIELDS_MESSAGES = array(
45 'track_id',
46 'message'
47 );
48
52 public $ticket;
53
57 public function __construct()
58 {
59 global $db;
60 $this->db = $db;
61 $this->ticket = new Ticket($this->db);
62 }
63
76 public function get($id)
77 {
78 return $this->getCommon($id, '', '');
79 }
80
95 public function getByTrackId($track_id)
96 {
97 return $this->getCommon(0, $track_id, '');
98 }
99
114 public function getByRef($ref)
115 {
116 return $this->getCommon(0, '', $ref);
117 }
118
128 private function getCommon($id = 0, $track_id = '', $ref = '')
129 {
130 if (!DolibarrApiAccess::$user->hasRight('ticket', 'read')) {
131 throw new RestException(403);
132 }
133
134 // Check parameters
135 if (($id < 0) && !$track_id && !$ref) {
136 throw new RestException(400, 'Wrong parameters');
137 }
138 if (empty($id) && empty($ref) && empty($track_id)) {
139 $result = $this->ticket->initAsSpecimen();
140 } else {
141 $result = $this->ticket->fetch($id, $ref, $track_id);
142 }
143 if (!$result) {
144 throw new RestException(404, 'Ticket not found');
145 }
146
147 // String for user assigned
148 if ($this->ticket->fk_user_assign > 0) {
149 $userStatic = new User($this->db);
150 $userStatic->fetch($this->ticket->fk_user_assign);
151 $this->ticket->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname;
152 }
153
154 // Messages of ticket
155 $messages = array();
156 $this->ticket->loadCacheMsgsTicket();
157 if (is_array($this->ticket->cache_msgs_ticket) && count($this->ticket->cache_msgs_ticket) > 0) {
158 $num = count($this->ticket->cache_msgs_ticket);
159 $i = 0;
160 while ($i < $num) {
161 if ($this->ticket->cache_msgs_ticket[$i]['fk_user_author'] > 0) {
162 $user_action = new User($this->db);
163 $user_action->fetch($this->ticket->cache_msgs_ticket[$i]['fk_user_author']);
164 }
165
166 // Now define messages
167 $messages[] = array(
168 'id' => $this->ticket->cache_msgs_ticket[$i]['id'],
169 'fk_user_action' => $this->ticket->cache_msgs_ticket[$i]['fk_user_author'],
170 'fk_user_action_socid' => $user_action->socid,
171 'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname),
172 'message' => $this->ticket->cache_msgs_ticket[$i]['message'],
173 'datec' => $this->ticket->cache_msgs_ticket[$i]['datec'],
174 'private' => $this->ticket->cache_msgs_ticket[$i]['private']
175 );
176 $i++;
177 }
178 $this->ticket->messages = $messages;
179 }
180
181 if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
182 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
183 }
184 return $this->_cleanObjectDatas($this->ticket);
185 }
186
204 public function index($socid = 0, $sortfield = "t.rowid", $sortorder = "ASC", $limit = 100, $page = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
205 {
206 if (!DolibarrApiAccess::$user->hasRight('ticket', 'read')) {
207 throw new RestException(403);
208 }
209
210 $obj_ret = array();
211
212 $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $socid;
213
214 $search_sale = null;
215 // If the internal user must only see his customers, force searching by him
216 $search_sale = 0;
217 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
218 $search_sale = DolibarrApiAccess::$user->id;
219 }
220
221 $sql = "SELECT t.rowid";
222 $sql .= " FROM ".MAIN_DB_PREFIX."ticket AS t";
223 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."ticket_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
224 $sql .= ' WHERE t.entity IN ('.getEntity('ticket', 1).')';
225 if ($socid > 0) {
226 $sql .= " AND t.fk_soc = ".((int) $socid);
227 }
228 // Search on sale representative
229 if ($search_sale && $search_sale != '-1') {
230 if ($search_sale == -2) {
231 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
232 } elseif ($search_sale > 0) {
233 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
234 }
235 }
236 // Add sql filters
237 if ($sqlfilters) {
238 $errormessage = '';
239 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
240 if ($errormessage) {
241 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
242 }
243 }
244
245 //this query will return total orders with the filters given
246 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
247
248 $sql .= $this->db->order($sortfield, $sortorder);
249
250 if ($limit) {
251 if ($page < 0) {
252 $page = 0;
253 }
254 $offset = $limit * $page;
255
256 $sql .= $this->db->plimit($limit, $offset);
257 }
258
259 $result = $this->db->query($sql);
260 if ($result) {
261 $num = $this->db->num_rows($result);
262 $i = 0;
263 while ($i < $num) {
264 $obj = $this->db->fetch_object($result);
265 $ticket_static = new Ticket($this->db);
266 if ($ticket_static->fetch($obj->rowid)) {
267 if ($ticket_static->fk_user_assign > 0) {
268 $userStatic = new User($this->db);
269 $userStatic->fetch($ticket_static->fk_user_assign);
270 $ticket_static->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname;
271 }
272 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($ticket_static), $properties);
273 }
274 $i++;
275 }
276 } else {
277 throw new RestException(503, 'Error when retrieve ticket list');
278 }
279
280 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
281 if ($pagination_data) {
282 $totalsResult = $this->db->query($sqlTotals);
283 $total = $this->db->fetch_object($totalsResult)->total;
284
285 $tmp = $obj_ret;
286 $obj_ret = [];
287
288 $obj_ret['data'] = $tmp;
289 $obj_ret['pagination'] = [
290 'total' => (int) $total,
291 'page' => $page, //count starts from 0
292 'page_count' => ceil((int) $total / $limit),
293 'limit' => $limit
294 ];
295 }
296
297 return $obj_ret;
298 }
299
306 public function post($request_data = null)
307 {
308 $ticketstatic = new Ticket($this->db);
309 if (!DolibarrApiAccess::$user->hasRight('ticket', 'write')) {
310 throw new RestException(403);
311 }
312 // Check mandatory fields
313 $result = $this->_validate($request_data);
314
315 foreach ($request_data as $field => $value) {
316 if ($field === 'caller') {
317 // 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
318 $this->ticket->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
319 continue;
320 }
321
322 $this->ticket->$field = $this->_checkValForAPI($field, $value, $this->ticket);
323 }
324 if (empty($this->ticket->ref)) {
325 $this->ticket->ref = $ticketstatic->getDefaultRef();
326 }
327 if (empty($this->ticket->track_id)) {
328 $this->ticket->track_id = generate_random_id(16);
329 }
330
331 if ($this->ticket->create(DolibarrApiAccess::$user) < 0) {
332 throw new RestException(500, "Error creating ticket", array_merge(array($this->ticket->error), $this->ticket->errors));
333 }
334
335 return $this->ticket->id;
336 }
337
345 public function postNewMessage($request_data = null)
346 {
347 $ticketstatic = new Ticket($this->db);
348 if (!DolibarrApiAccess::$user->hasRight('ticket', 'write')) {
349 throw new RestException(403);
350 }
351 // Check mandatory fields
352 $result = $this->_validateMessage($request_data);
353
354 foreach ($request_data as $field => $value) {
355 if ($field === 'caller') {
356 // 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
357 $this->ticket->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
358 continue;
359 }
360
361 $this->ticket->$field = $this->_checkValForAPI($field, $value, $this->ticket);
362 }
363 $ticketMessageText = $this->ticket->message;
364 $result = $this->ticket->fetch('', '', $this->ticket->track_id);
365 if (!$result) {
366 throw new RestException(404, 'Ticket not found');
367 }
368 $this->ticket->message = $ticketMessageText;
369 if (!$this->ticket->createTicketMessage(DolibarrApiAccess::$user)) {
370 throw new RestException(500, 'Error when creating ticket');
371 }
372 return $this->ticket->id;
373 }
374
382 public function put($id, $request_data = null)
383 {
384 if (!DolibarrApiAccess::$user->hasRight('ticket', 'write')) {
385 throw new RestException(403);
386 }
387
388 $result = $this->ticket->fetch($id);
389 if (!$result) {
390 throw new RestException(404, 'Ticket not found');
391 }
392
393 if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
394 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
395 }
396
397 foreach ($request_data as $field => $value) {
398 if ($field === 'caller') {
399 // 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
400 $this->ticket->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
401 continue;
402 }
403
404 $this->ticket->$field = $this->_checkValForAPI($field, $value, $this->ticket);
405 }
406
407 if ($this->ticket->update(DolibarrApiAccess::$user) > 0) {
408 return $this->get($id);
409 } else {
410 throw new RestException(500, $this->ticket->error);
411 }
412 }
413
421 public function delete($id)
422 {
423 if (!DolibarrApiAccess::$user->hasRight('ticket', 'delete')) {
424 throw new RestException(403);
425 }
426 $result = $this->ticket->fetch($id);
427 if (!$result) {
428 throw new RestException(404, 'Ticket not found');
429 }
430
431 if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
432 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
433 }
434
435 if (!$this->ticket->delete(DolibarrApiAccess::$user)) {
436 throw new RestException(500, 'Error when deleting ticket');
437 }
438
439 return array(
440 'success' => array(
441 'code' => 200,
442 'message' => 'Ticket deleted'
443 )
444 );
445 }
446
455 private function _validate($data)
456 {
457 $ticket = array();
458 foreach (Tickets::$FIELDS as $field) {
459 if (!isset($data[$field])) {
460 throw new RestException(400, "$field field missing");
461 }
462 $ticket[$field] = $data[$field];
463 }
464 return $ticket;
465 }
466
475 private function _validateMessage($data)
476 {
477 $ticket = array();
478 foreach (Tickets::$FIELDS_MESSAGES as $field) {
479 if (!isset($data[$field])) {
480 throw new RestException(400, "$field field missing");
481 }
482 $ticket[$field] = $data[$field];
483 }
484 return $ticket;
485 }
486
487 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
497 protected function _cleanObjectDatas($object)
498 {
499 // phpcs:enable
500 $object = parent::_cleanObjectDatas($object);
501
502 // Other attributes to clean
503 $attr2clean = array(
504 "contact",
505 "contact_id",
506 "ref_previous",
507 "ref_next",
508 "ref_ext",
509 "table_element_line",
510 "statut",
511 "country",
512 "country_id",
513 "country_code",
514 "barcode_type",
515 "barcode_type_code",
516 "barcode_type_label",
517 "barcode_type_coder",
518 "mode_reglement_id",
519 "cond_reglement_id",
520 "cond_reglement",
521 "fk_delivery_address",
522 "shipping_method_id",
523 "modelpdf",
524 "fk_account",
525 "note_public",
526 "note_private",
527 "note",
528 "total_ht",
529 "total_tva",
530 "total_localtax1",
531 "total_localtax2",
532 "total_ttc",
533 "fk_incoterms",
534 "label_incoterms",
535 "location_incoterms",
536 "name",
537 "lastname",
538 "firstname",
539 "civility_id",
540 "canvas",
541 "cache_msgs_ticket",
542 "cache_logs_ticket",
543 "cache_types_tickets",
544 "cache_category_tickets",
545 "regeximgext",
546 "labelStatus",
547 "labelStatusShort",
548 "multicurrency_code",
549 "multicurrency_tx",
550 "multicurrency_total_ht",
551 "multicurrency_total_ttc",
552 "multicurrency_total_tva",
553 "multicurrency_total_localtax1",
554 "multicurrency_total_localtax2"
555 );
556 foreach ($attr2clean as $toclean) {
557 unset($object->$toclean);
558 }
559
560 // If object has lines, remove $db property
561 if (isset($object->lines) && count($object->lines) > 0) {
562 $nboflines = count($object->lines);
563 for ($i = 0; $i < $nboflines; $i++) {
564 $this->_cleanObjectDatas($object->lines[$i]);
565 }
566 }
567
568 // If object has linked objects, remove $db property
569 if (isset($object->linkedObjects) && count($object->linkedObjects) > 0) {
570 foreach ($object->linkedObjects as $type_object => $linked_object) {
571 foreach ($linked_object as $object2clean) {
572 $this->_cleanObjectDatas($object2clean);
573 }
574 }
575 }
576 return $object;
577 }
578}
$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
getCommon($id=0, $track_id='', $ref='')
Get properties of a Ticket object Return an array with ticket information.
getByRef($ref)
Get properties of a Ticket object from ref.
__construct()
Constructor.
_cleanObjectDatas($object)
Clean sensible object datas.
index($socid=0, $sortfield="t.rowid", $sortorder="ASC", $limit=100, $page=0, $sqlfilters='', $properties='', $pagination_data=false)
List tickets.
postNewMessage($request_data=null)
Add a new message to an existing ticket identified by property ->track_id into request.
post($request_data=null)
Create ticket object.
put($id, $request_data=null)
Update ticket.
_validateMessage($data)
Validate fields before create or update object message.
getByTrackId($track_id)
Get properties of a Ticket object from track id.
_validate($data)
Validate fields before create or update object.
Class to manage Dolibarr users.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
Class to generate the form for creating a new ticket.
generate_random_id($car=16)
Generate a random id.