Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accounting exports api #15

Merged
merged 2 commits into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions apps/accounting_exports/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from django.db import models
from django.contrib.postgres.fields import ArrayField

from ms_business_central_api.models.fields import (
StringNotNullField,
StringNullField,
CustomJsonField,
CustomDateTimeField,
StringOptionsField
)
from apps.workspaces.models import BaseForeignWorkspaceModel
from apps.fyle.models import Expense

TYPE_CHOICES = (
('INVOICES', 'INVOICES'),
('DIRECT_COST', 'DIRECT_COST'),
('FETCHING_REIMBURSABLE_EXPENSES', 'FETCHING_REIMBURSABLE_EXPENSES'),
('FETCHING_CREDIT_CARD_EXPENENSES', 'FETCHING_CREDIT_CARD_EXPENENSES')
)

ERROR_TYPE_CHOICES = (('EMPLOYEE_MAPPING', 'EMPLOYEE_MAPPING'), ('CATEGORY_MAPPING', 'CATEGORY_MAPPING'), ('SAGE300_ERROR', 'SAGE300_ERROR'))
ruuushhh marked this conversation as resolved.
Show resolved Hide resolved

EXPORT_MODE_CHOICES = (
('MANUAL', 'MANUAL'),
('AUTO', 'AUTO')
)


class AccountingExport(BaseForeignWorkspaceModel):
"""
Table to store accounting exports
"""
id = models.AutoField(primary_key=True)
type = StringOptionsField(choices=TYPE_CHOICES, help_text='Task type')
fund_source = StringNotNullField(help_text='Expense fund source')
mapping_errors = ArrayField(help_text='Mapping errors', base_field=models.CharField(max_length=255), blank=True, null=True)
expenses = models.ManyToManyField(Expense, help_text="Expenses under this Expense Group")
task_id = StringNullField(help_text='Fyle Jobs task reference')
description = CustomJsonField(help_text='Description')
status = StringNotNullField(help_text='Task Status')
detail = CustomJsonField(help_text='Task Response')
sage_300_errors = CustomJsonField(help_text='Sage 300 Errors')
ruuushhh marked this conversation as resolved.
Show resolved Hide resolved
exported_at = CustomDateTimeField(help_text='time of export')

class Meta:
db_table = 'accounting_exports'
13 changes: 13 additions & 0 deletions apps/accounting_exports/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from rest_framework import serializers

from apps.accounting_exports.models import AccountingExport


class AccountingExportSerializer(serializers.ModelSerializer):
"""
Accounting Export serializer
"""

class Meta:
model = AccountingExport
fields = '__all__'
22 changes: 22 additions & 0 deletions apps/accounting_exports/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""sage_desktop_api URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.urls import path

from apps.accounting_exports.views import AccountingExportView


urlpatterns = [
path('', AccountingExportView.as_view(), name='accounting-exports'),
]
22 changes: 22 additions & 0 deletions apps/accounting_exports/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import logging

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics

from ms_business_central_api.utils import LookupFieldMixin
from apps.accounting_exports.serializers import AccountingExportSerializer
from apps.accounting_exports.models import AccountingExport


logger = logging.getLogger(__name__)
logger.level = logging.INFO


class AccountingExportView(LookupFieldMixin, generics.ListAPIView):
"""
Retrieve or Create Accounting Export
"""
serializer_class = AccountingExportSerializer
queryset = AccountingExport.objects.all().order_by("-updated_at")
filter_backends = (DjangoFilterBackend,)
filterset_fields = {"type": {"in"}, "updated_at": {"lte", "gte"}, "id": {"in"}, "status": {"in"}}
66 changes: 66 additions & 0 deletions apps/fyle/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
from django.db import models
from django.contrib.postgres.fields import ArrayField
from ms_business_central_api.models.fields import (
StringNotNullField,
StringNullField,
BooleanFalseField,
CustomJsonField,
CustomDateTimeField,
CustomEmailField,
FloatNullField
)
from apps.workspaces.models import BaseModel


class Expense(BaseModel):
"""
Expense
"""
id = models.AutoField(primary_key=True)
employee_email = CustomEmailField(help_text='Email id of the Fyle employee')
employee_name = StringNullField(help_text='Name of the Fyle employee')
category = StringNullField(help_text='Fyle Expense Category')
sub_category = StringNullField(help_text='Fyle Expense Sub-Category')
project = StringNullField(help_text='Project')
expense_id = StringNotNullField(unique=True, help_text='Expense ID')
org_id = StringNullField(help_text='Organization ID')
expense_number = StringNotNullField(help_text='Expense Number')
claim_number = StringNotNullField(help_text='Claim Number')
amount = models.FloatField(help_text='Home Amount')
currency = StringNotNullField(max_length=5, help_text='Home Currency')
foreign_amount = models.FloatField(null=True, help_text='Foreign Amount')
foreign_currency = StringNotNullField(max_length=5, help_text='Foreign Currency')
settlement_id = StringNullField(help_text='Settlement ID')
reimbursable = BooleanFalseField(help_text='Expense reimbursable or not')
state = StringNotNullField(help_text='Expense state')
vendor = StringNotNullField(help_text='Vendor')
cost_center = StringNullField(help_text='Fyle Expense Cost Center')
corporate_card_id = StringNullField(help_text='Corporate Card ID')
purpose = models.TextField(null=True, blank=True, help_text='Purpose')
report_id = StringNotNullField(help_text='Report ID')
billable = BooleanFalseField(help_text='Expense billable or not')
file_ids = ArrayField(base_field=models.CharField(max_length=255), null=True, help_text='File IDs')
spent_at = CustomDateTimeField(help_text='Expense spent at')
approved_at = CustomDateTimeField(help_text='Expense approved at')
posted_at = CustomDateTimeField(help_text='Date when the money is taken from the bank')
expense_created_at = CustomDateTimeField(help_text='Expense created at')
expense_updated_at = CustomDateTimeField(help_text='Expense created at')
fund_source = StringNotNullField(help_text='Expense fund source')
verified_at = CustomDateTimeField(help_text='Report verified at')
custom_properties = CustomJsonField(help_text="Custom Properties")
tax_amount = FloatNullField(help_text='Tax Amount')
tax_group_id = StringNullField(help_text='Tax Group ID')
exported = BooleanFalseField(help_text='Expense reimbursable or not')
previous_export_state = StringNullField(max_length=255, help_text='Previous export state')
accounting_export_summary = CustomJsonField(default=dict, help_text='Accounting Export Summary')

