dolibarr 23.0.3
api_supplier_proposals.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) 2025 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21use Luracast\Restler\RestException;
22
23require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
24
25
33{
37 public static $FIELDS = array(
38 'socid'
39 );
40
44 public $supplier_proposal;
45
49 public function __construct()
50 {
51 global $db;
52 $this->db = $db;
53 $this->supplier_proposal = new SupplierProposal($this->db);
54 }
55
64 public function delete($id)
65 {
66 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'supprimer')) {
67 throw new RestException(403);
68 }
69 $result = $this->supplier_proposal->fetch($id);
70 if (!$result) {
71 throw new RestException(404, 'Supplier Proposal not found');
72 }
73
74 if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->supplier_proposal->id)) {
75 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
76 }
77
78 if (!$this->supplier_proposal->delete(DolibarrApiAccess::$user)) {
79 throw new RestException(500, 'Error when delete Supplier Proposal : '.$this->supplier_proposal->error);
80 }
81
82 return array(
83 'success' => array(
84 'code' => 200,
85 'message' => 'Supplier Proposal deleted'
86 )
87 );
88 }
89
100 public function get($id)
101 {
102 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'lire')) {
103 throw new RestException(403);
104 }
105
106 $result = $this->supplier_proposal->fetch($id);
107 if (!$result) {
108 throw new RestException(404, 'Supplier Proposal not found');
109 }
110
111 if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->supplier_proposal->id)) {
112 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
113 }
114
115 $this->supplier_proposal->fetchObjectLinked();
116 return $this->_cleanObjectDatas($this->supplier_proposal);
117 }
118
127 public function post($request_data = null)
128 {
129 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'creer')) {
130 throw new RestException(403, "Insufficiant rights");
131 }
132 // Check mandatory fields
133 $result = $this->_validate($request_data);
134
135 foreach ($request_data as $field => $value) {
136 if ($field === 'caller') {
137 // 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
138 $this->supplier_proposal->context['caller'] = $request_data['caller'];
139 continue;
140 }
141
142 $this->supplier_proposal->$field = $value;
143 }
144 /*if (isset($request_data["lines"])) {
145 $lines = array();
146 foreach ($request_data["lines"] as $line) {
147 array_push($lines, (object) $line);
148 }
149 $this->propal->lines = $lines;
150 }*/
151 if ($this->supplier_proposal->create(DolibarrApiAccess::$user) < 0) {
152 throw new RestException(500, "Error creating supplier proposal", array_merge(array($this->supplier_proposal->error), $this->supplier_proposal->errors));
153 }
154
155 return $this->supplier_proposal->id;
156 }
157
167 public function put($id, $request_data = null)
168 {
169 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'creer')) {
170 throw new RestException(403);
171 }
172
173 $result = $this->supplier_proposal->fetch($id);
174 if (!$result) {
175 throw new RestException(404, 'Supplier proposal not found');
176 }
177
178 if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->supplier_proposal->id)) {
179 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
180 }
181 foreach ($request_data as $field => $value) {
182 if ($field == 'id') {
183 continue;
184 }
185 if ($field === 'caller') {
186 // 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
187 $this->supplier_proposal->context['caller'] = $request_data['caller'];
188 continue;
189 }
190 if ($field == 'array_options' && is_array($value)) {
191 foreach ($value as $index => $val) {
192 $this->supplier_proposal->array_options[$index] = $val;
193 }
194 continue;
195 }
196 $this->supplier_proposal->$field = $value;
197 }
198
199 // update end of validity date
200 if (empty($this->supplier_proposal->fin_validite) && !empty($this->supplier_proposal->duree_validite) && !empty($this->supplier_proposal->date_creation)) {
201 $this->supplier_proposal->fin_validite = $this->supplier_proposal->date_creation + ($this->supplier_proposal->duree_validite * 24 * 3600);
202 }
203 if (!empty($this->supplier_proposal->fin_validite)) {
204 if ($this->supplier_proposal->set_echeance(DolibarrApiAccess::$user, $this->supplier_proposal->fin_validite) < 0) {
205 throw new RestException(500, $this->supplier_proposal->error);
206 }
207 }
208
209 if ($this->supplier_proposal->update(DolibarrApiAccess::$user) > 0) {
210 return $this->get($id);
211 } else {
212 throw new RestException(500, $this->supplier_proposal->error);
213 }
214 }
215
233 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
234 {
235 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'lire')) {
236 throw new RestException(403);
237 }
238
239 $obj_ret = array();
240
241 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
242 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
243
244 // If the internal user must only see his customers, force searching by him
245 $search_sale = 0;
246 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
247 $search_sale = DolibarrApiAccess::$user->id;
248 }
249
250 $sql = "SELECT t.rowid";
251 $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal AS t";
252 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."supplier_proposal_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
253 $sql .= ' WHERE t.entity IN ('.getEntity('propal').')';
254 if ($socids) {
255 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
256 }
257 // Search on sale representative
258 if ($search_sale && $search_sale != '-1') {
259 if ($search_sale == -2) {
260 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
261 } elseif ($search_sale > 0) {
262 $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).")";
263 }
264 }
265 // Add sql filters
266 if ($sqlfilters) {
267 $errormessage = '';
268 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
269 if ($errormessage) {
270 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
271 }
272 }
273
274 //this query will return total supplier proposals with the filters given
275 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
276
277 $sql .= $this->db->order($sortfield, $sortorder);
278 if ($limit) {
279 if ($page < 0) {
280 $page = 0;
281 }
282 $offset = $limit * $page;
283
284 $sql .= $this->db->plimit($limit + 1, $offset);
285 }
286
287 $result = $this->db->query($sql);
288
289 if ($result) {
290 $num = $this->db->num_rows($result);
291 $min = min($num, ($limit <= 0 ? $num : $limit));
292 $i = 0;
293 while ($i < $min) {
294 $obj = $this->db->fetch_object($result);
295 $propal_static = new SupplierProposal($this->db);
296 if ($propal_static->fetch($obj->rowid)) {
297 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($propal_static), $properties);
298 }
299 $i++;
300 }
301 } else {
302 throw new RestException(503, 'Error when retrieving supplier proposal list : '.$this->db->lasterror());
303 }
304
305 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
306 if ($pagination_data) {
307 $totalsResult = $this->db->query($sqlTotals);
308 $total = $this->db->fetch_object($totalsResult)->total;
309
310 $tmp = $obj_ret;
311 $obj_ret = [];
312
313 $obj_ret['data'] = $tmp;
314 $obj_ret['pagination'] = [
315 'total' => (int) $total,
316 'page' => $page, //count starts from 0
317 'page_count' => ceil((int) $total / $limit),
318 'limit' => $limit
319 ];
320 }
321
322 return $obj_ret;
323 }
324
325
333 private function _validate($data)
334 {
335 if ($data === null) {
336 $data = array();
337 }
338 $propal = array();
339 foreach (SupplierProposals::$FIELDS as $field) {
340 if (!isset($data[$field])) {
341 throw new RestException(400, "$field field missing");
342 }
343 $propal[$field] = $data[$field];
344 }
345 return $propal;
346 }
347
348
349 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
359 protected function _cleanObjectDatas($object)
360 {
361 // phpcs:enable
362 $object = parent::_cleanObjectDatas($object);
363
364 unset($object->name);
365 unset($object->lastname);
366 unset($object->firstname);
367 unset($object->civility_id);
368 unset($object->address);
369 unset($object->datec);
370 unset($object->datev);
371
372 return $object;
373 }
374}
$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:33
_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.
Class to manage price ask supplier.
put($id, $request_data=null)
Update supplier proposal general fields (won't touch lines of supplier proposal)
post($request_data=null)
Create supplier proposal (price request) object.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $sqlfilters='', $properties='', $pagination_data=false)
List supplier proposals.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
_validate($data)
Validate fields before create or update object.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria