dolibarr 25.0.0-alpha
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';
27require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
28
36class Projects extends DolibarrApi
37{
41 public static $FIELDS = array(
42 'ref',
43 'title'
44 );
45
49 public $project;
50
54 public $task;
55
56
60 public function __construct()
61 {
62 global $db, $conf;
63 $this->db = $db;
64 $this->project = new Project($this->db);
65 $this->task = new Task($this->db);
66 }
67
79 public function get($id)
80 {
81 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
82 throw new RestException(403);
83 }
84
85 $result = $this->project->fetch($id);
86 if (!$result) {
87 throw new RestException(404, 'Project with supplied id not found');
88 }
89
90 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
91 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
92 }
93
94 $this->project->fetchObjectLinked();
95 return $this->_cleanObjectDatas($this->project);
96 }
97
111 public function getByRef($ref)
112 {
113 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
114 throw new RestException(403);
115 }
116
117 $result = $this->project->fetch(0, $ref);
118 if (!$result) {
119 throw new RestException(404, 'Project with supplied ref not found');
120 }
121
122 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
123 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
124 }
125
126 $this->project->fetchObjectLinked();
127 return $this->_cleanObjectDatas($this->project);
128 }
129
143 public function getByRefExt($ref_ext)
144 {
145 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
146 throw new RestException(403);
147 }
148
149 $result = $this->project->fetch(0, '', $ref_ext);
150 if (!$result) {
151 throw new RestException(404, 'Project with supplied ref_ext not found');
152 }
153
154 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
155 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
156 }
157
158 $this->project->fetchObjectLinked();
159 return $this->_cleanObjectDatas($this->project);
160 }
161
175 public function getByMsgId($email_msgid)
176 {
177 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
178 throw new RestException(403);
179 }
180
181 $result = $this->project->fetch(0, '', '', $email_msgid);
182 if (!$result) {
183 throw new RestException(404, 'Project with supplied email_msgid not found');
184 }
185
186 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
187 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
188 }
189
190 $this->project->fetchObjectLinked();
191 return $this->_cleanObjectDatas($this->project);
192 }
193
213 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
214 {
215 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
216 throw new RestException(403);
217 }
218
219 $obj_ret = array();
220
221 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
222 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
223
224 // If the internal user must only see his customers, force searching by him
225 $search_sale = 0;
226 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
227 $search_sale = DolibarrApiAccess::$user->id;
228 }
229
230 $sql = "SELECT t.rowid";
231 $sql .= " FROM " . MAIN_DB_PREFIX . "projet as t";
232 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe AS s ON (s.rowid = t.fk_soc)";
233 $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
234 if ($category > 0) {
235 $sql .= ", " . MAIN_DB_PREFIX . "categorie_project as c";
236 }
237 $sql .= ' WHERE t.entity IN (' . getEntity('project') . ')';
238 if ($socids) {
239 $sql .= " AND t.fk_soc IN (" . $this->db->sanitize($socids) . ")";
240 }
241 // 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
242 if (!DolibarrApiAccess::$user->hasRight('projet', 'all', 'lire')) {
243 $projectsListId = $this->project->getProjectsAuthorizedForUser(DolibarrApiAccess::$user, 0, 1, 0);
244 $sql .= " AND t.rowid IN (" . $this->db->sanitize($projectsListId) . ")";
245 }
246 // Search on sale representative
247 if ($search_sale && $search_sale != '-1') {
248 if ($search_sale == -2) {
249 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', 0, 1);
250 } elseif ($search_sale > 0) {
251 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', (int) $search_sale);
252 }
253 }
254 // Select projects of given category
255 if ($category > 0) {
256 $sql .= " AND c.fk_categorie = " . ((int) $category) . " AND c.fk_project = t.rowid ";
257 }
258 // Add sql filters
259 if ($sqlfilters) {
260 $errormessage = '';
261 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
262 if ($errormessage) {
263 throw new RestException(400, 'Error when validating parameter sqlfilters -> ' . $errormessage);
264 }
265 }
266
267 //this query will return total orders with the filters given
268 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
269
270 $sql .= $this->db->order($sortfield, $sortorder);
271 if ($limit) {
272 if ($page < 0) {
273 $page = 0;
274 }
275 $offset = $limit * $page;
276
277 $sql .= $this->db->plimit($limit + 1, $offset);
278 }
279
280 dol_syslog("API Rest request");
281 $result = $this->db->query($sql);
282
283 if ($result) {
284 $num = $this->db->num_rows($result);
285 $min = min($num, ($limit <= 0 ? $num : $limit));
286 $i = 0;
287 while ($i < $min) {
288 $obj = $this->db->fetch_object($result);
289 $project_static = new Project($this->db);
290 if ($project_static->fetch($obj->rowid)) {
291 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($project_static), $properties);
292 }
293 $i++;
294 }
295 } else {
296 throw new RestException(503, 'Error when retrieve project list : ' . $this->db->lasterror());
297 }
298
299 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
300 if ($pagination_data) {
301 $totalsResult = $this->db->query($sqlTotals);
302 $total = $this->db->fetch_object($totalsResult)->total;
303
304 $tmp = $obj_ret;
305 $obj_ret = [];
306
307 $obj_ret['data'] = $tmp;
308 $obj_ret['pagination'] = [
309 'total' => (int) $total,
310 'page' => $page, //count starts from 0
311 'page_count' => ceil((int) $total / $limit),
312 'limit' => $limit
313 ];
314 }
315
316 return $obj_ret;
317 }
318
328 public function post($request_data = null)
329 {
330 global $conf;
331 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
332 throw new RestException(403, "Insufficiant rights");
333 }
334 // Check mandatory fields
335 $result = $this->_validate($request_data);
336
337 foreach ($request_data as $field => $value) {
338 if ($field === 'caller') {
339 // 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
340 $this->project->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
341 continue;
342 }
343
344 $this->project->$field = $this->_checkValForAPI($field, $value, $this->project);
345 }
346 /*if (isset($request_data["lines"])) {
347 $lines = array();
348 foreach ($request_data["lines"] as $line) {
349 array_push($lines, (object) $line);
350 }
351 $this->project->lines = $lines;
352 }*/
353
354 // Auto-generate the "ref" field if it is set to "auto"
355 if ($this->project->ref == -1 || $this->project->ref === 'auto') {
356 $reldir = '';
357 $defaultref = '';
358 $file = '';
359 $classname = '';
360 $filefound = 0;
361 $modele = getDolGlobalString('PROJECT_ADDON', 'mod_project_simple');
362
363 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
364 foreach ($dirmodels as $reldir) {
365 $file = dol_buildpath($reldir . "core/modules/project/" . $modele . '.php', 0);
366 if (file_exists($file)) {
367 $filefound = 1;
368 $classname = $modele;
369 break;
370 }
371 }
372 if ($filefound && !empty($classname)) {
373 $result = dol_include_once($reldir . "core/modules/project/" . $modele . '.php');
374 if ($result !== false && class_exists($classname)) {
375 $modProject = new $classname();
376 '@phan-var-force ModeleNumRefProjects $modProject';
377 $defaultref = $modProject->getNextValue(null, $this->project);
378 } else {
379 dol_syslog("Failed to include module file or invalid classname: " . $reldir . "core/modules/project/" . $modele . '.php', LOG_ERR);
380 }
381 } else {
382 dol_syslog("Module file not found or classname is empty: " . $modele, LOG_ERR);
383 }
384
385 if (is_numeric($defaultref) && $defaultref <= 0) {
386 $defaultref = '';
387 }
388
389 if (empty($defaultref)) {
390 $defaultref = 'PJ' . dol_print_date(dol_now(), 'dayrfc');
391 }
392
393 $this->project->ref = $defaultref;
394 }
395
396 if ($this->project->create(DolibarrApiAccess::$user) < 0) {
397 throw new RestException(500, "Error creating project", array_merge(array($this->project->error), $this->project->errors));
398 }
399
400 return $this->project->id;
401 }
402
422 public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0)
423 {
424 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
425 throw new RestException(403);
426 }
427
428 $result = $this->project->fetch($id);
429 if (!$result) {
430 throw new RestException(404, 'project not found');
431 }
432
433 if (!DolibarrApi::_checkAccessToResource('ficheinter', $this->project->id)) {
434 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
435 }
436
437 $result = $this->project->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
438 if ($result < 0) {
439 throw new RestException(500, 'Error : ' . $this->project->errorsToString());
440 }
441
442 return $this->_cleanObjectDatas($this->project);
443 }
444
460 public function deleteContact($id, $contactid, $type)
461 {
462 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
463 throw new RestException(403);
464 }
465
466 $result = $this->project->fetch($id);
467
468 if (!$result) {
469 throw new RestException(404, 'Project not found');
470 }
471
472 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
473 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
474 }
475 foreach (array('internal', 'external') as $source) {
476 $contacts = $this->project->liste_contact(-1, $source);
477
478 foreach ($contacts as $contact) {
479 if ($contact['id'] == $contactid && $contact['code'] == $type) {
480 $result = $this->project->delete_contact($contact['rowid']);
481 if (!$result) {
482 throw new RestException(500, 'Error when deleted the contact');
483 }
484 }
485 }
486 }
487 return $this->_cleanObjectDatas($this->project);
488 }
502 public function getLines($id, $includetimespent = 0)
503 {
504 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
505 throw new RestException(403);
506 }
507
508 $result = $this->project->fetch($id);
509 if (!$result) {
510 throw new RestException(404, 'Project not found');
511 }
512
513 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
514 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
515 }
516 $this->project->getLinesArray(DolibarrApiAccess::$user);
517 $result = array();
518 foreach ($this->project->lines as $line) { // $line is a task
519 if ($includetimespent == 1) {
520 $timespent = $line->getSummaryOfTimeSpent(0);
521 }
522 if ($includetimespent == 2) {
523 $timespent = $line->fetchTimeSpentOnTask();
524 }
525 array_push($result, $this->_cleanObjectDatas($line));
526 }
527 return $result;
528 }
529
530
543 public function getRoles($id, $userid = 0)
544 {
545 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
546 throw new RestException(403);
547 }
548
549 $result = $this->project->fetch($id);
550 if (!$result) {
551 throw new RestException(404, 'Project not found');
552 }
553
554 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
555 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
556 }
557
558 require_once DOL_DOCUMENT_ROOT . '/projet/class/task.class.php';
559 $taskstatic = new Task($this->db);
560 $userp = DolibarrApiAccess::$user;
561 if ($userid > 0) {
562 $userp = new User($this->db);
563 $userp->fetch($userid);
564 }
565 $this->project->roles = $taskstatic->getUserRolesForProjectsOrTasks($userp, null, (string) $id, 0);
566 $result = array();
567 foreach ($this->project->roles as $line) {
568 array_push($result, $this->_cleanObjectDatas($line));
569 }
570
571 return $result;
572 }
573
574
587 /*
588 public function postLine($id, $request_data = null)
589 {
590 if(! DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
591 throw new RestException(403);
592 }
593
594 $result = $this->project->fetch($id);
595 if( ! $result ) {
596 throw new RestException(404, 'Project not found');
597 }
598
599 if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
600 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
601 }
602
603 $request_data = (object) $request_data;
604
605 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
606
607 $updateRes = $this->project->addline(
608 $request_data->desc,
609 $request_data->subprice,
610 $request_data->qty,
611 $request_data->tva_tx,
612 $request_data->localtax1_tx,
613 $request_data->localtax2_tx,
614 $request_data->fk_product,
615 $request_data->remise_percent,
616 $request_data->info_bits,
617 $request_data->fk_remise_except,
618 'HT',
619 0,
620 $request_data->date_start,
621 $request_data->date_end,
622 $request_data->product_type,
623 $request_data->rang,
624 $request_data->special_code,
625 $fk_parent_line,
626 $request_data->fk_fournprice,
627 $request_data->pa_ht,
628 $request_data->label,
629 $request_data->array_options,
630 $request_data->fk_unit,
631 $this->element,
632 $request_data->id
633 );
634
635 if ($updateRes > 0) {
636 return $updateRes;
637
638 }
639 return false;
640 }
641 */
642
656 /*
657 public function putLine($id, $lineid, $request_data = null)
658 {
659 if(! DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
660 throw new RestException(403);
661 }
662
663 $result = $this->project->fetch($id);
664 if( ! $result ) {
665 throw new RestException(404, 'Project not found');
666 }
667
668 if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
669 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
670 }
671
672 $request_data = (object) $request_data;
673
674 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
675
676 $updateRes = $this->project->updateline(
677 $lineid,
678 $request_data->desc,
679 $request_data->subprice,
680 $request_data->qty,
681 $request_data->remise_percent,
682 $request_data->tva_tx,
683 $request_data->localtax1_tx,
684 $request_data->localtax2_tx,
685 'HT',
686 $request_data->info_bits,
687 $request_data->date_start,
688 $request_data->date_end,
689 $request_data->product_type,
690 $request_data->fk_parent_line,
691 0,
692 $request_data->fk_fournprice,
693 $request_data->pa_ht,
694 $request_data->label,
695 $request_data->special_code,
696 $request_data->array_options,
697 $request_data->fk_unit
698 );
699
700 if ($updateRes > 0) {
701 $result = $this->get($id);
702 unset($result->line);
703 return $this->_cleanObjectDatas($result);
704 }
705 return false;
706 }*/
707
708
709
722 public function put($id, $request_data = null)
723 {
724 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
725 throw new RestException(403);
726 }
727
728 $result = $this->project->fetch($id);
729 if ($result <= 0) {
730 throw new RestException(404, 'Project not found');
731 }
732
733 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
734 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
735 }
736 foreach ($request_data as $field => $value) {
737 if ($field == 'id') {
738 continue;
739 }
740 if ($field === 'caller') {
741 // 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
742 $this->project->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
743 continue;
744 }
745 if ($field == 'array_options' && is_array($value)) {
746 foreach ($value as $index => $val) {
747 $this->project->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->project);
748 }
749 continue;
750 }
751
752 $this->project->$field = $this->_checkValForAPI($field, $value, $this->project);
753 }
754
755 if ($this->project->update(DolibarrApiAccess::$user) >= 0) {
756 return $this->get($id);
757 } else {
758 throw new RestException(500, $this->project->errorsToString());
759 }
760 }
761
772 public function delete($id)
773 {
774 if (!DolibarrApiAccess::$user->hasRight('projet', 'supprimer')) {
775 throw new RestException(403);
776 }
777 $result = $this->project->fetch($id);
778 if (!$result) {
779 throw new RestException(404, 'Project not found');
780 }
781
782 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
783 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
784 }
785
786 if (!$this->project->delete(DolibarrApiAccess::$user)) {
787 throw new RestException(500, 'Error when delete project : ' . $this->project->errorsToString());
788 }
789
790 return array(
791 'success' => array(
792 'code' => 200,
793 'message' => 'Project deleted'
794 )
795 );
796 }
797
821 public function validate($id, $notrigger = 0)
822 {
823 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
824 throw new RestException(403);
825 }
826 $result = $this->project->fetch($id);
827 if (!$result) {
828 throw new RestException(404, 'Project not found');
829 }
830
831 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
832 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
833 }
834
835 $result = $this->project->setValid(DolibarrApiAccess::$user, $notrigger);
836 if ($result == 0) {
837 throw new RestException(304, 'Error nothing done. May be object is already validated');
838 }
839 if ($result < 0) {
840 throw new RestException(500, 'Error when validating Project: ' . $this->project->errorsToString());
841 }
842
843 return array(
844 'success' => array(
845 'code' => 200,
846 'message' => 'Project validated'
847 )
848 );
849 }
850
869 public function listTimespent($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
870 {
871 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
872 throw new RestException(403);
873 }
874
875 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
876 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
877
878 // If the internal user must only see his customers, force searching by him
879 $search_sale = 0;
880 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
881 $search_sale = DolibarrApiAccess::$user->id;
882 }
883
884 // 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)
885 $canreadsalary = ((isModEnabled('salaries') && DolibarrApiAccess::$user->hasRight('salaries', 'read')) || !isModEnabled('salaries'));
886
887 $sql = "SELECT et.rowid, et.element_duration, et.element_datehour, et.fk_user, et.note as time_note,";
888 if ($canreadsalary) {
889 $sql .= " et.thm,";
890 }
891 $sql .= " u.login as user_login, u.firstname as user_firstname, u.lastname as user_lastname,";
892 $sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_title,";
893 $sql .= " t.rowid as task_id, t.ref as task_ref, t.label as task_label,";
894 $sql .= " s.rowid as soc_id, s.nom as soc_name";
895 $sql .= " FROM ".MAIN_DB_PREFIX."projet as p";
896 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."projet_task as t ON (t.fk_projet = p.rowid)";
897 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_time as et ON (et.fk_element = t.rowid AND et.elementtype = 'task')";
898 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe AS s ON (s.rowid = p.fk_soc)";
899 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."user AS u ON (u.rowid = et.fk_user)";
900 $sql .= ' WHERE t.entity IN ('.getEntity('project').')';
901 if ($socids) {
902 $sql .= " AND p.fk_soc IN (".$this->db->sanitize($socids).")";
903 }
904 // 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
905 if (!DolibarrApiAccess::$user->hasRight('projet', 'all', 'lire')) {
906 $projectsListId = $this->project->getProjectsAuthorizedForUser(DolibarrApiAccess::$user, 0, 1, 0);
907 $sql .= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
908 }
909
910 // Search on sale representative
911 if ($search_sale && $search_sale != '-1') {
912 if ($search_sale == -2) {
913 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', 0, 1);
914 } elseif ($search_sale > 0) {
915 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', (int) $search_sale);
916 }
917 }
918 // Select projects of given category
919 if ($category > 0) {
920 $sql .= " AND c.fk_categorie = ".((int) $category)." AND c.fk_project = t.rowid ";
921 }
922
923 // Add sql filters
924 if ($sqlfilters) {
925 // List of properties we can't filter on, whatever are permissions (to avoid guess by search binary attack).
926 // This includes sensitive properties of table llx_user joined by the request
927 $forbiddenfilterfields = array(
928 'pass',
929 'pass_crypted',
930 'pass_temp',
931 'api_key',
932 'openid',
933 'national_registration_number',
934 'birth',
935 'address',
936 'personal_mobile',
937 'personal_email',
938 'note_private',
939 'iplastlogin',
940 'ippreviouslogin'
941 );
942 // Salary data of user is sensitive payroll data, so it is forbidden if the caller has no permission to read salaries (same rule as for the users API)
943 if (!$canreadsalary) {
944 $forbiddenfilterfields[] = 'salary';
945 $forbiddenfilterfields[] = 'salaryextra';
946 $forbiddenfilterfields[] = 'thm';
947 $forbiddenfilterfields[] = 'tjm';
948 }
949 $errormessage = '';
950 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage, 0, 0, 0, $forbiddenfilterfields);
951 if ($errormessage) {
952 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
953 }
954 }
955
956 //this query will return total orders with the filters given
957 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
958
959 $sql .= $this->db->order($sortfield, $sortorder);
960 if ($limit) {
961 if ($page < 0) {
962 $page = 0;
963 }
964 $offset = $limit * $page;
965
966 $sql .= $this->db->plimit($limit + 1, $offset);
967 }
968
969 dol_syslog("API Rest request");
970 $result = $this->db->query($sql);
971 $obj_ret = array();
972 if ($result) {
973 $num = $this->db->num_rows($result);
974 $min = min($num, ($limit <= 0 ? $num : $limit));
975 $i = 0;
976 while ($i < $min) {
977 $obj = $this->db->fetch_object($result);
978 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($obj), $properties);
979 $i++;
980 }
981 } else {
982 throw new RestException(503, 'Error when retrieve timestamp list : '.$this->db->lasterror());
983 }
984
985
986 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
987 if ($pagination_data) {
988 $totalsResult = $this->db->query($sqlTotals);
989 $total = $this->db->fetch_object($totalsResult)->total;
990
991 $tmp = $obj_ret;
992 $obj_ret['data'] = $tmp;
993 $obj_ret['pagination'] = [
994 'total' => (int) $total,
995 'page' => $page, //count starts from 0
996 'page_count' => ceil((int) $total / $limit),
997 'limit' => $limit
998 ];
999 }
1000
1001 return $obj_ret;
1002 }
1003
1004 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
1014 protected function _cleanObjectDatas($object)
1015 {
1016 // phpcs:enable
1017 $object = parent::_cleanObjectDatas($object);
1018
1019 unset($object->datec);
1020 unset($object->datem);
1021 unset($object->barcode_type);
1022 unset($object->barcode_type_code);
1023 unset($object->barcode_type_label);
1024 unset($object->barcode_type_coder);
1025 unset($object->cond_reglement_id);
1026 unset($object->cond_reglement);
1027 unset($object->fk_delivery_address);
1028 unset($object->shipping_method_id);
1029 unset($object->fk_account);
1030 unset($object->note);
1031 unset($object->fk_incoterms);
1032 unset($object->label_incoterms);
1033 unset($object->location_incoterms);
1034 unset($object->name);
1035 unset($object->lastname);
1036 unset($object->firstname);
1037 unset($object->civility_id);
1038 unset($object->mode_reglement_id);
1039 unset($object->country);
1040 unset($object->country_id);
1041 unset($object->country_code);
1042
1043 unset($object->weekWorkLoad);
1044
1045 //unset($object->lines); // for task we use timespent_lines, but for project we use lines
1046
1047 unset($object->total_ht);
1048 unset($object->total_tva);
1049 unset($object->total_localtax1);
1050 unset($object->total_localtax2);
1051 unset($object->total_ttc);
1052
1053 unset($object->comments);
1054
1055 return $object;
1056 }
1057
1065 private function _validate($data)
1066 {
1067 $object = array();
1068 foreach (self::$FIELDS as $field) {
1069 if (!isset($data[$field])) {
1070 throw new RestException(400, "$field field missing");
1071 }
1072 $object[$field] = $data[$field];
1073 }
1074 return $object;
1075 }
1076
1077
1078
1079
1094 public function getContacts($id, $type = '')
1095 {
1096 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
1097 throw new RestException(403);
1098 }
1099
1100 $result = $this->project->fetch($id);
1101 if (!$result) {
1102 throw new RestException(404, 'Project not found');
1103 }
1104
1105 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
1106 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
1107 }
1108
1109 $contacts = $this->project->liste_contact(-1, 'external', 0, $type);
1110 $socpeoples = $this->project->liste_contact(-1, 'internal', 0, $type);
1111
1112 $contacts = array_merge($contacts, $socpeoples);
1113
1114 return $contacts;
1115 }
1116
1137 public function addToContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0, $affect_to_tasks = null)
1138 {
1139 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
1140 throw new RestException(403);
1141 }
1142
1143 $result = $this->project->fetch($id);
1144 if (!$result) {
1145 throw new RestException(404, 'Project not found');
1146 }
1147
1148 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
1149 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
1150 }
1151
1152 // Ajouter le contact au projet
1153 $result = $this->project->add_contact($fk_socpeople, $type_contact, $source, $notrigger);
1154 if ($result <= 0) {
1155 throw new RestException(500, 'Error : ' . $this->project->error . 'result :' . $result);
1156 }
1157
1158 // If requested, add the contact to tasks
1159 if ($affect_to_tasks !== null) {
1160 $this->project->getLinesArray(DolibarrApiAccess::$user);
1161 $taskContactType = ($type_contact == 'PROJECTLEADER' ? 'TASKEXECUTIVE' : 'TASKCONTRIBUTOR');
1162
1163 foreach ($this->project->lines as $task) {
1164 // If $affect_to_tasks is empty, assign to all tasks
1165 // Otherwise, check if the task is in the list
1166 if (empty($affect_to_tasks) || in_array($task->id, $affect_to_tasks)) {
1167 $result = $task->add_contact($fk_socpeople, $taskContactType, $source, $notrigger);
1168 if ($result < 0) {
1169 throw new RestException(500, 'Error adding contact to task '.$task->id.': '.$task->errorsToString());
1170 }
1171 }
1172 }
1173 }
1174
1175 $result = $this->project->fetch($id);
1176 if (!$result) {
1177 throw new RestException(404, 'Project not found');
1178 }
1179
1180 return $this->_cleanObjectDatas($this->project);
1181 }
1197 public function deleteToContact($id, $contactid, $type)
1198 {
1199 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
1200 throw new RestException(403);
1201 }
1202
1203 $result = $this->project->fetch($id);
1204 if (!$result) {
1205 throw new RestException(404, 'Project not found');
1206 }
1207
1208 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
1209 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
1210 }
1211
1212 foreach (array('internal', 'external') as $source) {
1213 $contacts = $this->project->liste_contact(-1, $source);
1214
1215 foreach ($contacts as $contact) {
1216 if ($contact['id'] == $contactid && $contact['code'] == $type) {
1217 $result = $this->project->delete_contact($contact['rowid']);
1218 if (!$result) {
1219 throw new RestException(500, 'Error when deleted the contact');
1220 }
1221 break 2;
1222 }
1223 }
1224 }
1225
1226 return $this->_cleanObjectDatas($this->project);
1227 }
1228
1240 public function getTimespent($id)
1241 {
1242 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
1243 throw new RestException(403);
1244 }
1245
1246 $result = $this->project->fetch($id);
1247 if (!$result) {
1248 throw new RestException(404, 'Project not found');
1249 }
1250
1251 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
1252 throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
1253 }
1254
1255
1256 $this->project->getLinesArray(DolibarrApiAccess::$user);
1257 $allTimespent = array();
1258 foreach ($this->project->lines as $task) {
1259 $allTimespent[] = $task->getSummaryOfTimeSpent();
1260 //var_dump($taskTimespent);
1261 //foreach ($taskTimespent as $time) {
1262 // $this->_cleanObjectDatas($time);
1263
1264 //}
1265 }
1266
1267 return $allTimespent;
1268 }
1269 // TODO
1270 // getSummaryOfTimeSpent
1271}
$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 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.
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.