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

Feat: Adding new Journal Entry changes #175

Merged
merged 4 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
85 changes: 44 additions & 41 deletions apps/business_central/exports/journal_entry/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,22 +41,26 @@ def create_or_update_object(self, accounting_export: AccountingExport, _: Advanc
:param accounting_export: expense group
:return: purchase invoices object
"""
expenses = accounting_export.expenses.all()
expense = accounting_export.expenses.first()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling and optimize database queries

Several issues need to be addressed:

  1. The method accepts advance_setting as a parameter but retrieves it again from the database. This is inefficient and inconsistent with the method signature.
  2. No error handling for the case when no expenses exist.
  3. The document_number logic could be simplified.

Apply these changes:

-        expense = accounting_export.expenses.first()
+        expense = accounting_export.expenses.first()
+        if not expense:
+            raise ValueError(f"No expenses found for accounting_export: {accounting_export.id}")

-        advance_setting = AdvancedSetting.objects.get(workspace_id=accounting_export.workspace_id)

-        document_number = accounting_export.description['expense_number'] if accounting_export.description and accounting_export.description.get('expense_number') else None
+        document_number = accounting_export.description.get('expense_number') if accounting_export.description else None

         comment = self.get_expense_comment(accounting_export.workspace_id, expense, expense.category, advance_setting)

Also applies to: 48-52


accounts_payable_account_id = export_settings.default_bank_account_id

document_number = accounting_export.description['claim_number'] if accounting_export.description and accounting_export.description.get('claim_number') else accounting_export.description['expense_number']
advance_setting = AdvancedSetting.objects.get(workspace_id=accounting_export.workspace_id)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Parameter naming inconsistency with implementation

The method parameter is named _: AdvancedSetting but the implementation retrieves and uses advance_setting. This suggests the parameter should be utilized instead of making a new database query.

-def create_or_update_object(self, accounting_export: AccountingExport, _: AdvancedSetting, export_settings: ExportSetting):
+def create_or_update_object(self, accounting_export: AccountingExport, advance_setting: AdvancedSetting, export_settings: ExportSetting):
-    advance_setting = AdvancedSetting.objects.get(workspace_id=accounting_export.workspace_id)

Also applies to: 50-52


comment = "Consolidated Credit Entry For Report/Expense {}".format(document_number)
print(accounting_export.__dict__)

document_number = expense.expense_number

comment = self.get_expense_comment(accounting_export.workspace_id, expense, expense.category, advance_setting)
Comment on lines +44 to +54
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Clean up implementation and add error handling

Several issues need to be addressed:

  1. Redundant database query for advance_setting
  2. Missing error handling for the case when no expenses exist
  3. Debug print statement should be removed
  4. Direct access to expense_number without validation

Apply these changes:

def create_or_update_object(self, accounting_export: AccountingExport, advance_setting: AdvancedSetting, export_settings: ExportSetting):
    expense = accounting_export.expenses.first()
+    if not expense:
+        raise ValueError(f"No expenses found for accounting_export: {accounting_export.id}")

    accounts_payable_account_id = export_settings.default_bank_account_id

-    advance_setting = AdvancedSetting.objects.get(workspace_id=accounting_export.workspace_id)

-    print(accounting_export.__dict__)

-    document_number = expense.expense_number
+    document_number = getattr(expense, 'expense_number', None)
+    if not document_number:
+        raise ValueError(f"No expense number found for expense: {expense.id}")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
expense = accounting_export.expenses.first()
accounts_payable_account_id = export_settings.default_bank_account_id
document_number = accounting_export.description['claim_number'] if accounting_export.description and accounting_export.description.get('claim_number') else accounting_export.description['expense_number']
advance_setting = AdvancedSetting.objects.get(workspace_id=accounting_export.workspace_id)
comment = "Consolidated Credit Entry For Report/Expense {}".format(document_number)
print(accounting_export.__dict__)
document_number = expense.expense_number
comment = self.get_expense_comment(accounting_export.workspace_id, expense, expense.category, advance_setting)
expense = accounting_export.expenses.first()
if not expense:
raise ValueError(f"No expenses found for accounting_export: {accounting_export.id}")
accounts_payable_account_id = export_settings.default_bank_account_id
document_number = getattr(expense, 'expense_number', None)
if not document_number:
raise ValueError(f"No expense number found for expense: {expense.id}")
comment = self.get_expense_comment(accounting_export.workspace_id, expense, expense.category, advance_setting)


invoice_date = self.get_invoice_date(accounting_export=accounting_export)

account_type, account_id = self.get_account_id_type(accounting_export=accounting_export, export_settings=export_settings)
account_type, account_id = self.get_account_id_type(accounting_export=accounting_export, export_settings=export_settings, merchant=expense.vendor)

journal_entry_object, _ = JournalEntry.objects.update_or_create(
accounting_export= accounting_export,
defaults={
'amount': sum([expense.amount for expense in expenses]),
'amount': expense.amount,
'document_number': document_number,
'accounts_payable_account_id': accounts_payable_account_id,
'account_id': account_id,
Expand Down Expand Up @@ -99,45 +103,44 @@ def create_or_update_object(self, accounting_export: AccountingExport, advance_s
:param accounting_export: expense group
:return: purchase invoices object
"""
expenses = accounting_export.expenses.all()
lineitem = accounting_export.expenses.first()
journal_entry = JournalEntry.objects.get(accounting_export=accounting_export)

journal_entry_lineitems = []

for lineitem in expenses:
category = lineitem.category if (lineitem.category == lineitem.sub_category or lineitem.sub_category == None) else '{0} / {1}'.format(lineitem.category, lineitem.sub_category)

account = CategoryMapping.objects.filter(
source_category__value=category,
workspace_id=accounting_export.workspace_id
).first()

comment = self.get_expense_comment(accounting_export.workspace_id, lineitem, lineitem.category, advance_setting)

invoice_date = self.get_invoice_date(accounting_export=accounting_export)

account_type, account_id = self.get_account_id_type(accounting_export=accounting_export, export_settings=export_settings, merchant=lineitem.vendor)

document_number = accounting_export.description['claim_number'] if accounting_export.description and accounting_export.description.get('claim_number') else accounting_export.description['expense_number']

dimensions = self.get_dimension_object(accounting_export, lineitem)

journal_entry_lineitems_object, _ = JournalEntryLineItems.objects.update_or_create(
journal_entry_id = journal_entry.id,
expense_id=lineitem.id,
defaults={
'amount': lineitem.amount * -1,
'account_id': account_id,
'account_type': account_type,
'document_number': document_number,
'accounts_payable_account_id': account.destination_account.destination_id,
'comment': comment,
'workspace_id': accounting_export.workspace_id,
'invoice_date': invoice_date,
'description': lineitem.purpose if lineitem.purpose else None,
'dimensions': dimensions
}
)
journal_entry_lineitems.append(journal_entry_lineitems_object)
category = lineitem.category if (lineitem.category == lineitem.sub_category or lineitem.sub_category == None) else '{0} / {1}'.format(lineitem.category, lineitem.sub_category)

Comment on lines +111 to +112
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Fix None comparison and simplify category formatting

The None comparison should use the is operator as per Python best practices.

-        category = lineitem.category if (lineitem.category == lineitem.sub_category or lineitem.sub_category == None) else '{0} / {1}'.format(lineitem.category, lineitem.sub_category)
+        category = lineitem.category if (lineitem.category == lineitem.sub_category or lineitem.sub_category is None) else f'{lineitem.category} / {lineitem.sub_category}'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
category = lineitem.category if (lineitem.category == lineitem.sub_category or lineitem.sub_category == None) else '{0} / {1}'.format(lineitem.category, lineitem.sub_category)
category = lineitem.category if (lineitem.category == lineitem.sub_category or lineitem.sub_category is None) else f'{lineitem.category} / {lineitem.sub_category}'
🧰 Tools
🪛 Ruff (0.7.0)

111-111: Comparison to None should be cond is None

Replace with cond is None

(E711)

account = CategoryMapping.objects.filter(
source_category__value=category,
workspace_id=accounting_export.workspace_id
).first()

Comment on lines +113 to +117
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for missing category mapping

The code assumes the category mapping will exist but doesn't handle the case where account might be None. This could lead to a NullPointerException when accessing account.destination_account.destination_id.

         account = CategoryMapping.objects.filter(
             source_category__value=category,
             workspace_id=accounting_export.workspace_id
         ).first()
+        if not account or not account.destination_account:
+            raise ValueError(f"No category mapping found for category: {category} in workspace: {accounting_export.workspace_id}")

Also applies to: 133-133

comment = self.get_expense_comment(accounting_export.workspace_id, lineitem, lineitem.category, advance_setting)

invoice_date = self.get_invoice_date(accounting_export=accounting_export)

account_type, account_id = self.get_account_id_type(accounting_export=accounting_export, export_settings=export_settings, merchant=lineitem.vendor)

document_number = lineitem.expense_number

dimensions = self.get_dimension_object(accounting_export, lineitem)

journal_entry_lineitems_object, _ = JournalEntryLineItems.objects.update_or_create(
journal_entry_id = journal_entry.id,
expense_id=lineitem.id,
defaults={
'amount': lineitem.amount * -1,
'account_id': account_id,
'account_type': account_type,
'document_number': document_number,
'accounts_payable_account_id': account.destination_account.destination_id,
'comment': comment,
'workspace_id': accounting_export.workspace_id,
'invoice_date': invoice_date,
'description': lineitem.purpose if lineitem.purpose else None,
'dimensions': dimensions
}
)
journal_entry_lineitems.append(journal_entry_lineitems_object)

return journal_entry_lineitems
12 changes: 10 additions & 2 deletions apps/business_central/exports/journal_entry/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
from apps.business_central.utils import BusinessCentralConnector
from apps.workspaces.models import BusinessCentralCredentials

from fyle_accounting_mappings.models import DestinationAttribute

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

Expand Down Expand Up @@ -42,6 +44,12 @@ def __construct_journal_entry(self, body: JournalEntry, lineitems: List[JournalE
batch_journal_entry_payload = []
dimensions = []

account_attribute_type = DestinationAttribute.objects.filter(workspace_id=body.workspace_id, destination_id=body.accounts_payable_account_id).first()

balance_account_type = 'G/L Account'
if account_attribute_type and account_attribute_type.attribute_type == 'BANK_ACCOUNT':
balance_account_type = 'Bank Account'

journal_entry_payload = {
'accountType': body.account_type,
'accountNumber': body.account_id,
Expand All @@ -50,7 +58,7 @@ def __construct_journal_entry(self, body: JournalEntry, lineitems: List[JournalE
'amount': body.amount,
'comment': body.comment,
'description': body.description,
'balanceAccountType': 'G/L Account',
'balanceAccountType': balance_account_type,
'balancingAccountNumber': body.accounts_payable_account_id

}
Expand All @@ -70,7 +78,7 @@ def __construct_journal_entry(self, body: JournalEntry, lineitems: List[JournalE
'amount': lineitem.amount,
'comment': lineitem.comment,
'description': lineitem.description if lineitem.description else '',
'balanceAccountType': 'G/L Account',
'balanceAccountType': balance_account_type,
'balancingAccountNumber': lineitem.accounts_payable_account_id
}

Expand Down
Loading