Files
akaunting-py/akauntingpy/api.py

190 lines
7.7 KiB
Python
Raw Normal View History

import requests
2022-11-25 23:03:43 +13:00
gimport logging
from requests.auth import HTTPBasicAuth
2022-05-27 23:00:35 +12:00
from akauntingpy import exceptions
from akauntingpy.helpers import *
__version__ = "1.0.5"
logger = logging.getLogger(__name__)
2022-11-25 23:03:43 +13:00
class Client(object):
"""
Akaunting interface.
"""
2022-05-27 23:00:35 +12:00
def __init__(
self,
url,
username,
password,
company_id,
2022-06-26 07:57:43 +12:00
ssl_verify=True,
currency_code="NZD",
currency_rate="1.0"):
"""
Create a new instance.
Args:
2022-06-26 07:57:43 +12:00
url (str): The URL to the Akaunting api. ** required **
username (str): The username of the Akaunting credentials. ** required **
password (str): The password of the Akaunting credentials. ** required **
company_id (str): The company ID from Akaunting
currency_code (str): The currency code. default is NZD
currency_rate (str): The currency rate. default is "1.0"
"""
self.url = url
2022-06-26 07:57:43 +12:00
self.ssl_verify = ssl_verify
self.authentication = HTTPBasicAuth(username, password)
self.headers = {
2022-05-16 14:48:53 +12:00
'User-Agent': 'AkauntingPy v' + __version__,
}
self.company_id = company_id
self.default_params = {'company_id': company_id}
self.currency_code = currency_code
self.currency_rate = currency_rate
2022-05-27 23:00:35 +12:00
def call(self, method="get", endpoint=None,
2022-05-27 23:11:18 +12:00
**params) -> dict:
2022-05-27 23:00:35 +12:00
2022-05-16 11:44:46 +12:00
response = requests.request(method=method,
url=self.url + "/" + endpoint,
headers=self.headers,
auth=self.authentication,
2022-06-26 07:57:43 +12:00
params=MergeDict(self.default_params, params),
verify=self.ssl_verify
2022-05-16 11:44:46 +12:00
)
2022-05-27 23:00:35 +12:00
response_ = response.json()
2022-05-16 11:08:15 +12:00
if response.status_code == 401:
raise exceptions.MissingPermission(response_['message'])
elif response.status_code == 422:
errors = []
for key in response_['errors']:
2022-05-27 23:00:35 +12:00
errors.append(RemoveFromString(["<strong>", "</strong>"],
response_['errors'][key][0])
+ " (" + key + ")")
raise exceptions.InvalidData(response_['message'] +
"\n" +
"\n".join(errors))
2022-05-16 11:41:49 +12:00
# elif response.status_code != 200 and response.status_code != 201:
# raise exceptions.Error(response_['message'])
elif response.status_code == 429:
# We hit the maximum requests
2022-11-25 23:03:43 +13:00
raise exceptions.TooManyAttempts(response_['message'])
return response_
2022-05-27 23:00:35 +12:00
def ping(self):
data = self.call(endpoint="ping")
return data
2022-05-27 23:00:35 +12:00
2022-05-16 11:41:49 +12:00
def get_accounts(self, **params):
data = self.call(endpoint="accounts", **params)
2022-05-27 23:00:35 +12:00
2022-05-27 22:19:17 +12:00
if params.get('search', False):
# Check if there is an account returned
2022-06-26 07:57:43 +12:00
try:
if data['meta']['pagination'].get('count') == 0:
# No account found
raise exceptions.AccountNotFound("Sorry, account not found matching search parameters: %s".format(
params.get('search')
))
except KeyError as e:
# New API 3.0
if data['meta']['total'] == 0:
raise exceptions.AccountNotFound("Sorry, account not found matching search parameters: %s".format(
params.get('search')
))
return data['data']
def get_contact(self, **params):
data = self.call(endpoint="contacts", **params)
print(data)
if params.get('search', False):
try:
# Check if there is an account returned
if data['meta']['pagination'].get('count') == 0:
# No account found
raise exceptions.AccountNotFound("Sorry, contact not found matching search parameters: %s".format(
params.get('search')
))
except KeyError as e:
# New API 3.0
if data['meta']['total'] == 0:
raise exceptions.AccountNotFound("Sorry, contact not found matching search parameters: %s".format(
params.get('search')
))
2022-05-27 23:00:35 +12:00
return data['data']
2022-05-27 23:00:35 +12:00
def create_transaction(self,
2022-05-27 23:11:18 +12:00
transaction_type='income', # Payment method type
2022-05-27 23:00:35 +12:00
account_id=None, # Account ID to assign
2022-06-26 07:57:43 +12:00
number="NULL", # Transaction number
2022-05-27 23:00:35 +12:00
category_id=None, # Category ID to assign
contact_id=None, # Contact ID/Client to assign
description=None, # Description
paid_at=None, # Date of expense/transfer or income
reference=None, # Reference for the payment
payment_method=None, # Payment method
currency_code=None, # Currency code
currency_rate=None, # Currency rate
amount=None, # Amount received/paid
**params # Any additional parameters
):
if currency_code is None:
# Set default value from class
currency_code = self.currency_code
if currency_rate is None:
# Set default value from class
currency_rate = self.currency_rate
2022-05-27 23:00:35 +12:00
data = self.call(endpoint="transactions",
method="POST",
2022-05-27 23:11:18 +12:00
search="type:" + transaction_type,
2022-06-26 07:57:43 +12:00
number=number,
2022-05-27 23:11:18 +12:00
type=transaction_type,
account_id=account_id,
category_id=category_id,
paid_at=paid_at,
contact_id=contact_id,
payment_method=payment_method,
reference=reference,
currency_code=currency_code,
currency_rate=currency_rate,
2022-05-30 15:21:14 +12:00
amount=EnsurePositiveInteger(amount),
2022-05-16 11:41:49 +12:00
description=description,
**params
)
2022-05-27 23:00:35 +12:00
return data
2022-05-30 15:21:14 +12:00
def create_transfer(self,
2022-06-26 07:57:43 +12:00
from_account_id=None, # Account ID to create transfer from
to_account_id=None, # Account ID to create transfer to
transferred_at=None, # Date of expense/transfer or income
payment_method="Bank Transfer", # Payment method
amount=None, # Amount received/paid
2022-11-25 23:03:43 +13:00
**params # Any additional parameters
2022-06-26 07:57:43 +12:00
):
logger.info("Transfer called with parameters")
logger.info("from_account_id: %s", from_account_id)
logger.info("to_account_id: %s", to_account_id)
logger.info("transferred_at: %s", transferred_at)
logger.info("payment_method: %s", payment_method)
logger.info("amount: %s", amount)
2022-11-25 23:03:43 +13:00
2022-06-26 07:57:43 +12:00
data = self.call(endpoint="transfers",
method="POST",
2022-05-30 15:21:14 +12:00
from_account_id=from_account_id,
to_account_id=to_account_id,
transferred_at=transferred_at,
payment_method=payment_method,
amount=EnsurePositiveInteger(amount),
**params
)
2022-06-26 07:57:43 +12:00
return data