1<?php
2/* Copyright (C) 2015   Jean-François Ferry     <jfefe@aternatik.fr>
3 * Copyright (C) 2016	Laurent Destailleur		<eldy@users.sourceforge.net>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19 use Luracast\Restler\RestException;
20
21 require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
22
23/**
24 * API class for Interventions
25 *
26 * @access protected
27 * @class  DolibarrApiAccess {@requires user,external}
28 */
29class Interventions extends DolibarrApi
30{
31
32	/**
33	 * @var array   $FIELDS     Mandatory fields, checked when create and update object
34	 */
35	static $FIELDS = array(
36	  'socid',
37	  'fk_project',
38	  'description',
39	);
40
41	/**
42	 * @var array   $FIELDS     Mandatory fields, checked when create and update object
43	 */
44	static $FIELDSLINE = array(
45	  'description',
46	  'date',
47	  'duree',
48	);
49
50	/**
51	 * @var fichinter $fichinter {@type fichinter}
52	 */
53	public $fichinter;
54
55	/**
56	 * Constructor
57	 */
58	public function __construct()
59	{
60		global $db, $conf;
61		$this->db = $db;
62		$this->fichinter = new Fichinter($this->db);
63	}
64
65	/**
66	 * Get properties of a Expense Report object
67	 *
68	 * Return an array with Expense Report information
69	 *
70	 * @param       int         $id         ID of Expense Report
71	 * @return 	    array|mixed             Data without useless information
72	 *
73	 * @throws 	RestException
74	 */
75	public function get($id)
76	{
77		if (!DolibarrApiAccess::$user->rights->ficheinter->lire) {
78			throw new RestException(401);
79		}
80
81		$result = $this->fichinter->fetch($id);
82		if (!$result) {
83			throw new RestException(404, 'Intervention not found');
84		}
85
86		if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
87			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
88		}
89
90		$this->fichinter->fetchObjectLinked();
91		return $this->_cleanObjectDatas($this->fichinter);
92	}
93
94	/**
95	 * List of interventions
96	 *
97	 * Return a list of interventions
98	 *
99	 * @param string	       $sortfield	        Sort field
100	 * @param string	       $sortorder	        Sort order
101	 * @param int	       $limit		        Limit for list
102	 * @param int	       $page		        Page number
103	 * @param string   	       $thirdparty_ids	        Thirdparty ids to filter orders of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
104	 * @param string           $sqlfilters              Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
105	 * @return  array                                   Array of order objects
106	 *
107	 * @throws RestException
108	 */
109	public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '')
110	{
111		global $db, $conf;
112
113		$obj_ret = array();
114
115		// case of external user, $thirdparty_ids param is ignored and replaced by user's socid
116		$socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
117
118		// If the internal user must only see his customers, force searching by him
119		$search_sale = 0;
120		if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
121
122		$sql = "SELECT t.rowid";
123		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
124		$sql .= " FROM ".MAIN_DB_PREFIX."fichinter as t";
125
126		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
127
128		$sql .= ' WHERE t.entity IN ('.getEntity('intervention').')';
129		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
130		if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
131		if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
132		// Insert sale filter
133		if ($search_sale > 0) {
134			$sql .= " AND sc.fk_user = ".$search_sale;
135		}
136		// Add sql filters
137		if ($sqlfilters)
138		{
139			if (!DolibarrApi::_checkFilters($sqlfilters))
140			{
141				throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
142			}
143			$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
144			$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
145		}
146
147		$sql .= $this->db->order($sortfield, $sortorder);
148		if ($limit) {
149			if ($page < 0)
150			{
151				$page = 0;
152			}
153			$offset = $limit * $page;
154
155			$sql .= $this->db->plimit($limit + 1, $offset);
156		}
157
158		dol_syslog("API Rest request");
159		$result = $this->db->query($sql);
160
161		if ($result)
162		{
163			$num = $this->db->num_rows($result);
164			$min = min($num, ($limit <= 0 ? $num : $limit));
165			$i = 0;
166			while ($i < $min)
167			{
168				$obj = $this->db->fetch_object($result);
169				$fichinter_static = new Fichinter($this->db);
170				if ($fichinter_static->fetch($obj->rowid)) {
171					$obj_ret[] = $this->_cleanObjectDatas($fichinter_static);
172				}
173				$i++;
174			}
175		} else {
176			throw new RestException(503, 'Error when retrieve intervention list : '.$this->db->lasterror());
177		}
178		if (!count($obj_ret)) {
179			throw new RestException(404, 'No intervention found');
180		}
181		return $obj_ret;
182	}
183
184	/**
185	 * Create intervention object
186	 *
187	 * @param   array   $request_data   Request data
188	 * @return  int     ID of intervention
189	 */
190	public function post($request_data = null)
191	{
192		if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
193			throw new RestException(401, "Insuffisant rights");
194		}
195		// Check mandatory fields
196		$result = $this->_validate($request_data);
197		foreach ($request_data as $field => $value) {
198			$this->fichinter->$field = $value;
199		}
200
201		if ($this->fichinter->create(DolibarrApiAccess::$user) < 0) {
202			throw new RestException(500, "Error creating intervention", array_merge(array($this->fichinter->error), $this->fichinter->errors));
203		}
204
205		return $this->fichinter->id;
206	}
207
208
209	/**
210	 * Get lines of an intervention
211	 *
212	 * @param int   $id             Id of intervention
213	 *
214	 * @url	GET {id}/lines
215	 *
216	 * @return int
217	 */
218	/* TODO
219    public function getLines($id)
220    {
221        if(! DolibarrApiAccess::$user->rights->ficheinter->lire) {
222            throw new RestException(401);
223        }
224
225        $result = $this->fichinter->fetch($id);
226        if( ! $result ) {
227            throw new RestException(404, 'Intervention not found');
228        }
229
230        if( ! DolibarrApi::_checkAccessToResource('fichinter',$this->fichinter->id)) {
231            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
232        }
233        $this->fichinter->getLinesArray();
234        $result = array();
235        foreach ($this->fichinter->lines as $line) {
236            array_push($result,$this->_cleanObjectDatas($line));
237        }
238        return $result;
239    }
240    */
241
242	/**
243	 * Add a line to given intervention
244	 *
245	 * @param 	int   	$id             Id of intervention to update
246	 * @param   array   $request_data   Request data
247	 *
248	 * @url     POST {id}/lines
249	 *
250	 * @return  int
251	 */
252	public function postLine($id, $request_data = null)
253	{
254		if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
255			throw new RestException(401, "Insuffisant rights");
256		}
257		// Check mandatory fields
258		$result = $this->_validateLine($request_data);
259
260		foreach ($request_data as $field => $value) {
261			$this->fichinter->$field = $value;
262		}
263
264		if (!$result) {
265			throw new RestException(404, 'Intervention not found');
266		}
267
268		if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
269			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
270		}
271
272		$updateRes = $this->fichinter->addLine(
273				DolibarrApiAccess::$user,
274				$id,
275				$this->fichinter->description,
276				$this->fichinter->date,
277				$this->fichinter->duree
278		);
279
280		if ($updateRes > 0) {
281			return $updateRes;
282		} else {
283			throw new RestException(400, $this->fichinter->error);
284		}
285	}
286
287	/**
288	 * Delete order
289	 *
290	 * @param   int     $id         Order ID
291	 * @return  array
292	 */
293	public function delete($id)
294	{
295		if (!DolibarrApiAccess::$user->rights->ficheinter->supprimer) {
296			throw new RestException(401);
297		}
298		$result = $this->fichinter->fetch($id);
299		if (!$result) {
300			throw new RestException(404, 'Intervention not found');
301		}
302
303		if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
304			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
305		}
306
307		if (!$this->fichinter->delete(DolibarrApiAccess::$user)) {
308			throw new RestException(500, 'Error when delete intervention : '.$this->fichinter->error);
309		}
310
311		return array(
312			'success' => array(
313				'code' => 200,
314				'message' => 'Intervention deleted'
315			)
316		);
317	}
318
319	/**
320	 * Validate an intervention
321	 *
322	 * If you get a bad value for param notrigger check, provide this in body
323	 * {
324	 *   "notrigger": 0
325	 * }
326	 *
327	 * @param   int $id             Intervention ID
328	 * @param   int $notrigger      1=Does not execute triggers, 0= execute triggers
329	 *
330	 * @url POST    {id}/validate
331	 *
332	 * @return  array
333	 */
334	public function validate($id, $notrigger = 0)
335	{
336		if (!DolibarrApiAccess::$user->rights->ficheinter->creer) {
337			throw new RestException(401, "Insuffisant rights");
338		}
339		$result = $this->fichinter->fetch($id);
340		if (!$result) {
341			throw new RestException(404, 'Intervention not found');
342		}
343
344		if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
345			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
346		}
347
348		$result = $this->fichinter->setValid(DolibarrApiAccess::$user, $notrigger);
349		if ($result == 0) {
350			throw new RestException(304, 'Error nothing done. May be object is already validated');
351		}
352		if ($result < 0) {
353			throw new RestException(500, 'Error when validating Intervention: '.$this->commande->error);
354		}
355
356		$this->fichinter->fetchObjectLinked();
357
358		return $this->_cleanObjectDatas($this->fichinter);
359	}
360
361	/**
362	 * Close an intervention
363	 *
364	 * @param   int 	$id             Intervention ID
365	 *
366	 * @url POST    {id}/close
367	 *
368	 * @return  array
369	 */
370	public function closeFichinter($id)
371	{
372		if (!DolibarrApiAccess::$user->rights->ficheinter->creer)
373		{
374			throw new RestException(401, "Insuffisant rights");
375		}
376		$result = $this->fichinter->fetch($id);
377		if (!$result) {
378			throw new RestException(404, 'Intervention not found');
379		}
380
381		if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) {
382			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
383		}
384
385		$result = $this->fichinter->setStatut(3);
386
387		if ($result == 0) {
388			throw new RestException(304, 'Error nothing done. May be object is already closed');
389		}
390		if ($result < 0) {
391			throw new RestException(500, 'Error when closing Intervention: '.$this->fichinter->error);
392		}
393
394		$this->fichinter->fetchObjectLinked();
395
396		return $this->_cleanObjectDatas($this->fichinter);
397	}
398
399	/**
400	 * Validate fields before create or update object
401	 *
402	 * @param array $data   Data to validate
403	 * @return array
404	 *
405	 * @throws RestException
406	 */
407	private function _validate($data)
408	{
409		$fichinter = array();
410		foreach (Interventions::$FIELDS as $field) {
411			if (!isset($data[$field]))
412				throw new RestException(400, "$field field missing");
413			$fichinter[$field] = $data[$field];
414		}
415		return $fichinter;
416	}
417
418
419	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
420	/**
421	 * Clean sensible object datas
422	 *
423	 * @param   Object  $object     Object to clean
424	 * @return  Object              Object with cleaned properties
425	 */
426	protected function _cleanObjectDatas($object)
427	{
428		// phpcs:enable
429		$object = parent::_cleanObjectDatas($object);
430
431		unset($object->statuts_short);
432		unset($object->statuts_logo);
433		unset($object->statuts);
434
435		return $object;
436	}
437
438	/**
439	 * Validate fields before create or update object
440	 *
441	 * @param array $data   Data to validate
442	 * @return array
443	 *
444	 * @throws RestException
445	 */
446	private function _validateLine($data)
447	{
448		$fichinter = array();
449		foreach (Interventions::$FIELDSLINE as $field) {
450			if (!isset($data[$field]))
451				throw new RestException(400, "$field field missing");
452			$fichinter[$field] = $data[$field];
453		}
454		return $fichinter;
455	}
456}
457