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: qbd direct team testing fixes #1095

Merged
merged 5 commits into from
Dec 10, 2024
Merged

Conversation

DhaaraniCIT
Copy link
Contributor

@DhaaraniCIT DhaaraniCIT commented Dec 5, 2024

Description

fix: qbd direct team testing fixes

Clickup

https://app.clickup.com/t/86cwzceku

Summary by CodeRabbit

  • New Features
    • Introduced dynamic monitoring for employee mapping and account types in the export settings component, enhancing form state management.
    • Added new methods to improve error handling and control flow based on user input.
    • Enhanced memo structure handling with updated default options and simplified logic for payload construction.
    • Improved display formatting in the multi-select component for better consistency and maintainability.
    • Added conditional rendering to display messages based on export group selections and application context.

Copy link
Contributor

coderabbitai bot commented Dec 5, 2024

Warning

Rate limit exceeded

@DhaaraniCIT has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 22 minutes and 19 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c24c61e and 835d327.

📒 Files selected for processing (1)
  • src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.ts (4 hunks)

Walkthrough

The changes introduce several new methods in the QbdDirectExportSettingsComponent class to enhance functionality related to account management within the export settings form. New watchers monitor changes in form controls, resetting account fields based on specific conditions. Additionally, the QbdDirectAdvancedSettingsModel class has been updated to streamline the handling of memo structures, and the UI components have been modified to utilize new methods for displaying selected items, improving maintainability and control flow.

Changes

File Change Summary
src/app/integrations/qbd-direct/qbd-direct-export-settings/qbd-direct-export-settings.component.ts Added methods: isCccExportGroupDisabled(), isReimbursableExportGroupDisabled(), defaultAccountsPayableAccountWatcher(), defaultCCCAccountsPayableAccountWatcher(), cccExportGroupingWatcher(), reimburesmentExpenseGroupingWatcher(). Updated exportsettingsWatcher and cccExportTypeWatcher.
src/app/core/models/qbd-direct/qbd-direct-configuration/qbd-direct-advanced-settings.model.ts Updated methods: defaultTopMemoOptions(), mapAPIResponseToFormGroup(), constructPayload(), simplifying memo structure handling.
src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.html Added properties: [isDisableTextRequired], [isDisabled] for export groups, updating logic to use new methods for disabling states.
src/app/shared/components/configuration/configuration-multi-select/configuration-multi-select.component.html Updated rendering of selected items and memo display to use getMemo(name) and getMemo(memo).
src/app/shared/components/configuration/configuration-multi-select/configuration-multi-select.component.ts Added method: getMemo(memo: string): string for processing display values.
src/app/core/models/db/task-log.model.ts Renamed property: export_log__id__in to id__in in TaskLogGetParams type.
src/app/core/services/common/dashboard.service.ts Updated getTasks method to change expenseGroupIds parameter key from export_log__id__in to id__in.
src/app/shared/components/configuration/configuration-select-field/configuration-select-field.component.html Added conditional rendering for messages based on formControllerName and appName, refining display logic.

Possibly related PRs

Suggested reviewers

  • ashwin1111

Poem

🐰 In the meadow where changes bloom,
New watchers rise, dispelling gloom.
Accounts and mappings dance in sync,
In the settings, they find their link.
With every click, the forms align,
A hop, a skip, all will be fine! 🌼


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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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/S Small PR label Dec 5, 2024
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 (1)
src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.ts (1)

Line range hint 214-250: Consider implementing a FormGroup service

The component is handling complex form control interactions across multiple methods. This could become harder to maintain as more form controls and validations are added.

Consider extracting form-related logic into a dedicated service:

  1. Create QbdDirectExportSettingsFormService:
@Injectable()
export class QbdDirectExportSettingsFormService {
  private form: FormGroup;
  
  initializeForm(exportSettings: QbdDirectExportSettingGet, destinationAccounts: QbdDirectDestinationAttribute[]): FormGroup {
    this.form = QbdDirectExportSettingModel.mapAPIResponseToFormGroup(exportSettings, destinationAccounts);
    this.setupWatchers();
    return this.form;
  }

