dolibarr 24.0.0-beta
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 if ($field == 'array_options' && is_array($value)) {
143 $this->supplier_proposal->fetch_optionals(); // To force the load of the extrafields definition by fetch_name_optionals_label()
144
145 foreach ($value as $index => $val) {
146 $this->supplier_proposal->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->supplier_proposal);
147 }
148 continue;
149 }
150 $this->supplier_proposal->$field = $this->_checkValForAPI($field, $value, $this->supplier_proposal);
151 }
152
153 /*if (isset($request_data["lines"])) {
154 $lines = array();
155 foreach ($request_data["lines"] as $line) {
156 array_push($lines, (object) $line);
157 }
158 $this->propal->lines = $lines;
159 }*/
160
161 if ($this->supplier_proposal->create(DolibarrApiAccess::$user) < 0) {
162 throw new RestException(500, "Error creating supplier proposal", array_merge(array($this->supplier_proposal->error), $this->supplier_proposal->errors));
163 }
164
165 return $this->supplier_proposal->id;
166 }
167
177 public function put($id, $request_data = null)
178 {
179 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'creer')) {
180 throw new RestException(403);
181 }
182
183 $result = $this->supplier_proposal->fetch($id);
184 if (!$result) {
185 throw new RestException(404, 'Supplier proposal not found');
186 }
187
188 if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->supplier_proposal->id)) {
189 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
190 }
191 foreach ($request_data as $field => $value) {
192 if ($field == 'id') {
193 continue;
194 }
195 if ($field === 'caller') {
196 // 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
197 $this->supplier_proposal->context['caller'] = $request_data['caller'];
198 continue;
199 }
200 if ($field == 'array_options' && is_array($value)) {
201 foreach ($value as $index => $val) {
202 $this->supplier_proposal->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->supplier_proposal);
203 }
204 continue;
205 }
206 $this->supplier_proposal->$field = $this->_checkValForAPI($field, $value, $this->supplier_proposal);
207 }
208
209 // update end of validity date
210 if (empty($this->supplier_proposal->fin_validite) && !empty($this->supplier_proposal->duree_validite) && !empty($this->supplier_proposal->date_creation)) {
211 $this->supplier_proposal->fin_validite = $this->supplier_proposal->date_creation + ($this->supplier_proposal->duree_validite * 24 * 3600);
212 }
213 if (!empty($this->supplier_proposal->fin_validite)) {
214 if ($this->supplier_proposal->set_echeance(DolibarrApiAccess::$user, $this->supplier_proposal->fin_validite) < 0) {
215 throw new RestException(500, $this->supplier_proposal->error);
216 }
217 }
218
219 if ($this->supplier_proposal->update(DolibarrApiAccess::$user) > 0) {
220 return $this->get($id);
221 } else {
222 throw new RestException(500, $this->supplier_proposal->error);
223 }
224 }
225
243 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
244 {
245 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'lire')) {
246 throw new RestException(403);
247 }
248
249 $obj_ret = array();
250
251 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
252 $socids = DolibarrApiAccess::$user->socid ?: $thirdparty_ids;
253
254 // If the internal user must only see his customers, force searching by him
255 $search_sale = 0;
256 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
257 $search_sale = DolibarrApiAccess::$user->id;
258 }
259
260 $sql = "SELECT t.rowid";
261 $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal AS t";
262 $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
263 $sql .= ' WHERE t.entity IN ('.getEntity('propal').')';
264 if ($socids) {
265 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
266 }
267 // Search on sale representative
268 if ($search_sale && $search_sale != '-1') {
269 if ($search_sale == -2) {
270 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
271 } elseif ($search_sale > 0) {
272 $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).")";
273 }
274 }
275 // Add sql filters
276 if ($sqlfilters) {
277 $errormessage = '';
278 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
279 if ($errormessage) {
280 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
281 }
282 }
283
284 //this query will return total supplier proposals with the filters given
285 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
286
287 $sql .= $this->db->order($sortfield, $sortorder);
288 if ($limit) {
289 if ($page < 0) {
290 $page = 0;
291 }
292 $offset = $limit * $page;
293
294 $sql .= $this->db->plimit($limit + 1, $offset);
295 }
296
297 $result = $this->db->query($sql);
298
299 if ($result) {
300 $num = $this->db->num_rows($result);
301 $min = min($num, ($limit <= 0 ? $num : $limit));
302 $i = 0;
303 while ($i < $min) {
304 $obj = $this->db->fetch_object($result);
305 $propal_static = new SupplierProposal($this->db);
306 if ($propal_static->fetch($obj->rowid)) {
307 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($propal_static), $properties);
308 }
309 $i++;
310 }
311 } else {
312 throw new RestException(503, 'Error when retrieving supplier proposal list : '.$this->db->lasterror());
313 }
314
315 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
316 if ($pagination_data) {
317 $totalsResult = $this->db->query($sqlTotals);
318 $total = $this->db->fetch_object($totalsResult)->total;
319
320 $tmp = $obj_ret;
321 $obj_ret = [];
322
323 $obj_ret['data'] = $tmp;
324 $obj_ret['pagination'] = [
325 'total' => (int) $total,
326 'page' => $page, //count starts from 0
327 'page_count' => ceil((int) $total / $limit),
328 'limit' => $limit
329 ];
330 }
331
332 return $obj_ret;
333 }
334
335
343 private function _validate($data)
344 {
345 if ($data === null) {
346 $data = array();
347 }
348 $propal = array();
349 foreach (SupplierProposals::$FIELDS as $field) {
350 if (!isset($data[$field])) {
351 throw new RestException(400, "$field field missing");
352 }
353 $propal[$field] = $data[$field];
354 }
355 return $propal;
356 }
357
358
359 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
369 protected function _cleanObjectDatas($object)
370 {
371 // phpcs:enable
372 $object = parent::_cleanObjectDatas($object);
373
374 unset($object->name);
375 unset($object->lastname);
376 unset($object->firstname);
377 unset($object->civility_id);
378 unset($object->address);
379 unset($object->datec);
380 unset($object->datev);
381
382 return $object;
383 }
384}
$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.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
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.