dolibarr 25.0.0-alpha
api_vatpayments.class.php
1<?php
2/*
3 * Copyright (C) 2026 Xabier Trigo Losada <xabi@galicloud.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use Luracast\Restler\RestException;
20
21require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
22require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/paymentvat.class.php';
23// PaymentVAT::delete() instantiates AccountLine without requiring it; load it here
24// so deleting a bank-linked payment via the API does not throw a fatal error.
25require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
26
35{
39 public static $FIELDS = array(
40 'datep',
41 'datev',
42 'amount',
43 'label',
44 );
45
49 public static $PAYMENT_FIELDS = array(
50 'datepaye',
51 'amount',
52 'paiementtype',
53 );
54
58 public function __construct()
59 {
60 global $db;
61 $this->db = $db;
62 }
63
73 public function get($id)
74 {
75 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
76 throw new RestException(403);
77 }
78
79 $vat = new Tva($this->db);
80 $result = $vat->fetch($id);
81 // Tva::fetch() returns 1 even when the record does not exist,
82 // so also check that the id was actually loaded.
83 if ($result <= 0 || empty($vat->id)) {
84 throw new RestException(404, 'VAT payment not found');
85 }
86
87 return $this->_cleanObjectDatas($vat);
88 }
89
108 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
109 {
110 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
111 throw new RestException(403);
112 }
113
114 $obj_ret = array();
115
116 $sql = "SELECT t.rowid";
117 $sql .= " FROM ".MAIN_DB_PREFIX."tva AS t";
118 $sql .= " WHERE t.entity IN (".getEntity('tva').")";
119
120 // Add sql filters
121 if ($sqlfilters) {
122 $errormessage = '';
123 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
124 if ($errormessage) {
125 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
126 }
127 }
128
129 // This query will count total records matching the filters (before pagination)
130 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
131
132 $sql .= $this->db->order($sortfield, $sortorder);
133 if ($limit) {
134 if ($page < 0) {
135 $page = 0;
136 }
137 $offset = $limit * $page;
138
139 $sql .= $this->db->plimit($limit + 1, $offset);
140 }
141
142 dol_syslog("API Rest request");
143 $result = $this->db->query($sql);
144
145 if (!$result) {
146 throw new RestException(503, 'Error when retrieving list of VAT payments: '.$this->db->lasterror());
147 }
148
149 $num = $this->db->num_rows($result);
150 $min = min($num, ($limit <= 0 ? $num : $limit));
151 for ($i = 0; $i < $min; $i++) {
152 $obj = $this->db->fetch_object($result);
153 $vat = new Tva($this->db);
154 if ($vat->fetch($obj->rowid) > 0) {
155 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($vat), $properties);
156 }
157 }
158
159 // If $pagination_data is true, the response will contain the element data with all values
160 // and the element pagination with pagination data (total, page, page_count, limit)
161 if ($pagination_data) {
162 $totalsResult = $this->db->query($sqlTotals);
163 $total = $this->db->fetch_object($totalsResult)->total;
164
165 $tmp = $obj_ret;
166 $obj_ret = array();
167
168 $obj_ret['data'] = $tmp;
169 $obj_ret['pagination'] = array(
170 'total' => (int) $total,
171 'page' => $page, // count starts from 0
172 'page_count' => ($limit > 0 ? (int) ceil((int) $total / $limit) : 1),
173 'limit' => $limit
174 );
175 }
176
177 return $obj_ret;
178 }
179
192 public function post($request_data = null)
193 {
194 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'creer')) {
195 throw new RestException(403);
196 }
197
198 // Check mandatory fields
199 $this->_validate($request_data);
200
201 $vat = new Tva($this->db);
202 foreach ($request_data as $field => $value) {
203 if ($field === 'caller') {
204 // 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
205 $vat->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
206 continue;
207 }
208
209 $vat->$field = $this->_checkValForAPI($field, $value, $vat);
210 }
211
212 if ($vat->create(DolibarrApiAccess::$user) < 0) {
213 throw new RestException(500, 'Error when creating VAT payment: '.$vat->errorsToString());
214 }
215
216 return $vat->id;
217 }
218
232 public function put($id, $request_data = null)
233 {
234 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'creer')) {
235 throw new RestException(403);
236 }
237
238 $vat = new Tva($this->db);
239 $result = $vat->fetch($id);
240 // Tva::fetch() returns 1 even when the record does not exist,
241 // so also check that the id was actually loaded.
242 if ($result <= 0 || empty($vat->id)) {
243 throw new RestException(404, 'VAT payment not found');
244 }
245
246 foreach ($request_data as $field => $value) {
247 if ($field == 'id') {
248 continue;
249 }
250 if ($field === 'caller') {
251 // 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
252 $vat->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
253 continue;
254 }
255 if ($field == 'array_options' && is_array($value)) {
256 foreach ($value as $index => $val) {
257 $vat->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $vat);
258 }
259 continue;
260 }
261
262 $vat->$field = $this->_checkValForAPI($field, $value, $vat);
263 }
264
265 if ($vat->update(DolibarrApiAccess::$user) > 0) {
266 return $this->get($id);
267 } else {
268 throw new RestException(500, 'Error when updating VAT payment: '.$vat->errorsToString());
269 }
270 }
271
284 public function delete($id)
285 {
286 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'supprimer')) {
287 throw new RestException(403);
288 }
289
290 $vat = new Tva($this->db);
291 $result = $vat->fetch($id);
292 // Tva::fetch() returns 1 even when the record does not exist,
293 // so also check that the id was actually loaded.
294 if ($result <= 0 || empty($vat->id)) {
295 throw new RestException(404, 'VAT payment not found');
296 }
297
298 // As the card does, and as DELETE /invoices/{id}: not once something is paid
299 if (!empty($vat->getSommePaiement())) {
300 throw new RestException(403, 'VAT declaration not erasable, it has payments');
301 }
302
303 if ($vat->delete(DolibarrApiAccess::$user) < 0) {
304 throw new RestException(500, 'Error when deleting VAT payment: '.$vat->errorsToString());
305 }
306
307 return array(
308 'success' => array(
309 'code' => 200,
310 'message' => 'VAT payment deleted'
311 )
312 );
313 }
314
331 public function getAllPayments($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0)
332 {
333 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
334 throw new RestException(403);
335 }
336
337 $list = array();
338
339 $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX."payment_vat AS t, ".MAIN_DB_PREFIX."tva AS s";
340 $sql .= " WHERE t.fk_tva = s.rowid AND s.entity IN (".getEntity('tva').")";
341 $sql .= $this->db->order($sortfield, $sortorder);
342 if ($limit) {
343 if ($page < 0) {
344 $page = 0;
345 }
346 $offset = $limit * $page;
347 $sql .= $this->db->plimit($limit + 1, $offset);
348 }
349
350 $result = $this->db->query($sql);
351 if (!$result) {
352 throw new RestException(503, 'Error when retrieving list of VAT payments: '.$this->db->lasterror());
353 }
354
355 $num = $this->db->num_rows($result);
356 $min = min($num, ($limit <= 0 ? $num : $limit));
357 for ($i = 0; $i < $min; $i++) {
358 $obj = $this->db->fetch_object($result);
359 $payment = new PaymentVAT($this->db);
360 if ($payment->fetch($obj->rowid) > 0) {
361 $list[] = $this->_cleanObjectDatas($payment);
362 }
363 }
364
365 return $list;
366 }
367
381 public function getPayments($id)
382 {
383 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
384 throw new RestException(403);
385 }
386
387 $list = array();
388
389 $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX."payment_vat AS t";
390 $sql .= " WHERE t.fk_tva = ".((int) $id);
391 $sql .= $this->db->order('t.rowid', 'ASC');
392
393 $result = $this->db->query($sql);
394 if (!$result) {
395 throw new RestException(503, 'Error when retrieving list of VAT payments: '.$this->db->lasterror());
396 }
397
398 $num = $this->db->num_rows($result);
399 for ($i = 0; $i < $num; $i++) {
400 $obj = $this->db->fetch_object($result);
401 $payment = new PaymentVAT($this->db);
402 if ($payment->fetch($obj->rowid) > 0) {
403 $list[] = $this->_cleanObjectDatas($payment);
404 }
405 }
406
407 return $list;
408 }
409
421 public function getPayment($pid)
422 {
423 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
424 throw new RestException(403);
425 }
426
427 $payment = new PaymentVAT($this->db);
428 $result = $payment->fetch($pid);
429 if ($result <= 0 || empty($payment->id)) {
430 throw new RestException(404, 'VAT payment not found');
431 }
432
433 return $this->_cleanObjectDatas($payment);
434 }
435
451 public function addPayment($id, $request_data = null)
452 {
453 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'creer')) {
454 throw new RestException(403);
455 }
456
457 // Check mandatory fields
458 $this->_validatePayment($request_data);
459
460 $payment = new PaymentVAT($this->db);
461 $payment->chid = $id;
462 $payment->datepaye = $request_data['datepaye'];
463 $payment->amounts = array($id => (float) $request_data['amount']);
464 $payment->paiementtype = $request_data['paiementtype'];
465 if (isset($request_data['num_payment'])) {
466 $payment->num_payment = $request_data['num_payment'];
467 }
468 if (isset($request_data['note'])) {
469 $payment->note = $request_data['note'];
470 }
471
472 if ($payment->create(DolibarrApiAccess::$user) < 0) {
473 throw new RestException(500, 'Error when creating VAT payment', array_merge(array($payment->error), $payment->errors));
474 }
475
476 if (isModEnabled("bank") && !empty($request_data['accountid'])) {
477 $payment->addPaymentToBank(DolibarrApiAccess::$user, 'payment_vat', '(VATPayment)', (int) $request_data['accountid'], '', '');
478 }
479
480 return $payment->id;
481 }
482
497 public function deletePayment($pid)
498 {
499 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'supprimer')) {
500 throw new RestException(403);
501 }
502
503 $payment = new PaymentVAT($this->db);
504 $result = $payment->fetch($pid);
505 if ($result <= 0 || empty($payment->id)) {
506 throw new RestException(404, 'VAT payment not found');
507 }
508
509 if ($payment->delete(DolibarrApiAccess::$user) < 0) {
510 throw new RestException(500, 'Error when deleting VAT payment: '.$payment->errorsToString());
511 }
512
513 return array(
514 'success' => array(
515 'code' => 200,
516 'message' => 'VAT payment deleted'
517 )
518 );
519 }
520
529 private function _validate($data)
530 {
531 if ($data === null) {
532 $data = array();
533 }
534 $vat = array();
535 foreach (VatPayments::$FIELDS as $field) {
536 if (!isset($data[$field])) {
537 throw new RestException(400, "$field field missing");
538 }
539 $vat[$field] = $data[$field];
540 }
541 return $vat;
542 }
543
552 private function _validatePayment($data)
553 {
554 if ($data === null) {
555 $data = array();
556 }
557 $payment = array();
558 foreach (VatPayments::$PAYMENT_FIELDS as $field) {
559 if (!isset($data[$field])) {
560 throw new RestException(400, "$field field missing");
561 }
562 $payment[$field] = $data[$field];
563 }
564 return $payment;
565 }
566
567 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
574 protected function _cleanObjectDatas($object)
575 {
576 // phpcs:enable
577 $object = parent::_cleanObjectDatas($object);
578
579 unset($object->statut);
580 unset($object->labelStatus);
581 unset($object->labelStatusShort);
582
583 return $object;
584 }
585}
$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.
Class to manage payments of social contributions.
Class to manage VAT - Value-added tax (also known in French as TVA)
Definition tva.class.php:39
_cleanObjectDatas($object)
Clean sensitive object data.
addPayment($id, $request_data=null)
Add a payment to a VAT declaration.
__construct()
Constructor.
put($id, $request_data=null)
Update a VAT payment (declaration).
deletePayment($pid)
Delete a VAT payment.
getPayments($id)
Get the list of payments of a given VAT declaration.
_validatePayment($data)
Validate fields before creating a VAT payment.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='', $pagination_data=false)
List VAT payments (declarations).
getPayment($pid)
Get a given VAT payment.
getAllPayments($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0)
List all VAT payments.
post($request_data=null)
Create a VAT payment (declaration).
_validate($data)
Validate fields before creating a VAT declaration.
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.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.