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