dolibarr 24.0.2
api_projects.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-2026 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2025 Charlene Benke <charlene@patas-monkey.com>
6 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2025 Jessica Kowal <jessicakowal69@gmail.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23use Luracast\Restler\RestException;
24
25require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
26require_once DOL_DOCUMENT_ROOT . '/projet/class/task.class.php';
27
35class Projects extends DolibarrApi
36{
40 public static $FIELDS = array(
41 'ref',
42 'title'
43 );
44
48 public $project;
49
53 public $task;
54
55
59 public function __construct()
60 {
61 global $db, $conf;
62 $this->db = $db;
63 $this->project = new Project($this->db);
64 $this->task = new Task($this->db);
65 }
66
78 public function get($id)
79 {
80 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
81 throw new RestException(403);
82 }
83
84 $result = $this->project->fetch($id);
85 if (!$result) {
86 throw new RestException(404, 'Project with supplied id not found');
87 }
88
89 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
90 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
91 }
92
93 $this->project->fetchObjectLinked();
94 return $this->_cleanObjectDatas($this->project);
95 }
96
110 public function getByRef($ref)
111 {
112 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
113 throw new RestException(403);
114 }
115
116 $result = $this->project->fetch(0, $ref);
117 if (!$result) {
118 throw new RestException(404, 'Project with supplied ref not found');
119 }
120
121 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
122 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
123 }
124
125 $this->project->fetchObjectLinked();
126 return $this->_cleanObjectDatas($this->project);
127 }
128
142 public function getByRefExt($ref_ext)
143 {
144 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
145 throw new RestException(403);
146 }
147
148 $result = $this->project->fetch(0, '', $ref_ext);
149 if (!$result) {
150 throw new RestException(404, 'Project with supplied ref_ext not found');
151 }
152
153 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
154 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
155 }
156
157 $this->project->fetchObjectLinked();
158 return $this->_cleanObjectDatas($this->project);
159 }
160
174 public function getByMsgId($email_msgid)
175 {
176 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
177 throw new RestException(403);
178 }
179
180 $result = $this->project->fetch(0, '', '', $email_msgid);
181 if (!$result) {
182 throw new RestException(404, 'Project with supplied email_msgid not found');
183 }
184
185 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
186 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
187 }
188
189 $this->project->fetchObjectLinked();
190 return $this->_cleanObjectDatas($this->project);
191 }
192
212 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
213 {
214 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
215 throw new RestException(403);
216 }
217
218 $obj_ret = array();
219
220 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
221 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
222
223 // If the internal user must only see his customers, force searching by him
224 $search_sale = 0;
225 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
226 $search_sale = DolibarrApiAccess::$user->id;
227 }
228
229 $sql = "SELECT t.rowid";
230 $sql .= " FROM " . MAIN_DB_PREFIX . "projet as t";
231 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe AS s ON (s.rowid = t.fk_soc)";
232 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "projet_extrafields AS ef ON ef.fk_object = t.rowid"; // So we will be able to filter on extrafields
233 if ($category > 0) {
234 $sql .= ", " . MAIN_DB_PREFIX . "categorie_project as c";
235 }
236 $sql .= ' WHERE t.entity IN (' . getEntity('project') . ')';
237 if ($socids) {
238 $sql .= " AND t.fk_soc IN (" . $this->db->sanitize($socids) . ")";
239 }
240 // If user has no permission to see all projects, we force the search on projects he is allowed to see only (public projects or projects he is a contact of), like the list.php page does
241 if (!DolibarrApiAccess::$user->hasRight('projet', 'all', 'lire')) {
242 $projectsListId = $this->project->getProjectsAuthorizedForUser(DolibarrApiAccess::$user, 0, 1, 0);
243 $sql .= " AND t.rowid IN (" . $this->db->sanitize($projectsListId) . ")";
244 }
245 // Search on sale representative
246 if ($search_sale && $search_sale != '-1') {
247 if ($search_sale == -2) {
248 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM " . MAIN_DB_PREFIX . "societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
249 } elseif ($search_sale > 0) {
250 $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) . ")";
251 }
252 }
253 // Select projects of given category
254 if ($category > 0) {
255 $sql .= " AND c.fk_categorie = " . ((int) $category) . " AND c.fk_project = t.rowid ";
256 }
257 // Add sql filters
258 if ($sqlfilters) {
259 $errormessage = '';
260 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
261 if ($errormessage) {
262 throw new RestException(400, 'Error when validating parameter sqlfilters -> ' . $errormessage);
263 }
264 }
265
266 //this query will return total orders with the filters given
267 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
268
269 $sql .= $this->db->order($sortfield, $sortorder);
270 if ($limit) {
271 if ($page < 0) {
272 $page = 0;
273 }
274 $offset = $limit * $page;
275
276 $sql .= $this->db->plimit($limit + 1, $offset);
277 }
278
279 dol_syslog("API Rest request");
280 $result = $this->db->query($sql);
281
282 if ($result) {
283 $num = $this->db->num_rows($result);
284 $min = min($num, ($limit <= 0 ? $num : $limit));
285 $i = 0;
286 while ($i < $min) {
287 $obj = $this->db->fetch_object($result);
288 $project_static = new Project($this->db);
289 if ($project_static->fetch($obj->rowid)) {
290 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($project_static), $properties);
291 }
292 $i++;
293 }
294 } else {
295 throw new RestException(503, 'Error when retrieve project list : ' . $this->db->lasterror());
296 }
297
298 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
299 if ($pagination_data) {
300 $totalsResult = $this->db->query($sqlTotals);
301 $total = $this->db->fetch_object($totalsResult)->total;
302
303 $tmp = $obj_ret;
304 $obj_ret = [];
305
306 $obj_ret['data'] = $tmp;
307 $obj_ret['pagination'] = [
308 'total' => (int) $total,
309 'page' => $page, //count starts from 0
310 'page_count' => ceil((int) $total / $limit),
311 'limit' => $limit
312 ];
313 }
314
315 return $obj_ret;
316 }
317
327 public function post($request_data = null)
328 {
329 global $conf;
330 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
331 throw new RestException(403, "Insufficiant rights");
332 }
333 // Check mandatory fields
334 $result = $this->_validate($request_data);
335
336 foreach ($request_data as $field => $value) {
337 if ($field === 'caller') {
338 // 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
339 $this->project->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
340 continue;
341 }
342
343 $this->project->$field = $this->_checkValForAPI($field, $value, $this->project);
344 }
345 /*if (isset($request_data["lines"])) {
346 $lines = array();
347 foreach ($request_data["lines"] as $line) {
348 array_push($lines, (object) $line);
349 }
350 $this->project->lines = $lines;
351 }*/
352
353 // Auto-generate the "ref" field if it is set to "auto"
354 if ($this->project->ref == -1 || $this->project->ref === 'auto') {
355 $reldir = '';
356 $defaultref = '';
357 $file = '';
358 $classname = '';
359 $filefound = 0;
360 $modele = getDolGlobalString('PROJECT_ADDON', 'mod_project_simple');
361
362 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
363 foreach ($dirmodels as $reldir) {
364 $file = dol_buildpath($reldir . "core/modules/project/" . $modele . '.php', 0);
365 if (file_exists($file)) {
366 $filefound = 1;
367 $classname = $modele;
368 break;
369 }
370 }
371 if ($filefound && !empty($classname)) {
372 $result = dol_include_once($reldir . "core/modules/project/" . $modele . '.php');
373 if ($result !== false && class_exists($classname)) {
374 $modProject = new $classname();
375 '@phan-var-force ModeleNumRefProjects $modProject';
376 $defaultref = $modProject->getNextValue(null, $this->project);
377 } else {
378 dol_syslog("Failed to include module file or invalid classname: " . $reldir . "core/modules/project/" . $modele . '.php', LOG_ERR);
379 }
380 } else {
381 dol_syslog("Module file not found or classname is empty: " . $modele, LOG_ERR);
382 }
383
384 if (is_numeric($defaultref) && $defaultref <= 0) {
385 $defaultref = '';
386 }
387
388 if (empty($defaultref)) {
389 $defaultref = 'PJ' . dol_print_date(dol_now(), 'dayrfc');
390 }
391
392 $this->project->ref = $defaultref;
393 }
394
395 if ($this->project->create(DolibarrApiAccess::$user) < 0) {
396 throw new RestException(500, "Error creating project", array_merge(array($this->project->error), $this->project->errors));
397 }
398
399 return $this->project->id;
400 }
401
421 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
422 {
423 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
424 throw new RestException(403);
425 }
426
427 $result = $this->project->fetch($id);
428 if (!$result) {
429 throw new RestException(404, 'project not found');
430 }
431
432 if (!DolibarrApi::_checkAccessToResource('ficheinter', $this->project->id)) {
433 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
434 }
435
436 $result = $this->project->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
437 if ($result < 0) {
438 throw new RestException(500, 'Error : ' . $this->project->error);
439 }
440
441 return $this->_cleanObjectDatas($this->project);
442 }
443
459 public function deleteContact($id, $contactid, $type)
460 {
461 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
462 throw new RestException(403);
463 }
464
465 $result = $this->project->fetch($id);
466
467 if (!$result) {
468 throw new RestException(404, 'Project not found');
469 }
470
471 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
472 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
473 }
474 foreach (array('internal', 'external') as $source) {
475 $contacts = $this->project->liste_contact(-1, $source);
476
477 foreach ($contacts as $contact) {
478 if ($contact['id'] == $contactid && $contact['code'] == $type) {
479 $result = $this->project->delete_contact($contact['rowid']);
480 if (!$result) {
481 throw new RestException(500, 'Error when deleted the contact');
482 }
483 }
484 }
485 }
486 return $this->_cleanObjectDatas($this->project);
487 }
501 public function getLines($id, $includetimespent = 0)
502 {
503 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
504 throw new RestException(403);
505 }
506
507 $result = $this->project->fetch($id);
508 if (!$result) {
509 throw new RestException(404, 'Project not found');
510 }
511
512 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
513 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
514 }
515 $this->project->getLinesArray(DolibarrApiAccess::$user);
516 $result = array();
517 foreach ($this->project->lines as $line) { // $line is a task
518 if ($includetimespent == 1) {
519 $timespent = $line->getSummaryOfTimeSpent(0);
520 }
521 if ($includetimespent == 2) {
522 $timespent = $line->fetchTimeSpentOnTask();
523 }
524 array_push($result, $this->_cleanObjectDatas($line));
525 }
526 return $result;
527 }
528
529
542 public function getRoles($id, $userid = 0)
543 {
544 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
545 throw new RestException(403);
546 }
547
548 $result = $this->project->fetch($id);
549 if (!$result) {
550 throw new RestException(404, 'Project not found');
551 }
552
553 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
554 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
555 }
556
557 require_once DOL_DOCUMENT_ROOT . '/projet/class/task.class.php';
558 $taskstatic = new Task($this->db);
559 $userp = DolibarrApiAccess::$user;
560 if ($userid > 0) {
561 $userp = new User($this->db);
562 $userp->fetch($userid);
563 }
564 $this->project->roles = $taskstatic->getUserRolesForProjectsOrTasks($userp, null, (string) $id, 0);
565 $result = array();
566 foreach ($this->project->roles as $line) {
567 array_push($result, $this->_cleanObjectDatas($line));
568 }
569
570 return $result;
571 }
572
573
586 /*
587 public function postLine($id, $request_data = null)
588 {
589 if(! DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
590 throw new RestException(403);
591 }
592
593 $result = $this->project->fetch($id);
594 if( ! $result ) {
595 throw new RestException(404, 'Project not found');
596 }
597
598 if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
599 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
600 }
601
602 $request_data = (object) $request_data;
603
604 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
605
606 $updateRes = $this->project->addline(
607 $request_data->desc,
608 $request_data->subprice,
609 $request_data->qty,
610 $request_data->tva_tx,
611 $request_data->localtax1_tx,
612 $request_data->localtax2_tx,
613 $request_data->fk_product,
614 $request_data->remise_percent,
615 $request_data->info_bits,
616 $request_data->fk_remise_except,
617 'HT',
618 0,
619 $request_data->date_start,
620 $request_data->date_end,
621 $request_data->product_type,
622 $request_data->rang,
623 $request_data->special_code,
624 $fk_parent_line,
625 $request_data->fk_fournprice,
626 $request_data->pa_ht,
627 $request_data->label,
628 $request_data->array_options,
629 $request_data->fk_unit,
630 $this->element,
631 $request_data->id
632 );
633
634 if ($updateRes > 0) {
635 return $updateRes;
636
637 }
638 return false;
639 }
640 */
641
655 /*
656 public function putLine($id, $lineid, $request_data = null)
657 {
658 if(! DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
659 throw new RestException(403);
660 }
661
662 $result = $this->project->fetch($id);
663 if( ! $result ) {
664 throw new RestException(404, 'Project not found');
665 }
666
667 if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
668 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
669 }
670
671 $request_data = (object) $request_data;
672
673 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
674
675 $updateRes = $this->project->updateline(
676 $lineid,
677 $request_data->desc,
678 $request_data->subprice,
679 $request_data->qty,
680 $request_data->remise_percent,
681 $request_data->tva_tx,
682 $request_data->localtax1_tx,
683 $request_data->localtax2_tx,
684 'HT',
685 $request_data->info_bits,
686 $request_data->date_start,
687 $request_data->date_end,
688 $request_data->product_type,
689 $request_data->fk_parent_line,
690 0,
691 $request_data->fk_fournprice,
692 $request_data->pa_ht,
693 $request_data->label,
694 $request_data->special_code,
695 $request_data->array_options,
696 $request_data->fk_unit
697 );
698
699 if ($updateRes > 0) {
700 $result = $this->get($id);
701 unset($result->line);
702 return $this->_cleanObjectDatas($result);
703 }
704 return false;
705 }*/
706
707
708
721 public function put($id, $request_data = null)
722 {
723 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
724 throw new RestException(403);
725 }
726
727 $result = $this->project->fetch($id);
728 if ($result <= 0) {
729 throw new RestException(404, 'Project not found');
730 }
731
732 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
733 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
734 }
735 foreach ($request_data as $field => $value) {
736 if ($field == 'id') {
737 continue;
738 }
739 if ($field === 'caller') {
740 // 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
741 $this->project->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
742 continue;
743 }
744 if ($field == 'array_options' && is_array($value)) {
745 foreach ($value as $index => $val) {
746 $this->project->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->project);
747 }
748 continue;
749 }
750
751 $this->project->$field = $this->_checkValForAPI($field, $value, $this->project);
752 }
753
754 if ($this->project->update(DolibarrApiAccess::$user) >= 0) {
755 return $this->get($id);
756 } else {
757 throw new RestException(500, $this->project->error);
758 }
759 }
760
771 public function delete($id)
772 {
773 if (!DolibarrApiAccess::$user->hasRight('projet', 'supprimer')) {
774 throw new RestException(403);
775 }
776 $result = $this->project->fetch($id);
777 if (!$result) {
778 throw new RestException(404, 'Project not found');
779 }
780
781 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
782 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
783 }
784
785 if (!$this->project->delete(DolibarrApiAccess::$user)) {
786 throw new RestException(500, 'Error when delete project : ' . $this->project->error);
787 }
788
789 return array(
790 'success' => array(
791 'code' => 200,
792 'message' => 'Project deleted'
793 )
794 );
795 }
796
820 public function validate($id, $notrigger = 0)
821 {
822 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
823 throw new RestException(403);
824 }
825 $result = $this->project->fetch($id);
826 if (!$result) {
827 throw new RestException(404, 'Project not found');
828 }
829
830 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
831 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
832 }
833
834 $result = $this->project->setValid(DolibarrApiAccess::$user, $notrigger);
835 if ($result == 0) {
836 throw new RestException(304, 'Error nothing done. May be object is already validated');
837 }
838 if ($result < 0) {
839 throw new RestException(500, 'Error when validating Project: ' . $this->project->error);
840 }
841
842 return array(
843 'success' => array(
844 'code' => 200,
845 'message' => 'Project validated'
846 )
847 );
848 }
849
868 public function listTimespent($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
869 {
870 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
871 throw new RestException(403);
872 }
873
874 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
875 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
876
877 // If the internal user must only see his customers, force searching by him
878 $search_sale = 0;
879 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
880 $search_sale = DolibarrApiAccess::$user->id;
881 }
882
883 // The hourly rate thm is sensitive payroll data, so it is returned only if the caller has permission to read salaries (same rule as for the users API)
884 $canreadsalary = ((isModEnabled('salaries') && DolibarrApiAccess::$user->hasRight('salaries', 'read')) || !isModEnabled('salaries'));
885
886 $sql = "SELECT et.rowid, et.element_duration, et.element_datehour, et.fk_user, et.note as time_note,";
887 if ($canreadsalary) {
888 $sql .= " et.thm,";
889 }
890 $sql .= " u.login as user_login, u.firstname as user_firstname, u.lastname as user_lastname,";
891 $sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_title,";
892 $sql .= " t.rowid as task_id, t.ref as task_ref, t.label as task_label,";
893 $sql .= " s.rowid as soc_id, s.nom as soc_name";
894 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
895 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."projet_task as t ON (t.fk_projet = p.rowid)";
896 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_time as et ON (et.fk_element = t.rowid AND et.elementtype = 'task')";
897 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = p.fk_soc)";
898 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."user AS u ON (u.rowid = et.fk_user)";
899 $sql .= ' WHERE t.entity IN ('.getEntity('project').')';
900 if ($socids) {
901 $sql .= " AND p.fk_soc IN (".$this->db->sanitize($socids).")";
902 }
903 // If user has no permission to see all projects, we force the search on projects he is allowed to see only (public projects or projects he is a contact of), like the list.php page does
904 if (!DolibarrApiAccess::$user->hasRight('projet', 'all', 'lire')) {
905 $projectsListId = $this->project->getProjectsAuthorizedForUser(DolibarrApiAccess::$user, 0, 1, 0);
906 $sql .= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
907 }
908
909 // Search on sale representative
910 if ($search_sale && $search_sale != '-1') {
911 if ($search_sale == -2) {
912 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
913 } elseif ($search_sale > 0) {
914 $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).")";
915 }
916 }
917 // Select projects of given category
918 if ($category > 0) {
919 $sql .= " AND c.fk_categorie = ".((int) $category)." AND c.fk_project = t.rowid ";
920 }
921
922 // Add sql filters
923 if ($sqlfilters) {
924 $errormessage = '';
925 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
926 if ($errormessage) {
927 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
928 }
929 }
930
931 //this query will return total orders with the filters given
932 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
933
934 $sql .= $this->db->order($sortfield, $sortorder);
935 if ($limit) {
936 if ($page < 0) {
937 $page = 0;
938 }
939 $offset = $limit * $page;
940
941 $sql .= $this->db->plimit($limit + 1, $offset);
942 }
943
944 dol_syslog("API Rest request");
945 $result = $this->db->query($sql);
946 $obj_ret = array();
947 if ($result) {
948 $num = $this->db->num_rows($result);
949 $min = min($num, ($limit <= 0 ? $num : $limit));
950 $i = 0;
951 while ($i < $min) {
952 $obj = $this->db->fetch_object($result);
953 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($obj), $properties);
954 $i++;
955 }
956 } else {
957 throw new RestException(503, 'Error when retrieve timestamp list : '.$this->db->lasterror());
958 }
959
960
961 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
962 if ($pagination_data) {
963 $totalsResult = $this->db->query($sqlTotals);
964 $total = $this->db->fetch_object($totalsResult)->total;
965
966 $tmp = $obj_ret;
967 $obj_ret['data'] = $tmp;
968 $obj_ret['pagination'] = [
969 'total' => (int) $total,
970 'page' => $page, //count starts from 0
971 'page_count' => ceil((int) $total / $limit),
972 'limit' => $limit
973 ];
974 }
975
976 return $obj_ret;
977 }
978
979 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
989 protected function _cleanObjectDatas($object)
990 {
991 // phpcs:enable
992 $object = parent::_cleanObjectDatas($object);
993
994 unset($object->datec);
995 unset($object->datem);
996 unset($object->barcode_type);
997 unset($object->barcode_type_code);
998 unset($object->barcode_type_label);
999 unset($object->barcode_type_coder);
1000 unset($object->cond_reglement_id);
1001 unset($object->cond_reglement);
1002 unset($object->fk_delivery_address);
1003 unset($object->shipping_method_id);
1004 unset($object->fk_account);
1005 unset($object->note);
1006 unset($object->fk_incoterms);
1007 unset($object->label_incoterms);
1008 unset($object->location_incoterms);
1009 unset($object->name);
1010 unset($object->lastname);
1011 unset($object->firstname);
1012 unset($object->civility_id);
1013 unset($object->mode_reglement_id);
1014 unset($object->country);
1015 unset($object->country_id);
1016 unset($object->country_code);
1017
1018 unset($object->weekWorkLoad);
1019 unset($object->weekWorkLoad);
1020
1021 //unset($object->lines); // for task we use timespent_lines, but for project we use lines
1022
1023 unset($object->total_ht);
1024 unset($object->total_tva);
1025 unset($object->total_localtax1);
1026 unset($object->total_localtax2);
1027 unset($object->total_ttc);
1028
1029 unset($object->comments);
1030
1031 return $object;
1032 }
1033
1041 private function _validate($data)
1042 {
1043 $object = array();
1044 foreach (self::$FIELDS as $field) {
1045 if (!isset($data[$field])) {
1046 throw new RestException(400, "$field field missing");
1047 }
1048 $object[$field] = $data[$field];
1049 }
1050 return $object;
1051 }
1052
1053
1054
1055
1070 public function getContacts($id, $type = '')
1071 {
1072 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
1073 throw new RestException(403);
1074 }
1075
1076 $result = $this->project->fetch($id);
1077 if (!$result) {
1078 throw new RestException(404, 'Project not found');
1079 }
1080
1081 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
1082 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
1083 }
1084
1085 $contacts = $this->project->liste_contact(-1, 'external', 0, $type);
1086 $socpeoples = $this->project->liste_contact(-1, 'internal', 0, $type);
1087
1088 $contacts = array_merge($contacts, $socpeoples);
1089
1090 return $contacts;
1091 }
1092
1113 public function addToContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0, $affect_to_tasks = null)
1114 {
1115 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
1116 throw new RestException(403);
1117 }
1118
1119 $result = $this->project->fetch($id);
1120 if (!$result) {
1121 throw new RestException(404, 'Project not found');
1122 }
1123
1124 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
1125 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
1126 }
1127
1128 // Ajouter le contact au projet
1129 $result = $this->project->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
1130 if ($result <= 0) {
1131 throw new RestException(500, 'Error : ' . $this->project->error . 'result :' . $result);
1132 }
1133
1134 // If requested, add the contact to tasks
1135 if ($affect_to_tasks !== null) {
1136 $this->project->getLinesArray(DolibarrApiAccess::$user);
1137 $taskContactType = ($type_contact == 'PROJECTLEADER' ? 'TASKEXECUTIVE' : 'TASKCONTRIBUTOR');
1138
1139 foreach ($this->project->lines as $task) {
1140 // If $affect_to_tasks is empty, assign to all tasks
1141 // Otherwise, check if the task is in the list
1142 if (empty($affect_to_tasks) || in_array($task->id, $affect_to_tasks)) {
1143 $result = $task->add_contact($fk_socpeople, $taskContactType, $source, $notrigger);
1144 if ($result < 0) {
1145 throw new RestException(500, 'Error adding contact to task '.$task->id.': '.$task->error);
1146 }
1147 }
1148 }
1149 }
1150
1151 $result = $this->project->fetch($id);
1152 if (!$result) {
1153 throw new RestException(404, 'Project not found');
1154 }
1155
1156 return $this->_cleanObjectDatas($this->project);
1157 }
1173 public function deleteToContact($id, $contactid, $type)
1174 {
1175 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
1176 throw new RestException(403);
1177 }
1178
1179 $result = $this->project->fetch($id);
1180 if (!$result) {
1181 throw new RestException(404, 'Project not found');
1182 }
1183
1184 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
1185 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
1186 }
1187
1188 foreach (array('internal', 'external') as $source) {
1189 $contacts = $this->project->liste_contact(-1, $source);
1190
1191 foreach ($contacts as $contact) {
1192 if ($contact['id'] == $contactid && $contact['code'] == $type) {
1193 $result = $this->project->delete_contact($contact['rowid']);
1194 if (!$result) {
1195 throw new RestException(500, 'Error when deleted the contact');
1196 }
1197 break 2;
1198 }
1199 }
1200 }
1201
1202 return $this->_cleanObjectDatas($this->project);
1203 }
1204
1216 public function getTimespent($id)
1217 {
1218 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
1219 throw new RestException(403);
1220 }
1221
1222 $result = $this->project->fetch($id);
1223 if (!$result) {
1224 throw new RestException(404, 'Project not found');
1225 }
1226
1227 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
1228 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
1229 }
1230
1231
1232 $this->project->getLinesArray(DolibarrApiAccess::$user);
1233 $allTimespent = array();
1234 foreach ($this->project->lines as $task) {
1235 $allTimespent[] = $task->getSummaryOfTimeSpent();
1236 //var_dump($taskTimespent);
1237 //foreach ($taskTimespent as $time) {
1238 // $this->_cleanObjectDatas($time);
1239
1240 //}
1241 }
1242
1243 return $allTimespent;
1244 }
1245 // TODO
1246 // getSummaryOfTimeSpent
1247}
$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 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 projects.
addContact($id, $fk_socpeople, $type_contact, $source, $notrigger=0)
Adds a contact to an project.
post($request_data=null)
Create project object.
addToContact($id, $fk_socpeople, $type_contact, $source, $notrigger=0, $affect_to_tasks=null)
Adds a contact to a project.
getByMsgId($email_msgid)
Get properties of a project object.
getLines($id, $includetimespent=0)
Get tasks of a project.
validate($id, $notrigger=0)
Validate a project.
_validate($data)
Validate fields before create or update object.
getByRef($ref)
Get properties of a project object.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $category=0, $sqlfilters='', $properties='', $pagination_data=false)
List projects.
getTimespent($id)
Get timespent of a project (from all its tasks)
__construct()
Constructor.
deleteToContact($id, $contactid, $type)
Delete a contact type of given project.
put($id, $request_data=null)
Add a task to given project.
listTimespent($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $category=0, $sqlfilters='', $properties='', $pagination_data=false)
Get all timespent.
deleteContact($id, $contactid, $type)
Delete a contact type of given project.
getByRefExt($ref_ext)
Get properties of a project object.
getRoles($id, $userid=0)
Get roles a user is assigned to a project with.
getContacts($id, $type='')
Get contacts of given project.
Class to manage tasks.
Class to manage Dolibarr users.
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.
dol_now($mode='gmt')
Return date for now.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
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.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.