dolibarr 22.0.5
api_expensereports.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) 2020-2024 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2025 William Mead <william@m34d.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22use Luracast\Restler\RestException;
23
24require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
25require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php';
26
27
37{
41 public static $FIELDS = array(
42 'fk_user_author',
43 'date_debut',
44 'date_fin',
45 );
46
50 public static $FIELDSPAYMENT = array(
51 "fk_typepayment",
52 'datep',
53 'amounts',
54 );
55
59 public $expensereport;
60
64 public static $FIELDSNOTUPDATABLE = array(
65 'fk_statut', 'status', 'statut', 'paid',
66 'fk_user_valid', 'fk_user_approve', 'fk_user_refuse', 'fk_user_cancel', 'fk_user_creat', 'fk_user_modif',
67 'date_valid', 'date_approve', 'date_refuse', 'date_cancel', 'detail_refuse', 'detail_cancel',
68 'total_ht', 'total_tva', 'total_ttc', 'total_localtax1', 'total_localtax2',
69 'ref', 'entity',
70 );
71
72
76 public function __construct()
77 {
78 global $db;
79
80 $this->db = $db;
81 $this->expensereport = new ExpenseReport($this->db);
82 }
83
96 public function get($id)
97 {
98 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'lire')) {
99 throw new RestException(403);
100 }
101
102 $result = $this->expensereport->fetch($id);
103 if (!$result) {
104 throw new RestException(404, 'Expense report not found');
105 }
106
107 if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) {
108 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
109 }
110
111 $this->expensereport->fetchObjectLinked();
112 return $this->_cleanObjectDatas($this->expensereport);
113 }
114
136 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = '', $sqlfilters = '', $properties = '', $pagination_data = false)
137 {
138 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'lire')) {
139 throw new RestException(403);
140 }
141
142 $obj_ret = array();
143
144 // case of external user, $societe param is ignored and replaced by user's socid
145 //$socid = DolibarrApiAccess::$user->socid ?: $societe;
146
147 $sql = "SELECT t.rowid";
148 $sql .= " FROM ".MAIN_DB_PREFIX."expensereport AS t LEFT JOIN ".MAIN_DB_PREFIX."expensereport_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
149 $sql .= ' WHERE t.entity IN ('.getEntity('expensereport').')';
150 if ($user_ids) {
151 $sql .= " AND t.fk_user_author IN (".$this->db->sanitize($user_ids).")";
152 }
153
154 // Add sql filters
155 if ($sqlfilters) {
156 $errormessage = '';
157 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
158 if ($errormessage) {
159 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
160 }
161 }
162
163 //this query will return total orders with the filters given
164 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
165
166 $sql .= $this->db->order($sortfield, $sortorder);
167 if ($limit) {
168 if ($page < 0) {
169 $page = 0;
170 }
171 $offset = $limit * $page;
172
173 $sql .= $this->db->plimit($limit + 1, $offset);
174 }
175
176 $result = $this->db->query($sql);
177
178 if ($result) {
179 $num = $this->db->num_rows($result);
180 $min = min($num, ($limit <= 0 ? $num : $limit));
181 $i = 0;
182 while ($i < $min) {
183 $obj = $this->db->fetch_object($result);
184 $expensereport_static = new ExpenseReport($this->db);
185 if ($expensereport_static->fetch($obj->rowid)) {
186 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($expensereport_static), $properties);
187 }
188 $i++;
189 }
190 } else {
191 throw new RestException(503, 'Error when retrieve Expense Report list : '.$this->db->lasterror());
192 }
193
194 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
195 if ($pagination_data) {
196 $totalsResult = $this->db->query($sqlTotals);
197 $total = $this->db->fetch_object($totalsResult)->total;
198
199 $tmp = $obj_ret;
200 $obj_ret = [];
201
202 $obj_ret['data'] = $tmp;
203 $obj_ret['pagination'] = [
204 'total' => (int) $total,
205 'page' => $page, //count starts from 0
206 'page_count' => ceil((int) $total / $limit),
207 'limit' => $limit
208 ];
209 }
210
211 return $obj_ret;
212 }
213
226 public function post($request_data = null)
227 {
228 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'creer')) {
229 throw new RestException(403, "Insuffisant rights");
230 }
231
232 // Check mandatory fields
233 $result = $this->_validate($request_data);
234
235 // Same rule as expensereport/card.php: a report can be created only for the user or a user of his hierarchy
236 $fk_user_author = (int) ($request_data['fk_user_author'] ?? 0);
237 if ($fk_user_author > 0 && $fk_user_author != DolibarrApiAccess::$user->id
238 && (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || !DolibarrApiAccess::$user->hasRight('expensereport', 'writeall_advance'))
239 && !in_array($fk_user_author, DolibarrApiAccess::$user->getAllChildIds(1))) {
240 throw new RestException(403, 'User '.$fk_user_author.' is not in the hierarchy of login '.DolibarrApiAccess::$user->login);
241 }
242 // Exclude properties that must be set by the workflow methods or computed from the lines
243 foreach (ExpenseReports::$FIELDSNOTUPDATABLE as $field) {
244 unset($request_data[$field]);
245 }
246
247 foreach ($request_data as $field => $value) {
248 if ($field === 'caller') {
249 // 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
250 $this->expensereport->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
251 continue;
252 }
253
254 $this->expensereport->$field = $this->_checkValForAPI($field, $value, $this->expensereport);
255 }
256 /*if (isset($request_data["lines"])) {
257 $lines = array();
258 foreach ($request_data["lines"] as $line) {
259 array_push($lines, (object) $line);
260 }
261 $this->expensereport->lines = $lines;
262 }*/
263 if ($this->expensereport->create(DolibarrApiAccess::$user) < 0) {
264 throw new RestException(500, "Error creating expensereport", array_merge(array($this->expensereport->error), $this->expensereport->errors));
265 }
266
267 return $this->expensereport->id;
268 }
269
279 /*
280 public function getLines($id)
281 {
282 if(! DolibarrApiAccess::$user->hasRight('expensereport', 'lire')) {
283 throw new RestException(403);
284 }
285
286 $result = $this->expensereport->fetch($id);
287 if( ! $result ) {
288 throw new RestException(404, 'expensereport not found');
289 }
290
291 if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) {
292 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
293 }
294 $this->expensereport->getLinesArray();
295 $result = array();
296 foreach ($this->expensereport->lines as $line) {
297 array_push($result,$this->_cleanObjectDatas($line));
298 }
299 return $result;
300 }
301 */
302
315 /*
316 public function postLine($id, $request_data = null)
317 {
318 if(! DolibarrApiAccess::$user->hasRight('expensereport', 'creer')) {
319 throw new RestException(403);
320 }
321
322 $result = $this->expensereport->fetch($id);
323 if( ! $result ) {
324 throw new RestException(404, 'expensereport not found');
325 }
326
327 if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) {
328 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
329 }
330
331 $request_data = (object) $request_data;
332
333 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
334 $request_data->label = sanitizeVal($request_data->label);
335
336 $updateRes = $this->expensereport->addline(
337 $request_data->desc,
338 $request_data->subprice,
339 $request_data->qty,
340 $request_data->tva_tx,
341 $request_data->localtax1_tx,
342 $request_data->localtax2_tx,
343 $request_data->fk_product,
344 $request_data->remise_percent,
345 $request_data->info_bits,
346 $request_data->fk_remise_except,
347 'HT',
348 0,
349 $request_data->date_start,
350 $request_data->date_end,
351 $request_data->product_type,
352 $request_data->rang,
353 $request_data->special_code,
354 $fk_parent_line,
355 $request_data->fk_fournprice,
356 $request_data->pa_ht,
357 $request_data->label,
358 $request_data->array_options,
359 $request_data->fk_unit,
360 $this->element,
361 $request_data->id
362 );
363
364 if ($updateRes > 0) {
365 return $updateRes;
366
367 }
368 return false;
369 }
370 */
371
385 /*
386 public function putLine($id, $lineid, $request_data = null)
387 {
388 if(! DolibarrApiAccess::$user->hasRight('expensereport', 'creer')) {
389 throw new RestException(403);
390 }
391
392 $result = $this->expensereport->fetch($id);
393 if( ! $result ) {
394 throw new RestException(404, 'expensereport not found');
395 }
396
397 if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) {
398 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
399 }
400
401 $request_data = (object) $request_data;
402
403 $request_data->desc = sanitizeVal($request_data->desc, 'restricthtml');
404 $request_data->label = sanitizeVal($request_data->label);
405
406 $updateRes = $this->expensereport->updateline(
407 $lineid,
408 $request_data->desc,
409 $request_data->subprice,
410 $request_data->qty,
411 $request_data->remise_percent,
412 $request_data->tva_tx,
413 $request_data->localtax1_tx,
414 $request_data->localtax2_tx,
415 'HT',
416 $request_data->info_bits,
417 $request_data->date_start,
418 $request_data->date_end,
419 $request_data->product_type,
420 $request_data->fk_parent_line,
421 0,
422 $request_data->fk_fournprice,
423 $request_data->pa_ht,
424 $request_data->label,
425 $request_data->special_code,
426 $request_data->array_options,
427 $request_data->fk_unit
428 );
429
430 if ($updateRes > 0) {
431 $result = $this->get($id);
432 unset($result->line);
433 return $this->_cleanObjectDatas($result);
434 }
435 return false;
436 }
437 */
438
449 /*
450 public function deleteLine($id, $lineid)
451 {
452 if(! DolibarrApiAccess::$user->hasRight('expensereport', 'creer')) {
453 throw new RestException(403);
454 }
455
456 $result = $this->expensereport->fetch($id);
457 if( ! $result ) {
458 throw new RestException(404, 'expensereport not found');
459 }
460
461 if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) {
462 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
463 }
464
465 // TODO Check the lineid $lineid is a line of object
466
467 $updateRes = $this->expensereport->deleteLine($lineid);
468 if ($updateRes == 1) {
469 return $this->get($id);
470 }
471 return false;
472 }
473 */
474
492 public function put($id, $request_data = null)
493 {
494 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'creer')) {
495 throw new RestException(403);
496 }
497
498 $result = $this->expensereport->fetch($id);
499 if (!$result) {
500 throw new RestException(404, 'expensereport not found');
501 }
502
503 if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport)) {
504 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
505 }
506 // Same rule as expensereport/card.php: only a draft or a refused report can be modified
507 if (!in_array($this->expensereport->status, array(ExpenseReport::STATUS_DRAFT, ExpenseReport::STATUS_REFUSED))) {
508 throw new RestException(403, 'Only a draft or refused expense report can be modified');
509 }
510 // Exclude properties that must be set by the workflow methods or computed from the lines
511 foreach (ExpenseReports::$FIELDSNOTUPDATABLE as $field) {
512 unset($request_data[$field]);
513 }
514 foreach ($request_data as $field => $value) {
515 if ($field == 'id') {
516 continue;
517 }
518 if ($field === 'caller') {
519 // 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
520 $this->expensereport->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
521 continue;
522 }
523
524 if ($field == 'array_options' && is_array($value)) {
525 foreach ($value as $index => $val) {
526 $this->expensereport->array_options[$index] = $this->_checkValForAPI($field, $val, $this->expensereport);
527 }
528 continue;
529 }
530
531 if (!in_array($field, array('fk_statut', 'fk_user_approve'))) { // Exclude properties that must be set by other workflow methods
532 $this->expensereport->$field = $this->_checkValForAPI($field, $value, $this->expensereport);
533 }
534 }
535
536 if ($this->expensereport->update(DolibarrApiAccess::$user) > 0) {
537 return $this->get($id);
538 } else {
539 throw new RestException(500, $this->expensereport->error);
540 }
541 }
542
555 public function delete($id)
556 {
557 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'supprimer')) {
558 throw new RestException(403);
559 }
560
561 $result = $this->expensereport->fetch($id);
562 if (!$result) {
563 throw new RestException(404, 'Expense Report not found');
564 }
565
566 if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) {
567 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
568 }
569
570 if ($this->expensereport->delete(DolibarrApiAccess::$user) <= 0) {
571 throw new RestException(500, 'Error when delete Expense Report : '.$this->expensereport->error);
572 }
573
574 return array(
575 'success' => array(
576 'code' => 200,
577 'message' => 'Expense Report deleted'
578 )
579 );
580 }
581
601 public function validate($id, $notrigger = 0)
602 {
603 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'creer')) {
604 throw new RestException(403, "Insuffisant rights");
605 }
606 $result = $this->expensereport->fetch($id);
607 if (!$result) {
608 throw new RestException(404, 'Expense report not found');
609 }
610
611 if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) {
612 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
613 }
614
615 $result = $this->expensereport->setValidate(DolibarrApiAccess::$user, $notrigger);
616 if ($result == 0) {
617 throw new RestException(304, 'Error nothing done. May be object is already validated');
618 }
619 if ($result < 0) {
620 throw new RestException(500, 'Error when validating expense report: '.$this->expensereport->error);
621 }
622
623 $this->expensereport->fetchObjectLinked();
624
625 return $this->_cleanObjectDatas($this->expensereport);
626 }
627
628
648 public function approve($id, $notrigger = 0)
649 {
650 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'approve')) {
651 throw new RestException(403, "Insuffisant rights");
652 }
653 $result = $this->expensereport->fetch($id);
654 if (!$result) {
655 throw new RestException(404, 'Expense report not found');
656 }
657
658 if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) {
659 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
660 }
661
662 $result = $this->expensereport->setApproved(DolibarrApiAccess::$user, $notrigger);
663 if ($result == 0) {
664 throw new RestException(304, 'Error nothing done. May be object is already approved');
665 }
666 if ($result < 0) {
667 throw new RestException(500, 'Error when approving expense report: '.$this->expensereport->error);
668 }
669
670 $this->expensereport->fetchObjectLinked();
671
672 return $this->_cleanObjectDatas($this->expensereport);
673 }
674
675
696 public function deny($id, $details, $notrigger = 0)
697 {
698 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'approve')) {
699 throw new RestException(403, "Insuffisant rights");
700 }
701 $result = $this->expensereport->fetch($id);
702 if (!$result) {
703 throw new RestException(404, 'Expense report not found');
704 }
705
706 if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) {
707 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
708 }
709
710 $result = $this->expensereport->setDeny(DolibarrApiAccess::$user, $details, $notrigger);
711 if ($result == 0) {
712 throw new RestException(304, 'Error nothing done. May be object is already denied');
713 }
714 if ($result < 0) {
715 throw new RestException(500, 'Error when denying expense report: '.$this->expensereport->error);
716 }
717
718 $this->expensereport->fetchObjectLinked();
719
720 return $this->_cleanObjectDatas($this->expensereport);
721 }
722
723
741 public function getAllPayments($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0)
742 {
743 $list = array();
744
745 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'lire')) {
746 throw new RestException(403);
747 }
748
749 $sql = "SELECT t.rowid FROM " . MAIN_DB_PREFIX . "payment_expensereport as t, ".MAIN_DB_PREFIX."expensereport as e";
750 $sql .= " WHERE e.rowid = t.fk_expensereport";
751 $sql .= ' AND e.entity IN ('.getEntity('expensereport').')';
752
753 $sql .= $this->db->order($sortfield, $sortorder);
754 if ($limit) {
755 if ($page < 0) {
756 $page = 0;
757 }
758 $offset = $limit * $page;
759
760 $sql .= $this->db->plimit($limit + 1, $offset);
761 }
762
763 dol_syslog("API Rest request");
764 $result = $this->db->query($sql);
765
766 if ($result) {
767 $num = $this->db->num_rows($result);
768 $min = min($num, ($limit <= 0 ? $num : $limit));
769 for ($i = 0; $i < $min; $i++) {
770 $obj = $this->db->fetch_object($result);
771 $paymentExpenseReport = new PaymentExpenseReport($this->db);
772 if ($paymentExpenseReport->fetch($obj->rowid) > 0) {
773 $list[] = $this->_cleanObjectDatas($paymentExpenseReport);
774 }
775 }
776 } else {
777 throw new RestException(503, 'Error when retrieving list of paymentexpensereport: ' . $this->db->lasterror());
778 }
779
780 return $list;
781 }
782
795 public function getPayments($pid)
796 {
797 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'lire')) {
798 throw new RestException(403);
799 }
800
801 $paymentExpenseReport = new PaymentExpenseReport($this->db);
802 $result = $paymentExpenseReport->fetch($pid);
803 if (!$result) {
804 throw new RestException(404, 'paymentExpenseReport not found');
805 }
806
807 return $this->_cleanObjectDatas($paymentExpenseReport);
808 }
809
824 public function addPayment($id, $request_data = null)
825 {
826 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'to_paid')) {
827 throw new RestException(403);
828 }
829 // Check mandatory fields
830 $result = $this->_validatepayment($request_data);
831
832 if ($this->expensereport->fetch($id) <= 0) {
833 throw new RestException(404, 'Expense report not found');
834 }
835 // The 'creer' right alone says nothing about whose report this is. expensereport/payment/payment.php
836 // gets the hierarchy check from restrictedArea(); the API must ask for it explicitly, like get() does.
837 if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport)) {
838 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
839 }
840 if (isModEnabled("bank") && !((int) ($request_data['accountid'] ?? 0) > 0)) {
841 throw new RestException(400, "accountid field missing");
842 }
843
844 $paymentExpenseReport = new PaymentExpenseReport($this->db);
845 $paymentExpenseReport->fk_expensereport = $id;
846 foreach ($request_data as $field => $value) {
847 $paymentExpenseReport->$field = $this->_checkValForAPI($field, $value, $paymentExpenseReport);
848 }
849
850 // Same checks as expensereport/payment/payment.php: only an approved report is paid, never more than the remainder
851 if ($this->expensereport->status != ExpenseReport::STATUS_APPROVED) {
852 throw new RestException(400, 'Expense report must be approved to be paid');
853 }
854 $totalpayment = 0;
855 foreach ((array) $paymentExpenseReport->amounts as $value) {
856 $totalpayment += (float) price2num($value, 'MT');
857 }
858 $remaintopay = (float) price2num($this->expensereport->total_ttc - $this->expensereport->getSumPayments(), 'MT');
859 if ((float) price2num($totalpayment, 'MT') > $remaintopay) {
860 throw new RestException(400, 'Payment higher than remainder to pay ('.$remaintopay.')');
861 }
862
863 // Same sequence as expensereport/payment/payment.php: all or nothing
864 $this->db->begin();
865
866 if ($paymentExpenseReport->create(DolibarrApiAccess::$user) < 0) {
867 $this->db->rollback();
868 throw new RestException(400, 'Payment error : '.$paymentExpenseReport->errorsToString());
869 }
870 if (isModEnabled("bank")) {
871 $result = $paymentExpenseReport->addPaymentToBank(
872 DolibarrApiAccess::$user,
873 'payment_expensereport',
874 '(ExpenseReportPayment)',
875 (int) $request_data['accountid'],
876 '',
877 ''
878 );
879 if ($result <= 0) {
880 $this->db->rollback();
881 throw new RestException(400, 'Add payment to bank error : '.$paymentExpenseReport->errorsToString());
882 }
883 }
884
885 $remaintopay = price2num($this->expensereport->total_ttc - $this->expensereport->getSumPayments(), 'MT');
886 if ($remaintopay == 0 && $this->expensereport->setPaid($this->expensereport->id, DolibarrApiAccess::$user) < 0) {
887 $this->db->rollback();
888 throw new RestException(400, 'Set paid error : '.$this->expensereport->errorsToString());
889 }
890
891 $this->db->commit();
892
893 return $paymentExpenseReport->id;
894 }
895
910 public function updatePayment($id, $request_data = null)
911 {
912 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'to_paid')) {
913 throw new RestException(403);
914 }
915
916 $paymentExpenseReport = new PaymentExpenseReport($this->db);
917 $result = $paymentExpenseReport->fetch($id);
918 if (!$result) {
919 throw new RestException(404, 'payment of expense report not found');
920 }
921
922 // Check access to the parent expense report
923 $result = $this->expensereport->fetch($paymentExpenseReport->fk_expensereport);
924 if (!$result) {
925 throw new RestException(404, 'Expense report not found');
926 }
927
928 if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport)) {
929 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
930 }
931
932 foreach ($request_data as $field => $value) {
933 if ($field == 'id' || $field == 'fk_expensereport') { // A payment can't be moved to another report
934 continue;
935 }
936 $paymentExpenseReport->$field = $this->_checkValForAPI($field, $value, $paymentExpenseReport);
937 }
938
939 // The payments of the report can't exceed its total
940 $oldpayment = new PaymentExpenseReport($this->db);
941 $oldpayment->fetch($paymentExpenseReport->id);
942 $remaintopay = (float) price2num($this->expensereport->total_ttc - $this->expensereport->getSumPayments() + (float) $oldpayment->amount, 'MT');
943 if ((float) price2num($paymentExpenseReport->amount, 'MT') > $remaintopay) {
944 throw new RestException(400, 'Payment higher than remainder to pay ('.$remaintopay.')');
945 }
946
947 if ($paymentExpenseReport->update(DolibarrApiAccess::$user) > 0) {
948 return $this->get($id);
949 } else {
950 throw new RestException(500, $paymentExpenseReport->error);
951 }
952 }
953
962 /*public function delete($id)
963 {
964 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'creer') {
965 throw new RestException(403);
966 }
967 $paymentExpenseReport = new PaymentExpenseReport($this->db);
968 $result = $paymentExpenseReport->fetch($id);
969 if (!$result) {
970 throw new RestException(404, 'paymentExpenseReport not found');
971 }
972
973 if ($paymentExpenseReport->delete(DolibarrApiAccess::$user) < 0) {
974 throw new RestException(403, 'error when deleting paymentExpenseReport');
975 }
976
977 return array(
978 'success' => array(
979 'code' => 200,
980 'message' => 'paymentExpenseReport deleted'
981 )
982 );
983 }*/
984
985
986
987 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
994 protected function _cleanObjectDatas($object)
995 {
996 // phpcs:enable
997 $object = parent::_cleanObjectDatas($object);
998
999 unset($object->fk_statut);
1000 unset($object->statut);
1001 unset($object->user);
1002 unset($object->thirdparty);
1003
1004 unset($object->cond_reglement);
1005 unset($object->shipping_method_id);
1006
1007 unset($object->barcode_type);
1008 unset($object->barcode_type_code);
1009 unset($object->barcode_type_label);
1010 unset($object->barcode_type_coder);
1011
1012 unset($object->code_paiement);
1013 unset($object->code_statut);
1014 unset($object->fk_c_paiement);
1015 unset($object->fk_incoterms);
1016 unset($object->label_incoterms);
1017 unset($object->location_incoterms);
1018 unset($object->mode_reglement_id);
1019 unset($object->cond_reglement_id);
1020
1021 unset($object->name);
1022 unset($object->lastname);
1023 unset($object->firstname);
1024 unset($object->civility_id);
1025 unset($object->cond_reglement_id);
1026 unset($object->contact);
1027 unset($object->contact_id);
1028
1029 unset($object->state);
1030 unset($object->state_id);
1031 unset($object->state_code);
1032 unset($object->country);
1033 unset($object->country_id);
1034 unset($object->country_code);
1035
1036 unset($object->note); // We already use note_public and note_pricate
1037
1038 return $object;
1039 }
1040
1048 private function _validate($data)
1049 {
1050 if ($data === null) {
1051 $data = array();
1052 }
1053 $expensereport = array();
1054 foreach (ExpenseReports::$FIELDS as $field) {
1055 if (!isset($data[$field])) {
1056 throw new RestException(400, "$field field missing");
1057 }
1058 $expensereport[$field] = $data[$field];
1059 }
1060 return $expensereport;
1061 }
1062
1070 private function _validatepayment($data)
1071 {
1072 if ($data === null) {
1073 $data = array();
1074 }
1075 $expensereport = array();
1076 foreach (ExpenseReports::$FIELDSPAYMENT as $field) {
1077 if (!isset($data[$field])) {
1078 throw new RestException(400, "$field field missing");
1079 }
1080 $expensereport[$field] = $data[$field];
1081 }
1082 return $expensereport;
1083 }
1084}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
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.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:98
Class to manage Trips and Expenses.
const STATUS_DRAFT
Draft status.
const STATUS_APPROVED
Classified approved.
const STATUS_REFUSED
Classified refused.
getPayments($pid)
Get an expense report payment.
deny($id, $details, $notrigger=0)
Deny an expense report.
_cleanObjectDatas($object)
Delete paymentExpenseReport.
_validate($data)
Validate fields before create or update object.
validate($id, $notrigger=0)
Validate an expense report.
updatePayment($id, $request_data=null)
Update a payment of an expense report.
approve($id, $notrigger=0)
Approve an expense report.
put($id, $request_data=null)
Get lines of an Expense Report.
addPayment($id, $request_data=null)
Create a payment for an expense report.
getAllPayments($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0)
Get the list of payments of an expense report.
post($request_data=null)
Create an expense report.
_validatepayment($data)
Validate fields before create or update object.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $user_ids='', $sqlfilters='', $properties='', $pagination_data=false)
List expense reports.
Class to manage payments of expense report.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
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.