dolibarr 25.0.0-alpha
api_socialcontributions.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/sociales/class/chargesociales.class.php';
22require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/paymentsocialcontribution.class.php';
23// PaymentSocialContribution::delete() instantiates AccountLine without requiring
24// it; load it here so deleting a bank-linked payment via the API does not fatal.
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 'fk_type',
42 'date_ech',
43 'period',
44 'amount',
45 'label',
46 );
47
51 public static $PAYMENT_FIELDS = array(
52 'datepaye',
53 'amount',
54 'paiementtype',
55 );
56
60 public function __construct()
61 {
62 global $db;
63 $this->db = $db;
64 }
65
75 public function get($id)
76 {
77 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
78 throw new RestException(403);
79 }
80
81 $contrib = new ChargeSociales($this->db);
82 $result = $contrib->fetch($id);
83 if ($result <= 0 || empty($contrib->id)) {
84 throw new RestException(404, 'Social contribution not found');
85 }
86
87 return $this->_cleanObjectDatas($contrib);
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."chargesociales AS t";
118 $sql .= " WHERE t.entity IN (".getEntity('chargesociales').")";
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 social contributions: '.$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 $contrib = new ChargeSociales($this->db);
154 if ($contrib->fetch($obj->rowid) > 0) {
155 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($contrib), $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 $contrib = new ChargeSociales($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 $contrib->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
206 continue;
207 }
208 // The business class stores the contribution type id in property "type" (int)
209 if ($field == 'fk_type') {
210 $contrib->type = (int) $value;
211 continue;
212 }
213
214 $contrib->$field = $this->_checkValForAPI($field, $value, $contrib);
215 }
216
217 if ($contrib->create(DolibarrApiAccess::$user) < 0) {
218 throw new RestException(500, 'Error when creating social contribution: '.$contrib->errorsToString());
219 }
220
221 return $contrib->id;
222 }
223
237 public function put($id, $request_data = null)
238 {
239 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'creer')) {
240 throw new RestException(403);
241 }
242
243 $contrib = new ChargeSociales($this->db);
244 $result = $contrib->fetch($id);
245 if ($result <= 0 || empty($contrib->id)) {
246 throw new RestException(404, 'Social contribution not found');
247 }
248
249 foreach ($request_data as $field => $value) {
250 if ($field == 'id') {
251 continue;
252 }
253 if ($field === 'caller') {
254 // 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
255 $contrib->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
256 continue;
257 }
258 if ($field == 'array_options' && is_array($value)) {
259 foreach ($value as $index => $val) {
260 $contrib->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $contrib);
261 }
262 continue;
263 }
264 // The business class stores the contribution type id in property "type" (int)
265 if ($field == 'fk_type') {
266 $contrib->type = (int) $value;
267 continue;
268 }
269
270 $contrib->$field = $this->_checkValForAPI($field, $value, $contrib);
271 }
272
273 if ($contrib->update(DolibarrApiAccess::$user) > 0) {
274 return $this->get($id);
275 } else {
276 throw new RestException(500, 'Error when updating social contribution: '.$contrib->errorsToString());
277 }
278 }
279
292 public function delete($id)
293 {
294 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'supprimer')) {
295 throw new RestException(403);
296 }
297
298 $contrib = new ChargeSociales($this->db);
299 $result = $contrib->fetch($id);
300 if ($result <= 0 || empty($contrib->id)) {
301 throw new RestException(404, 'Social contribution not found');
302 }
303
304 // As the card does, and as DELETE /invoices/{id}: not once something is paid
305 if (!empty($contrib->getSommePaiement())) {
306 throw new RestException(403, 'Social contribution not erasable, it has payments');
307 }
308
309 if ($contrib->delete(DolibarrApiAccess::$user) < 0) {
310 throw new RestException(500, 'Error when deleting social contribution: '.$contrib->errorsToString());
311 }
312
313 return array(
314 'success' => array(
315 'code' => 200,
316 'message' => 'Social contribution deleted'
317 )
318 );
319 }
320
337 public function getAllPayments($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0)
338 {
339 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
340 throw new RestException(403);
341 }
342
343 $list = array();
344
345 $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX."paiementcharge AS t, ".MAIN_DB_PREFIX."chargesociales AS s";
346 $sql .= " WHERE t.fk_charge = s.rowid AND s.entity IN (".getEntity('chargesociales').")";
347 $sql .= $this->db->order($sortfield, $sortorder);
348 if ($limit) {
349 if ($page < 0) {
350 $page = 0;
351 }
352 $offset = $limit * $page;
353 $sql .= $this->db->plimit($limit + 1, $offset);
354 }
355
356 $result = $this->db->query($sql);
357 if (!$result) {
358 throw new RestException(503, 'Error when retrieving list of payments: '.$this->db->lasterror());
359 }
360
361 $num = $this->db->num_rows($result);
362 $min = min($num, ($limit <= 0 ? $num : $limit));
363 for ($i = 0; $i < $min; $i++) {
364 $obj = $this->db->fetch_object($result);
365 $payment = new PaymentSocialContribution($this->db);
366 if ($payment->fetch($obj->rowid) > 0) {
367 $list[] = $this->_cleanObjectDatas($payment);
368 }
369 }
370
371 return $list;
372 }
373
387 public function getPayments($id)
388 {
389 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
390 throw new RestException(403);
391 }
392
393 $list = array();
394
395 $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX."paiementcharge AS t";
396 $sql .= " WHERE t.fk_charge = ".((int) $id);
397 $sql .= $this->db->order('t.rowid', 'ASC');
398
399 $result = $this->db->query($sql);
400 if (!$result) {
401 throw new RestException(503, 'Error when retrieving list of payments: '.$this->db->lasterror());
402 }
403
404 $num = $this->db->num_rows($result);
405 for ($i = 0; $i < $num; $i++) {
406 $obj = $this->db->fetch_object($result);
407 $payment = new PaymentSocialContribution($this->db);
408 if ($payment->fetch($obj->rowid) > 0) {
409 $list[] = $this->_cleanObjectDatas($payment);
410 }
411 }
412
413 return $list;
414 }
415
427 public function getPayment($pid)
428 {
429 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'lire')) {
430 throw new RestException(403);
431 }
432
433 $payment = new PaymentSocialContribution($this->db);
434 $result = $payment->fetch($pid);
435 if ($result <= 0 || empty($payment->id)) {
436 throw new RestException(404, 'Payment not found');
437 }
438
439 return $this->_cleanObjectDatas($payment);
440 }
441
457 public function addPayment($id, $request_data = null)
458 {
459 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'creer')) {
460 throw new RestException(403);
461 }
462
463 // Check mandatory fields
464 $this->_validatePayment($request_data);
465 if (isModEnabled("bank") && !((int) ($request_data['accountid'] ?? 0) > 0)) {
466 throw new RestException(400, 'accountid field missing');
467 }
468 // A day alone is taken at noon, as the payment form does
469 $datepaye = is_numeric($request_data['datepaye']) ? (int) $request_data['datepaye'] : dol_stringtotime((string) $request_data['datepaye'], 1, 1);
470 if (empty($datepaye)) {
471 throw new RestException(400, 'datepaye must be a timestamp or a date YYYY-MM-DD');
472 }
473
474 $contrib = new ChargeSociales($this->db);
475 if ($contrib->fetch($id) <= 0 || empty($contrib->id)) {
476 throw new RestException(404, 'Social contribution not found');
477 }
478
479 $payment = new PaymentSocialContribution($this->db);
480 $payment->chid = $contrib->id;
481 $payment->datepaye = $datepaye;
482 $payment->amounts = array($contrib->id => (float) $request_data['amount']);
483 $payment->paiementtype = $request_data['paiementtype'];
484 if (isset($request_data['num_payment'])) {
485 $payment->num_payment = $request_data['num_payment'];
486 }
487 if (isset($request_data['note'])) {
488 $payment->note = $request_data['note'];
489 }
490 // Same default as the payment form: a contribution paid in full is closed
491 $closepaidcontrib = isset($request_data['closepaidcontrib']) ? (int) $request_data['closepaidcontrib'] : 1;
492
493 // Payment and bank line are written together, or not at all
494 $this->db->begin();
495
496 if ($payment->create(DolibarrApiAccess::$user, $closepaidcontrib) < 0) {
497 $this->db->rollback();
498 throw new RestException(400, 'Payment error : '.$payment->errorsToString());
499 }
500
501 if (isModEnabled("bank")) {
502 if ($payment->addPaymentToBank(DolibarrApiAccess::$user, 'payment_sc', '(SocialContributionPayment)', (int) $request_data['accountid'], '', '') <= 0) {
503 $this->db->rollback();
504 throw new RestException(400, 'Add payment to bank error : '.$payment->errorsToString());
505 }
506 }
507
508 $this->db->commit();
509
510 return $payment->id;
511 }
512
527 public function deletePayment($pid)
528 {
529 if (!DolibarrApiAccess::$user->hasRight('tax', 'charges', 'supprimer')) {
530 throw new RestException(403);
531 }
532
533 $payment = new PaymentSocialContribution($this->db);
534 $result = $payment->fetch($pid);
535 if ($result <= 0 || empty($payment->id)) {
536 throw new RestException(404, 'Payment not found');
537 }
538
539 if ($payment->delete(DolibarrApiAccess::$user) < 0) {
540 throw new RestException(500, 'Error when deleting payment: '.$payment->errorsToString());
541 }
542
543 return array(
544 'success' => array(
545 'code' => 200,
546 'message' => 'Payment deleted'
547 )
548 );
549 }
550
559 private function _validate($data)
560 {
561 if ($data === null) {
562 $data = array();
563 }
564 $contrib = array();
565 foreach (SocialContributions::$FIELDS as $field) {
566 if (!isset($data[$field])) {
567 throw new RestException(400, "$field field missing");
568 }
569 $contrib[$field] = $data[$field];
570 }
571 return $contrib;
572 }
573
582 private function _validatePayment($data)
583 {
584 if ($data === null) {
585 $data = array();
586 }
587 $payment = array();
588 foreach (SocialContributions::$PAYMENT_FIELDS as $field) {
589 if (!isset($data[$field])) {
590 throw new RestException(400, "$field field missing");
591 }
592 $payment[$field] = $data[$field];
593 }
594 return $payment;
595 }
596
597 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
604 protected function _cleanObjectDatas($object)
605 {
606 // phpcs:enable
607 $object = parent::_cleanObjectDatas($object);
608
609 unset($object->statut);
610 unset($object->labelStatus);
611 unset($object->labelStatusShort);
612
613 return $object;
614 }
615}
$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 managing the social charges.
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.
_validate($data)
Validate fields before creating a social contribution.
put($id, $request_data=null)
Update a social contribution.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='', $pagination_data=false)
List social contributions.
post($request_data=null)
Create a social contribution.
_cleanObjectDatas($object)
Clean sensitive object data.
getPayment($pid)
Get a given social contribution payment.
_validatePayment($data)
Validate fields before creating a payment.
addPayment($id, $request_data=null)
Add a payment to a social contribution.
getAllPayments($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0)
List all social contribution payments.
deletePayment($pid)
Delete a social contribution payment.
getPayments($id)
Get the list of payments of a given social contribution.
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:442
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.