dolibarr 24.0.0-beta
api_bankaccounts.class.php
1<?php
2/*
3 * Copyright (C) 2016 Xebax Christy <xebax@wanadoo.fr>
4 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2025 Charlene Benke <charlene@patas-monkey.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 . '/compta/bank/class/account.class.php';
25
34{
38 public static $FIELDS = array(
39 'ref',
40 'label',
41 'type',
42 'currency_code',
43 'country_id'
44 );
45
49 public function __construct()
50 {
51 global $db;
52 $this->db = $db;
53 }
54
71 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $category = 0, $sqlfilters = '', $properties = '')
72 {
73 $list = array();
74
75 if (!DolibarrApiAccess::$user->hasRight('banque', 'lire')) {
76 throw new RestException(403);
77 }
78
79 $sql = "SELECT t.rowid FROM ".MAIN_DB_PREFIX."bank_account AS t LEFT JOIN ".MAIN_DB_PREFIX."bank_account_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
80 if ($category > 0) {
81 $sql .= ", " . MAIN_DB_PREFIX . "categorie_account as c";
82 }
83 $sql .= ' WHERE t.entity IN (' . getEntity('bank_account') . ')';
84 // Select accounts of given category
85 if ($category > 0) {
86 $sql .= " AND c.fk_categorie = " . ((int) $category) . " AND c.fk_account = t.rowid";
87 }
88 // Add sql filters
89 if ($sqlfilters) {
90 $errormessage = '';
91 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
92 if ($errormessage) {
93 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
94 }
95 }
96
97 $sql .= $this->db->order($sortfield, $sortorder);
98 if ($limit) {
99 if ($page < 0) {
100 $page = 0;
101 }
102 $offset = $limit * $page;
103
104 $sql .= $this->db->plimit($limit + 1, $offset);
105 }
106
107 dol_syslog("API Rest request");
108 $result = $this->db->query($sql);
109
110 if ($result) {
111 $num = $this->db->num_rows($result);
112 $min = min($num, ($limit <= 0 ? $num : $limit));
113 for ($i = 0; $i < $min; $i++) {
114 $obj = $this->db->fetch_object($result);
115 $account = new Account($this->db);
116 if ($account->fetch($obj->rowid) > 0) {
117 $account->balance = $account->solde(1); // 1=Exclude future operation date
118 $list[] = $this->_filterObjectProperties($this->_cleanObjectDatas($account), $properties);
119 }
120 }
121 } else {
122 throw new RestException(503, 'Error when retrieving list of accounts: ' . $this->db->lasterror());
123 }
124
125 return $list;
126 }
127
136 public function get($id)
137 {
138 if (!DolibarrApiAccess::$user->hasRight('banque', 'lire')) {
139 throw new RestException(403);
140 }
141
142 $account = new Account($this->db);
143 $result = $account->fetch($id);
144 if (!$result) {
145 throw new RestException(404, 'account not found');
146 }
147
148 return $this->_cleanObjectDatas($account);
149 }
150
159 public function post($request_data = null)
160 {
161 if (!DolibarrApiAccess::$user->hasRight('banque', 'configurer')) {
162 throw new RestException(403);
163 }
164 // Check mandatory fields
165 $this->_validate($request_data);
166
167 $account = new Account($this->db);
168 // Date of the initial balance (required to create an account).
169 $account->date_solde = time();
170 foreach ($request_data as $field => $value) {
171 if ($field === 'caller') {
172 // 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
173 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
174 continue;
175 }
176
177 $account->$field = $this->_checkValForAPI($field, $value, $account);
178 }
179
180 if ($account->create(DolibarrApiAccess::$user) < 0) {
181 throw new RestException(500, 'Error creating bank account', array_merge(array($account->error), $account->errors));
182 }
183 return $account->id;
184 }
185
210 public function transfer($bankaccount_from_id = 0, $bankaccount_to_id = 0, $date = null, $description = "", $amount = 0.0, $amount_to = 0.0, $cheque_number = "")
211 {
212 if (!DolibarrApiAccess::$user->hasRight('banque', 'configurer')) {
213 throw new RestException(403);
214 }
215
216 require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
217
218 $accountfrom = new Account($this->db);
219 $resultAccountFrom = $accountfrom->fetch($bankaccount_from_id);
220
221 if ($resultAccountFrom === 0) {
222 throw new RestException(404, 'The BankAccount for bankaccount_from_id provided does not exist.');
223 }
224
225 $accountto = new Account($this->db);
226 $resultAccountTo = $accountto->fetch($bankaccount_to_id);
227
228 if ($resultAccountTo === 0) {
229 throw new RestException(404, 'The BankAccount for bankaccount_to_id provided does not exist.');
230 }
231
232 if ($accountto->currency_code == $accountfrom->currency_code) {
233 $amount_to = $amount;
234 } else {
235 if (!$amount_to || empty($amount_to)) {
236 throw new RestException(422, 'You must provide amount_to value since bankaccount_from and bankaccount_to does not share the same currency.');
237 }
238 }
239
240 if ($amount_to < 0) {
241 throw new RestException(422, 'You must provide a positive value for amount.');
242 }
243
244 if ($accountto->id == $accountfrom->id) {
245 throw new RestException(422, 'bankaccount_from_id and bankaccount_to_id must be different !');
246 }
247
248 $this->db->begin();
249
250 $error = 0;
251 $bank_line_id_from = 0;
252 $bank_line_id_to = 0;
253 $result = 0;
254 $user = DolibarrApiAccess::$user;
255
256 // By default, electronic transfer from bank to bank
257 $typefrom = 'PRE';
258 $typeto = 'VIR';
259
260 if ($accountto->type == Account::TYPE_CASH || $accountfrom->type == Account::TYPE_CASH) {
261 // This is transfer of change
262 $typefrom = 'LIQ';
263 $typeto = 'LIQ';
264 }
265
266 // Clean data
267 $description = sanitizeVal($description, 'alphanohtml');
268 $cheque_number = sanitizeVal($cheque_number, 'alphanohtml');
269
274 if (!$error) {
275 $bank_line_id_from = $accountfrom->addline((int) $date, $typefrom, $description, -1 * (float) price2num($amount), '', 0, $user, $cheque_number);
276 }
277 if (!($bank_line_id_from > 0)) {
278 $error++;
279 }
280
281 if (!$error) {
282 $bank_line_id_to = $accountto->addline((int) $date, $typeto, $description, (float) price2num($amount_to), '', 0, $user, $cheque_number);
283 }
284 if (!($bank_line_id_to > 0)) {
285 $error++;
286 }
287
292 $url = DOL_URL_ROOT . '/compta/bank/line.php?rowid=';
293 $label = '(banktransfert)';
294 $type = 'banktransfert';
295
296 if (!$error) {
297 $result = $accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, $url, $label, $type);
298 }
299 if (!($result > 0)) {
300 $error++;
301 }
302
303 if (!$error) {
304 $result = $accountto->add_url_line($bank_line_id_to, $bank_line_id_from, $url, $label, $type);
305 }
306 if (!($result > 0)) {
307 $error++;
308 }
309
310 if (!$error) {
311 $this->db->commit();
312
313 return array(
314 'success' => array(
315 'code' => 201,
316 'message' => 'Internal wire transfer created successfully.',
317 'bank_id_from' => $bank_line_id_from,
318 'bank_id_to' => $bank_line_id_to,
319 )
320 );
321 } else {
322 $this->db->rollback();
323 throw new RestException(500, $accountfrom->error . ' ' . $accountto->error);
324 }
325 }
326
336 public function put($id, $request_data = null)
337 {
338 if (!DolibarrApiAccess::$user->hasRight('banque', 'configurer')) {
339 throw new RestException(403);
340 }
341
342 $account = new Account($this->db);
343 $result = $account->fetch($id);
344 if (!$result) {
345 throw new RestException(404, 'account not found');
346 }
347
348 foreach ($request_data as $field => $value) {
349 if ($field == 'id') {
350 continue;
351 }
352 if ($field === 'caller') {
353 // 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
354 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
355 continue;
356 }
357
358 if ($field == 'array_options' && is_array($value)) {
359 foreach ($value as $index => $val) {
360 $account->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $account);
361 }
362 continue;
363 }
364 $account->$field = $this->_checkValForAPI($field, $value, $account);
365 }
366
367 if ($account->update(DolibarrApiAccess::$user) > 0) {
368 return $this->get($id);
369 } else {
370 throw new RestException(500, $account->error);
371 }
372 }
373
382 public function delete($id)
383 {
384 if (!DolibarrApiAccess::$user->hasRight('banque', 'configurer')) {
385 throw new RestException(403);
386 }
387 $account = new Account($this->db);
388 $result = $account->fetch($id);
389 if (!$result) {
390 throw new RestException(404, 'account not found');
391 }
392
393 if ($account->delete(DolibarrApiAccess::$user) < 0) {
394 throw new RestException(500, 'error when deleting account');
395 }
396
397 return array(
398 'success' => array(
399 'code' => 200,
400 'message' => 'account deleted'
401 )
402 );
403 }
404
413 private function _validate($data)
414 {
415 if ($data === null) {
416 $data = array();
417 }
418 $account = array();
419 foreach (BankAccounts::$FIELDS as $field) {
420 if (!isset($data[$field])) {
421 throw new RestException(400, "$field field missing");
422 }
423 $account[$field] = $data[$field];
424 }
425 return $account;
426 }
427
428 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
438 protected function _cleanObjectDatas($object)
439 {
440 // phpcs:enable
441 $object = parent::_cleanObjectDatas($object);
442
443 unset($object->rowid);
444
445 return $object;
446 }
447
461 public function getLines($id, $sqlfilters = '')
462 {
463 $list = array();
464
465 if (!DolibarrApiAccess::$user->hasRight('banque', 'lire')) {
466 throw new RestException(403);
467 }
468
469 $account = new Account($this->db);
470 $result = $account->fetch($id);
471 if (!$result) {
472 throw new RestException(404, 'account not found');
473 }
474
475 $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "bank ";
476 $sql .= " WHERE fk_account = " . ((int) $id);
477
478 // Add sql filters
479 if ($sqlfilters) {
480 $errormessage = '';
481 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
482 if ($errormessage) {
483 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
484 }
485 }
486
487 $sql .= " ORDER BY rowid";
488
489 $result = $this->db->query($sql);
490
491 if ($result) {
492 $num = $this->db->num_rows($result);
493 //$min = min($num, ($limit <= 0 ? $num : $limit));
494 for ($i = 0; $i < $num; $i++) {
495 $obj = $this->db->fetch_object($result);
496 $accountLine = new AccountLine($this->db);
497 if ($accountLine->fetch($obj->rowid) > 0) {
498 $list[] = $this->_cleanObjectDatas($accountLine);
499 }
500 }
501 } else {
502 throw new RestException(503, 'Error when retrieving list of account lines: ' . $this->db->lasterror());
503 }
504
505 return $list;
506 }
507
527 public function addLine($id, $date, $type, $label, $amount, $category = 0, $cheque_number = '', $cheque_writer = '', $cheque_bank = '', $accountancycode = '', $datev = null, $num_releve = '')
528 {
529 if (!DolibarrApiAccess::$user->hasRight('banque', 'modifier')) {
530 throw new RestException(403);
531 }
532
533 $account = new Account($this->db);
534 $result = $account->fetch($id);
535 if (!$result) {
536 throw new RestException(404, 'account not found');
537 }
538
539 $type = sanitizeVal($type);
540 $label = sanitizeVal($label);
541 $cheque_number = sanitizeVal($cheque_number);
542 $cheque_writer = sanitizeVal($cheque_writer);
543 $cheque_bank = sanitizeVal($cheque_bank);
544 $accountancycode = sanitizeVal($accountancycode);
545 $num_releve = sanitizeVal($num_releve);
546
547 $result = $account->addline(
548 (int) $date,
549 $type,
550 $label,
551 $amount,
552 $cheque_number,
553 $category,
554 DolibarrApiAccess::$user,
555 $cheque_writer,
556 $cheque_bank,
557 $accountancycode,
558 (int) $datev,
559 $num_releve
560 );
561 if ($result < 0) {
562 throw new RestException(503, 'Error when adding line to account: ' . $account->error);
563 }
564 return $result;
565 }
566
580 public function addLink($id, $line_id, $url_id, $url, $label, $type)
581 {
582 if (!DolibarrApiAccess::$user->hasRight('banque', 'modifier')) {
583 throw new RestException(403);
584 }
585
586 $account = new Account($this->db);
587 $result = $account->fetch($id);
588 if (!$result) {
589 throw new RestException(404, 'account not found');
590 }
591
592 $accountLine = new AccountLine($this->db);
593 $result = $accountLine->fetch($line_id);
594 if (!$result) {
595 throw new RestException(404, 'account line not found');
596 }
597
598 if ($accountLine->fk_account != $id) {
599 throw new RestException(400, 'Line does not belong to this account');
600 }
601
602 $url = sanitizeVal($url);
603 $label = sanitizeVal($label);
604 $type = sanitizeVal($type);
605
606 $result = $account->add_url_line($line_id, $url_id, $url, $label, $type);
607 if ($result < 0) {
608 throw new RestException(503, 'Error when adding link to account line: ' . $account->error);
609 }
610 return $result;
611 }
612
626 public function getLinks($id, $line_id)
627 {
628 if (!DolibarrApiAccess::$user->hasRight('banque', 'lire')) {
629 throw new RestException(403);
630 }
631
632 $account = new Account($this->db);
633 $result = $account->fetch($id);
634 if (!$result) {
635 throw new RestException(404, 'account not found');
636 }
637
638 $links = $account->get_url($line_id); // Get an array('url'=>, 'url_id'=>, 'label'=>, 'type'=> 'fk_bank'=> )
639 foreach ($links as &$link) {
640 unset($link[0], $link[1], $link[2], $link[3]); // Remove the numeric keys
641 }
642
643 return $links;
644 }
645
655 public function getDetailAccountLine($line_id)
656 {
657 if (!DolibarrApiAccess::$user->hasRight('banque', 'lire')) {
658 throw new RestException(403);
659 }
660
661 $accountLine = new AccountLine($this->db);
662 $result = $accountLine->fetch($line_id);
663 if (!$result) {
664 throw new RestException(404, 'account Line not found');
665 }
666
667 return $this->_cleanObjectDatas($accountLine);
668 }
669
680 public function updateLine($id, $line_id, $label)
681 {
682 if (!DolibarrApiAccess::$user->hasRight('banque', 'modifier')) {
683 throw new RestException(403);
684 }
685
686 $account = new Account($this->db);
687 $result = $account->fetch($id);
688 if (!$result) {
689 throw new RestException(404, 'account not found');
690 }
691
692 $accountLine = new AccountLine($this->db);
693 $result = $accountLine->fetch($line_id);
694 if (!$result) {
695 throw new RestException(404, 'account line not found');
696 }
697
698 if ($accountLine->fk_account != $id) {
699 throw new RestException(400, 'Line does not belong to this account');
700 }
701
702 $accountLine->label = sanitizeVal($label);
703
704 $result = $accountLine->updateLabel();
705 if ($result < 0) {
706 throw new RestException(503, 'Error when updating link to account line: ' . $accountLine->error);
707 }
708 return $accountLine->id;
709 }
710
722 public function deleteLine($id, $line_id)
723 {
724 if (!DolibarrApiAccess::$user->hasRight('banque', 'modifier')) {
725 throw new RestException(403);
726 }
727
728 $account = new Account($this->db);
729 $result = $account->fetch($id);
730 if (!$result) {
731 throw new RestException(404, 'account not found');
732 }
733
734 $accountLine = new AccountLine($this->db);
735 $result = $accountLine->fetch($line_id);
736 if (!$result) {
737 throw new RestException(404, 'account line not found');
738 }
739
740 if ($accountLine->fk_account != $id) {
741 throw new RestException(400, 'Line does not belong to this account');
742 }
743
744 if ($accountLine->delete(DolibarrApiAccess::$user) < 0) {
745 throw new RestException(500, 'error when deleting account line');
746 }
747
748 return array(
749 'success' => array(
750 'code' => 200,
751 'message' => "account line $line_id deleted"
752 )
753 );
754 }
755
765 public function getBalance($id)
766 {
767 if (!DolibarrApiAccess::$user->hasRight('banque', 'lire')) {
768 throw new RestException(403);
769 }
770
771 $account = new Account($this->db);
772 $result = $account->fetch($id);
773
774 if (!$result) {
775 throw new RestException(404, 'account not found');
776 }
777
778 $balance = $account->solde(1); //1=Exclude future operation date (this is to exclude input made in advance and have real account sold)
779
780 return $balance;
781 }
782}
$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 to manage bank accounts.
const TYPE_CASH
Cash account.
Class to manage bank transaction lines.
post($request_data=null)
Create account object.
addLink($id, $line_id, $url_id, $url, $label, $type)
Add a link to an account line.
put($id, $request_data=null)
Update account.
_validate($data)
Validate fields before creating an object.
getLinks($id, $line_id)
Get the list of links for a line of the account.
transfer($bankaccount_from_id=0, $bankaccount_to_id=0, $date=null, $description="", $amount=0.0, $amount_to=0.0, $cheque_number="")
Create an internal wire transfer between two bank accounts.
__construct()
Constructor.
getBalance($id)
Get the current account balance.
addLine($id, $date, $type, $label, $amount, $category=0, $cheque_number='', $cheque_writer='', $cheque_bank='', $accountancycode='', $datev=null, $num_releve='')
Add a line to an account.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $category=0, $sqlfilters='', $properties='')
Get the list of accounts.
getDetailAccountLine($line_id)
Get the detail of a given line of the bank account.
getLines($id, $sqlfilters='')
Get the list of lines of the account.
deleteLine($id, $line_id)
Delete an account line.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
updateLine($id, $line_id, $label)
Update an account line.
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.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
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.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.