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->errorsToString());
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 if ($this->supplier_proposal->update(DolibarrApiAccess::$user) > 0) {
211 return $this->get($id);
212 } else {
213 throw new RestException(500, $this->supplier_proposal->errorsToString());
214 }
215 }
216
233 public function postLine($id, $request_data = null)
234 {
235 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'creer')) {
236 throw new RestException(403);
237 }
238
239 $result = $this->supplier_proposal->fetch($id);
240 if (!$result) {
241 throw new RestException(404, 'Supplier proposal not found');
242 }
243
244 if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->supplier_proposal->id)) {
245 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
246 }
247
248 $request_data = (object) $request_data;
249
250 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
251 $request_data->label = sanitizeVal($request_data->label);
252
253 $updateRes = $this->supplier_proposal->addline(
254 $request_data->desc,
255 $request_data->subprice,
256 $request_data->qty,
257 $request_data->tva_tx,
258 $request_data->localtax1_tx,
259 $request_data->localtax2_tx,
260 $request_data->fk_product,
261 $request_data->remise_percent,
262 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
263 $request_data->subprice,
264 $request_data->info_bits,
265 $request_data->product_type,
266 $request_data->rang,
267 $request_data->special_code,
268 $request_data->fk_parent_line,
269 $request_data->fk_fournprice,
270 $request_data->pa_ht,
271 $request_data->label,
272 $request_data->array_options,
273 $request_data->ref_fourn,
274 $request_data->fk_unit,
275 $request_data->origin,
276 $request_data->origin_id,
277 $request_data->multicurrency_subprice,
278 $request_data->date_start,
279 $request_data->date_end
280 );
281
282 if ($updateRes > 0) {
283 return $updateRes;
284 } else {
285 throw new RestException(400, $this->supplier_proposal->errorsToString());
286 }
287 }
288
306 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
307 {
308 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'lire')) {
309 throw new RestException(403);
310 }
311
312 $obj_ret = array();
313
314 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
315 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
316
317 // If the internal user must only see his customers, force searching by him
318 $search_sale = 0;
319 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
320 $search_sale = DolibarrApiAccess::$user->id;
321 }
322
323 $sql = "SELECT t.rowid";
324 $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal AS t";
325 $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
326 $sql .= ' WHERE t.entity IN ('.getEntity('propal').')';
327 if ($socids) {
328 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
329 }
330 // Search on sale representative
331 if ($search_sale && $search_sale != '-1') {
332 if ($search_sale == -2) {
333 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', 0, 1);
334 } elseif ($search_sale > 0) {
335 $sql .= " AND ".getSalesRepresentativeSqlFilter('t.fk_soc', (int) $search_sale);
336 }
337 }
338 // Add sql filters
339 if ($sqlfilters) {
340 $errormessage = '';
341 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
342 if ($errormessage) {
343 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
344 }
345 }
346
347 //this query will return total supplier proposals with the filters given
348 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
349
350 $sql .= $this->db->order($sortfield, $sortorder);
351 if ($limit) {
352 if ($page < 0) {
353 $page = 0;
354 }
355 $offset = $limit * $page;
356
357 $sql .= $this->db->plimit($limit + 1, $offset);
358 }
359
360 $result = $this->db->query($sql);
361
362 if ($result) {
363 $num = $this->db->num_rows($result);
364 $min = min($num, ($limit <= 0 ? $num : $limit));
365 $i = 0;
366 while ($i < $min) {
367 $obj = $this->db->fetch_object($result);
368 $propal_static = new SupplierProposal($this->db);
369 if ($propal_static->fetch($obj->rowid)) {
370 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($propal_static), $properties);
371 }
372 $i++;
373 }
374 } else {
375 throw new RestException(503, 'Error when retrieving supplier proposal list : '.$this->db->lasterror());
376 }
377
378 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
379 if ($pagination_data) {
380 $totalsResult = $this->db->query($sqlTotals);
381 $total = $this->db->fetch_object($totalsResult)->total;
382
383 $tmp = $obj_ret;
384 $obj_ret = [];
385
386 $obj_ret['data'] = $tmp;
387 $obj_ret['pagination'] = [
388 'total' => (int) $total,
389 'page' => $page, //count starts from 0
390 'page_count' => ceil((int) $total / $limit),
391 'limit' => $limit
392 ];
393 }
394
395 return $obj_ret;
396 }
397
398
406 private function _validate($data)
407 {
408 if ($data === null) {
409 $data = array();
410 }
411 $propal = array();
412 foreach (SupplierProposals::$FIELDS as $field) {
413 if (!isset($data[$field])) {
414 throw new RestException(400, "$field field missing");
415 }
416 $propal[$field] = $data[$field];
417 }
418 return $propal;
419 }
420
421
422 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
432 protected function _cleanObjectDatas($object)
433 {
434 // phpcs:enable
435 $object = parent::_cleanObjectDatas($object);
436
437 unset($object->name);
438 unset($object->lastname);
439 unset($object->firstname);
440 unset($object->civility_id);
441 unset($object->address);
442 unset($object->datec);
443 unset($object->datev);
444
445 return $object;
446 }
447}
$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)
postLine($id, $request_data=null)
Add a line to a supplier proposal (price request)
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, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.