class Meta:
db_table = 'expenses'


class Reimbursement:
"""
Creating a dummy class to be able to user
fyle_integrations_platform_connector correctly
"""
pass
6 changes: 4 additions & 2 deletions apps/workspaces/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.urls import path
from django.urls import path, include

from apps.workspaces.views import (
ReadyView,
Expand All @@ -19,7 +19,9 @@
path('<int:workspace_id>/admins/', WorkspaceAdminsView.as_view(), name='admin'),
]

other_app_paths = []
other_app_paths = [
path('<int:workspace_id>/accounting_exports/', include('apps.accounting_exports.urls')),
]

urlpatterns = []
urlpatterns.extend(workspace_app_paths)
Expand Down
30 changes: 29 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@
from apps.fyle.helpers import get_access_token
from apps.workspaces.models import (
Workspace,
FyleCredential
FyleCredential,
)
from apps.accounting_exports.models import AccountingExport
from ms_business_central_api.tests import settings

from .test_fyle.fixtures import fixtures as fyle_fixtures
Expand Down Expand Up @@ -139,3 +140,30 @@ def add_fyle_credentials():
workspace_id=workspace_id,
cluster_domain='https://dummy_cluster_domain.com',
)


@pytest.fixture()
@pytest.mark.django_db(databases=['default'])
def add_accounting_export_expenses():
"""
Pytest fixture to add accounting export to a workspace
"""
workspace_ids = [
1, 2, 3
]
for workspace_id in workspace_ids:
AccountingExport.objects.update_or_create(
workspace_id=workspace_id,
type='FETCHING_REIMBURSABLE_EXPENSES',
defaults={
'status': 'IN_PROGRESS'
}
)

AccountingExport.objects.update_or_create(
workspace_id=workspace_id,
type='FETCHING_CREDIT_CARD_EXPENENSES',
defaults={
'status': 'IN_PROGRESS'
}
)
38 changes: 38 additions & 0 deletions tests/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import json
from os import path


def dict_compare_keys(d1, d2, key_path=''):
"""
Compare two dicts recursively and see if dict1 has any keys that dict2 does not
Returns: list of key paths
"""
res = []
if not d1:
return res
if not isinstance(d1, dict):
return res
for k in d1:
if k not in d2:
missing_key_path = f'{key_path}->{k}'
res.append(missing_key_path)
else:
if isinstance(d1[k], dict):
key_path1 = f'{key_path}->{k}'
res1 = dict_compare_keys(d1[k], d2[k], key_path1)
res = res + res1
elif isinstance(d1[k], list):
key_path1 = f'{key_path}->{k}[0]'
dv1 = d1[k][0] if len(d1[k]) > 0 else None
dv2 = d2[k][0] if len(d2[k]) > 0 else None
res1 = dict_compare_keys(dv1, dv2, key_path1)
res = res + res1
return res


def get_response_dict(filename):
basepath = path.dirname(__file__)
filepath = path.join(basepath, filename)
mock_json = open(filepath, 'r').read()
mock_dict = json.loads(mock_json)
return mock_dict
19 changes: 19 additions & 0 deletions tests/test_accounting_exports/test_views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import json
from django.urls import reverse
from tests.helpers import dict_compare_keys
from tests.test_fyle.fixtures import fixtures as data


def test_get_accounting_exports(api_client, test_connection, create_temp_workspace, add_fyle_credentials, add_accounting_export_expenses):
"""
Test get accounting exports
"""
url = reverse('accounting-exports', kwargs={'workspace_id': 1})

api_client.credentials(HTTP_AUTHORIZATION='Bearer {}'.format(test_connection.access_token))

response = api_client.get(url)
assert response.status_code == 200
response = json.loads(response.content)

assert dict_compare_keys(response, data['accounting_export_response']) == [], 'accounting export api return diffs in keys'
41 changes: 40 additions & 1 deletion tests/test_fyle/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,44 @@
},
'user_id': 'usqywo0f3nBY',
}
}
},
'accounting_export_response': {
"count":2,
"next":"None",
"previous":"None",
"results":[
{
"id":2,
"created_at":"2023-10-26T03:24:43.513291Z",
"updated_at":"2023-10-26T03:24:43.513296Z",
"type":"FETCHING_REIMBURSABLE_EXPENSES",
"fund_source":"",
"mapping_errors":"None",
"task_id":"None",
"description":[],
"status":"IN_PROGRESS",
"detail":[],
"sage_300_errors":[],
"exported_at":"None",
"workspace":1,
"expenses":[]
},
{
"id":1,
"created_at":"2023-10-26T03:24:43.511973Z",
"updated_at":"2023-10-26T03:24:43.511978Z",
"type":"FETCHING_CREDIT_CARD_EXPENENSES",
"fund_source":"",
"mapping_errors":"None",
"task_id":"None",
"description":[],
"status":"IN_PROGRESS",
"detail":[],
"sage_300_errors":[],
"exported_at":"None",
"workspace":1,
"expenses":[]
}
]
},
}
Loading