dolibarr 25.0.0-alpha
api_tickets.class.php
1<?php
2/* Copyright (C) 2016 Jean-François Ferry <hello@librethic.io>
3 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
6 * Copyright (C) 2026 Nick Fragoulis
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.'/ticket/class/ticket.class.php';
25require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
26require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
27
28
35class Tickets extends DolibarrApi
36{
40 public static $FIELDS = array(
41 'subject',
42 'message'
43 );
44
48 public static $FIELDS_MESSAGES = array(
49 'track_id',
50 'message'
51 );
52
56 public $ticket;
57
61 public function __construct()
62 {
63 global $db;
64 $this->db = $db;
65 $this->ticket = new Ticket($this->db);
66 }
67
81 public function get($id, $contact_list = 1)
82 {
83 return $this->getCommon($id, '', '', $contact_list);
84 }
85
101 public function getByTrackId($track_id, $contact_list = 1)
102 {
103 return $this->getCommon(0, $track_id, '', $contact_list);
104 }
105
121 public function getByRef($ref, $contact_list = 1)
122 {
123 return $this->getCommon(0, '', $ref, $contact_list);
124 }
125
136 private function getCommon($id = 0, $track_id = '', $ref = '', $contact_list = 1)
137 {
138 global $conf;
139
140 if (!DolibarrApiAccess::$user->hasRight('ticket', 'read')) {
141 throw new RestException(403);
142 }
143
144 // Check parameters
145 if (($id < 0) && !$track_id && !$ref) {
146 throw new RestException(400, 'Wrong parameters');
147 }
148 if (empty($id) && empty($ref) && empty($track_id)) {
149 $result = $this->ticket->initAsSpecimen();
150 } else {
151 $result = $this->ticket->fetch($id, $ref, $track_id);
152 }
153 if (!$result) {
154 throw new RestException(404, 'Ticket not found');
155 }
156
157 // Messages of ticket
158 $messages = array();
159
160 $this->ticket->loadCacheMsgsTicket();
161
162 if (is_array($this->ticket->cache_msgs_ticket) && count($this->ticket->cache_msgs_ticket) > 0) {
163 $num = count($this->ticket->cache_msgs_ticket);
164 $i = 0;
165 while ($i < $num) {
166 $iduseraction = $this->ticket->cache_msgs_ticket[$i]['fk_user_action'];
167 if ($iduseraction > 0) {
168 if (empty($conf->cache['user'][$iduseraction])) {
169 $user_action = new User($this->db);
170 $user_action->fetch($iduseraction);
171
172 $conf->cache['user'][$iduseraction] = $user_action;
173 } else {
174 $user_action = $conf->cache['user'][$iduseraction];
175 }
176 } else {
177 $user_action = null;
178 }
179
180 // Now define messages
181 $messages[] = array(
182 'id' => $this->ticket->cache_msgs_ticket[$i]['id'],
183 'fk_user_action' => $this->ticket->cache_msgs_ticket[$i]['fk_user_action'], // Id of user owning the event
184 'fk_user_action_socid' => $user_action === null ? '' : $user_action->socid,
185 'fk_user_action_string' => $user_action === null ? '' : dolGetFirstLastname($user_action->firstname, $user_action->lastname),
186 'datec' => $this->ticket->cache_msgs_ticket[$i]['datec'],
187 'datep' => $this->ticket->cache_msgs_ticket[$i]['datep'],
188 'subject' => $this->ticket->cache_msgs_ticket[$i]['subject'],
189 'message' => $this->ticket->cache_msgs_ticket[$i]['message'],
190 'private' => $this->ticket->cache_msgs_ticket[$i]['private']
191 );
192 $i++;
193 }
194 $this->ticket->messages = $messages;
195 }
196
197 if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
198 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
199 }
200
201 if ($contact_list > -1) {
202 // Add external contacts ids
203 $tmparray = $this->ticket->liste_contact(-1, 'external', $contact_list);
204 if (is_array($tmparray)) {
205 $this->ticket->contacts_ids = $tmparray;
206 }
207 $tmparray = $this->ticket->liste_contact(-1, 'internal', $contact_list);
208 if (is_array($tmparray)) {
209 $this->ticket->contacts_ids_internal = $tmparray;
210 }
211 }
212
213 return $this->_cleanObjectDatas($this->ticket);
214 }
215
235 public function index($socid = 0, $sortfield = "t.rowid", $sortorder = "ASC", $limit = 100, $page = 0, $sqlfilters = '', $properties = '', $loadcontacts = 0, $pagination_data = false)
236 {
237 if (!DolibarrApiAccess::$user->hasRight('ticket', 'read')) {
238 throw new RestException(403);
239 }
240
241 $obj_ret = array();
242
243 $socid = DolibarrApiAccess::$user->socid ?: $socid;
244
245 $search_sale = null;
246 // If the internal user must only see his customers, force searching by him
247 $search_sale = 0;
248 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
249 $search_sale = DolibarrApiAccess::$user->id;
250 }
251
252 $sql = "SELECT t.rowid";
253 $sql .= " FROM ".MAIN_DB_PREFIX."ticket AS t";
254 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = t.fk_soc)";
255 $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
256 $sql .= ' WHERE t.entity IN ('.getEntity('ticket', 1).')';
257 if ($socid > 0) {
258 $sql .= " AND t.fk_soc = ".((int) $socid);
259 }
260 // Search on sale representative
261 if ($search_sale && $search_sale != '-1') {
262 if ($search_sale == -2) {
263 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', 0, 1);
264 } elseif ($search_sale > 0) {
265 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', (int) $search_sale);
266 }
267 }
268 // Add sql filters
269 if ($sqlfilters) {
270 $errormessage = '';
271 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
272 if ($errormessage) {
273 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
274 }
275 }
276
277 //this query will return total orders with the filters given
278 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
279
280 $sql .= $this->db->order($sortfield, $sortorder);
281
282 if ($limit) {
283 if ($page < 0) {
284 $page = 0;
285 }
286 $offset = $limit * $page;
287
288 $sql .= $this->db->plimit($limit, $offset);
289 }
290
291 $result = $this->db->query($sql);
292 if ($result) {
293 $i = 0;
294 $num = $this->db->num_rows($result);
295 $min = min($num, ($limit <= 0 ? $num : $limit));
296 while ($i < $min) {
297 $obj = $this->db->fetch_object($result);
298 $ticket_static = new Ticket($this->db);
299 if ($ticket_static->fetch($obj->rowid)) {
300 if ($ticket_static->fk_user_assign > 0) {
301 $userStatic = new User($this->db);
302 $userStatic->fetch($ticket_static->fk_user_assign);
303 //$ticket_static->fk_user_assign_string = dolGetFirstLastname($userStatic->firstname, $userStatic->lastname);
304 }
305
306 if ($loadcontacts) {
307 // Add external contacts ids
308 $tmparray = $ticket_static->liste_contact(-1, 'external', 1);
309 if (is_array($tmparray)) {
310 $ticket_static->contacts_ids = $tmparray;
311 }
312 $tmparray = $ticket_static->liste_contact(-1, 'internal', 1);
313 if (is_array($tmparray)) {
314 $ticket_static->contacts_ids_internal = $tmparray;
315 }
316 }
317
318 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($ticket_static), $properties);
319 }
320 $i++;
321 }
322 } else {
323 throw new RestException(503, 'Error when retrieve ticket list');
324 }
325
326 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
327 if ($pagination_data) {
328 $totalsResult = $this->db->query($sqlTotals);
329 $total = $this->db->fetch_object($totalsResult)->total;
330
331 $tmp = $obj_ret;
332 $obj_ret = [];
333
334 $obj_ret['data'] = $tmp;
335 $obj_ret['pagination'] = [
336 'total' => (int) $total,
337 'page' => $page, //count starts from 0
338 'page_count' => ceil((int) $total / $limit),
339 'limit' => $limit
340 ];
341 }
342
343 return $obj_ret;
344 }
345
354 public function post($request_data = null)
355 {
356 $ticketstatic = new Ticket($this->db);
357 if (!DolibarrApiAccess::$user->hasRight('ticket', 'write')) {
358 throw new RestException(403);
359 }
360
361 // Check mandatory fields
362 $this->_validate($request_data);
363
364 // Check thirdparty validity
365 $socid = (int) ($request_data['socid'] ?? 0);
366 if ($socid > 0) {
367 $thirdpartytmp = new Societe($this->db);
368 $thirdparty_result = $thirdpartytmp->fetch($socid);
369 if ($thirdparty_result < 1) {
370 throw new RestException(404, 'Thirdparty with id='.$socid.' not found or not allowed');
371 }
372 if (!DolibarrApi::_checkAccessToResource('societe', $thirdpartytmp->id)) {
373 throw new RestException(404, 'Thirdparty with id='.$thirdpartytmp->id.' not found or not allowed');
374 }
375 }
376
377 foreach ($request_data as $field => $value) {
378 if ($field === 'caller') {
379 // 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
380 $this->ticket->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
381 continue;
382 }
383
384 $this->ticket->$field = $this->_checkValForAPI($field, $value, $this->ticket);
385 }
386 if (empty($this->ticket->ref)) {
387 $this->ticket->ref = $ticketstatic->getDefaultRef();
388 }
389 if (empty($this->ticket->track_id)) {
390 $this->ticket->track_id = generate_random_id(16);
391 }
392
393 if ($this->ticket->create(DolibarrApiAccess::$user) < 0) {
394 throw new RestException(500, "Error creating ticket", array_merge(array($this->ticket->error), $this->ticket->errors));
395 }
396
397 return $this->ticket->id;
398 }
399
410 public function postNewMessage($request_data = null)
411 {
412 if (!DolibarrApiAccess::$user->hasRight('ticket', 'write')) {
413 throw new RestException(403);
414 }
415
416 // Check mandatory fields
417 $result = $this->_validateMessage($request_data);
418
419 $return_action_id = false;
420 if (isset($request_data['return_action_id'])) {
421 $return_action_id = !empty($request_data['return_action_id']);
422 unset($request_data['return_action_id']);
423 }
424
425 $attachments = array();
426 if (isset($request_data['attachments']) && is_array($request_data['attachments'])) {
427 $attachments = $request_data['attachments'];
428 unset($request_data['attachments']);
429 }
430
431 foreach ($request_data as $field => $value) {
432 if ($field === 'caller') {
433 // 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
434 $this->ticket->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
435 continue;
436 }
437
438 $this->ticket->$field = $this->_checkValForAPI($field, $value, $this->ticket);
439 }
440 $ticketMessageText = $this->ticket->message;
441 // Allow targeting the ticket by id or ref, not only track_id
442 if (!empty($this->ticket->id)) {
443 $result = $this->ticket->fetch($this->ticket->id);
444 } elseif (!empty($this->ticket->ref)) {
445 $result = $this->ticket->fetch(0, $this->ticket->ref);
446 } else {
447 $result = $this->ticket->fetch(0, '', $this->ticket->track_id);
448 }
449 if ($result <= 0) {
450 throw new RestException(404, 'Ticket not found');
451 }
452
453 if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
454 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
455 }
456
457 $this->ticket->message = $ticketMessageText;
458
459 $filename_list = array();
460 $mimetype_list = array();
461 $mimefilename_list = array();
462 if (!empty($attachments)) {
463 global $conf;
464 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
465
466 $destdir = $conf->ticket->dir_output.'/'.$this->ticket->ref;
467 if (!dol_is_dir($destdir) && dol_mkdir($destdir) < 0) {
468 throw new RestException(500, 'Error while trying to create directory '.$destdir);
469 }
470
471 foreach ($attachments as $attachment) {
472 if (!is_array($attachment) || empty($attachment['filename'])) {
473 continue;
474 }
475
476 $filename = dol_sanitizeFileName($attachment['filename']);
477 if (empty($filename)) {
478 continue;
479 }
480
481 $filecontent = isset($attachment['filecontent']) ? $attachment['filecontent'] : '';
482 $fileencoding = isset($attachment['fileencoding']) ? $attachment['fileencoding'] : '';
483 $content = ($fileencoding === 'base64') ? base64_decode($filecontent) : $filecontent;
484 if ($content === false) {
485 throw new RestException(400, 'Failed to decode attachment '.$filename);
486 }
487
488 $destfile = $destdir.'/'.$filename;
489 if (is_file($destfile)) {
490 $pathinfo = pathinfo($filename);
491 $suffix = ' - '.dol_print_date(dol_now(), 'dayhourlog');
492 $extension = !empty($pathinfo['extension']) ? '.'.$pathinfo['extension'] : '';
493 $basename = !empty($pathinfo['filename']) ? $pathinfo['filename'] : preg_replace('/\.[^.]+$/', '', $filename);
494 $destfile = $destdir.'/'.$basename.$suffix.$extension;
495 }
496
497 $destfiletmp = DOL_DATA_ROOT.'/admin/temp/'.basename($destfile);
498 if (!dol_is_dir(dirname($destfiletmp))) {
499 dol_mkdir(dirname($destfiletmp));
500 }
501
502 $fhandle = @fopen($destfiletmp, 'w');
503 if (!$fhandle) {
504 throw new RestException(500, "Failed to open file '".$destfiletmp."' for write");
505 }
506 $nbofbyteswrote = fwrite($fhandle, $content);
507 fclose($fhandle);
508 if ($nbofbyteswrote === false) {
509 throw new RestException(500, "Failed to write file '".$destfiletmp."'");
510 }
511
512 $moreinfo = array(
513 'description' => 'File uploaded using ticket API',
514 'src_object_type' => $this->ticket->element,
515 'src_object_id' => $this->ticket->id,
516 'gen_or_uploaded' => 'uploaded'
517 );
518 $resultmove = dol_move($destfiletmp, $destfile, '0', 1, 0, 1, $moreinfo);
519 if (!$resultmove) {
520 throw new RestException(500, "Failed to move file into '".$destfile."'");
521 }
522
523 $filename_list[] = $destfile;
524 $mimefilename_list[] = basename($destfile);
525 $mimetype_list[] = !empty($attachment['mimetype']) ? $attachment['mimetype'] : '';
526 }
527 }
528
529 $actionid = $this->ticket->createTicketMessage(DolibarrApiAccess::$user, 0, $filename_list, $mimetype_list, $mimefilename_list);
530 if ($actionid <= 0) {
531 throw new RestException(500, 'Error when creating ticket');
532 }
533 if ($return_action_id) {
534 return array('ticket_id' => $this->ticket->id, 'action_id' => $actionid);
535 }
536 return $this->ticket->id;
537 }
538
548 public function put($id, $request_data = null)
549 {
550 if (!DolibarrApiAccess::$user->hasRight('ticket', 'write')) {
551 throw new RestException(403);
552 }
553
554 $result = $this->ticket->fetch($id);
555 if (!$result) {
556 throw new RestException(404, 'Ticket not found');
557 }
558
559 if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
560 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
561 }
562
563 // Check thirdparty validity
564 $socid = (int) ($request_data['socid'] ?? 0);
565 if ($socid > 0) {
566 $thirdpartytmp = new Societe($this->db);
567 $thirdparty_result = $thirdpartytmp->fetch($socid);
568 if ($thirdparty_result < 1) {
569 throw new RestException(404, 'Thirdparty with id='.$socid.' not found or not allowed');
570 }
571 if (!DolibarrApi::_checkAccessToResource('societe', $thirdpartytmp->id)) {
572 throw new RestException(404, 'Thirdparty with id='.$thirdpartytmp->id.' not found or not allowed');
573 }
574 }
575
576 foreach ($request_data as $field => $value) {
577 if ($field === 'caller') {
578 // 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
579 $this->ticket->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
580 continue;
581 }
582
583 if ($field == 'id') {
584 continue;
585 }
586 if ($field == 'array_options' && is_array($value)) {
587 foreach ($value as $index => $val) {
588 $this->ticket->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->ticket);
589 }
590 continue;
591 }
592
593 $this->ticket->$field = $this->_checkValForAPI($field, $value, $this->ticket);
594 }
595
596 if ($this->ticket->update(DolibarrApiAccess::$user) > 0) {
597 return $this->get($id);
598 } else {
599 throw new RestException(500, $this->ticket->errorsToString());
600 }
601 }
602
621 public function close($id, $cancel = 0)
622 {
623 if (!$this->canManage()) {
624 throw new RestException(403);
625 }
626 if ($this->ticket->fetch((int) $id) <= 0) {
627 throw new RestException(404, 'Ticket not found');
628 }
629 if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
630 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
631 }
632 if (in_array((int) $this->ticket->status, array(Ticket::STATUS_CLOSED, Ticket::STATUS_CANCELED), true)) {
633 throw new RestException(409, 'Ticket is already closed or canceled');
634 }
635 if ($this->ticket->close(DolibarrApiAccess::$user, $cancel ? 1 : 0) <= 0) {
636 throw new RestException(500, 'Error when closing the ticket: '.$this->ticket->errorsToString());
637 }
638
639 return $this->get((int) $id);
640 }
641
660 public function assign($id, $fk_user_assign = 0)
661 {
662 if (!$this->canManage()) {
663 throw new RestException(403);
664 }
665 if ($this->ticket->fetch((int) $id) <= 0) {
666 throw new RestException(404, 'Ticket not found');
667 }
668 if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
669 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
670 }
671 $fk_user_assign = (int) $fk_user_assign;
672 if ($fk_user_assign > 0) {
673 $assignee = new User($this->db);
674 if ($assignee->fetch($fk_user_assign) <= 0 || (int) $assignee->status !== 1) {
675 throw new RestException(400, 'User '.$fk_user_assign.' not found or not active');
676 }
677 }
678
679 $previous = (int) $this->ticket->fk_user_assign;
680 $this->db->begin();
681 $error = 0;
682 if ($this->ticket->assignUser(DolibarrApiAccess::$user, $fk_user_assign) < 0) {
683 $error++;
684 }
685 // The internal support contact follows the assignment, as on the card.
686 if (!$error && $previous > 0) {
687 foreach ($this->ticket->listeContact(-1, 'internal', 0, 'SUPPORTTEC') as $contact) {
688 if ((int) $contact['id'] !== $fk_user_assign && $this->ticket->delete_contact($contact['rowid']) < 0) {
689 $error++;
690 }
691 }
692 }
693 if (!$error && $fk_user_assign > 0 && $fk_user_assign !== $previous && $this->ticket->add_contact($fk_user_assign, 'SUPPORTTEC', 'internal') < 0) {
694 $error++;
695 }
696 if ($error) {
697 $this->db->rollback();
698 throw new RestException(500, 'Error when assigning the ticket: '.$this->ticket->errorsToString());
699 }
700 $this->db->commit();
701
702 return $this->get((int) $id);
703 }
704
710 private function canManage()
711 {
712 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) {
713 return (bool) DolibarrApiAccess::$user->hasRight('ticket', 'manage_advance');
714 }
715
716 return (bool) DolibarrApiAccess::$user->hasRight('ticket', 'write');
717 }
718
727 public function delete($id)
728 {
729 if (!DolibarrApiAccess::$user->hasRight('ticket', 'delete')) {
730 throw new RestException(403);
731 }
732 $result = $this->ticket->fetch($id);
733 if (!$result) {
734 throw new RestException(404, 'Ticket not found');
735 }
736
737 if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
738 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
739 }
740
741 if (!$this->ticket->delete(DolibarrApiAccess::$user)) {
742 throw new RestException(500, 'Error when deleting ticket');
743 }
744
745 return array(
746 'success' => array(
747 'code' => 200,
748 'message' => 'Ticket deleted'
749 )
750 );
751 }
752
761 private function _validate($data)
762 {
763 if ($data === null) {
764 $data = array();
765 }
766 $ticket = array();
767 foreach (Tickets::$FIELDS as $field) {
768 if (!isset($data[$field])) {
769 throw new RestException(400, "$field field missing");
770 }
771 $ticket[$field] = $data[$field];
772 }
773 return $ticket;
774 }
775
784 private function _validateMessage($data)
785 {
786 if ($data === null) {
787 $data = array();
788 }
789 $ticket = array();
790 foreach (Tickets::$FIELDS_MESSAGES as $field) {
791 if (!isset($data[$field])) {
792 throw new RestException(400, "$field field missing");
793 }
794 $ticket[$field] = $data[$field];
795 }
796 return $ticket;
797 }
798
799 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
811 protected function _cleanObjectDatas($object)
812 {
813 // phpcs:enable
814 $object = parent::_cleanObjectDatas($object);
815
816 // Other attributes to clean
817 $attr2clean = array(
818 "contact",
819 "contact_id",
820 "ref_previous",
821 "ref_next",
822 "ref_ext",
823 "table_element_line",
824 "statut",
825 "country",
826 "country_id",
827 "country_code",
828 "barcode_type",
829 "barcode_type_code",
830 "barcode_type_label",
831 "barcode_type_coder",
832 "mode_reglement_id",
833 "cond_reglement_id",
834 "cond_reglement",
835 "fk_delivery_address",
836 "shipping_method_id",
837 "modelpdf",
838 "fk_account",
839 "note_public",
840 "note_private",
841 "note",
842 "total_ht",
843 "total_tva",
844 "total_localtax1",
845 "total_localtax2",
846 "total_ttc",
847 "fk_incoterms",
848 "label_incoterms",
849 "location_incoterms",
850 "name",
851 "lastname",
852 "firstname",
853 "civility_id",
854 "canvas",
855 "cache_msgs_ticket",
856 "cache_logs_ticket",
857 "cache_types_tickets",
858 "regeximgext",
859 "labelStatus",
860 "labelStatusShort",
861 "multicurrency_code",
862 "multicurrency_tx",
863 "multicurrency_total_ht",
864 "multicurrency_total_ttc",
865 "multicurrency_total_tva",
866 "multicurrency_total_localtax1",
867 "multicurrency_total_localtax2"
868 );
869 foreach ($attr2clean as $toclean) {
870 unset($object->$toclean);
871 }
872
873 // If object has lines, remove $db property
874 if (isset($object->lines) && count($object->lines) > 0) {
875 $nboflines = count($object->lines);
876 for ($i = 0; $i < $nboflines; $i++) {
877 $this->_cleanObjectDatas($object->lines[$i]);
878 }
879 }
880
881 // If object has linked objects, remove $db property
882 if (isset($object->linkedObjects) && count($object->linkedObjects) > 0) {
883 foreach ($object->linkedObjects as $type_object => $linked_object) {
884 foreach ($linked_object as $object2clean) {
885 $this->_cleanObjectDatas($object2clean);
886 }
887 }
888 }
889 return $object;
890 }
891
912 public function postContact(int $id, int $contactid, string $type, string $source = "external", int $notrigger = 0): array
913 {
914 // Check permissions
915 if (!DolibarrApiAccess::$user->hasRight('ticket', 'write')) {
916 throw new RestException(403);
917 }
918
919 // test source
920 if (empty($source)) {
921 throw new RestException(400, 'Source can not be empty');
922 }
923 // test type
924 if (empty($type)) {
925 throw new RestException(400, 'type can not be empty');
926 }
927
928 // Check type/source contact exists
929 $sqlCheckTypeSource = "SELECT tc.rowid";
930 $sqlCheckTypeSource .= " FROM ".$this->db->prefix()."c_type_contact as tc";
931 $sqlCheckTypeSource .= " WHERE tc.element LIKE 'ticket'";
932 $sqlCheckTypeSource .= " AND tc.source = '".$this->db->escape($source)."'";
933 $sqlCheckTypeSource .= " AND tc.code = '".$this->db->escape($type)."'";
934 $sqlCheckTypeSource .= " AND tc.active = 1";
935 $result = $this->db->query($sqlCheckTypeSource);
936
937 if ($result && $this->db->num_rows($result) == 0) {
938 throw new RestException(400, 'Contact type not found');
939 }
940
941 // Check contact exists
942 if ($source == "external") {
943 // Check external contact exists
944 $sqlCheckExternalContact = "SELECT 1 as exist";
945 $sqlCheckExternalContact .= " FROM ".MAIN_DB_PREFIX."socpeople";
946 $sqlCheckExternalContact .= " WHERE rowid = " . intval($contactid);
947 $result = $this->db->query($sqlCheckExternalContact);
948
949 if ($result && $this->db->num_rows($result) == 0) {
950 throw new RestException(404, 'External contact not found');
951 }
952 } else {
953 // Check internal contact exists
954 $sqlCheckInternalContact = "SELECT 1 as exist";
955 $sqlCheckInternalContact .= " FROM ".MAIN_DB_PREFIX."user";
956 $sqlCheckInternalContact .= " WHERE rowid = " . intval($contactid);
957 $result = $this->db->query($sqlCheckInternalContact);
958
959 if ($result && $this->db->num_rows($result) == 0) {
960 throw new RestException(404, 'Internal contact not found');
961 }
962 }
963
964 // tests done, let's get it
965 $result = $this->ticket->fetch($id);
966 if (!$result) {
967 throw new RestException(404, 'Ticket not found');
968 }
969 if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
970 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
971 }
972
973 $result = $this->ticket->add_contact($contactid, $type, $source, $notrigger);
974
975 if ($result == 0) {
976 throw new RestException(400, 'Already exists: Contact='.$contactid.' is already linked to the ticket='.$id.' as source='.$source.' and type='.$type);
977 } elseif ($result == -1) {
978 throw new RestException(400, 'Wrong contact='.$contactid);
979 } elseif ($result == -2) {
980 throw new RestException(400, 'Wrong type='.$type);
981 } elseif ($result == -3) {
982 throw new RestException(400, 'Not allowed contacts');
983 } elseif ($result == -4) {
984 throw new RestException(400, 'ErrorCommercialNotAllowedForThirdparty');
985 } elseif ($result == -5) {
986 throw new RestException(400, 'Trigger failed');
987 } elseif ($result == -6) {
988 throw new RestException(400, 'DB_ERROR_RECORD_ALREADY_EXISTS');
989 } elseif ($result == -7) {
990 throw new RestException(400, 'Some other error');
991 } elseif ($result <= -8) {
992 throw new RestException(400, 'Unknown error occurred');
993 }
994
995 return array(
996 'success' => array(
997 'code' => 200,
998 'message' => 'Contact='.$contactid.' linked to the ticket='.$id.' as '.$source.' '.$type
999 )
1000 );
1001 }
1002
1022 public function deleteContact(int $id, int $contactid, string $type, string $source = "external"): array
1023 {
1024 // Check permissions
1025 if (!DolibarrApiAccess::$user->hasRight('ticket', 'write')) {
1026 throw new RestException(403);
1027 }
1028
1029 // test source
1030 if (empty($source)) {
1031 throw new RestException(400, 'Source can not be empty');
1032 }
1033 // test type
1034 if (empty($type)) {
1035 throw new RestException(400, 'type can not be empty');
1036 }
1037
1038 $result = $this->ticket->fetch($id);
1039 if (!$result) {
1040 throw new RestException(404, 'Ticket not found');
1041 }
1042
1043 if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) {
1044 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1045 }
1046
1047 $contacts = $this->ticket->liste_contact(-1, $source);
1048 foreach ($contacts as $contact) {
1049 if ($contact['id'] == $contactid && $contact['code'] == $type) {
1050 $result = $this->ticket->delete_contact($contact['rowid']);
1051
1052 if (!$result) {
1053 throw new RestException(500, 'Error when deleting the contact '.$contact['rowid']);
1054 }
1055 }
1056 }
1057
1058 return array(
1059 'success' => array(
1060 'code' => 200,
1061 'message' => 'Contact unlinked from ticket'
1062 )
1063 );
1064 }
1065}
$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 third parties objects (customers, suppliers, prospects...)
canManage()
Whether the API user may close and assign tickets, as on the ticket card.
getByTrackId($track_id, $contact_list=1)
Get properties of a Ticket object from track id.
deleteContact(int $id, int $contactid, string $type, string $source="external")
Unlink a contact type of given ticket.
getCommon($id=0, $track_id='', $ref='', $contact_list=1)
Get properties of a Ticket object Return an array with ticket information.
__construct()
Constructor.
index($socid=0, $sortfield="t.rowid", $sortorder="ASC", $limit=100, $page=0, $sqlfilters='', $properties='', $loadcontacts=0, $pagination_data=false)
List tickets.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
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.
assign($id, $fk_user_assign=0)
Assign a ticket to a user, or unassign it.
put($id, $request_data=null)
Update ticket.
_validateMessage($data)
Validate fields before create or update object message.
postContact(int $id, int $contactid, string $type, string $source="external", int $notrigger=0)
Add a contact type of given ticket.
getByRef($ref, $contact_list=1)
Get properties of a Ticket object from ref.
close($id, $cancel=0)
Close a ticket, or cancel it.
_validate($data)
Validate fields before create or update object.
Class to manage Dolibarr users.
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_is_dir($folder)
Test if filename is a directory.
dol_now($mode='gmt')
Return date for now.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Class to generate the form for creating a new ticket.
generate_random_id($car=16)
Generate a random id.