  private setupWatchers(): void {
    // Move all watcher logic here
  }
}
  1. Update component to use the service:
export class QbdDirectExportSettingsComponent implements OnInit {
  constructor(
    private formService: QbdDirectExportSettingsFormService,
    // ... other dependencies
  ) {}

  private getSettingsAndSetupForm(): void {
    // ... existing code ...
    this.exportSettingsForm = this.formService.initializeForm(this.exportSettings, this.destinationAccounts);
  }
}

This separation would:

  • Improve testability
  • Reduce component complexity
  • Make form logic more reusable
  • Make it easier to maintain form-related code
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 84a4838 and e61457c.

📒 Files selected for processing (1)
  • src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.ts (2 hunks)

Comment on lines 214 to 224
defaultAccountsPayableAccountWatcher() {
this.exportSettingsForm.controls.employeeMapping.valueChanges.subscribe((employeeMapping) => {
if (employeeMapping === EmployeeFieldMapping.EMPLOYEE) {
if (this.exportSettingsForm.controls.nameInJE.value === EmployeeFieldMapping.EMPLOYEE && this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.value.detail.account_type === 'AccountsPayable') {
this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.patchValue(null);
} else if (this.exportSettingsForm.controls.defaultReimbursableAccountsPayableAccountName.value.detail.account_type === 'AccountsPayable') {
this.exportSettingsForm.controls.defaultReimbursableAccountsPayableAccountName.patchValue(null);
}
}
});
}
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 checks and improve code robustness

The method has several potential issues that should be addressed:

  1. Missing null checks for value.detail which could cause runtime errors
  2. 'AccountsPayable' is used as a magic string
  3. Complex nested conditions could be simplified
  4. Missing error handling for the subscription

