9 Commits
1.0.0 ... 1.0.1

14 changed files with 268 additions and 99 deletions

6
.gitignore vendored
View File

@@ -8,4 +8,8 @@ coverage.xml
# Ignore Scratch files # Ignore Scratch files
scratch/* scratch/*
!/scratch/README.md !/scratch/README.md
# Ignore virtualenv
.venv
venv

8
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/

15
.idea/akaunting-py.iml generated Normal file
View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
<excludeFolder url="file://$MODULE_DIR$/.pytest_cache" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="PyDocumentationSettings">
<option name="format" value="PLAIN" />
<option name="myDocStringFormat" value="Plain" />
</component>
</module>

View File

@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

4
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (akaunting-py)" project-jdk-type="Python SDK" />
</project>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/akaunting-py.iml" filepath="$PROJECT_DIR$/.idea/akaunting-py.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@@ -1,20 +1,26 @@
import requests import requests
import json
from requests.auth import HTTPBasicAuth from requests.auth import HTTPBasicAuth
from akauntingpy import exceptions, __version__ from setuptools_scm import get_version
from akauntingpy import exceptions
from akauntingpy.helpers import * from akauntingpy.helpers import *
__version__ = get_version(root='..', relative_to=__file__)
class Client(object): class Client(object):
""" """
Akaunting interface. Akaunting interface.
""" """
def __init__( def __init__(
self, self,
url, url,
username, username,
password, password,
company_id): company_id,
currency_code="NZD",
currency_rate="1.0"):
""" """
Create a new instance. Create a new instance.
Args: Args:
@@ -29,66 +35,79 @@ class Client(object):
} }
self.company_id = company_id self.company_id = company_id
self.default_params = {'company_id': company_id} self.default_params = {'company_id': company_id}
self.currency_code = currency_code
def call(self, method="get", endpoint=None, self.currency_rate = currency_rate
**params) -> dict():
response = None def call(self, method="get", endpoint=None,
**params) -> dict:
response = requests.request(method=method, response = requests.request(method=method,
url=self.url + "/" + endpoint, url=self.url + "/" + endpoint,
headers=self.headers, headers=self.headers,
auth=self.authentication, auth=self.authentication,
params=MergeDict(self.default_params, params) params=MergeDict(self.default_params, params)
) )
print(response)
response_ = response.json() response_ = response.json()
print(response_)
if response.status_code == 401: if response.status_code == 401:
raise exceptions.MissingPermission(response_['message']) raise exceptions.MissingPermission(response_['message'])
elif response.status_code == 422: elif response.status_code == 422:
errors = [] errors = []
for key in response_['errors']: for key in response_['errors']:
errors.append(RemoveFromString(["<strong>","</strong>"], errors.append(RemoveFromString(["<strong>", "</strong>"],
response_['errors'][key][0]) response_['errors'][key][0])
+ " (" + key + ")") + " (" + key + ")")
raise exceptions.InvalidData(response_['message'] + raise exceptions.InvalidData(response_['message'] +
"\n" + "\n" +
"\n".join(errors)) "\n".join(errors))
# elif response.status_code != 200 and response.status_code != 201: # elif response.status_code != 200 and response.status_code != 201:
# raise exceptions.Error(response_['message']) # raise exceptions.Error(response_['message'])
return response_ return response_
def ping(self): def ping(self):
data = self.call(endpoint="ping") data = self.call(endpoint="ping")
return data return data
def get_accounts(self, **params): def get_accounts(self, **params):
data = self.call(endpoint="accounts") data = self.call(endpoint="accounts", **params)
if params.get('search', False):
# Check if there is an account returned
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')
))
return data['data'] return data['data']
def create_transaction(self, def create_transaction(self,
type='income', # Payment method type transaction_type='income', # Payment method type
account_id=None, # Account ID to assign account_id=None, # Account ID to assign
category_id=None, # Category ID to assign category_id=None, # Category ID to assign
contact_id=None, # Contact ID/Client to assign contact_id=None, # Contact ID/Client to assign
description=None, # Description description=None, # Description
paid_at=None, # Date of expense/transfer or income paid_at=None, # Date of expense/transfer or income
reference=None, # Reference for the payment reference=None, # Reference for the payment
payment_method=None, # Payment method payment_method=None, # Payment method
currency_code=None, # Currency code currency_code=None, # Currency code
currency_rate=None, # Currency rate currency_rate=None, # Currency rate
amount=None, # Amount received/paid amount=None, # Amount received/paid
**params # Any additional parameters **params # Any additional parameters
): ):
if currency_code is None:
data = self.call(endpoint="transactions", # Set default value from class
method="POST", currency_code = self.currency_code
search="type:" + type, if currency_rate is None:
type=type, # Set default value from class
currency_rate = self.currency_rate
data = self.call(endpoint="transactions",
method="POST",
search="type:" + transaction_type,
type=transaction_type,
account_id=account_id, account_id=account_id,
category_id=category_id, category_id=category_id,
paid_at=paid_at, paid_at=paid_at,
@@ -101,4 +120,4 @@ class Client(object):
description=description, description=description,
**params **params
) )
return data return data

View File

@@ -18,3 +18,11 @@ class InvalidData(Error):
Args: Args:
Error (_type_): _description_ Error (_type_): _description_
""" """
class AccountNotFound(Error):
"""
Account not found
Args:
Error (_type_): _description_
"""

View File

@@ -0,0 +1,34 @@
{
"data":[
{
"id":2,
"company_id":1,
"name":"Some Account",
"number":"**-9011-*******-03",
"currency_code":"NZD",
"opening_balance":0,
"opening_balance_formatted":"$0.00",
"current_balance":100,
"current_balance_formatted":"$100.00",
"bank_name":"A Bank",
"bank_phone":"None",
"bank_address":"None",
"enabled":true,
"created_by":1,
"created_at":"2022-05-13T16:16:16+12:00",
"updated_at":"2022-05-13T16:16:16+12:00"
}
],
"meta":{
"pagination":{
"total":1,
"count":1,
"per_page":25,
"current_page":1,
"total_pages":1,
"links":{
}
}
}
}

View File

@@ -0,0 +1,15 @@
{
"data":[],
"meta":{
"pagination":{
"total":0,
"count":0,
"per_page":25,
"current_page":0,
"total_pages":0,
"links":{
}
}
}
}

View File

@@ -1,2 +1,5 @@
requests >= 2.21.0 requests ~= 2.27.0
pytest requests-mock ~= 1.9.3
pytest ~= 7.1.2
pytest-cov ~= 3.0
setuptools-scm ~= 6.4.2

View File

@@ -20,6 +20,7 @@ setup(
packages=find_packages(), packages=find_packages(),
install_requires=[ install_requires=[
'requests >= 2.21.0', 'requests >= 2.21.0',
'setuptools-scm >= 6.4.2'
], ],
classifiers=[ classifiers=[
'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3',

View File

@@ -1,77 +1,90 @@
import sys import sys
from this import d
sys.path.insert(1, '.') sys.path.insert(1, '.')
import pytest from helpers import RetrieveJSONFromFile
import akauntingpy import akauntingpy
from akauntingpy.exceptions import * from akauntingpy.exceptions import *
from helpers import RetrieveJSONFromFile import pytest
from requests.auth import HTTPBasicAuth from requests.auth import HTTPBasicAuth
class TestAPI: class TestAPI:
@pytest.fixture() @pytest.fixture()
def setUp(self): def setUp(self):
c = akauntingpy.Client("https://akaunting.guise.net.nz/api", c = akauntingpy.Client("https://akaunting.guise.net.nz/api",
"aaron@guise.net.nz", "aaron@guise.net.nz",
"L3Tm31N0w", "L3Tm31N0w",
1) 1)
yield c yield c
@pytest.fixture() @pytest.fixture()
def setUpFailed(self): def setUpFailed(self):
c = akauntingpy.Client("https://akaunting.guise.net.nz/api", c = akauntingpy.Client("https://akaunting.guise.net.nz/api",
"aaron@guise.net.nz", "aaron@guise.net.nz",
"L3Tm31N0w1", "L3Tm31N0w1",
1) 1)
yield c yield c
def test_init(self, setUp): def test_init(self, setUp):
c = setUp c = setUp
assert isinstance(c, akauntingpy.Client) assert isinstance(c, akauntingpy.Client)
assert c.url == "https://akaunting.guise.net.nz/api" assert c.url == "https://akaunting.guise.net.nz/api"
assert isinstance(c.authentication, HTTPBasicAuth) assert isinstance(c.authentication, HTTPBasicAuth)
def test_ping_success(self, setUp, requests_mock): def test_ping_success(self, setUp, requests_mock):
c = setUp c = setUp
requests_mock.get(c.url + '/ping', requests_mock.get(c.url + '/ping',
json=RetrieveJSONFromFile("data/pingSuccess.json"), json=RetrieveJSONFromFile("data/pingSuccess.json"),
status_code=200) status_code=200)
data = c.ping() data = c.ping()
# The returned data should have status = ok # The returned data should have status = ok
assert data['status'] == 'ok' assert data['status'] == 'ok'
def test_ping_failed(self, setUpFailed, requests_mock): def test_ping_failed(self, setUpFailed, requests_mock):
c = setUpFailed c = setUpFailed
requests_mock.get(c.url + '/ping', requests_mock.get(c.url + '/ping',
json=RetrieveJSONFromFile("data/pingFailure.json"), json=RetrieveJSONFromFile("data/pingFailure.json"),
status_code=401) status_code=401)
with pytest.raises(MissingPermission, match="Invalid credentials."): with pytest.raises(MissingPermission, match="Invalid credentials."):
data = c.ping() data = c.ping()
assert data['status_code'] == 401 assert data['status_code'] == 401
def test_get_accounts(self, setUp, requests_mock): def test_get_accounts(self, setUp, requests_mock):
c = setUp c = setUp
requests_mock.get(c.url + "/accounts", requests_mock.get(c.url + "/accounts",
json=RetrieveJSONFromFile("data/GetAccountsList.json")) json=RetrieveJSONFromFile("data/GetAccountsList.json"))
data = c.get_accounts(params={'page': 1, 'limit': 200}) data = c.get_accounts(params={'page': 1, 'limit': 200})
def test_get_account_search(self, setUp, requests_mock):
c = setUp
requests_mock.get(c.url + "/accounts?search=number%3A38-9011-0510023-03&params=page&params=limit&company_id=1",
json=RetrieveJSONFromFile("data/GetAccountsSearch.json"))
data = c.get_accounts(search="number:38-9011-0510023-03", params={'page': 1, 'limit': 200})
def test_get_account_search_not_found(self, setUp, requests_mock):
c = setUp
requests_mock.get(c.url + "/accounts?search=number%3Aarandomvalue&company_id=1",
json=RetrieveJSONFromFile("data/GetAccountsSearchNotFound.json"))
with pytest.raises(AccountNotFound):
data = c.get_accounts(search="number:arandomvalue")
def test_create_transaction_income_success(self, setUp, requests_mock, def test_create_transaction_income_success(self, setUp, requests_mock,
type='income', # Payment method type transaction_type='income', # Payment method type
account_id=2, # Account ID to assign account_id=2, # Account ID to assign
category_id=3, # Category ID to assign category_id=3, # Category ID to assign
contact_id=None, # Contact ID/Client to assign contact_id=None, # Contact ID/Client to assign
paid_at="2022-05-15", # Date of expense/transfer or income paid_at="2022-05-15", # Date of expense/transfer or income
reference=None, # Reference for the payment reference=None, # Reference for the payment
payment_method="bank_transfer", # Payment method payment_method="bank_transfer", # Payment method
currency_code="NZD", # Currency code currency_code="NZD", # Currency code
currency_rate=1, # Currency rate currency_rate=1, # Currency rate
amount="25.00", # Amount received/paid amount="25.00", # Amount received/paid
): ):
c = setUp c = setUp
requests_mock.post(c.url + "/transactions", requests_mock.post(c.url + "/transactions",
json=RetrieveJSONFromFile("data/CreateTransactionIncomeSuccess.json"), json=RetrieveJSONFromFile("data/CreateTransactionIncomeSuccess.json"),
status_code=201) status_code=201)
data = c.create_transaction(type=type, data = c.create_transaction(transaction_type=transaction_type,
account_id=account_id, account_id=account_id,
category_id=category_id, category_id=category_id,
paid_at=paid_at, paid_at=paid_at,
@@ -83,18 +96,44 @@ class TestAPI:
amount=amount, amount=amount,
description="Some description of the transaction" description="Some description of the transaction"
) )
def test_create_transaction_income_failed(self, setUp, requests_mock, def test_create_transaction_income_default_currency_success(self, setUp, requests_mock,
contact_id=None, # Contact ID/Client to assign transaction_type='income', # Payment method type
reference=None, # Reference for the payment account_id=2, # Account ID to assign
currency_code="NZD", # Currency code category_id=3, # Category ID to assign
currency_rate=1, # Currency rate contact_id=None, # Contact ID/Client to assign
amount="25.00", # Amount received/paid paid_at="2022-05-15",
): # Date of expense/transfer or income
reference=None, # Reference for the payment
payment_method="bank_transfer", # Payment method
amount="25.00", # Amount received/paid
):
c = setUp c = setUp
requests_mock.post(c.url + "/transactions", requests_mock.post(c.url + "/transactions",
json=RetrieveJSONFromFile("data/CreateTransactionIncomeFailed.json"), json=RetrieveJSONFromFile("data/CreateTransactionIncomeSuccess.json"),
status_code=422) status_code=201)
data = c.create_transaction(transaction_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,
amount=amount,
description="Some description of the transaction"
)
def test_create_transaction_income_failed(self, setUp, requests_mock,
contact_id=None, # Contact ID/Client to assign
reference=None, # Reference for the payment
currency_code="NZD", # Currency code
currency_rate=1, # Currency rate
amount="25.00", # Amount received/paid
):
c = setUp
requests_mock.post(c.url + "/transactions",
json=RetrieveJSONFromFile("data/CreateTransactionIncomeFailed.json"),
status_code=422)
with pytest.raises(InvalidData, match="The given data was invalid.*"): with pytest.raises(InvalidData, match="The given data was invalid.*"):
data = c.create_transaction(contact_id=contact_id, data = c.create_transaction(contact_id=contact_id,
reference=reference, reference=reference,
@@ -103,13 +142,13 @@ class TestAPI:
amount=amount, amount=amount,
description="Some description of the transaction" description="Some description of the transaction"
) )
def test_create_transaction_expense_success(self, setUp, requests_mock): def test_create_transaction_expense_success(self, setUp, requests_mock):
c = setUp c = setUp
requests_mock.post(c.url + "/transactions", requests_mock.post(c.url + "/transactions",
json=RetrieveJSONFromFile("data/CreateTransactionExpenseSuccess.json"), json=RetrieveJSONFromFile("data/CreateTransactionExpenseSuccess.json"),
status_code=201) status_code=201)
data = c.create_transaction(type="expense", data = c.create_transaction(transaction_type="expense",
amount=100.00, amount=100.00,
account_id=3, account_id=3,
paid_at="2022-05-16", paid_at="2022-05-16",
@@ -119,4 +158,3 @@ class TestAPI:
category_id="4", category_id="4",
description="Some expenditures" description="Some expenditures"
) )