dolibarr 25.0.0-alpha
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';
24require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
25
26
34{
38 public static $FIELDS = array(
39 'socid'
40 );
41
45 public $supplier_proposal;
46
50 public function __construct()
51 {
52 global $db;
53 $this->db = $db;
54 $this->supplier_proposal = new SupplierProposal($this->db);
55 }
56
65 public function delete($id)
66 {
67 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'supprimer')) {
68 throw new RestException(403);
69 }
70 $result = $this->supplier_proposal->fetch($id);
71 if (!$result) {
72 throw new RestException(404, 'Supplier Proposal not found');
73 }
74
75 if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->supplier_proposal->id)) {
76 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
77 }
78
79 if (!$this->supplier_proposal->delete(DolibarrApiAccess::$user)) {
80 throw new RestException(500, 'Error when delete Supplier Proposal : '.$this->supplier_proposal->error);
81 }
82
83 return array(
84 'success' => array(
85 'code' => 200,
86 'message' => 'Supplier Proposal deleted'
87 )
88 );
89 }
90
101 public function get($id)
102 {
103 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'lire')) {
104 throw new RestException(403);
105 }
106
107 $result = $this->supplier_proposal->fetch($id);
108 if (!$result) {
109 throw new RestException(404, 'Supplier Proposal not found');
110 }
111
112 if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->supplier_proposal->id)) {
113 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
114 }
115
116 $this->supplier_proposal->fetchObjectLinked();
117 return $this->_cleanObjectDatas($this->supplier_proposal);
118 }
119
128 public function post($request_data = null)
129 {
130 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'creer')) {
131 throw new RestException(403, "Insufficiant rights");
132 }
133 // Check mandatory fields
134 $result = $this->_validate($request_data);
135
136 foreach ($request_data as $field => $value) {
137 if ($field === 'caller') {
138 // 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
139 $this->supplier_proposal->context['caller'] = $request_data['caller'];
140 continue;
141 }
142
143 if ($field == 'array_options' && is_array($value)) {
144 $this->supplier_proposal->fetch_optionals(); // To force the load of the extrafields definition by fetch_name_optionals_label()
145
146 foreach ($value as $index => $val) {
147 $this->supplier_proposal->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->supplier_proposal);
148 }
149 continue;
150 }
151 $this->supplier_proposal->$field = $this->_checkValForAPI($field, $value, $this->supplier_proposal);
152 }
153
154 /*if (isset($request_data["lines"])) {
155 $lines = array();
156 foreach ($request_data["lines"] as $line) {
157 array_push($lines, (object) $line);
158 }
159 $this->propal->lines = $lines;
160 }*/
161
162 if ($this->supplier_proposal->create(DolibarrApiAccess::$user) < 0) {
163 throw new RestException(500, "Error creating supplier proposal", array_merge(array($this->supplier_proposal->error), $this->supplier_proposal->errors));
164 }
165
166 return $this->supplier_proposal->id;
167 }
168
178 public function put($id, $request_data = null)
179 {
180 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'creer')) {
181 throw new RestException(403);
182 }
183
184 $result = $this->supplier_proposal->fetch($id);
185 if (!$result) {
186 throw new RestException(404, 'Supplier proposal not found');
187 }
188
189 if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->supplier_proposal->id)) {
190 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
191 }
192 foreach ($request_data as $field => $value) {
193 if ($field == 'id') {
194 continue;
195 }
196 if ($field === 'caller') {
197 // 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
198 $this->supplier_proposal->context['caller'] = $request_data['caller'];
199 continue;
200 }
201 if ($field == 'array_options' && is_array($value)) {
202 foreach ($value as $index => $val) {
203 $this->supplier_proposal->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->supplier_proposal);
204 }
205 continue;
206 }
207 $this->supplier_proposal->$field = $this->_checkValForAPI($field, $value, $this->supplier_proposal);
208 }
209
210 // update end of validity date
211 if (empty($this->supplier_proposal->fin_validite) && !empty($this->supplier_proposal->duree_validite) && !empty($this->supplier_proposal->date_creation)) {
212 $this->supplier_proposal->fin_validite = $this->supplier_proposal->date_creation + ($this->supplier_proposal->duree_validite * 24 * 3600);
213 }
214 if (!empty($this->supplier_proposal->fin_validite)) {
215 if ($this->supplier_proposal->set_echeance(DolibarrApiAccess::$user, $this->supplier_proposal->fin_validite) < 0) {
216 throw new RestException(500, $this->supplier_proposal->error);
217 }
218 }
219
220 if ($this->supplier_proposal->update(DolibarrApiAccess::$user) > 0) {
221 return $this->get($id);
222 } else {
223 throw new RestException(500, $this->supplier_proposal->error);
224 }
225 }
226
244 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
245 {
246 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'lire')) {
247 throw new RestException(403);
248 }
249
250 $obj_ret = array();
251
252 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
253 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
254
255 // If the internal user must only see his customers, force searching by him
256 $search_sale = 0;
257 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
258 $search_sale = DolibarrApiAccess::$user->id;
259 }
260
261 $sql = "SELECT t.rowid";
262 $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal AS t";
263 $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
264 $sql .= ' WHERE t.entity IN ('.getEntity('propal').')';
265 if ($socids) {
266 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
267 }
268 // Search on sale representative
269 if ($search_sale && $search_sale != '-1') {
270 if ($search_sale == -2) {
271 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', 0, 1);
272 } elseif ($search_sale > 0) {
273 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', (int) $search_sale);
274 }
275 }
276 // Add sql filters
277 if ($sqlfilters) {
278 $errormessage = '';
279 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
280 if ($errormessage) {
281 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
282 }
283 }
284
285 //this query will return total supplier proposals with the filters given
286 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
287
288 $sql .= $this->db->order($sortfield, $sortorder);
289 if ($limit) {
290 if ($page < 0) {
291 $page = 0;
292 }
293 $offset = $limit * $page;
294
295 $sql .= $this->db->plimit($limit + 1, $offset);
296 }
297
298 $result = $this->db->query($sql);
299
300 if ($result) {
301 $num = $this->db->num_rows($result);
302 $min = min($num, ($limit <= 0 ? $num : $limit));
303 $i = 0;
304 while ($i < $min) {
305 $obj = $this->db->fetch_object($result);
306 $propal_static = new SupplierProposal($this->db);
307 if ($propal_static->fetch($obj->rowid)) {
308 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($propal_static), $properties);
309 }
310 $i++;
311 }
312 } else {
313 throw new RestException(503, 'Error when retrieving supplier proposal list : '.$this->db->lasterror());
314 }
315
316 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
317 if ($pagination_data) {
318 $totalsResult = $this->db->query($sqlTotals);
319 $total = $this->db->fetch_object($totalsResult)->total;
320
321 $tmp = $obj_ret;
322 $obj_ret = [];
323
324 $obj_ret['data'] = $tmp;
325 $obj_ret['pagination'] = [
326 'total' => (int) $total,
327 'page' => $page, //count starts from 0
328 'page_count' => ceil((int) $total / $limit),
329 'limit' => $limit
330 ];
331 }
332
333 return $obj_ret;
334 }
335
336
344 private function _validate($data)
345 {
346 if ($data === null) {
347 $data = array();
348 }
349 $propal = array();
350 foreach (SupplierProposals::$FIELDS as $field) {
351 if (!isset($data[$field])) {
352 throw new RestException(400, "$field field missing");
353 }
354 $propal[$field] = $data[$field];
355 }
356 return $propal;
357 }
358
359
360 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
370 protected function _cleanObjectDatas($object)
371 {
372 // phpcs:enable
373 $object = parent::_cleanObjectDatas($object);
374
375 unset($object->name);
376 unset($object->lastname);
377 unset($object->firstname);
378 unset($object->civility_id);
379 unset($object->address);
380 unset($object->datec);
381 unset($object->datev);
382
383 return $object;
384 }
385}
$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: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 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.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria