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

fix: JE fixes #1093

Merged
merged 4 commits into from
Dec 4, 2024
Merged

fix: JE fixes #1093

merged 4 commits into from
Dec 4, 2024

Conversation

DhaaraniCIT
Copy link
Contributor

@DhaaraniCIT DhaaraniCIT commented Dec 3, 2024

Description

fix: JE fixes

Clickup

Please add link here

Summary by CodeRabbit

  • New Features

    • Enhanced form interactivity and responsiveness based on user selections.
    • Conditional rendering of fields for improved user experience.
    • Introduced a new search option feature with debounce functionality for better performance.
    • Updated validation logic to emphasize the importance of the employeeMapping field.
    • Added support for chart of accounts in the dashboard and error section components.
  • Bug Fixes

    • Improved visibility control for various form components based on form state.
    • Corrected method naming for clarity and consistency in functionality.
    • Enhanced error handling during save operations and settings retrieval.
    • Adjusted API parameter naming for task retrieval to align with new conventions.

@DhaaraniCIT DhaaraniCIT added the deploy Triggers deployment of active branch to Staging label Dec 3, 2024
Copy link
Contributor

coderabbitai bot commented Dec 3, 2024

Walkthrough

The changes in this pull request focus on enhancing the qbd-direct-export-settings.component.html and qbd-direct-export-settings.component.ts files. Adjustments were made to the destinationAttributes property for two app-configuration-select-field components, correcting a typo in the method name and modifying how options for accounts payable are derived. The QbdDirectExportSettingsComponent class also saw updates in method naming, error handling, and the management of asynchronous operations, including the introduction of a new method for handling search updates.

Changes

File Change Summary
src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.html Updated destinationAttributes for app-configuration-select-field components to use cccAccountOptions.
src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.ts Renamed cccAccpuntOptions to cccAccountOptions. Updated cccExportTypeWatcher and added optionSearchWatcher for managing search updates. Enhanced error handling in save and getSettingsAndSetupForm methods.
src/app/core/models/common/helper.model.ts Modified clearValidatorAndResetValue method to exclude employeeMapping from being reset.
src/app/core/models/db/task-log.model.ts Renamed property export_log__id to export_log__id__in in TaskLogGetParams type.
src/app/core/models/qbd-direct/qbd-direct-configuration/qbd-direct-advanced-settings.model.ts Added static method topMemoExpenseKeyNameConversion to modify memo structures.
src/app/core/models/qbd-direct/qbd-direct-configuration/qbd-direct-export-settings.model.ts Updated validation logic for employeeMapping in getMandatoryField and getValidators methods.
src/app/core/services/common/dashboard.service.ts Changed expenseGroupIds key from 'export_log__id' to 'export_log__id__in' in getTasks method.
src/app/core/models/db/destination-attribute.model.ts Added import for QbdDirectDestinationAttribute and updated GroupedDestinationAttribute type to include it.
src/app/integrations/qbd-direct/qbd-direct-main/qbd-direct-dashboard/qbd-direct-dashboard.component.html Added new input property chartOfAccounts to app-dashboard-error-section component.
src/app/integrations/qbd-direct/qbd-direct-main/qbd-direct-dashboard/qbd-direct-dashboard.component.ts Introduced chartOfAccounts property to QbdDirectDashboardComponent, initialized in setupPage method.
src/app/shared/components/dashboard/dashboard-error-section/dashboard-error-section.component.ts Added input property chartOfAccounts and introduced destinationOptionsWatcher method for filtering options.

Possibly related PRs

Suggested labels

size/M

Suggested reviewers

  • ashwin1111

🐇 In the meadow, changes bloom,
A form transformed, dispelling gloom.
With options fresh and fields that sway,
The rabbit hops, it's a brighter day!
Dynamic choices, a joyful dance,
In the world of exports, we take a chance! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the size/XS Extra Small PR label Dec 3, 2024
Copy link

github-actions bot commented Dec 3, 2024

PR description must contain a link to a ClickUp (case-insensitive)

1 similar comment
Copy link

github-actions bot commented Dec 3, 2024

PR description must contain a link to a ClickUp (case-insensitive)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.html (1)

Line range hint 251-259: Improve export grouping field configuration

A few suggestions to improve this section:

  1. Consider moving the complex disable condition to a component method for better maintainability
  2. Add a tooltip or help text explaining why grouping is disabled for CREDIT_CARD_PURCHASE and JOURNAL_ENTRY types
  3. The isDisableTextRequired is set but no disable text is visible in the template

Consider refactoring to:

- [isDisabled]="exportSettingsForm.get('creditCardExportType')?.value === QBDCorporateCreditCardExpensesObject.CREDIT_CARD_PURCHASE || exportSettingsForm.get('creditCardExportType')?.value === QBDCorporateCreditCardExpensesObject.JOURNAL_ENTRY ? true : false"
+ [isDisabled]="isExportGroupingDisabled()"
+ [disabledText]="getExportGroupingDisabledText()"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 304ba01 and 2c82ff8.

📒 Files selected for processing (1)
  • src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.html (1 hunks)
🔇 Additional comments (1)
src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.html (1)

Line range hint 158-170: Review employee mapping visibility logic

The employee mapping section for credit card expenses is only shown when:

  1. Reimbursable expenses are disabled (!exportSettingsForm.get('reimbursableExpense')?.value) AND
  2. Credit card export type is Journal Entry

This could lead to missing employee mapping configuration when both reimbursable and credit card expenses are enabled. Consider if this is the intended behavior.

Let's check if this is handled in the component class:

@@ -194,7 +194,7 @@
<div *ngIf="helperService.isFieldRequired(exportSettingsForm, 'defaultCCCAccountsPayableAccountName')">
<app-configuration-select-field
[form]="exportSettingsForm"
[destinationAttributes]="destinationOptionsWatcher(['AccountsPayable'] , destinationAccounts)"
[destinationAttributes]="cccAccpuntOptions(exportSettingsForm.get('creditCardExportType')?.value)"
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Fix typo in function name cccAccpuntOptions

The function name contains a typo in both the component class and template:

  • src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.ts: Function declaration cccAccpuntOptions
  • src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.html: Function usage cccAccpuntOptions

Rename the function to cccAccountOptions to fix the spelling error.

🔗 Analysis chain

Fix typo in function name cccAccpuntOptions

The function name contains a typo: "Accpunt" should be "Account".

Let's verify if this typo exists in the component class:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the misspelled function name in component files
rg "cccAccpuntOptions" --type ts

Length of output: 218


Script:

#!/bin/bash
# Get the implementation of the misspelled function to understand its usage
ast-grep --pattern 'cccAccpuntOptions($$$) {
  $$$
}'

Length of output: 55


Script:

#!/bin/bash
# Let's try a different pattern to find the function implementation
rg "cccAccpuntOptions" -A 10 --type ts

Length of output: 2216

Copy link

github-actions bot commented Dec 3, 2024

PR description must contain a link to a ClickUp (case-insensitive)

1 similar comment
Copy link

github-actions bot commented Dec 3, 2024

PR description must contain a link to a ClickUp (case-insensitive)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (3)
src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.ts (3)

Line range hint 111-120: Consider refactoring complex conditional logic for better readability

The method handles multiple business cases with nested conditions. Consider extracting the account type arrays into named constants to improve readability and maintainability.

+ private readonly CREDIT_CARD_ACCOUNT_TYPES = ['CreditCard'];
+ private readonly EMPLOYEE_ACCOUNT_TYPES = ['Bank', 'CreditCard', 'OtherCurrentLiability', 'LongTermLiability'];
+ private readonly DEFAULT_ACCOUNT_TYPES = ['Bank', 'AccountsPayable', 'CreditCard', 'OtherCurrentLiability', 'LongTermLiability'];

  cccAccountOptions(cccExportType: string): DestinationAttribute[] {
    if (cccExportType === QBDCorporateCreditCardExpensesObject.CREDIT_CARD_PURCHASE) {
-     return this.destinationOptionsWatcher(['CreditCard'], this.destinationAccounts);
+     return this.destinationOptionsWatcher(this.CREDIT_CARD_ACCOUNT_TYPES, this.destinationAccounts);
    } else if (cccExportType === QBDCorporateCreditCardExpensesObject.JOURNAL_ENTRY && 
               this.exportSettingsForm.controls.employeeMapping.value === EmployeeFieldMapping.EMPLOYEE && 
               this.exportSettingsForm.controls.nameInJE.value === EmployeeFieldMapping.EMPLOYEE) {
-     return this.destinationOptionsWatcher(['Bank', 'CreditCard', 'OtherCurrentLiability', 'LongTermLiability'], this.destinationAccounts);
+     return this.destinationOptionsWatcher(this.EMPLOYEE_ACCOUNT_TYPES, this.destinationAccounts);
    }
-   return this.destinationOptionsWatcher(['Bank', 'AccountsPayable', 'CreditCard', 'OtherCurrentLiability', 'LongTermLiability'], this.destinationAccounts);
+   return this.destinationOptionsWatcher(this.DEFAULT_ACCOUNT_TYPES, this.destinationAccounts);
  }

Line range hint 122-149: Add subscription cleanup and error handling

The subscription to optionSearchUpdate should be cleaned up on component destruction to prevent memory leaks. Additionally, error handling should be added for the API call.

+ private destroy$ = new Subject<void>();

  private optionSearchWatcher(): void {
    this.optionSearchUpdate.pipe(
      debounceTime(1000),
+     takeUntil(this.destroy$)
    ).subscribe((event: ExportSettingOptionSearch) => {
      let existingOptions: QbdDirectDestinationAttribute[] = [];
      existingOptions = this.destinationAccounts;
      let newOptions: QbdDirectDestinationAttribute[];

      this.mappingService.getPaginatedDestinationAttributes(event.destinationOptionKey, event.searchTerm).pipe(
+       catchError((error) => {
+         this.isOptionSearchInProgress = false;
+         this.toastService.displayToastMessage(ToastSeverity.ERROR, 'Error fetching options');
+         return EMPTY;
+       })
      ).subscribe((response) => {
        // ... rest of the code
      });
    });
  }

+ ngOnDestroy(): void {
+   this.destroy$.next();
+   this.destroy$.complete();
+ }

Line range hint 1-300: Consider splitting component for better maintainability

The component handles multiple responsibilities including:

  • Export settings form management
  • Search functionality
  • Multiple watchers
  • Complex state management

Consider splitting this into smaller, more focused components or services to improve maintainability and testability.

Suggestions:

  1. Extract form management logic into a dedicated service
  2. Create a separate service for handling destination attributes and search
  3. Consider using NgRx/RxJS state management for complex state handling
  4. Split the template into smaller, reusable components

Would you like assistance in planning this refactoring?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2c82ff8 and b322eee.

📒 Files selected for processing (2)
  • src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.html (2 hunks)
  • src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.html

Comment on lines 184 to 188
this.exportSettingsForm.controls.creditCardExportType.valueChanges.subscribe((creditCardExportTypeValue) => {
this.exportSettingsForm.controls.creditCardExportGroup.patchValue(this.creditCardExpenseGroupingFieldOptions[1].value);
this.exportSettingsForm.controls.creditCardExportGroup.patchValue(QbdDirectExportSettingModel.expenseGroupingFieldOptions()[1].value);
this.exportSettingsForm.controls.creditCardExportGroup.disable();
this.creditCardExpenseGroupingFieldOptions = [QbdDirectExportSettingModel.expenseGroupingFieldOptions()[1]];
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace hardcoded index with explicit value reference

Using a hardcoded index [1] for accessing options is fragile and could break if the options array changes. Consider using a constant or finding the option by value.

  cccExportTypeWatcher(): void {
    this.exportSettingsForm.controls.creditCardExportType.valueChanges.subscribe((creditCardExportTypeValue) => {
-       this.exportSettingsForm.controls.creditCardExportGroup.patchValue(QbdDirectExportSettingModel.expenseGroupingFieldOptions()[1].value);
+       const defaultOption = QbdDirectExportSettingModel.expenseGroupingFieldOptions().find(option => 
+         option.value === QbdDirectExpenseGroupBy.EXPENSE
+       );
+       if (!defaultOption) {
+         throw new Error('Default expense grouping option not found');
+       }
+       this.exportSettingsForm.controls.creditCardExportGroup.patchValue(defaultOption.value);
        this.exportSettingsForm.controls.creditCardExportGroup.disable();
-       this.creditCardExpenseGroupingFieldOptions = [QbdDirectExportSettingModel.expenseGroupingFieldOptions()[1]];
+       this.creditCardExpenseGroupingFieldOptions = [defaultOption];
    });
  }
📝 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
this.exportSettingsForm.controls.creditCardExportType.valueChanges.subscribe((creditCardExportTypeValue) => {
this.exportSettingsForm.controls.creditCardExportGroup.patchValue(this.creditCardExpenseGroupingFieldOptions[1].value);
this.exportSettingsForm.controls.creditCardExportGroup.patchValue(QbdDirectExportSettingModel.expenseGroupingFieldOptions()[1].value);
this.exportSettingsForm.controls.creditCardExportGroup.disable();
this.creditCardExpenseGroupingFieldOptions = [QbdDirectExportSettingModel.expenseGroupingFieldOptions()[1]];
});
this.exportSettingsForm.controls.creditCardExportType.valueChanges.subscribe((creditCardExportTypeValue) => {
const defaultOption = QbdDirectExportSettingModel.expenseGroupingFieldOptions().find(option =>
option.value === QbdDirectExpenseGroupBy.EXPENSE
);
if (!defaultOption) {
throw new Error('Default expense grouping option not found');
}
this.exportSettingsForm.controls.creditCardExportGroup.patchValue(defaultOption.value);
this.exportSettingsForm.controls.creditCardExportGroup.disable();
this.creditCardExpenseGroupingFieldOptions = [defaultOption];
});

@DhaaraniCIT DhaaraniCIT added deploy Triggers deployment of active branch to Staging and removed deploy Triggers deployment of active branch to Staging labels Dec 4, 2024
@github-actions github-actions bot added size/S Small PR and removed size/XS Extra Small PR labels Dec 4, 2024
Copy link

github-actions bot commented Dec 4, 2024

PR description must contain a link to a ClickUp (case-insensitive)

1 similar comment
Copy link

github-actions bot commented Dec 4, 2024

PR description must contain a link to a ClickUp (case-insensitive)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
src/app/core/models/qbd-direct/qbd-direct-configuration/qbd-direct-advanced-settings.model.ts (1)

55-55: Address static method references and simplify null checks

The current implementation has two issues:

  1. Uses this in static context (flagged by static analysis)
  2. Has complex null checking logic

Consider this cleaner implementation:

-            topMemoStructure: new FormControl(advancedSettings?.top_level_memo_structure && advancedSettings?.top_level_memo_structure.length > 0 ? this.topMemoExpenseKeyNameConversion(advancedSettings?.top_level_memo_structure) : this.defaultTopMemoOptions(), Validators.required),
+            topMemoStructure: new FormControl(
+                QbdDirectAdvancedSettingsModel.topMemoExpenseKeyNameConversion(advancedSettings?.top_level_memo_structure) || 
+                QbdDirectAdvancedSettingsModel.defaultTopMemoOptions(),
+                Validators.required
+            ),
🧰 Tools
🪛 Biome (1.9.4)

[error] 55-55: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 55-55: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

src/app/core/services/common/dashboard.service.ts (1)

61-61: Consider simplifying the complex ternary expression.

While the change to use export_log__id__in is correct and consistent with the model update, the nested ternary operator is becoming hard to read.

Consider refactoring to improve readability:

-const expenseKey = appName === AppName.INTACCT ? 'expense_group_ids' : appName === AppName.QBD_DIRECT ? 'export_log__id__in' : 'expense_group_id__in';
+const getExpenseKey = (appName?: AppName): string => {
+  switch (appName) {
+    case AppName.INTACCT:
+      return 'expense_group_ids';
+    case AppName.QBD_DIRECT:
+      return 'export_log__id__in';
+    default:
+      return 'expense_group_id__in';
+  }
+};
+const expenseKey = getExpenseKey(appName);

This approach:

  1. Improves readability
  2. Makes it easier to add new cases
  3. Makes the logic more maintainable
src/app/core/models/qbd-direct/qbd-direct-configuration/qbd-direct-export-settings.model.ts (1)

Line range hint 177-203: Consider broader implications of validation changes

The validation rule changes for employeeMapping could affect:

  1. UI components that rely on these validation rules
  2. Error messages and user feedback
  3. Existing data that might not meet the new validation requirements

Please ensure that:

  • Related components are updated to handle the new validation rules
  • Error messages clearly indicate when employeeMapping is required
  • A data migration plan is in place if needed
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b322eee and 44d41c6.

📒 Files selected for processing (6)
  • src/app/core/models/common/helper.model.ts (1 hunks)
  • src/app/core/models/db/task-log.model.ts (1 hunks)
  • src/app/core/models/qbd-direct/qbd-direct-configuration/qbd-direct-advanced-settings.model.ts (2 hunks)
  • src/app/core/models/qbd-direct/qbd-direct-configuration/qbd-direct-export-settings.model.ts (2 hunks)
  • src/app/core/services/common/dashboard.service.ts (1 hunks)
  • src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.html (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.html
🧰 Additional context used
🪛 Biome (1.9.4)
src/app/core/models/qbd-direct/qbd-direct-configuration/qbd-direct-advanced-settings.model.ts

[error] 55-55: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)


[error] 55-55: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

🔇 Additional comments (2)
src/app/core/models/db/task-log.model.ts (1)

26-26: LGTM! Consistent with REST API filtering conventions.

The rename from export_log__id to export_log__id__in better reflects that this parameter accepts multiple IDs for filtering, following standard REST API naming conventions.

src/app/core/models/qbd-direct/qbd-direct-configuration/qbd-direct-export-settings.model.ts (1)

187-187: Verify validation behavior for employeeMapping

The validation rules for employeeMapping have been updated to be more specific to export types, which is good. However, please verify that:

  1. Removing employeeMapping from reimbursableExpense array doesn't create validation gaps
  2. These validation rules work correctly with the getMandatoryField logic

Let's verify the validation behavior:

Also applies to: 195-196, 203-203

✅ Verification successful

Let's gather more specific information about the validation rules and their usage.


Let's try a different approach to gather the validation logic:


After analyzing the file content, I can now provide a final response:

Validation rules for employeeMapping are correctly structured

The changes to employeeMapping validation are intentional and properly implemented:

  1. The removal from reimbursableExpense array is correct because employeeMapping is now handled through the exportModuleRule structure, which provides more granular control
  2. The getMandatoryField logic aligns with the validation rules:
    • For BILL type: employeeMapping is required (via exportModuleRule)
    • For JOURNAL_ENTRY type: employeeMapping is required (via exportModuleRule)
    • For credit card expenses: employeeMapping is required only for JOURNAL_ENTRY type (via both getMandatoryField and exportModuleRule)

The validation structure ensures there are no gaps in validation coverage and maintains consistency between the validation rules and mandatory field logic.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for tests or usages of these validation rules
rg -l "getValidators|getMandatoryField.*employeeMapping" --type ts

# Search for any related validation error handling
rg "employeeMapping.*error" --type ts

Length of output: 1359


Script:

#!/bin/bash
# Check the implementation of getValidators and getMandatoryField in the file
ast-grep --pattern 'getValidators() {
  $$$
}'

# Look for employeeMapping related validation tests
rg -A 5 "employeeMapping.*test" --type ts

# Check the actual implementation in the component
rg -A 10 "employeeMapping.*validate" --type ts

# Look for the specific validation logic around reimbursableExpense
ast-grep --pattern 'reimbursableExpense: [$_]'

Length of output: 190


Script:

#!/bin/bash
# Get the content of the file we're reviewing to see the full context
cat src/app/core/models/qbd-direct/qbd-direct-configuration/qbd-direct-export-settings.model.ts

# Search for any references to employeeMapping in validation contexts
rg -B 2 -A 2 "employeeMapping.*validation|validate.*employeeMapping" --type ts

# Look for any tests related to these export settings
fd "export-settings.spec" --type ts --exec cat {}

Length of output: 15114

Comment on lines +32 to +39
static topMemoExpenseKeyNameConversion(keys: string[]): string[] {
keys.forEach((key: string, index: number) => {
if (key === 'expense_key') {
keys[index] = 'Expense/Report ID';
}
});
return keys;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve method implementation to follow best practices

The current implementation has potential issues:

  1. Mutates the input array directly
  2. Lacks input validation
  3. Has unclear return semantics (both mutates and returns)

Consider this safer implementation:

-    static topMemoExpenseKeyNameConversion(keys: string[]): string[] {
-        keys.forEach((key: string, index: number) => {
-            if (key === 'expense_key') {
-                keys[index] = 'Expense/Report ID';
-            }
-        });
-        return keys;
-    }
+    static topMemoExpenseKeyNameConversion(keys: string[] | null | undefined): string[] {
+        if (!keys?.length) {
+            return [];
+        }
+        return keys.map((key: string) => 
+            key === 'expense_key' ? 'Expense/Report ID' : key
+        );
+    }
📝 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
static topMemoExpenseKeyNameConversion(keys: string[]): string[] {
keys.forEach((key: string, index: number) => {
if (key === 'expense_key') {
keys[index] = 'Expense/Report ID';
}
});
return keys;
}
static topMemoExpenseKeyNameConversion(keys: string[] | null | undefined): string[] {
if (!keys?.length) {
return [];
}
return keys.map((key: string) =>
key === 'expense_key' ? 'Expense/Report ID' : key
);
}

@@ -14,7 +14,7 @@ export class HelperUtility {
form.controls[controllerName].clearValidators();

// Temporary hack: Don't reset value for fields that are used in reimbursable + ccc section
if (controllerName !== 'accountsPayable' && controllerName !== 'defaultCCCAccount' && controllerName !== 'bankAccount' && controllerName !== 'creditCardAccount' && controllerName !== 'defaultCreditCardVendor' && controllerName !== 'nameInJournalEntry' && controllerName !== 'exportScheduleFrequency') {
if (controllerName !== 'accountsPayable' && controllerName !== 'defaultCCCAccount' && controllerName !== 'bankAccount' && controllerName !== 'creditCardAccount' && controllerName !== 'defaultCreditCardVendor' && controllerName !== 'nameInJournalEntry' && controllerName !== 'exportScheduleFrequency' && controllerName !== 'employeeMapping') {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring the growing list of exceptions.

The current approach of listing specific field names as exceptions is becoming unwieldy and harder to maintain. The comment "Temporary hack" also suggests this needs improvement.

Consider refactoring to a more maintainable solution:

-if (controllerName !== 'accountsPayable' && controllerName !== 'defaultCCCAccount' && controllerName !== 'bankAccount' && controllerName !== 'creditCardAccount' && controllerName !== 'defaultCreditCardVendor' && controllerName !== 'nameInJournalEntry' && controllerName !== 'exportScheduleFrequency' && controllerName !== 'employeeMapping') {
+const PRESERVE_VALUE_FIELDS = new Set([
+  'accountsPayable',
+  'defaultCCCAccount',
+  'bankAccount',
+  'creditCardAccount',
+  'defaultCreditCardVendor',
+  'nameInJournalEntry',
+  'exportScheduleFrequency',
+  'employeeMapping'
+]);
+
+if (!PRESERVE_VALUE_FIELDS.has(controllerName)) {

This approach:

  1. Makes the list of exceptions more maintainable
  2. Improves readability
  3. Provides better performance for lookups
  4. Makes it easier to add/remove fields

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +177 to +178
case 'employeeMapping':
return !form.get('reimbursableExportType')?.value && form.get('creditCardExportType')?.value && form.get('creditCardExportType')?.value === QBDCorporateCreditCardExpensesObject.JOURNAL_ENTRY;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Review the employeeMapping mandatory field logic

The current condition for making employeeMapping mandatory seems inconsistent. It only requires employeeMapping when reimbursableExportType is NOT set, but the validation rules later show that employeeMapping is required for both BILL and JOURNAL_ENTRY types. This could lead to validation inconsistencies.

Consider updating the condition to:

case 'employeeMapping':
-  return !form.get('reimbursableExportType')?.value && form.get('creditCardExportType')?.value && form.get('creditCardExportType')?.value === QBDCorporateCreditCardExpensesObject.JOURNAL_ENTRY;
+  return (form.get('reimbursableExportType')?.value === QBDReimbursableExpensesObject.BILL || 
+          form.get('reimbursableExportType')?.value === QBDReimbursableExpensesObject.JOURNAL_ENTRY) || 
+         (form.get('creditCardExportType')?.value === QBDCorporateCreditCardExpensesObject.JOURNAL_ENTRY);

Committable suggestion skipped: line range outside the PR's diff.

@github-actions github-actions bot added size/M Medium PR and removed size/S Small PR labels Dec 4, 2024
Copy link

github-actions bot commented Dec 4, 2024

PR description must contain a link to a ClickUp (case-insensitive)

Copy link

github-actions bot commented Dec 4, 2024

Unit Test Coverage % values
Statements 34.75% ( 4249 / 12225 )
Branches 28.6% ( 1231 / 4304 )
Functions 27.42% ( 940 / 3427 )
Lines 34.9% ( 4179 / 11974 )

Copy link

github-actions bot commented Dec 4, 2024

PR description must contain a link to a ClickUp (case-insensitive)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
src/app/integrations/qbd-direct/qbd-direct-main/qbd-direct-dashboard/qbd-direct-dashboard.component.ts (1)

Line range hint 143-157: Enhance error handling for API calls

The setupPage method only handles errors for getAccountingExportSummary$. Consider adding error handling for other API calls to ensure graceful degradation.

Example implementation:

private setupPage(): void {
  forkJoin([
    this.getExportErrors$.pipe(catchError(() => of({ results: [] }))),
    this.getAccountingExportSummary$.pipe(catchError(() => of(null))),
    this.dashboardService.getAllTasks(...).pipe(catchError(() => of({ results: [] }))),
    this.dashboardService.getExportableAccountingExportIds('v2').pipe(catchError(() => of({ exportable_export_log_ids: [] }))),
    this.QbdDirectExportSettingsService.getQbdExportSettings().pipe(catchError(() => of({}))),
    this.importSettingService.getImportSettings().pipe(catchError(() => of({ import_settings: { chart_of_accounts: [] } })))
  ]).subscribe(...)
}
src/app/shared/components/dashboard/dashboard-error-section/dashboard-error-section.component.ts (2)

55-56: Add documentation and consider default value.

The chartOfAccounts input property would benefit from:

  1. JSDoc documentation explaining its purpose and expected values
  2. A default empty array value to prevent potential undefined errors
+  /**
+   * List of account types used to filter QBD Direct destination options
+   */
-  @Input() chartOfAccounts: string[];
+  @Input() chartOfAccounts: string[] = [];

152-152: Improve type safety and readability.

The current implementation could be enhanced:

  1. Split the long line for better readability
  2. Add type guard to ensure safe type casting
-          this.destinationOptions = this.appName !== AppName.QBD_DIRECT ? groupedDestinationResponse.ACCOUNT : this.destinationOptionsWatcher( this.chartOfAccounts, groupedDestinationResponse.ACCOUNT as QbdDirectDestinationAttribute[]);
+          const accounts = groupedDestinationResponse.ACCOUNT;
+          this.destinationOptions = this.appName !== AppName.QBD_DIRECT 
+            ? accounts
+            : this.filterDestinationOptionsByAccountType(
+                this.chartOfAccounts,
+                this.isQbdDirectDestinationAttribute(accounts) ? accounts : []
+              );
+
+  private isQbdDirectDestinationAttribute(accounts: any[]): accounts is QbdDirectDestinationAttribute[] {
+    return accounts?.length > 0 && accounts.every(account => 
+      account.detail && typeof account.detail.account_type === 'string'
+    );
+  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 44d41c6 and fb2c214.

📒 Files selected for processing (4)
  • src/app/core/models/db/destination-attribute.model.ts (2 hunks)
  • src/app/integrations/qbd-direct/qbd-direct-main/qbd-direct-dashboard/qbd-direct-dashboard.component.html (1 hunks)
  • src/app/integrations/qbd-direct/qbd-direct-main/qbd-direct-dashboard/qbd-direct-dashboard.component.ts (2 hunks)
  • src/app/shared/components/dashboard/dashboard-error-section/dashboard-error-section.component.ts (4 hunks)
🔇 Additional comments (5)
src/app/integrations/qbd-direct/qbd-direct-main/qbd-direct-dashboard/qbd-direct-dashboard.component.html (1)

46-46: LGTM: Property binding for chartOfAccounts

The addition of the [chartOfAccounts] input property to the error section component is properly implemented and follows Angular's property binding conventions.

src/app/core/models/db/destination-attribute.model.ts (1)

40-40: LGTM: Type extension for QBD Direct integration

The addition of QbdDirectDestinationAttribute to the union type is consistent with the existing pattern for other integrations.

src/app/integrations/qbd-direct/qbd-direct-main/qbd-direct-dashboard/qbd-direct-dashboard.component.ts (1)

81-82: LGTM: Chart of accounts property declaration

The property is correctly typed as string array.

src/app/shared/components/dashboard/dashboard-error-section/dashboard-error-section.component.ts (2)

16-16: LGTM!

The import statement for QbdDirectDestinationAttribute is correctly placed and follows project conventions.


Line range hint 1-256: Verify error handling consistency across different app types.

Please ensure that these QBD Direct specific changes don't affect error handling for other app types. Consider adding tests to verify:

  1. Error handling behavior remains unchanged for non-QBD Direct apps
  2. New QBD Direct filtering logic works correctly with various account types
  3. Component maintains backward compatibility
✅ Verification successful

Based on the gathered evidence, I can now provide the final response:

QBD Direct changes maintain error handling consistency across app types

The changes for QBD Direct integration are properly isolated and maintain backward compatibility:

  • Error model implementation remains app-agnostic, handling all error types uniformly through formatErrors and getErroredMappings
  • QBD Direct specific logic is properly guarded with appName !== AppName.QBD_DIRECT condition
  • Core error handling for category and employee mappings remains unchanged
  • The component maintains consistent error tracking and resolution across all app types

However, test coverage needs improvement as the spec file only contains a basic creation test (marked with xdescribe). Consider adding tests for:

  • QBD Direct specific destination option filtering
  • Error handling across different app types
  • Mapping resolution scenarios
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test files and error handling patterns
echo "Searching for related test files..."
fd -e spec.ts dashboard-error-section

echo "Checking error handling patterns across app types..."
rg -A 5 "handleResolvedMappingStat|showErrorDialog" --type ts

echo "Checking QBD Direct specific error handling..."
rg -A 5 "QBD_DIRECT.*error" --type ts

Length of output: 2381


Script:

#!/bin/bash
# Let's check the test file to verify error handling across different app types
echo "Checking test coverage for error handling..."
cat src/app/shared/components/dashboard/dashboard-error-section/dashboard-error-section.component.spec.ts

echo "\nChecking QBD Direct specific implementations..."
ast-grep --pattern 'if ($condition) {
  $$$
  this.destinationOptions = this.appName !== AppName.QBD_DIRECT ? $_ : this.destinationOptionsWatcher($$$)
  $$$
}'

echo "\nChecking app type handling in the component..."
rg -B 2 -A 2 "AppName\." src/app/shared/components/dashboard/dashboard-error-section/dashboard-error-section.component.ts

Length of output: 2089


Script:

#!/bin/bash
# Let's check the error model and handling implementation
echo "Checking ErrorModel implementation..."
rg -A 10 "class ErrorModel" --type ts

echo "\nChecking error handling for different app types..."
rg -A 5 "formatErrors|getErroredMappings" --type ts

echo "\nChecking destination attribute handling..."
ast-grep --pattern 'getGroupedDestinationAttributes($$$) {
  $$$
}'

Length of output: 5489

@@ -1,4 +1,5 @@
import { BusinessCentralDestinationAttributes } from "../business-central/db/business-central-destination-attribute.model";
import { QbdDirectDestinationAttribute } from "../qbd-direct/db/qbd-direct-destination-attribuite.model";
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in import path

The import path contains a spelling error: "attribuite" should be "attribute".

-import { QbdDirectDestinationAttribute } from "../qbd-direct/db/qbd-direct-destination-attribuite.model";
+import { QbdDirectDestinationAttribute } from "../qbd-direct/db/qbd-direct-destination-attribute.model";
📝 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
import { QbdDirectDestinationAttribute } from "../qbd-direct/db/qbd-direct-destination-attribuite.model";
import { QbdDirectDestinationAttribute } from "../qbd-direct/db/qbd-direct-destination-attribute.model";

Comment on lines +156 to +157
this.chartOfAccounts = responses[5].import_settings.chart_of_accounts;

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add null safety check for import_settings

The code assumes import_settings exists in the response. Add a null check to prevent potential runtime errors.

-      this.chartOfAccounts = responses[5].import_settings.chart_of_accounts;
+      this.chartOfAccounts = responses[5].import_settings?.chart_of_accounts ?? [];
📝 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
this.chartOfAccounts = responses[5].import_settings.chart_of_accounts;
this.chartOfAccounts = responses[5].import_settings?.chart_of_accounts ?? [];

Comment on lines +140 to +142
destinationOptionsWatcher(detailAccountType: string[], destinationOptions: QbdDirectDestinationAttribute[]): DestinationAttribute[] {
return destinationOptions.filter((account: QbdDirectDestinationAttribute) => detailAccountType.includes(account.detail.account_type));
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider improving method name and robustness.

The current implementation could be enhanced for better clarity and safety:

  1. The method name destinationOptionsWatcher suggests it's watching for changes, but it's actually filtering options. Consider renaming to filterDestinationOptionsByAccountType.
  2. Add null checks to prevent runtime errors.
-  destinationOptionsWatcher(detailAccountType: string[], destinationOptions: QbdDirectDestinationAttribute[]): DestinationAttribute[] {
-    return destinationOptions.filter((account: QbdDirectDestinationAttribute) =>  detailAccountType.includes(account.detail.account_type));
+  private filterDestinationOptionsByAccountType(detailAccountType: string[], destinationOptions: QbdDirectDestinationAttribute[]): DestinationAttribute[] {
+    if (!detailAccountType?.length || !destinationOptions?.length) {
+      return [];
+    }
+    return destinationOptions.filter((account: QbdDirectDestinationAttribute) => 
+      account.detail?.account_type && detailAccountType.includes(account.detail.account_type)
+    );
📝 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
destinationOptionsWatcher(detailAccountType: string[], destinationOptions: QbdDirectDestinationAttribute[]): DestinationAttribute[] {
return destinationOptions.filter((account: QbdDirectDestinationAttribute) => detailAccountType.includes(account.detail.account_type));
}
private filterDestinationOptionsByAccountType(detailAccountType: string[], destinationOptions: QbdDirectDestinationAttribute[]): DestinationAttribute[] {
if (!detailAccountType?.length || !destinationOptions?.length) {
return [];
}
return destinationOptions.filter((account: QbdDirectDestinationAttribute) =>
account.detail?.account_type && detailAccountType.includes(account.detail.account_type)
);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deploy Triggers deployment of active branch to Staging size/M Medium PR
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants