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';
26require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
27
36{
40 public static $FIELDS = array(
41 'datep',
42 'datev',
43 'amount',
44 'label',
45 );
46
50 public static $PAYMENT_FIELDS = array(
51 'datepaye',
52 'amount',
53 'paiementtype',
54 );
55
59 public function __construct()
60 {
61 global $db;
62 $this->db = $db;
63 }
64
74 public function get($id)
75 {
76 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
77 throw new RestException(403);
78 }
79
80 $vat = new Tva($this->db);
81 $result = $vat->fetch($id);
82 // Tva::fetch() returns 1 even when the record does not exist,
83 // so also check that the id was actually loaded.
84 if ($result <= 0 || empty($vat->id)) {
85 throw new RestException(404, 'VAT payment not found');
86 }
87
88 return $this->_cleanObjectDatas($vat);
89 }
90
109 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
110 {
111 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
112 throw new RestException(403);
113 }
114
115 $obj_ret = array();
116
117 $sql = "SELECT t.rowid";
118 $sql .= " FROM ".MAIN_DB_PREFIX."tva AS t";
119 $sql .= " WHERE t.entity IN (".getEntity('tva').")";
120
121 // Add sql filters
122 if ($sqlfilters) {
123 $errormessage = '';
124 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
125 if ($errormessage) {
126 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
127 }
128 }
129
130 // This query will count total records matching the filters (before pagination)
131 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
132
133 $sql .= $this->db->order($sortfield, $sortorder);
134 if ($limit) {
135 if ($page < 0) {
136 $page = 0;
137 }
138 $offset = $limit * $page;
139
140 $sql .= $this->db->plimit($limit + 1, $offset);
141 }
142
143 dol_syslog("API Rest request");
144 $result = $this->db->query($sql);
145
146 if (!$result) {
147 throw new RestException(503, 'Error when retrieving list of VAT payments: '.$this->db->lasterror());
148 }
149
150 $num = $this->db->num_rows($result);
151 $min = min($num, ($limit <= 0 ? $num : $limit));
152 for ($i = 0; $i < $min; $i++) {
153 $obj = $this->db->fetch_object($result);
154 $vat = new Tva($this->db);
155 if ($vat->fetch($obj->rowid) > 0) {
156 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($vat), $properties);
157 }
158 }
159
160 // If $pagination_data is true, the response will contain the element data with all values
161 // and the element pagination with pagination data (total, page, page_count, limit)
162 if ($pagination_data) {
163 $totalsResult = $this->db->query($sqlTotals);
164 $total = $this->db->fetch_object($totalsResult)->total;
165
166 $tmp = $obj_ret;
167 $obj_ret = array();
168
169 $obj_ret['data'] = $tmp;
170 $obj_ret['pagination'] = array(
171 'total' => (int) $total,
172 'page' => $page, // count starts from 0
173 'page_count' => ($limit > 0 ? (int) ceil((int) $total / $limit) : 1),
174 'limit' => $limit
175 );
176 }
177
178 return $obj_ret;
179 }
180
193 public function post($request_data = null)
194 {
195 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'creer')) {
196 throw new RestException(403);
197 }
198
199 // Check mandatory fields
200 $this->_validate($request_data);
201
202 $vat = new Tva($this->db);
203 foreach ($request_data as $field => $value) {
204 if ($field === 'caller') {
205 // 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
206 $vat->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
207 continue;
208 }
209
210 $vat->$field = $this->_checkValForAPI($field, $value, $vat);
211 }
212
213 if ($vat->create(DolibarrApiAccess::$user) < 0) {
214 throw new RestException(500, 'Error when creating VAT payment: '.$vat->errorsToString());
215 }
216
217 return $vat->id;
218 }
219
233 public function put($id, $request_data = null)
234 {
235 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'creer')) {
236 throw new RestException(403);
237 }
238
239 $vat = new Tva($this->db);
240 $result = $vat->fetch($id);
241 // Tva::fetch() returns 1 even when the record does not exist,
242 // so also check that the id was actually loaded.
243 if ($result <= 0 || empty($vat->id)) {
244 throw new RestException(404, 'VAT payment not found');
245 }
246
247 foreach ($request_data as $field => $value) {
248 if ($field == 'id') {
249 continue;
250 }
251 if ($field === 'caller') {
252 // 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
253 $vat->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
254 continue;
255 }
256 if ($field == 'array_options' && is_array($value)) {
257 foreach ($value as $index => $val) {
258 $vat->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $vat);
259 }
260 continue;
261 }
262
263 $vat->$field = $this->_checkValForAPI($field, $value, $vat);
264 }
265
266 if ($vat->update(DolibarrApiAccess::$user) > 0) {
267 return $this->get($id);
268 } else {
269 throw new RestException(500, 'Error when updating VAT payment: '.$vat->errorsToString());
270 }
271 }
272
285 public function delete($id)
286 {
287 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'supprimer')) {
288 throw new RestException(403);
289 }
290
291 $vat = new Tva($this->db);
292 $result = $vat->fetch($id);
293 // Tva::fetch() returns 1 even when the record does not exist,
294 // so also check that the id was actually loaded.
295 if ($result <= 0 || empty($vat->id)) {
296 throw new RestException(404, 'VAT payment not found');
297 }
298
299 // As the card does, and as DELETE /invoices/{id}: not once something is paid
300 if (!empty($vat->getSommePaiement())) {
301 throw new RestException(403, 'VAT declaration not erasable, it has payments');
302 }
303
304 if ($vat->delete(DolibarrApiAccess::$user) < 0) {
305 throw new RestException(500, 'Error when deleting VAT payment: '.$vat->errorsToString());
306 }
307
308 return array(
309 'success' => array(
310 'code' => 200,
311 'message' => 'VAT payment deleted'
312 )
313 );
314 }
315
332 public function getAllPayments($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0)
333 {
334 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
335 throw new RestException(403);
336 }
337
338 $list = array();
339
340 $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX."payment_vat AS t, ".MAIN_DB_PREFIX."tva AS s";
341 $sql .= " WHERE t.fk_tva = s.rowid AND s.entity IN (".getEntity('tva').")";
342 $sql .= $this->db->order($sortfield, $sortorder);
343 if ($limit) {
344 if ($page < 0) {
345 $page = 0;
346 }
347 $offset = $limit * $page;
348 $sql .= $this->db->plimit($limit + 1, $offset);
349 }
350
351 $result = $this->db->query($sql);
352 if (!$result) {
353 throw new RestException(503, 'Error when retrieving list of VAT payments: '.$this->db->lasterror());
354 }
355
356 $num = $this->db->num_rows($result);
357 $min = min($num, ($limit <= 0 ? $num : $limit));
358 for ($i = 0; $i < $min; $i++) {
359 $obj = $this->db->fetch_object($result);
360 $payment = new PaymentVAT($this->db);
361 if ($payment->fetch($obj->rowid) > 0) {
362 $list[] = $this->_cleanObjectDatas($payment);
363 }
364 }
365
366 return $list;
367 }
368
382 public function getPayments($id)
383 {
384 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
385 throw new RestException(403);
386 }
387
388 $list = array();
389
390 $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX."payment_vat AS t";
391 $sql .= " WHERE t.fk_tva = ".((int) $id);
392 $sql .= $this->db->order('t.rowid', 'ASC');
393
394 $result = $this->db->query($sql);
395 if (!$result) {
396 throw new RestException(503, 'Error when retrieving list of VAT payments: '.$this->db->lasterror());
397 }
398
399 $num = $this->db->num_rows($result);
400 for ($i = 0; $i < $num; $i++) {
401 $obj = $this->db->fetch_object($result);
402 $payment = new PaymentVAT($this->db);
403 if ($payment->fetch($obj->rowid) > 0) {
404 $list[] = $this->_cleanObjectDatas($payment);
405 }
406 }
407
408 return $list;
409 }
410
422 public function getPayment($pid)
423 {
424 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
425 throw new RestException(403);
426 }
427
428 $payment = new PaymentVAT($this->db);
429 $result = $payment->fetch($pid);
430 if ($result <= 0 || empty($payment->id)) {
431 throw new RestException(404, 'VAT payment not found');
432 }
433
434 return $this->_cleanObjectDatas($payment);
435 }
436
452 public function addPayment($id, $request_data = null)
453 {
454 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'creer')) {
455 throw new RestException(403);
456 }
457
458 // Check mandatory fields
459 $this->_validatePayment($request_data);
460 if (isModEnabled("bank") && !((int) ($request_data['accountid'] ?? 0) > 0)) {
461 throw new RestException(400, 'accountid field missing');
462 }
463 // A day alone is taken at noon, as the payment form does
464 $datepaye = is_numeric($request_data['datepaye']) ? (int) $request_data['datepaye'] : dol_stringtotime((string) $request_data['datepaye'], 1, 1);
465 if (empty($datepaye)) {
466 throw new RestException(400, 'datepaye must be a timestamp or a date YYYY-MM-DD');
467 }
468
469 $vat = new Tva($this->db);
470 if ($vat->fetch($id) <= 0 || empty($vat->id)) {
471 throw new RestException(404, 'VAT declaration not found');
472 }
473
474 $payment = new PaymentVAT($this->db);
475 $payment->chid = $vat->id;
476 $payment->datepaye = $datepaye;
477 $payment->amounts = array($vat->id => (float) $request_data['amount']);
478 $payment->paiementtype = $request_data['paiementtype'];
479 if (isset($request_data['num_payment'])) {
480 $payment->num_payment = $request_data['num_payment'];
481 }
482 if (isset($request_data['note'])) {
483 $payment->note = $request_data['note'];
484 }
485 // Same default as the payment form: a VAT declaration paid in full is closed
486 $closepaidvat = isset($request_data['closepaidvat']) ? (int) $request_data['closepaidvat'] : 1;
487
488 // Payment and bank line are written together, or not at all
489 $this->db->begin();
490
491 if ($payment->create(DolibarrApiAccess::$user, $closepaidvat) < 0) {
492 $this->db->rollback();
493 throw new RestException(400, 'Payment error : '.$payment->errorsToString());
494 }
495
496 if (isModEnabled("bank")) {
497 if ($payment->addPaymentToBank(DolibarrApiAccess::$user, 'payment_vat', '(VATPayment)', (int) $request_data['accountid'], '', '') <= 0) {
498 $this->db->rollback();
499 throw new RestException(400, 'Add payment to bank error : '.$payment->errorsToString());
500 }
501 }
502
503 $this->db->commit();
504
505 return $payment->id;
506 }
507
522 public function deletePayment($pid)
523 {
524 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'supprimer')) {
525 throw new RestException(403);
526 }
527
528 $payment = new PaymentVAT($this->db);
529 $result = $payment->fetch($pid);
530 if ($result <= 0 || empty($payment->id)) {
531 throw new RestException(404, 'VAT payment not found');
532 }
533
534 if ($payment->delete(DolibarrApiAccess::$user) < 0) {
535 throw new RestException(500, 'Error when deleting VAT payment: '.$payment->errorsToString());
536 }
537
538 return array(
539 'success' => array(
540 'code' => 200,
541 'message' => 'VAT payment deleted'
542 )
543 );
544 }
545
554 private function _validate($data)
555 {
556 if ($data === null) {
557 $data = array();
558 }
559 $vat = array();
560 foreach (VatPayments::$FIELDS as $field) {
561 if (!isset($data[$field])) {
562 throw new RestException(400, "$field field missing");
563 }
564 $vat[$field] = $data[$field];
565 }
566 return $vat;
567 }
568
577 private function _validatePayment($data)
578 {
579 if ($data === null) {
580 $data = array();
581 }
582 $payment = array();
583 foreach (VatPayments::$PAYMENT_FIELDS as $field) {
584 if (!isset($data[$field])) {
585 throw new RestException(400, "$field field missing");
586 }
587 $payment[$field] = $data[$field];
588 }
589 return $payment;
590 }
591
592 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
599 protected function _cleanObjectDatas($object)
600 {
601 // phpcs:enable
602 $object = parent::_cleanObjectDatas($object);
603
604 unset($object->statut);
605 unset($object->labelStatus);
606 unset($object->labelStatusShort);
607
608 return $object;
609 }
610}
$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.
dol_stringtotime($string, $gm=1, $processnotimeasnoon=0)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:452
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.