dolibarr 21.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 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20use Luracast\Restler\RestException;
21
22require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
23require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
24
31class Projects extends DolibarrApi
32{
36 public static $FIELDS = array(
37 'ref',
38 'title'
39 );
40
44 public $project;
45
49 public $task;
50
51
55 public function __construct()
56 {
57 global $db, $conf;
58 $this->db = $db;
59 $this->project = new Project($this->db);
60 $this->task = new Task($this->db);
61 }
62
73 public function get($id)
74 {
75 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
76 throw new RestException(403);
77 }
78
79 $result = $this->project->fetch($id);
80 if (!$result) {
81 throw new RestException(404, 'Project with supplied id not found');
82 }
83
84 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
85 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
86 }
87
88 $this->project->fetchObjectLinked();
89 return $this->_cleanObjectDatas($this->project);
90 }
91
104 public function getByRef($ref)
105 {
106 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
107 throw new RestException(403);
108 }
109
110 $result = $this->project->fetch(0, $ref);
111 if (!$result) {
112 throw new RestException(404, 'Project with supplied ref not found');
113 }
114
115 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
116 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
117 }
118
119 $this->project->fetchObjectLinked();
120 return $this->_cleanObjectDatas($this->project);
121 }
122
135 public function getByRefExt($ref_ext)
136 {
137 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
138 throw new RestException(403);
139 }
140
141 $result = $this->project->fetch(0, '', $ref_ext);
142 if (!$result) {
143 throw new RestException(404, 'Project with supplied ref_ext not found');
144 }
145
146 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
147 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
148 }
149
150 $this->project->fetchObjectLinked();
151 return $this->_cleanObjectDatas($this->project);
152 }
153
166 public function getByMsgId($email_msgid)
167 {
168 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
169 throw new RestException(403);
170 }
171
172 $result = $this->project->fetch(0, '', '', $email_msgid);
173 if (!$result) {
174 throw new RestException(404, 'Project with supplied email_msgid not found');
175 }
176
177 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
178 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
179 }
180
181 $this->project->fetchObjectLinked();
182 return $this->_cleanObjectDatas($this->project);
183 }
184
201 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
202 {
203 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
204 throw new RestException(403);
205 }
206
207 $obj_ret = array();
208
209 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
210 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
211
212 // If the internal user must only see his customers, force searching by him
213 $search_sale = 0;
214 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
215 $search_sale = DolibarrApiAccess::$user->id;
216 }
217
218 $sql = "SELECT t.rowid";
219 $sql .= " FROM ".MAIN_DB_PREFIX."projet as t";
220 $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
221 if ($category > 0) {
222 $sql .= ", ".MAIN_DB_PREFIX."categorie_project as c";
223 }
224 $sql .= ' WHERE t.entity IN ('.getEntity('project').')';
225 if ($socids) {
226 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
227 }
228 // Search on sale representative
229 if ($search_sale && $search_sale != '-1') {
230 if ($search_sale == -2) {
231 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
232 } elseif ($search_sale > 0) {
233 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
234 }
235 }
236 // Select projects of given category
237 if ($category > 0) {
238 $sql .= " AND c.fk_categorie = ".((int) $category)." AND c.fk_project = t.rowid ";
239 }
240 // Add sql filters
241 if ($sqlfilters) {
242 $errormessage = '';
243 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
244 if ($errormessage) {
245 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
246 }
247 }
248
249 //this query will return total orders with the filters given
250 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
251
252 $sql .= $this->db->order($sortfield, $sortorder);
253 if ($limit) {
254 if ($page < 0) {
255 $page = 0;
256 }
257 $offset = $limit * $page;
258
259 $sql .= $this->db->plimit($limit + 1, $offset);
260 }
261
262 dol_syslog("API Rest request");
263 $result = $this->db->query($sql);
264
265 if ($result) {
266 $num = $this->db->num_rows($result);
267 $min = min($num, ($limit <= 0 ? $num : $limit));
268 $i = 0;
269 while ($i < $min) {
270 $obj = $this->db->fetch_object($result);
271 $project_static = new Project($this->db);
272 if ($project_static->fetch($obj->rowid)) {
273 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($project_static), $properties);
274 }
275 $i++;
276 }
277 } else {
278 throw new RestException(503, 'Error when retrieve project list : '.$this->db->lasterror());
279 }
280
281 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
282 if ($pagination_data) {
283 $totalsResult = $this->db->query($sqlTotals);
284 $total = $this->db->fetch_object($totalsResult)->total;
285
286 $tmp = $obj_ret;
287 $obj_ret = [];
288
289 $obj_ret['data'] = $tmp;
290 $obj_ret['pagination'] = [
291 'total' => (int) $total,
292 'page' => $page, //count starts from 0
293 'page_count' => ceil((int) $total / $limit),
294 'limit' => $limit
295 ];
296 }
297
298 return $obj_ret;
299 }
300
307 public function post($request_data = null)
308 {
309 global $conf;
310 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
311 throw new RestException(403, "Insuffisant rights");
312 }
313 // Check mandatory fields
314 $result = $this->_validate($request_data);
315
316 foreach ($request_data as $field => $value) {
317 if ($field === 'caller') {
318 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
319 $this->project->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
320 continue;
321 }
322
323 $this->project->$field = $this->_checkValForAPI($field, $value, $this->project);
324 }
325 /*if (isset($request_data["lines"])) {
326 $lines = array();
327 foreach ($request_data["lines"] as $line) {
328 array_push($lines, (object) $line);
329 }
330 $this->project->lines = $lines;
331 }*/
332
333 // Auto-generate the "ref" field if it is set to "auto"
334 if ($this->project->ref == -1 || $this->project->ref === 'auto') {
335 $reldir = '';
336 $defaultref = '';
337 $file = '';
338 $classname = '';
339 $filefound = 0;
340 $modele = getDolGlobalString('PROJECT_ADDON', 'mod_project_simple');
341
342 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
343 foreach ($dirmodels as $reldir) {
344 $file = dol_buildpath($reldir."core/modules/project/".$modele.'.php', 0);
345 if (file_exists($file)) {
346 $filefound = 1;
347 $classname = $modele;
348 break;
349 }
350 }
351 if ($filefound && !empty($classname)) {
352 $result = dol_include_once($reldir . "core/modules/project/" . $modele . '.php');
353 if ($result !== false && class_exists($classname)) {
354 $modProject = new $classname();
355 $defaultref = $modProject->getNextValue(null, $this->project);
356 } else {
357 dol_syslog("Failed to include module file or invalid classname: " . $reldir . "core/modules/project/" . $modele . '.php', LOG_ERR);
358 }
359 } else {
360 dol_syslog("Module file not found or classname is empty: " . $modele, LOG_ERR);
361 }
362
363 if (is_numeric($defaultref) && $defaultref <= 0) {
364 $defaultref = '';
365 }
366
367 if (empty($defaultref)) {
368 $defaultref = 'PJ' . dol_print_date(dol_now(), 'dayrfc');
369 }
370
371 $this->project->ref = $defaultref;
372 }
373
374 if ($this->project->create(DolibarrApiAccess::$user) < 0) {
375 throw new RestException(500, "Error creating project", array_merge(array($this->project->error), $this->project->errors));
376 }
377
378 return $this->project->id;
379 }
380
391 public function getLines($id, $includetimespent = 0)
392 {
393 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
394 throw new RestException(403);
395 }
396
397 $result = $this->project->fetch($id);
398 if (!$result) {
399 throw new RestException(404, 'Project not found');
400 }
401
402 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
403 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
404 }
405 $this->project->getLinesArray(DolibarrApiAccess::$user);
406 $result = array();
407 foreach ($this->project->lines as $line) { // $line is a task
408 if ($includetimespent == 1) {
409 $timespent = $line->getSummaryOfTimeSpent(0);
410 }
411 if ($includetimespent == 2) {
412 $timespent = $line->fetchTimeSpentOnTask();
413 }
414 array_push($result, $this->_cleanObjectDatas($line));
415 }
416 return $result;
417 }
418
419
429 public function getRoles($id, $userid = 0)
430 {
431 global $db;
432
433 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
434 throw new RestException(403);
435 }
436
437 $result = $this->project->fetch($id);
438 if (!$result) {
439 throw new RestException(404, 'Project not found');
440 }
441
442 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
443 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
444 }
445
446 require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
447 $taskstatic = new Task($this->db);
448 $userp = DolibarrApiAccess::$user;
449 if ($userid > 0) {
450 $userp = new User($this->db);
451 $userp->fetch($userid);
452 }
453 $this->project->roles = $taskstatic->getUserRolesForProjectsOrTasks($userp, null, $id, 0);
454 $result = array();
455 foreach ($this->project->roles as $line) {
456 array_push($result, $this->_cleanObjectDatas($line));
457 }
458
459 return $result;
460 }
461
462
473 /*
474 public function postLine($id, $request_data = null)
475 {
476 if(! DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
477 throw new RestException(403);
478 }
479
480 $result = $this->project->fetch($id);
481 if( ! $result ) {
482 throw new RestException(404, 'Project not found');
483 }
484
485 if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
486 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
487 }
488
489 $request_data = (object) $request_data;
490
491 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
492
493 $updateRes = $this->project->addline(
494 $request_data->desc,
495 $request_data->subprice,
496 $request_data->qty,
497 $request_data->tva_tx,
498 $request_data->localtax1_tx,
499 $request_data->localtax2_tx,
500 $request_data->fk_product,
501 $request_data->remise_percent,
502 $request_data->info_bits,
503 $request_data->fk_remise_except,
504 'HT',
505 0,
506 $request_data->date_start,
507 $request_data->date_end,
508 $request_data->product_type,
509 $request_data->rang,
510 $request_data->special_code,
511 $fk_parent_line,
512 $request_data->fk_fournprice,
513 $request_data->pa_ht,
514 $request_data->label,
515 $request_data->array_options,
516 $request_data->fk_unit,
517 $this->element,
518 $request_data->id
519 );
520
521 if ($updateRes > 0) {
522 return $updateRes;
523
524 }
525 return false;
526 }
527 */
528
540 /*
541 public function putLine($id, $lineid, $request_data = null)
542 {
543 if(! DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
544 throw new RestException(403);
545 }
546
547 $result = $this->project->fetch($id);
548 if( ! $result ) {
549 throw new RestException(404, 'Project not found');
550 }
551
552 if( ! DolibarrApi::_checkAccessToResource('project',$this->project->id)) {
553 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
554 }
555
556 $request_data = (object) $request_data;
557
558 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
559
560 $updateRes = $this->project->updateline(
561 $lineid,
562 $request_data->desc,
563 $request_data->subprice,
564 $request_data->qty,
565 $request_data->remise_percent,
566 $request_data->tva_tx,
567 $request_data->localtax1_tx,
568 $request_data->localtax2_tx,
569 'HT',
570 $request_data->info_bits,
571 $request_data->date_start,
572 $request_data->date_end,
573 $request_data->product_type,
574 $request_data->fk_parent_line,
575 0,
576 $request_data->fk_fournprice,
577 $request_data->pa_ht,
578 $request_data->label,
579 $request_data->special_code,
580 $request_data->array_options,
581 $request_data->fk_unit
582 );
583
584 if ($updateRes > 0) {
585 $result = $this->get($id);
586 unset($result->line);
587 return $this->_cleanObjectDatas($result);
588 }
589 return false;
590 }*/
591
592
593
601 public function put($id, $request_data = null)
602 {
603 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
604 throw new RestException(403);
605 }
606
607 $result = $this->project->fetch($id);
608 if ($result <= 0) {
609 throw new RestException(404, 'Project not found');
610 }
611
612 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
613 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
614 }
615 foreach ($request_data as $field => $value) {
616 if ($field == 'id') {
617 continue;
618 }
619 if ($field === 'caller') {
620 // 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
621 $this->project->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
622 continue;
623 }
624 if ($field == 'array_options' && is_array($value)) {
625 foreach ($value as $index => $val) {
626 $this->project->array_options[$index] = $this->_checkValForAPI($field, $val, $this->project);
627 }
628 continue;
629 }
630
631 $this->project->$field = $this->_checkValForAPI($field, $value, $this->project);
632 }
633
634 if ($this->project->update(DolibarrApiAccess::$user) >= 0) {
635 return $this->get($id);
636 } else {
637 throw new RestException(500, $this->project->error);
638 }
639 }
640
648 public function delete($id)
649 {
650 if (!DolibarrApiAccess::$user->hasRight('projet', 'supprimer')) {
651 throw new RestException(403);
652 }
653 $result = $this->project->fetch($id);
654 if (!$result) {
655 throw new RestException(404, 'Project not found');
656 }
657
658 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
659 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
660 }
661
662 if (!$this->project->delete(DolibarrApiAccess::$user)) {
663 throw new RestException(500, 'Error when delete project : '.$this->project->error);
664 }
665
666 return array(
667 'success' => array(
668 'code' => 200,
669 'message' => 'Project deleted'
670 )
671 );
672 }
673
692 public function validate($id, $notrigger = 0)
693 {
694 if (!DolibarrApiAccess::$user->hasRight('projet', 'creer')) {
695 throw new RestException(403);
696 }
697 $result = $this->project->fetch($id);
698 if (!$result) {
699 throw new RestException(404, 'Project not found');
700 }
701
702 if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) {
703 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
704 }
705
706 $result = $this->project->setValid(DolibarrApiAccess::$user, $notrigger);
707 if ($result == 0) {
708 throw new RestException(304, 'Error nothing done. May be object is already validated');
709 }
710 if ($result < 0) {
711 throw new RestException(500, 'Error when validating Project: '.$this->project->error);
712 }
713
714 return array(
715 'success' => array(
716 'code' => 200,
717 'message' => 'Project validated'
718 )
719 );
720 }
721
722
723 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
730 protected function _cleanObjectDatas($object)
731 {
732 // phpcs:enable
733 $object = parent::_cleanObjectDatas($object);
734
735 unset($object->datec);
736 unset($object->datem);
737 unset($object->barcode_type);
738 unset($object->barcode_type_code);
739 unset($object->barcode_type_label);
740 unset($object->barcode_type_coder);
741 unset($object->cond_reglement_id);
742 unset($object->cond_reglement);
743 unset($object->fk_delivery_address);
744 unset($object->shipping_method_id);
745 unset($object->fk_account);
746 unset($object->note);
747 unset($object->fk_incoterms);
748 unset($object->label_incoterms);
749 unset($object->location_incoterms);
750 unset($object->name);
751 unset($object->lastname);
752 unset($object->firstname);
753 unset($object->civility_id);
754 unset($object->mode_reglement_id);
755 unset($object->country);
756 unset($object->country_id);
757 unset($object->country_code);
758
759 unset($object->weekWorkLoad);
760 unset($object->weekWorkLoad);
761
762 //unset($object->lines); // for task we use timespent_lines, but for project we use lines
763
764 unset($object->total_ht);
765 unset($object->total_tva);
766 unset($object->total_localtax1);
767 unset($object->total_localtax2);
768 unset($object->total_ttc);
769
770 unset($object->comments);
771
772 return $object;
773 }
774
782 private function _validate($data)
783 {
784 $object = array();
785 foreach (self::$FIELDS as $field) {
786 if (!isset($data[$field])) {
787 throw new RestException(400, "$field field missing");
788 }
789 $object[$field] = $data[$field];
790 }
791 return $object;
792 }
793
794
795 // TODO
796 // getSummaryOfTimeSpent
797}
$id
Definition account.php:39
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:58
Class for API REST v1.
Definition api.class.php:30
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:82
Class to manage projects.
post($request_data=null)
Create project object.
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.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $category=0, $sqlfilters='', $properties='', $pagination_data=false)
List projects.
__construct()
Constructor.
put($id, $request_data=null)
Add a task to 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.
Class to manage tasks.
Class to manage Dolibarr users.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
dol_now($mode='auto')
Return date for now.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
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_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.