Consider this safer implementation:

 defaultAccountsPayableAccountWatcher() {
-  this.exportSettingsForm.controls.employeeMapping.valueChanges.subscribe((employeeMapping) => {
+  this.exportSettingsForm.controls.employeeMapping.valueChanges.subscribe({
+    next: (employeeMapping) => {
     if (employeeMapping === EmployeeFieldMapping.EMPLOYEE) {
-      if (this.exportSettingsForm.controls.nameInJE.value === EmployeeFieldMapping.EMPLOYEE && this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.value.detail.account_type === 'AccountsPayable') {
+      const cccAccount = this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.value?.detail;
+      const reimbursableAccount = this.exportSettingsForm.controls.defaultReimbursableAccountsPayableAccountName.value?.detail;
+      
+      if (this.exportSettingsForm.controls.nameInJE.value === EmployeeFieldMapping.EMPLOYEE && 
+          cccAccount?.account_type === QbdDirectAccountType.ACCOUNTS_PAYABLE) {
         this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.patchValue(null);
-      } else if (this.exportSettingsForm.controls.defaultReimbursableAccountsPayableAccountName.value.detail.account_type === 'AccountsPayable') {
+      } else if (reimbursableAccount?.account_type === QbdDirectAccountType.ACCOUNTS_PAYABLE) {
         this.exportSettingsForm.controls.defaultReimbursableAccountsPayableAccountName.patchValue(null);
       }
     }
+    },
+    error: (error) => {
+      console.error('Error in employeeMapping subscription:', error);
+    }
   });
 }

Also, consider adding an enum for account types:

enum QbdDirectAccountType {
  ACCOUNTS_PAYABLE = 'AccountsPayable',
  // ... other account types
}

Comment on lines +247 to +250

this.defaultAccountsPayableAccountWatcher();

this.defaultCCCAccountsPayableAccountWatcher();
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

Prevent memory leaks and improve watcher organization

The watchers are correctly integrated, but there are two concerns:

  1. Subscriptions aren't being cleaned up, which could lead to memory leaks
  2. Related watchers could be grouped together for better maintainability

Consider these improvements:

  1. Add subscription management:
private subscriptions: Subscription[] = [];

private exportsettingsWatcher(): void {
  // Group related watchers
  // Credit card related
  this.subscriptions.push(this.cccExportTypeWatcher());
  this.subscriptions.push(this.cccExpenseGroupWatcher());
  this.subscriptions.push(this.defaultCCCAccountsPayableAccountWatcher());

  // Employee mapping related
  this.subscriptions.push(this.employeeMappingWatcher());
  this.subscriptions.push(this.defaultAccountsPayableAccountWatcher());

  // Reimbursable related
  this.subscriptions.push(this.reimbursableExpenseGroupWatcher());
}

ngOnDestroy() {
  this.subscriptions.forEach(subscription => subscription.unsubscribe());
}
  1. Update watcher methods to return their subscriptions:
defaultAccountsPayableAccountWatcher(): Subscription {
  return this.exportSettingsForm.controls.employeeMapping.valueChanges.subscribe({
    // ... existing implementation
  });
}

Comment on lines +226 to +232
defaultCCCAccountsPayableAccountWatcher() {
this.exportSettingsForm.controls.nameInJE.valueChanges.subscribe((nameInJE) => {
if (nameInJE === EmployeeFieldMapping.EMPLOYEE && this.exportSettingsForm.controls.employeeMapping.value === EmployeeFieldMapping.EMPLOYEE && this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.value.detail.account_type === 'AccountsPayable') {
this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.patchValue(null);
}
});
}
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

Improve error handling and code readability

Similar to the previous method, this one needs improvements in error handling and null safety.

Consider this safer implementation:

 defaultCCCAccountsPayableAccountWatcher() {
-  this.exportSettingsForm.controls.nameInJE.valueChanges.subscribe((nameInJE) => {
-    if (nameInJE === EmployeeFieldMapping.EMPLOYEE && this.exportSettingsForm.controls.employeeMapping.value === EmployeeFieldMapping.EMPLOYEE && this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.value.detail.account_type === 'AccountsPayable') {
-      this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.patchValue(null);
+  this.exportSettingsForm.controls.nameInJE.valueChanges.subscribe({
+    next: (nameInJE) => {
+      const isEmployeeMapping = this.exportSettingsForm.controls.employeeMapping.value === EmployeeFieldMapping.EMPLOYEE;
+      const cccAccount = this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.value?.detail;
+      
+      if (nameInJE === EmployeeFieldMapping.EMPLOYEE && 
+          isEmployeeMapping && 
+          cccAccount?.account_type === QbdDirectAccountType.ACCOUNTS_PAYABLE) {
+        this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.patchValue(null);
+      }
+    },
+    error: (error) => {
+      console.error('Error in nameInJE subscription:', error);
    }
   });
 }

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 9, 2024
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: 2

🧹 Outside diff range and nitpick comments (6)
src/app/shared/components/configuration/configuration-multi-select/configuration-multi-select.component.html (2)

Line range hint 25-27: Remove commented drag-and-drop code

The commented code contains drag-and-drop functionality that appears to be unused. If this feature is no longer needed, the commented code should be removed to improve code maintainability.

-    <!-- <div pDraggable="gens" pDroppable="gens" dragHandle=".barsHandle" (onDragStart)="onDragStart(index)" (onDrop)="onDrop(index)" >
-        <p class="tw-text-sub-text-color tw-text-14-px">{{ gens | titlecase | snakeCaseToSpaceCase }}</p>
-    </div> -->

Line range hint 18-31: Consider adding aria-labels for accessibility

While the changes look good, the multi-select component could benefit from improved accessibility by adding appropriate aria-labels to help screen readers.

-                    <p *ngFor="let name of value;let i = index">{{ getMemo(name) }}<span *ngIf="i !== value?.length-1">,&nbsp;</span></p>
+                    <p *ngFor="let name of value;let i = index" aria-label="Selected item: {{getMemo(name)}}">{{ getMemo(name) }}<span *ngIf="i !== value?.length-1">,&nbsp;</span></p>
-                    <p class="tw-text-14-px">{{ getMemo(memo) }}</p>
+                    <p class="tw-text-14-px" aria-label="Available item: {{getMemo(memo)}}">{{ getMemo(memo) }}</p>
src/app/shared/components/configuration/configuration-multi-select/configuration-multi-select.component.ts (1)

54-56: Improve code maintainability and documentation.

Consider these improvements:

+// Special memo keys that need custom display text
+const MEMO_DISPLAY_MAP = {
+  expense_key: 'Expense/Report Id'
+} as const;
+
+/**
+ * Transforms memo keys into human-readable display text
+ * @param memo - The memo key to transform
+ * @returns Transformed display text
+ */
 getMemo(memo: string): string {
-  return memo === 'expense_key' ? 'Expense/Report Id' : new SnakeCaseToSpaceCasePipe().transform(new TitleCasePipe().transform(memo));
+  return MEMO_DISPLAY_MAP[memo] ?? new SnakeCaseToSpaceCasePipe().transform(new TitleCasePipe().transform(memo));
 }
src/app/core/models/qbd-direct/qbd-direct-configuration/qbd-direct-advanced-settings.model.ts (1)

29-29: Consider using constants for memo options.

Define memo options as constants to improve maintainability and reusability.

+private static readonly DEFAULT_TOP_MEMO_OPTIONS = ['employee_name', 'expense_key'] as const;

 static defaultTopMemoOptions(): string[] {
-  return ["employee_name", "expense_key"];
+  return [...this.DEFAULT_TOP_MEMO_OPTIONS];
 }
src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.ts (1)

104-120: Improve code maintainability and readability.

Consider extracting the account type check into a constant and adding type safety.

+const ACCOUNTS_PAYABLE_TYPE = 'AccountsPayable' as const;

 isCccExportGroupDisabled(): boolean {
   if (this.exportSettingsForm.get('creditCardExportType')?.value === QBDCorporateCreditCardExpensesObject.CREDIT_CARD_PURCHASE) {
     return true;
   }
-  if (this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.value?.detail.account_type === 'AccountsPayable') {
+  if (this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.value?.detail.account_type === ACCOUNTS_PAYABLE_TYPE) {
     return true;
   }
   return false;
 }

 isReimbursableExportGroupDisabled(): boolean {
-  if (this.exportSettingsForm.controls.defaultReimbursableAccountsPayableAccountName.value?.detail.account_type === 'AccountsPayable' && 
+  if (this.exportSettingsForm.controls.defaultReimbursableAccountsPayableAccountName.value?.detail.account_type === ACCOUNTS_PAYABLE_TYPE && 
       this.exportSettingsForm.controls.reimbursableExportType.value === QbdDirectReimbursableExpensesObject.JOURNAL_ENTRY) {
     return true;
   }
   return false;
 }
src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.html (1)

Line range hint 1-284: Consider enhancing error handling and accessibility

The form structure is well-organized, but consider these improvements:

  1. Add aria-labels to form controls for better accessibility
  2. Add error messages for validation failures
  3. Consider adding loading states for async operations (e.g., when searchOptionsDropdown is triggered)

These enhancements would improve the user experience, especially for users relying on screen readers or experiencing slow network conditions.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e61457c and f87b816.

📒 Files selected for processing (5)
  • src/app/core/models/qbd-direct/qbd-direct-configuration/qbd-direct-advanced-settings.model.ts (3 hunks)
  • 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 (4 hunks)
  • src/app/shared/components/configuration/configuration-multi-select/configuration-multi-select.component.html (2 hunks)
  • src/app/shared/components/configuration/configuration-multi-select/configuration-multi-select.component.ts (2 hunks)
🧰 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)

🔇 Additional comments (6)
src/app/shared/components/configuration/configuration-multi-select/configuration-multi-select.component.html (2)

29-29: Ensure consistent memo formatting

The same getMemo() method is now used for both selected items and dropdown items, which improves consistency. This is a good change as it centralizes the formatting logic.


18-18: Verify edge cases in getMemo() implementation

The change from using pipes (titlecase | snakeCaseToSpaceCase) to getMemo() method suggests a move towards centralized formatting logic. However, we need to ensure the new method handles all edge cases properly.

✅ Verification successful

The getMemo() method is properly implemented and handles edge cases

The verification shows that the getMemo() method in configuration-multi-select.component.ts is properly implemented with appropriate edge case handling:

  1. It handles the special case of 'expense_key' by returning 'Expense/Report Id'
  2. For all other cases, it applies two transformations:
    • TitleCasePipe to capitalize words
    • SnakeCaseToSpaceCasePipe to convert snake_case to readable format

The method is part of a centralized formatting approach used consistently across various advanced settings components (QBO, NetSuite, Business Central, etc.) that all use the same memo formatting logic through AdvancedSettingsModel.formatMemoPreview().

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for getMemo implementation to verify edge case handling
ast-grep --pattern 'getMemo($value) {
  $$$
}'

# Search for tests covering getMemo
rg -g '*.spec.ts' 'getMemo'

Length of output: 76


Script:

#!/bin/bash
# Let's try a broader search for the component class and its methods
ast-grep --pattern 'class ConfigurationMultiSelectComponent {
  $$$
}'

# Also search for the component file directly
rg -g '*.ts' 'class ConfigurationMultiSelectComponent'

# Search for any method containing 'memo' in the component
rg -g '*.ts' -B 2 -A 5 'getMemo|formatMemo' src/

Length of output: 32891

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

78-78: LGTM: Simplified memo structure handling.

The simplified handling of top_level_memo_structure in the payload construction is cleaner and more maintainable.

src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.ts (2)

233-243: ⚠️ Potential issue

Add null checks and improve code robustness.

The watcher has potential null reference issues.

 defaultAccountsPayableAccountWatcher() {
-  this.exportSettingsForm.controls.employeeMapping.valueChanges.subscribe((employeeMapping) => {
+  this.exportSettingsForm.controls.employeeMapping.valueChanges.subscribe({
+    next: (employeeMapping) => {
     if (employeeMapping === EmployeeFieldMapping.EMPLOYEE) {
-      if (this.exportSettingsForm.controls.defaultReimbursableAccountsPayableAccountName.value.detail.account_type === 'AccountsPayable') {
+      const reimbursableAccount = this.exportSettingsForm.controls.defaultReimbursableAccountsPayableAccountName.value?.detail;
+      const cccAccount = this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.value?.detail;
+      
+      if (reimbursableAccount?.account_type === ACCOUNTS_PAYABLE_TYPE) {
         this.exportSettingsForm.controls.defaultReimbursableAccountsPayableAccountName.patchValue(null);
-        if (this.exportSettingsForm.controls.nameInJE.value === EmployeeFieldMapping.EMPLOYEE && this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.value.detail.account_type === 'AccountsPayable') {
+        if (this.exportSettingsForm.controls.nameInJE.value === EmployeeFieldMapping.EMPLOYEE && 
+            cccAccount?.account_type === ACCOUNTS_PAYABLE_TYPE) {
           this.exportSettingsForm.controls.defaultCCCAccountsPayableAccountName.patchValue(null);
         }
       }
     }
+    },
+    error: (error) => {
+      console.error('Error in employeeMapping subscription:', error);
+    }
   });
 }

285-292: ⚠️ Potential issue

Prevent memory leaks and improve watcher organization.

The watchers need proper cleanup to prevent memory leaks.

+private subscriptions: Subscription[] = [];

 private exportsettingsWatcher(): void {
-  this.cccExportTypeWatcher();
-  this.employeeMappingWatcher();
-  this.reimbursableExpenseGroupWatcher();
-  this.cccExpenseGroupWatcher();
-  this.defaultAccountsPayableAccountWatcher();
-  this.defaultCCCAccountsPayableAccountWatcher();
-  this.cccExportGroupingWatcher();
-  this.reimburesmentExpenseGroupingWatcher();
+  // Group related watchers
+  // Credit card related
+  this.subscriptions.push(
+    this.cccExportTypeWatcher(),
+    this.cccExpenseGroupWatcher(),
+    this.cccExportGroupingWatcher()
+  );
+
+  // Employee mapping related
+  this.subscriptions.push(
+    this.employeeMappingWatcher(),
+    this.defaultAccountsPayableAccountWatcher(),
+    this.defaultCCCAccountsPayableAccountWatcher()
+  );
+
+  // Reimbursable related
+  this.subscriptions.push(
+    this.reimbursableExpenseGroupWatcher(),
+    this.reimburesmentExpenseGroupingWatcher()
+  );
 }

+ngOnDestroy() {
+  this.subscriptions.forEach(subscription => subscription.unsubscribe());
+}
src/app/integrations/qbd-direct/qbd-direct-shared/qbd-direct-export-settings/qbd-direct-export-settings.component.html (1)

100-101: Verify the implementation of isReimbursableExportGroupDisabled()

The addition of disable controls for the reimbursable export group looks good, but let's verify the implementation of the controlling method.

Let's check the implementation of this method:

✅ Verification successful

Implementation of isReimbursableExportGroupDisabled() is properly implemented

The method is correctly implemented in the component. It disables the export group when:

  • The default reimbursable accounts payable account is of type 'AccountsPayable'
  • AND the reimbursable export type is set to JOURNAL_ENTRY

This logic aligns with the template usage where both the visual state and interaction state are controlled consistently.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the implementation of isReimbursableExportGroupDisabled method
ast-grep --pattern 'isReimbursableExportGroupDisabled() {
  $$$
}'

Length of output: 68


Script:

#!/bin/bash
# Let's try a different approach to find the method implementation
# First, let's find the component file
fd -e ts "qbd-direct-export-settings.component.ts"

# Then let's search for the method with ripgrep for better context
rg "isReimbursableExportGroupDisabled" -A 5

Length of output: 2517

@@ -52,7 +52,7 @@ export class QbdDirectAdvancedSettingsModel extends AdvancedSettingsModel {

return new FormGroup({
expenseMemoStructure: new FormControl(advancedSettings?.line_level_memo_structure && advancedSettings?.line_level_memo_structure.length > 0 ? this.formatMemoStructure(this.defaultMemoFields(), advancedSettings?.line_level_memo_structure) : this.defaultMemoFields(), Validators.required),
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(advancedSettings?.top_level_memo_structure && advancedSettings?.top_level_memo_structure.length > 0 ? advancedSettings?.top_level_memo_structure : this.defaultTopMemoOptions(), Validators.required),
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 static method using instance reference.

The static analysis tool correctly identified use of this in a static context.

-topMemoStructure: new FormControl(advancedSettings?.top_level_memo_structure && advancedSettings?.top_level_memo_structure.length > 0 ? advancedSettings?.top_level_memo_structure : this.defaultTopMemoOptions(), Validators.required),
+topMemoStructure: new FormControl(advancedSettings?.top_level_memo_structure && advancedSettings?.top_level_memo_structure.length > 0 ? advancedSettings?.top_level_memo_structure : QbdDirectAdvancedSettingsModel.defaultTopMemoOptions(), Validators.required),
📝 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
topMemoStructure: new FormControl(advancedSettings?.top_level_memo_structure && advancedSettings?.top_level_memo_structure.length > 0 ? advancedSettings?.top_level_memo_structure : this.defaultTopMemoOptions(), Validators.required),
topMemoStructure: new FormControl(advancedSettings?.top_level_memo_structure && advancedSettings?.top_level_memo_structure.length > 0 ? 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)

@@ -239,7 +241,7 @@
[iconPath]="'question-square-outline'"
[placeholder]="'Select expense grouping'"
[isDisableTextRequired]="true"
[isDisabled]="exportSettingsForm.get('creditCardExportType')?.value === QBDCorporateCreditCardExpensesObject.CREDIT_CARD_PURCHASE || exportSettingsForm.get('creditCardExportType')?.value === QBDCorporateCreditCardExpensesObject.JOURNAL_ENTRY ? true : false"
[isDisabled]="isCccExportGroupDisabled()"
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

Inconsistency in disable text behavior between credit card and reimbursable export groups

The code inspection reveals that the reimbursable export group dynamically sets both isDisabled and isDisableTextRequired based on isReimbursableExportGroupDisabled(), while the credit card export group has isDisableTextRequired hardcoded to true. This inconsistency should be fixed to maintain a uniform behavior:

-                        [isDisableTextRequired]="true"
+                        [isDisableTextRequired]="isCccExportGroupDisabled()"

The implementation of both disable methods shows they handle different but valid business cases:

  • isCccExportGroupDisabled() - disables when credit card type is "CREDIT_CARD_PURCHASE" or when using an Accounts Payable account
  • isReimbursableExportGroupDisabled() - disables for Accounts Payable accounts with Journal Entry export type
🔗 Analysis chain

Verify consistency between credit card and reimbursable export group controls

The change to use isCccExportGroupDisabled() aligns with the pattern used for reimbursable exports. However, there's an inconsistency in how isDisableTextRequired is handled between the two sections.

Consider making the credit card export group's isDisableTextRequired dynamic to match the reimbursable section:

-                        [isDisableTextRequired]="true"
+                        [isDisableTextRequired]="isCccExportGroupDisabled()"

Let's verify the implementation of the disable method:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for the implementation of isCccExportGroupDisabled method
ast-grep --pattern 'isCccExportGroupDisabled() {
  $$$
}'

Length of output: 59


Script:

#!/bin/bash
# Let's try a different pattern to find the method implementation
ast-grep --pattern 'isCccExportGroupDisabled'

# Also search with ripgrep for more context
rg "isCccExportGroupDisabled" -A 5

Length of output: 2242


Script:

#!/bin/bash
# Let's find the reimbursable export group implementation for comparison
rg "isReimbursableExportGroupDisabled" -A 5

# Also search for any other configuration-select-field usage with isDisableTextRequired
rg "isDisableTextRequired" -B 2 -A 2

Length of output: 10525

@DhaaraniCIT DhaaraniCIT added the deploy Triggers deployment of active branch to Staging label Dec 9, 2024
Comment on lines 256 to 259
if (defaultCCCAccountsPayableAccountNameValue?.detail?.account_type === 'AccountsPayable') {
this.exportSettingsForm.controls.creditCardExportGroup.patchValue(QbdDirectExportSettingModel.expenseGroupingFieldOptions()[1].value);
this.exportSettingsForm.controls.creditCardExportGroup.disable();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

let's have an else case to creditCardExportGroup.enable() it back

if (defaultReimbursableAccountsPayableAccountNameValue?.detail?.account_type === 'AccountsPayable') {
this.exportSettingsForm.controls.reimbursableExportGroup.patchValue(QbdDirectExportSettingModel.expenseGroupingFieldOptions()[1].value);
this.exportSettingsForm.controls.reimbursableExportGroup.disable();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

let's have an else case to reimbursableExportGroup.enable() it back

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: 0

🧹 Outside diff range and nitpick comments (3)
src/app/shared/components/configuration/configuration-select-field/configuration-select-field.component.html (1)

101-101: Consider enhancing the auto-selection message clarity

While the message correctly explains the auto-selection behavior, consider making it more explicit about which Accounts Payable settings trigger this behavior and what exactly gets auto-selected.

-<span *ngIf="(formControllerName === 'reimbursableExportGroup' || formControllerName === 'creditCardExportGroup') && appName === AppName.QBD_DIRECT && form.controls.creditCardExportType.value !== 'CREDIT_CARD_PURCHASE'"> Auto-selected when your default credit account is set to an Accounts Payable account</span>
+<span *ngIf="(formControllerName === 'reimbursableExportGroup' || formControllerName === 'creditCardExportGroup') && appName === AppName.QBD_DIRECT && form.controls.creditCardExportType.value !== 'CREDIT_CARD_PURCHASE'"> This export group is auto-selected because your default credit account in QuickBooks Desktop is set to an Accounts Payable (A/P) account</span>
src/app/core/models/db/task-log.model.ts (1)

26-26: Consider adding JSDoc comments for the interface properties.

Adding documentation for the id__in parameter would help clarify its purpose and expected format.

 export type TaskLogGetParams = {
+  /** Array of task log IDs to filter by */
   id__in?: number[];
 };
src/app/core/services/common/dashboard.service.ts (1)

61-61: Consider improving readability of the parameter key selection.

While the logic is correct, the nested ternary operator could be made more readable using a switch statement or object mapping.

Here's a more maintainable approach:

-      const expenseKey = appName === AppName.INTACCT ? 'expense_group_ids' : appName === AppName.QBD_DIRECT ? 'id__in' : 'expense_group_id__in';
+      const expenseKeyMap = {
+        [AppName.INTACCT]: 'expense_group_ids',
+        [AppName.QBD_DIRECT]: 'id__in',
+      };
+      const expenseKey = expenseKeyMap[appName] || 'expense_group_id__in';
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f87b816 and c24c61e.

📒 Files selected for processing (4)
  • src/app/core/models/db/task-log.model.ts (1 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 (2 hunks)
  • src/app/shared/components/configuration/configuration-select-field/configuration-select-field.component.html (1 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 comments (3)
src/app/shared/components/configuration/configuration-select-field/configuration-select-field.component.html (1)

101-101: Verify the completeness of the auto-selection condition

The current condition checks for non-'CREDIT_CARD_PURCHASE' type, but we should verify if this covers all cases where auto-selection occurs.

✅ Verification successful

Let me analyze the results and generate one more verification script to get complete information about the auto-selection logic.


Auto-selection condition is correctly implemented

Based on the code analysis, the auto-selection message is correctly displayed and the logic is complete. The auto-selection occurs in two scenarios:

  • When creditCardExportType is not 'CREDIT_CARD_PURCHASE' AND
  • When the default credit account is set to an Accounts Payable account type

This is verified by the implementation in qbd-direct-export-settings.component.ts where:

  1. The component automatically sets and disables creditCardExportGroup when defaultCCCAccountsPayableAccountName is of type 'AccountsPayable'
  2. The component handles the non-CREDIT_CARD_PURCHASE case separately
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for related conditions in the codebase
echo "Searching for related creditCardExportType conditions..."
rg -A 5 "creditCardExportType.*CREDIT_CARD_PURCHASE"

echo "Searching for auto-selection logic in QBD Direct..."
ast-grep --pattern 'creditCardExportGroup.*auto.*select'

Length of output: 15092


Script:

#!/bin/bash
# Search for the auto-selection logic in QBD Direct specifically around default credit account and Accounts Payable
echo "Searching for default credit account and auto-selection logic..."
rg -A 5 "defaultCCCAccountsPayableAccountName.*account_type.*AccountsPayable"

# Search for creditCardExportGroup related logic
echo "Searching for creditCardExportGroup related logic..."
ast-grep --pattern 'creditCardExportGroup.*(patch|set|update)'

Length of output: 4481

src/app/core/models/db/task-log.model.ts (1)

26-26: LGTM! Verify all usages of the renamed parameter.

The simplified parameter name id__in is cleaner than export_log__id__in. However, as this is a breaking change, we should verify all its usages.

✅ Verification successful

Parameter rename is safe to proceed

The verification shows that:

  • The old parameter name export_log__id__in is not used anywhere in the codebase
  • The new parameter name id__in is consistently used across the codebase:
    • In dashboard.service.ts for QBD_DIRECT app type
    • In accounting-export.service.ts for API parameters
    • Similar naming pattern is followed in other models (xero-task-log.model.ts, accounting-export.model.ts)

The change aligns with the existing parameter naming conventions in the codebase and doesn't break any existing usage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usages of the old parameter name
rg "export_log__id__in" --type ts

# Search for usages of the new parameter name
rg "id__in.*TaskLogGetParams" --type ts

Length of output: 75


Script:

#!/bin/bash
# Let's first find all files that might contain TaskLogGetParams
rg "TaskLogGetParams" --type ts -l

# Then search for any usage of id__in in those files
rg "id__in" --type ts -A 2 -B 2

Length of output: 2287

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

61-61: Verify error handling for invalid expense group IDs.

Since we're changing the parameter key for QBD_DIRECT, we should ensure proper error handling exists for invalid IDs.

Copy link

Unit Test Coverage % values
Statements 34.09% ( 4192 / 12296 )
Branches 27.8% ( 1205 / 4334 )
Functions 26.71% ( 921 / 3448 )
Lines 34.24% ( 4124 / 12043 )

@DhaaraniCIT DhaaraniCIT merged commit 2331fcd into master Dec 10, 2024
4 checks passed
DhaaraniCIT added a commit that referenced this pull request Dec 10, 2024
* qbd direct team testing fixes

* Qbd direct bug fixes

* fixes

* PR fix
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.

2 participants