dolibarr 22.0.5
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 // courant and type are the same thing but the one used when
180 // creating an account is courant
181 $account->courant = $account->type; // deprecated, kept for backward compatibility
182
183 if ($account->create(DolibarrApiAccess::$user) < 0) {
184 throw new RestException(500, 'Error creating bank account', array_merge(array($account->error), $account->errors));
185 }
186 return $account->id;
187 }
188
213 public function transfer($bankaccount_from_id = 0, $bankaccount_to_id = 0, $date = null, $description = "", $amount = 0.0, $amount_to = 0.0, $cheque_number = "")
214 {
215 if (!DolibarrApiAccess::$user->hasRight('banque', 'configurer')) {
216 throw new RestException(403);
217 }
218
219 require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
220
221 $accountfrom = new Account($this->db);
222 $resultAccountFrom = $accountfrom->fetch($bankaccount_from_id);
223
224 if ($resultAccountFrom === 0) {
225 throw new RestException(404, 'The BankAccount for bankaccount_from_id provided does not exist.');
226 }
227
228 $accountto = new Account($this->db);
229 $resultAccountTo = $accountto->fetch($bankaccount_to_id);
230
231 if ($resultAccountTo === 0) {
232 throw new RestException(404, 'The BankAccount for bankaccount_to_id provided does not exist.');
233 }
234
235 if ($accountto->currency_code == $accountfrom->currency_code) {
236 $amount_to = $amount;
237 } else {
238 if (!$amount_to || empty($amount_to)) {
239 throw new RestException(422, 'You must provide amount_to value since bankaccount_from and bankaccount_to does not share the same currency.');
240 }
241 }
242
243 if ($amount_to < 0) {
244 throw new RestException(422, 'You must provide a positive value for amount.');
245 }
246
247 if ($accountto->id == $accountfrom->id) {
248 throw new RestException(422, 'bankaccount_from_id and bankaccount_to_id must be different !');
249 }
250
251 $this->db->begin();
252
253 $error = 0;
254 $bank_line_id_from = 0;
255 $bank_line_id_to = 0;
256 $result = 0;
257 $user = DolibarrApiAccess::$user;
258
259 // By default, electronic transfer from bank to bank
260 $typefrom = 'PRE';
261 $typeto = 'VIR';
262
263 if ($accountto->type == Account::TYPE_CASH || $accountfrom->type == Account::TYPE_CASH) {
264 // This is transfer of change
265 $typefrom = 'LIQ';
266 $typeto = 'LIQ';
267 }
268
269 // Clean data
270 $description = sanitizeVal($description, 'alphanohtml');
271 $cheque_number = sanitizeVal($cheque_number, 'alphanohtml');
272
277 if (!$error) {
278 $bank_line_id_from = $accountfrom->addline((int) $date, $typefrom, $description, -1 * (float) price2num($amount), '', 0, $user, $cheque_number);
279 }
280 if (!($bank_line_id_from > 0)) {
281 $error++;
282 }
283
284 if (!$error) {
285 $bank_line_id_to = $accountto->addline((int) $date, $typeto, $description, (float) price2num($amount_to), '', 0, $user, $cheque_number);
286 }
287 if (!($bank_line_id_to > 0)) {
288 $error++;
289 }
290
295 $url = DOL_URL_ROOT . '/compta/bank/line.php?rowid=';
296 $label = '(banktransfert)';
297 $type = 'banktransfert';
298
299 if (!$error) {
300 $result = $accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, $url, $label, $type);
301 }
302 if (!($result > 0)) {
303 $error++;
304 }
305
306 if (!$error) {
307 $result = $accountto->add_url_line($bank_line_id_to, $bank_line_id_from, $url, $label, $type);
308 }
309 if (!($result > 0)) {
310 $error++;
311 }
312
313 if (!$error) {
314 $this->db->commit();
315
316 return array(
317 'success' => array(
318 'code' => 201,
319 'message' => 'Internal wire transfer created successfully.',
320 'bank_id_from' => $bank_line_id_from,
321 'bank_id_to' => $bank_line_id_to,
322 )
323 );
324 } else {
325 $this->db->rollback();
326 throw new RestException(500, $accountfrom->error . ' ' . $accountto->error);
327 }
328 }
329
339 public function put($id, $request_data = null)
340 {
341 if (!DolibarrApiAccess::$user->hasRight('banque', 'configurer')) {
342 throw new RestException(403);
343 }
344
345 $account = new Account($this->db);
346 $result = $account->fetch($id);
347 if (!$result) {
348 throw new RestException(404, 'account not found');
349 }
350
351 foreach ($request_data as $field => $value) {
352 if ($field == 'id') {
353 continue;
354 }
355 if ($field === 'caller') {
356 // 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
357 $account->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
358 continue;
359 }
360
361 if ($field == 'array_options' && is_array($value)) {
362 foreach ($value as $index => $val) {
363 $account->array_options[$index] = $this->_checkValForAPI($field, $val, $account);
364 }
365 continue;
366 }
367 $account->$field = $this->_checkValForAPI($field, $value, $account);
368 }
369
370 if ($account->update(DolibarrApiAccess::$user) > 0) {
371 return $this->get($id);
372 } else {
373 throw new RestException(500, $account->error);
374 }
375 }
376
385 public function delete($id)
386 {
387 if (!DolibarrApiAccess::$user->hasRight('banque', 'configurer')) {
388 throw new RestException(403);
389 }
390 $account = new Account($this->db);
391 $result = $account->fetch($id);
392 if (!$result) {
393 throw new RestException(404, 'account not found');
394 }
395
396 if ($account->delete(DolibarrApiAccess::$user) < 0) {
397 throw new RestException(500, 'error when deleting account');
398 }
399
400 return array(
401 'success' => array(
402 'code' => 200,
403 'message' => 'account deleted'
404 )
405 );
406 }
407
416 private function _validate($data)
417 {
418 if ($data === null) {
419 $data = array();
420 }
421 $account = array();
422 foreach (BankAccounts::$FIELDS as $field) {
423 if (!isset($data[$field])) {
424 throw new RestException(400, "$field field missing");
425 }
426 $account[$field] = $data[$field];
427 }
428 return $account;
429 }
430
431 // 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 for ($i = 0; $i < $num; $i++) {
494 $obj = $this->db->fetch_object($result);
495 $accountLine = new AccountLine($this->db);
496 if ($accountLine->fetch($obj->rowid) > 0) {
497 $list[] = $this->_cleanObjectDatas($accountLine);
498 }
499 }
500 } else {
501 throw new RestException(503, 'Error when retrieving list of account lines: ' . $this->db->lasterror());
502 }
503
504 return $list;
505 }
506
526 public function addLine($id, $date, $type, $label, $amount, $category = 0, $cheque_number = '', $cheque_writer = '', $cheque_bank = '', $accountancycode = '', $datev = null, $num_releve = '')
527 {
528 if (!DolibarrApiAccess::$user->hasRight('banque', 'modifier')) {
529 throw new RestException(403);
530 }
531
532 $account = new Account($this->db);
533 $result = $account->fetch($id);
534 if (!$result) {
535 throw new RestException(404, 'account not found');
536 }
537
538 $type = sanitizeVal($type);
539 $label = sanitizeVal($label);
540 $cheque_number = sanitizeVal($cheque_number);
541 $cheque_writer = sanitizeVal($cheque_writer);
542 $cheque_bank = sanitizeVal($cheque_bank);
543 $accountancycode = sanitizeVal($accountancycode);
544 $num_releve = sanitizeVal($num_releve);
545
546 $result = $account->addline(
547 (int) $date,
548 $type,
549 $label,
550 $amount,
551 $cheque_number,
552 $category,
553 DolibarrApiAccess::$user,
554 $cheque_writer,
555 $cheque_bank,
556 $accountancycode,
557 (int) $datev,
558 $num_releve
559 );
560 if ($result < 0) {
561 throw new RestException(503, 'Error when adding line to account: ' . $account->error);
562 }
563 return $result;
564 }
565
579 public function addLink($id, $line_id, $url_id, $url, $label, $type)
580 {
581 if (!DolibarrApiAccess::$user->hasRight('banque', 'modifier')) {
582 throw new RestException(403);
583 }
584
585 $account = new Account($this->db);
586 $result = $account->fetch($id);
587 if (!$result) {
588 throw new RestException(404, 'account not found');
589 }
590
591 $accountLine = new AccountLine($this->db);
592 $result = $accountLine->fetch($line_id);
593 if (!$result) {
594 throw new RestException(404, 'account line not found');
595 }
596
597 $url = sanitizeVal($url);
598 $label = sanitizeVal($label);
599 $type = sanitizeVal($type);
600
601 $result = $account->add_url_line($line_id, $url_id, $url, $label, $type);
602 if ($result < 0) {
603 throw new RestException(503, 'Error when adding link to account line: ' . $account->error);
604 }
605 return $result;
606 }
607
621 public function getLinks($id, $line_id)
622 {
623 if (!DolibarrApiAccess::$user->hasRight('banque', 'lire')) {
624 throw new RestException(403);
625 }
626
627 $account = new Account($this->db);
628 $result = $account->fetch($id);
629 if (!$result) {
630 throw new RestException(404, 'account not found');
631 }
632
633 $links = $account->get_url($line_id); // Get an array('url'=>, 'url_id'=>, 'label'=>, 'type'=> 'fk_bank'=> )
634 foreach ($links as &$link) {
635 unset($link[0], $link[1], $link[2], $link[3]); // Remove the numeric keys
636 }
637
638 return $links;
639 }
640
651 public function updateLine($id, $line_id, $label)
652 {
653 if (!DolibarrApiAccess::$user->rights->banque->modifier) {
654 throw new RestException(403);
655 }
656
657 $account = new Account($this->db);
658 $result = $account->fetch($id);
659 if (!$result) {
660 throw new RestException(404, 'account not found');
661 }
662
663 $accountLine = new AccountLine($this->db);
664 $result = $accountLine->fetch($line_id);
665 if (!$result) {
666 throw new RestException(404, 'account line not found');
667 }
668
669 $accountLine->label = sanitizeVal($label);
670
671 $result = $accountLine->updateLabel();
672 if ($result < 0) {
673 throw new RestException(503, 'Error when updating link to account line: ' . $accountLine->error);
674 }
675 return $accountLine->id;
676 }
677
689 public function deleteLine($id, $line_id)
690 {
691 if (!DolibarrApiAccess::$user->rights->banque->modifier) {
692 throw new RestException(403);
693 }
694
695 $account = new Account($this->db);
696 $result = $account->fetch($id);
697 if (!$result) {
698 throw new RestException(404, 'account not found');
699 }
700
701 $accountLine = new AccountLine($this->db);
702 $result = $accountLine->fetch($line_id);
703 if (!$result) {
704 throw new RestException(404, 'account line not found');
705 }
706
707 if ($accountLine->delete(DolibarrApiAccess::$user) < 0) {
708 throw new RestException(500, 'error when deleting account line');
709 }
710
711 return array(
712 'success' => array(
713 'code' => 200,
714 'message' => "account line $line_id deleted"
715 )
716 );
717 }
718
728 public function getBalance($id)
729 {
730 if (!DolibarrApiAccess::$user->hasRight('banque', 'lire')) {
731 throw new RestException(403);
732 }
733
734 $account = new Account($this->db);
735 $result = $account->fetch($id);
736
737 if (!$result) {
738 throw new RestException(404, 'account not found');
739 }
740 $balance = $account->solde(1); //1=Exclude future operation date (this is to exclude input made in advance and have real account sold)
741 return $balance;
742 }
743}
$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 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 current account balance by ID.
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.
getLines($id, $sqlfilters='')
Get the list of lines of the account.
deleteLine($id, $line_id)
Delete an account line.
static $FIELDS
array $FIELDS Mandatory fields, checked when creating an object
_cleanObjectDatas($object)
Clean sensible object datas.
updateLine($id, $line_id, $label)
Update an account line.
Class for API REST v1.
Definition api.class.php:33
_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.
Definition api.class.php:98
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
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.