dolibarr 21.0.0-beta
api_contracts.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) 2018-2020 Frédéric France <frederic.france@netlogic.fr>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20 use Luracast\Restler\RestException;
21
22 require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
23
31{
35 public static $FIELDS = array(
36 'socid',
37 'date_contrat',
38 'commercial_signature_id',
39 'commercial_suivi_id'
40 );
41
45 public $contract;
46
50 public function __construct()
51 {
52 global $db, $conf;
53 $this->db = $db;
54 $this->contract = new Contrat($this->db);
55 }
56
66 public function get($id)
67 {
68 if (!DolibarrApiAccess::$user->hasRight('contrat', 'lire')) {
69 throw new RestException(403);
70 }
71
72 $result = $this->contract->fetch($id);
73 if (!$result) {
74 throw new RestException(404, 'Contract not found');
75 }
76
77 if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
78 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
79 }
80
81 $this->contract->fetchObjectLinked();
82 return $this->_cleanObjectDatas($this->contract);
83 }
84
103 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
104 {
105 global $db, $conf;
106
107 if (!DolibarrApiAccess::$user->hasRight('contrat', 'lire')) {
108 throw new RestException(403);
109 }
110
111 $obj_ret = array();
112
113 // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
114 $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
115
116 // If the internal user must only see his customers, force searching by him
117 $search_sale = 0;
118 if (!DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socids) {
119 $search_sale = DolibarrApiAccess::$user->id;
120 }
121
122 $sql = "SELECT t.rowid";
123 $sql .= " FROM ".MAIN_DB_PREFIX."contrat AS t LEFT JOIN ".MAIN_DB_PREFIX."contrat_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
124 $sql .= ' WHERE t.entity IN ('.getEntity('contrat').')';
125 if ($socids) {
126 $sql .= " AND t.fk_soc IN (".$this->db->sanitize($socids).")";
127 }
128 // Search on sale representative
129 if ($search_sale && $search_sale != '-1') {
130 if ($search_sale == -2) {
131 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
132 } elseif ($search_sale > 0) {
133 $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).")";
134 }
135 }
136 // Add sql filters
137 if ($sqlfilters) {
138 $errormessage = '';
139 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
140 if ($errormessage) {
141 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
142 }
143 }
144
145 //this query will return total orders with the filters given
146 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
147
148 $sql .= $this->db->order($sortfield, $sortorder);
149 if ($limit) {
150 if ($page < 0) {
151 $page = 0;
152 }
153 $offset = $limit * $page;
154
155 $sql .= $this->db->plimit($limit + 1, $offset);
156 }
157
158 dol_syslog("API Rest request");
159 $result = $this->db->query($sql);
160
161 if ($result) {
162 $num = $this->db->num_rows($result);
163 $min = min($num, ($limit <= 0 ? $num : $limit));
164 $i = 0;
165 while ($i < $min) {
166 $obj = $this->db->fetch_object($result);
167 $contrat_static = new Contrat($this->db);
168 if ($contrat_static->fetch($obj->rowid)) {
169 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($contrat_static), $properties);
170 }
171 $i++;
172 }
173 } else {
174 throw new RestException(503, 'Error when retrieve contrat list : '.$this->db->lasterror());
175 }
176
177 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
178 if ($pagination_data) {
179 $totalsResult = $this->db->query($sqlTotals);
180 $total = $this->db->fetch_object($totalsResult)->total;
181
182 $tmp = $obj_ret;
183 $obj_ret = [];
184
185 $obj_ret['data'] = $tmp;
186 $obj_ret['pagination'] = [
187 'total' => (int) $total,
188 'page' => $page, //count starts from 0
189 'page_count' => ceil((int) $total / $limit),
190 'limit' => $limit
191 ];
192 }
193
194 return $obj_ret;
195 }
196
203 public function post($request_data = null)
204 {
205 if (!DolibarrApiAccess::$user->hasRight('contrat', 'creer')) {
206 throw new RestException(403, "Insufficient rights");
207 }
208 // Check mandatory fields
209 $result = $this->_validate($request_data);
210
211 foreach ($request_data as $field => $value) {
212 if ($field === 'caller') {
213 // 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
214 $this->contract->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
215 continue;
216 }
217
218 $this->contract->$field = $this->_checkValForAPI($field, $value, $this->contract);
219 }
220 /*if (isset($request_data["lines"])) {
221 $lines = array();
222 foreach ($request_data["lines"] as $line) {
223 array_push($lines, (object) $line);
224 }
225 $this->contract->lines = $lines;
226 }*/
227 if ($this->contract->create(DolibarrApiAccess::$user) < 0) {
228 throw new RestException(500, "Error creating contract", array_merge(array($this->contract->error), $this->contract->errors));
229 }
230
231 return $this->contract->id;
232 }
233
243 public function getLines($id)
244 {
245 if (!DolibarrApiAccess::$user->hasRight('contrat', 'lire')) {
246 throw new RestException(403);
247 }
248
249 $result = $this->contract->fetch($id);
250 if (!$result) {
251 throw new RestException(404, 'Contract not found');
252 }
253
254 if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
255 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
256 }
257 $this->contract->getLinesArray();
258 $result = array();
259 foreach ($this->contract->lines as $line) {
260 array_push($result, $this->_cleanObjectDatas($line));
261 }
262 return $result;
263 }
264
275 public function postLine($id, $request_data = null)
276 {
277 if (!DolibarrApiAccess::$user->hasRight('contrat', 'creer')) {
278 throw new RestException(403);
279 }
280
281 $result = $this->contract->fetch($id);
282 if (!$result) {
283 throw new RestException(404, 'Contract not found');
284 }
285
286 if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
287 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
288 }
289
290 $request_data = (object) $request_data;
291
292 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
293 $request_data->price_base_type = sanitizeVal($request_data->price_base_type);
294
295 $updateRes = $this->contract->addline(
296 $request_data->desc,
297 $request_data->subprice,
298 $request_data->qty,
299 $request_data->tva_tx,
300 $request_data->localtax1_tx,
301 $request_data->localtax2_tx,
302 $request_data->fk_product,
303 $request_data->remise_percent,
304 $request_data->date_start,
305 $request_data->date_end,
306 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
307 $request_data->subprice_excl_tax,
308 $request_data->info_bits,
309 $request_data->fk_fournprice,
310 $request_data->pa_ht,
311 $request_data->array_options,
312 $request_data->fk_unit,
313 $request_data->rang
314 );
315
316 if ($updateRes > 0) {
317 return $updateRes;
318 }
319 return false;
320 }
321
333 public function putLine($id, $lineid, $request_data = null)
334 {
335 if (!DolibarrApiAccess::$user->hasRight('contrat', 'creer')) {
336 throw new RestException(403);
337 }
338
339 $result = $this->contract->fetch($id);
340 if (!$result) {
341 throw new RestException(404, 'Contrat not found');
342 }
343
344 if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
345 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
346 }
347
348 $request_data = (object) $request_data;
349
350 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
351 $request_data->price_base_type = sanitizeVal($request_data->price_base_type);
352
353 $updateRes = $this->contract->updateline(
354 $lineid,
355 $request_data->desc,
356 $request_data->subprice,
357 $request_data->qty,
358 $request_data->remise_percent,
359 $request_data->date_start,
360 $request_data->date_end,
361 $request_data->tva_tx,
362 $request_data->localtax1_tx,
363 $request_data->localtax2_tx,
364 $request_data->date_start_real,
365 $request_data->date_end_real,
366 $request_data->price_base_type ? $request_data->price_base_type : 'HT',
367 $request_data->info_bits,
368 $request_data->fk_fourn_price,
369 $request_data->pa_ht,
370 $request_data->array_options,
371 $request_data->fk_unit
372 );
373
374 if ($updateRes > 0) {
375 $result = $this->get($id);
376 unset($result->line);
377 return $this->_cleanObjectDatas($result);
378 }
379
380 return false;
381 }
382
396 public function activateLine($id, $lineid, $datestart, $dateend = null, $comment = null)
397 {
398 if (!DolibarrApiAccess::$user->hasRight('contrat', 'creer')) {
399 throw new RestException(403);
400 }
401
402 $result = $this->contract->fetch($id);
403 if (!$result) {
404 throw new RestException(404, 'Contrat not found');
405 }
406
407 if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
408 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
409 }
410
411 $updateRes = $this->contract->active_line(DolibarrApiAccess::$user, $lineid, $datestart, $dateend, $comment);
412
413 if ($updateRes > 0) {
414 $result = $this->get($id);
415 unset($result->line);
416 return $this->_cleanObjectDatas($result);
417 }
418
419 return false;
420 }
421
434 public function unactivateLine($id, $lineid, $datestart, $comment = null)
435 {
436 if (!DolibarrApiAccess::$user->hasRight('contrat', 'creer')) {
437 throw new RestException(403);
438 }
439
440 $result = $this->contract->fetch($id);
441 if (!$result) {
442 throw new RestException(404, 'Contrat not found');
443 }
444
445 if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
446 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
447 }
448
449 $updateRes = $this->contract->close_line(DolibarrApiAccess::$user, $lineid, $datestart, $comment);
450
451 if ($updateRes > 0) {
452 $result = $this->get($id);
453 unset($result->line);
454 return $this->_cleanObjectDatas($result);
455 }
456
457 return false;
458 }
459
474 public function deleteLine($id, $lineid)
475 {
476 if (!DolibarrApiAccess::$user->hasRight('contrat', 'creer')) {
477 throw new RestException(403);
478 }
479
480 $result = $this->contract->fetch($id);
481 if (!$result) {
482 throw new RestException(404, 'Contrat not found');
483 }
484
485 if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
486 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
487 }
488
489 // TODO Check the lineid $lineid is a line of object
490
491 $updateRes = $this->contract->deleteLine($lineid, DolibarrApiAccess::$user);
492 if ($updateRes > 0) {
493 return $this->get($id);
494 } else {
495 throw new RestException(405, $this->contract->error);
496 }
497 }
498
506 public function put($id, $request_data = null)
507 {
508 if (!DolibarrApiAccess::$user->hasRight('contrat', 'creer')) {
509 throw new RestException(403);
510 }
511
512 $result = $this->contract->fetch($id);
513 if (!$result) {
514 throw new RestException(404, 'Contrat not found');
515 }
516
517 if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
518 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
519 }
520 foreach ($request_data as $field => $value) {
521 if ($field == 'id') {
522 continue;
523 }
524 if ($field === 'caller') {
525 // 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
526 $this->contract->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
527 continue;
528 }
529 if ($field == 'array_options' && is_array($value)) {
530 foreach ($value as $index => $val) {
531 $this->contract->array_options[$index] = $this->_checkValForAPI($field, $val, $this->contract);;
532 }
533 continue;
534 }
535
536 $this->contract->$field = $this->_checkValForAPI($field, $value, $this->contract);
537 }
538
539 if ($this->contract->update(DolibarrApiAccess::$user) > 0) {
540 return $this->get($id);
541 } else {
542 throw new RestException(500, $this->contract->error);
543 }
544 }
545
553 public function delete($id)
554 {
555 if (!DolibarrApiAccess::$user->hasRight('contrat', 'supprimer')) {
556 throw new RestException(403);
557 }
558 $result = $this->contract->fetch($id);
559 if (!$result) {
560 throw new RestException(404, 'Contract not found');
561 }
562
563 if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
564 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
565 }
566
567 if (!$this->contract->delete(DolibarrApiAccess::$user)) {
568 throw new RestException(500, 'Error when delete contract : '.$this->contract->error);
569 }
570
571 return array(
572 'success' => array(
573 'code' => 200,
574 'message' => 'Contract deleted'
575 )
576 );
577 }
578
595 public function validate($id, $notrigger = 0)
596 {
597 if (!DolibarrApiAccess::$user->hasRight('contrat', 'creer')) {
598 throw new RestException(403);
599 }
600 $result = $this->contract->fetch($id);
601 if (!$result) {
602 throw new RestException(404, 'Contract not found');
603 }
604
605 if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
606 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
607 }
608
609 $result = $this->contract->validate(DolibarrApiAccess::$user, '', $notrigger);
610 if ($result == 0) {
611 throw new RestException(304, 'Error nothing done. May be object is already validated');
612 }
613 if ($result < 0) {
614 throw new RestException(500, 'Error when validating Contract: '.$this->contract->error);
615 }
616
617 return array(
618 'success' => array(
619 'code' => 200,
620 'message' => 'Contract validated (Ref='.$this->contract->ref.')'
621 )
622 );
623 }
624
641 public function close($id, $notrigger = 0)
642 {
643 if (!DolibarrApiAccess::$user->hasRight('contrat', 'creer')) {
644 throw new RestException(403);
645 }
646 $result = $this->contract->fetch($id);
647 if (!$result) {
648 throw new RestException(404, 'Contract not found');
649 }
650
651 if (!DolibarrApi::_checkAccessToResource('contrat', $this->contract->id)) {
652 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
653 }
654
655 $result = $this->contract->closeAll(DolibarrApiAccess::$user, $notrigger);
656 if ($result == 0) {
657 throw new RestException(304, 'Error nothing done. May be object is already close');
658 }
659 if ($result < 0) {
660 throw new RestException(500, 'Error when closing Contract: '.$this->contract->error);
661 }
662
663 return array(
664 'success' => array(
665 'code' => 200,
666 'message' => 'Contract closed (Ref='.$this->contract->ref.'). All services were closed.'
667 )
668 );
669 }
670
671
672
673 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
680 protected function _cleanObjectDatas($object)
681 {
682 // phpcs:enable
683 $object = parent::_cleanObjectDatas($object);
684
685 unset($object->address);
686 unset($object->civility_id);
687
688 return $object;
689 }
690
698 private function _validate($data)
699 {
700 $contrat = array();
701 foreach (Contracts::$FIELDS as $field) {
702 if (!isset($data[$field])) {
703 throw new RestException(400, "$field field missing");
704 }
705 $contrat[$field] = $data[$field];
706 }
707 return $contrat;
708 }
709}
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $thirdparty_ids='', $sqlfilters='', $properties='', $pagination_data=false)
List contracts.
getLines($id)
Get lines of a contract.
putLine($id, $lineid, $request_data=null)
Update a line to given contract.
_validate($data)
Validate fields before create or update object.
put($id, $request_data=null)
Update contract general fields (won't touch lines of contract)
deleteLine($id, $lineid)
Delete a line to given contract.
_cleanObjectDatas($object)
Clean sensible object datas.
activateLine($id, $lineid, $datestart, $dateend=null, $comment=null)
Activate a service line of a given contract.
validate($id, $notrigger=0)
Validate a contract.
post($request_data=null)
Create contract object.
unactivateLine($id, $lineid, $datestart, $comment=null)
Unactivate a service line of a given contract.
__construct()
Constructor.
close($id, $notrigger=0)
Close all services of a contract.
postLine($id, $request_data=null)
Add a line to given contract.
Class for API REST v1.
Definition api.class.php:30
_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.
Definition api.class.php:82
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79