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
19use Luracast\Restler\RestException;
20
21require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
22
23
24/**
25 * API class for orders
26 *
27 * @access protected
28 * @class  DolibarrApiAccess {@requires user,external}
29 */
30class Supplierproposals extends DolibarrApi
31{
32
33	/**
34	 * @var array   $FIELDS     Mandatory fields, checked when create and update object
35	 */
36	static $FIELDS = array(
37		'socid'
38	);
39
40	/**
41	 * @var SupplierProposal $supplier_proposal {@type SupplierProposal}
42	 */
43	public $supplier_proposal;
44
45	/**
46	 * Constructor
47	 */
48	public function __construct()
49	{
50		global $db, $conf;
51		$this->db = $db;
52		$this->supplier_proposal = new SupplierProposal($this->db);
53	}
54
55	/**
56	 * Get properties of a supplier proposal (price request) object
57	 *
58	 * Return an array with supplier proposal informations
59	 *
60	 * @param       int         $id         ID of supplier proposal
61	 * @return 	array|mixed data without useless information
62	 *
63	 * @throws 	RestException
64	 */
65	public function get($id)
66	{
67		if (!DolibarrApiAccess::$user->rights->supplier_proposal->lire) {
68			throw new RestException(401);
69		}
70
71		$result = $this->supplier_proposal->fetch($id);
72		if (!$result) {
73			throw new RestException(404, 'Supplier Proposal not found');
74		}
75
76		if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->propal->id)) {
77			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
78		}
79
80		$this->supplier_proposal->fetchObjectLinked();
81		return $this->_cleanObjectDatas($this->supplier_proposal);
82	}
83
84	/**
85	 * List supplier proposals
86	 *
87	 * Get a list of supplier proposals
88	 *
89	 * @param string	$sortfield	        Sort field
90	 * @param string	$sortorder	        Sort order
91	 * @param int		$limit		        Limit for list
92	 * @param int		$page		        Page number
93	 * @param string   	$thirdparty_ids	    Thirdparty ids to filter supplier proposals (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
94	 * @param string    $sqlfilters         Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')"
95	 * @return  array                       Array of order objects
96	 */
97	public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '')
98	{
99		global $db, $conf;
100
101		$obj_ret = array();
102
103		// case of external user, $thirdparty_ids param is ignored and replaced by user's socid
104		$socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
105
106		// If the internal user must only see his customers, force searching by him
107		$search_sale = 0;
108		if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id;
109
110		$sql = "SELECT t.rowid";
111		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)
112		$sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as t";
113
114		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
115
116		$sql .= ' WHERE t.entity IN ('.getEntity('propal').')';
117		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc";
118		if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")";
119		if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale
120		// Insert sale filter
121		if ($search_sale > 0)
122		{
123			$sql .= " AND sc.fk_user = ".$search_sale;
124		}
125		// Add sql filters
126		if ($sqlfilters)
127		{
128			if (!DolibarrApi::_checkFilters($sqlfilters))
129			{
130				throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
131			}
132			$regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
133			$sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
134		}
135
136		$sql .= $this->db->order($sortfield, $sortorder);
137		if ($limit) {
138			if ($page < 0)
139			{
140				$page = 0;
141			}
142			$offset = $limit * $page;
143
144			$sql .= $this->db->plimit($limit + 1, $offset);
145		}
146
147		$result = $this->db->query($sql);
148
149		if ($result)
150		{
151			$num = $this->db->num_rows($result);
152			$min = min($num, ($limit <= 0 ? $num : $limit));
153			$i = 0;
154			while ($i < $min)
155			{
156				$obj = $this->db->fetch_object($result);
157				$propal_static = new SupplierProposal($this->db);
158				if ($propal_static->fetch($obj->rowid)) {
159					$obj_ret[] = $this->_cleanObjectDatas($propal_static);
160				}
161				$i++;
162			}
163		} else {
164			throw new RestException(503, 'Error when retrieving supplier proposal list : '.$this->db->lasterror());
165		}
166		if (!count($obj_ret)) {
167			throw new RestException(404, 'No supplier proposal found');
168		}
169		return $obj_ret;
170	}
171
172
173	/**
174	 * Validate fields before create or update object
175	 *
176	 * @param   array           $data   Array with data to verify
177	 * @return  array
178	 * @throws  RestException
179	 */
180	private function _validate($data)
181	{
182		$propal = array();
183		foreach (SupplierProposals::$FIELDS as $field) {
184			if (!isset($data[$field]))
185				throw new RestException(400, "$field field missing");
186			$propal[$field] = $data[$field];
187		}
188		return $propal;
189	}
190
191
192	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
193	/**
194	 * Clean sensible object datas
195	 *
196	 * @param   Object  $object     Object to clean
197	 * @return  Object              Object with cleaned properties
198	 */
199	protected function _cleanObjectDatas($object)
200	{
201		// phpcs:enable
202		$object = parent::_cleanObjectDatas($object);
203
204		unset($object->name);
205		unset($object->lastname);
206		unset($object->firstname);
207		unset($object->civility_id);
208		unset($object->address);
209		unset($object->datec);
210		unset($object->datev);
211
212		return $object;
213	}
214}
215