Skip to content

fix: issue 1699#729

Merged
carlbrugger merged 4 commits intomainfrom
fix-issue-1699
Jan 8, 2025
Merged

fix: issue 1699#729
carlbrugger merged 4 commits intomainfrom
fix-issue-1699

Conversation

@carlbrugger
Copy link
Contributor

@carlbrugger carlbrugger commented Jan 8, 2025

Closes: https://github.com/FlatFilers/support-triage/issues/1699

Please explain how to summarize this PR for the Changelog:

The PR closes https://github.com/FlatFilers/support-triage/issues/1699 by removing the trailing null header cells after the last non-null header cell.

Tell code reviewer how and what to test:

@carlbrugger carlbrugger requested a review from damonbanks January 8, 2025 20:06
@carlbrugger carlbrugger marked this pull request as ready for review January 8, 2025 20:06
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 8, 2025

Walkthrough

This pull request introduces modifications to the XLSX extractor plugin, focusing on improving header row processing. The changes primarily target the parser.ts and utils.ts files, implementing new utility functions to handle header and row extraction more robustly. The key enhancement is the ability to trim trailing null or empty header cells, ensuring cleaner and more accurate data extraction from Excel files.

Changes

File Change Summary
plugins/xlsx-extractor/src/parser.ts - Updated convertSheet function to use new utility functions
- Simplified row and header processing
- Improved header detection and cleaning
plugins/xlsx-extractor/src/utils.ts - Modified prependNonUniqueHeaderColumns function signature and implementation
- Added isNullOrWhitespace utility function
- Added trimTrailingEmptyCells utility function
plugins/xlsx-extractor/src/utils.spec.ts - Updated tests for prependNonUniqueHeaderColumns to reflect new input/output formats (arrays instead of objects)
.changeset/spotty-cougars-smash.md - Added changelog entry for the patch release

Assessment against linked issues

Objective Addressed Explanation
Investigate Excel file extraction failure [#1699] Changes appear to address header processing, but full resolution requires further testing with the specific problematic file

Possibly related PRs


🪧 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. (Beta)
  • @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.

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

🧹 Nitpick comments (2)
plugins/xlsx-extractor/src/utils.ts (1)

1-11: Ensure consistent header naming when headers are duplicated

The prependNonUniqueHeaderColumns function correctly handles duplicate headers by appending a count suffix. However, starting the count from zero might be confusing for end-users. Consider starting the count from 1 to improve readability.

Apply this diff to start the count from 1:

 export function prependNonUniqueHeaderColumns(headers: string[]): string[] {
   const counts = new Map<string, number>()

   return headers.map((value) => {
     const cleanValue = (value || 'empty').replace('*', '')
     const count = counts.get(cleanValue) || 0
+    counts.set(cleanValue, count + 1)

-    return count ? `${cleanValue}_${count}` : cleanValue
+    return count ? `${cleanValue}_${count + 1}` : cleanValue
   })
 }
plugins/xlsx-extractor/src/parser.ts (1)

130-132: Optimize removal of trailing empty rows

The loop for removing trailing empty rows is effective but can be inefficient for large datasets with many empty rows at the end. Consider using a reverse loop for better performance.

Apply this diff to use a reverse loop:

 // remove **trailing** empty rows
-while (rows.length > 0 && rows[rows.length - 1].every(isNullOrWhitespace)) {
-  rows.pop()
-}
+for (let i = rows.length - 1; i >= 0; i--) {
+  if (rows[i].every(isNullOrWhitespace)) {
+    rows.splice(i, 1)
+  } else {
+    break
+  }
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cbabee8 and 6c02197.

⛔ Files ignored due to path filters (3)
  • flatfilers/sandbox/package.json is excluded by !**/*.json
  • package-lock.json is excluded by !**/package-lock.json, !**/*.json
  • plugins/xlsx-extractor/package.json is excluded by !**/*.json
📒 Files selected for processing (3)
  • .changeset/spotty-cougars-smash.md (1 hunks)
  • plugins/xlsx-extractor/src/parser.ts (5 hunks)
  • plugins/xlsx-extractor/src/utils.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/spotty-cougars-smash.md
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Setup
🔇 Additional comments (1)
plugins/xlsx-extractor/src/parser.ts (1)

161-164: Ensure headers and data rows are correctly aligned

When headerSelectionEnabled is true, excelHeaders may include more columns than slicedHeader, potentially causing misalignment between headers and data rows. Verify that the slicing of excelHeaders correctly matches the data columns.

Run the following script to compare the lengths of headers and data rows:

Comment on lines +13 to +14
export const isNullOrWhitespace = (value: any) =>
value === null || (typeof value === 'string' && value.trim() === '')
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

Handle undefined values in isNullOrWhitespace function

The isNullOrWhitespace function checks for null and empty strings but does not account for undefined values. This may lead to unexpected behavior if undefined values are present in the data. Consider updating the function to handle undefined values as well.

Apply this diff to include undefined in the null checks:

 export const isNullOrWhitespace = (value: any) =>
-  value === null || (typeof value === 'string' && value.trim() === '')
+  value == null || (typeof value === 'string' && value.trim() === '')
📝 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
export const isNullOrWhitespace = (value: any) =>
value === null || (typeof value === 'string' && value.trim() === '')
export const isNullOrWhitespace = (value: any) =>
value == null || (typeof value === 'string' && value.trim() === '')

Comment on lines +16 to +23
export const trimTrailingEmptyCells = (row: string[]): string[] => {
let lastNonNullIndex = 0
for (let i = 0; i < row.length; i++) {
if (!isNullOrWhitespace(row[i])) {
lastNonNullIndex = i
}
}

return result
return row.slice(0, lastNonNullIndex + 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

Correct handling when all cells are empty in trimTrailingEmptyCells

If all cells in the row are empty or whitespace, the lastNonNullIndex remains at 0, resulting in the function returning an array with one empty element. This may not be the intended behavior. Consider modifying the function to return an empty array when all cells are empty.

Apply this diff to adjust the function logic:

 export const trimTrailingEmptyCells = (row: string[]): string[] => {
-  let lastNonNullIndex = 0
+  let lastNonNullIndex = -1
   for (let i = 0; i < row.length; i++) {
     if (!isNullOrWhitespace(row[i])) {
       lastNonNullIndex = i
     }
   }
-  return row.slice(0, lastNonNullIndex + 1)
+  return lastNonNullIndex >= 0 ? row.slice(0, lastNonNullIndex + 1) : []
 }
📝 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
export const trimTrailingEmptyCells = (row: string[]): string[] => {
let lastNonNullIndex = 0
for (let i = 0; i < row.length; i++) {
if (!isNullOrWhitespace(row[i])) {
lastNonNullIndex = i
}
}
return result
return row.slice(0, lastNonNullIndex + 1)
export const trimTrailingEmptyCells = (row: string[]): string[] => {
let lastNonNullIndex = -1
for (let i = 0; i < row.length; i++) {
if (!isNullOrWhitespace(row[i])) {
lastNonNullIndex = i
}
}
return lastNonNullIndex >= 0 ? row.slice(0, lastNonNullIndex + 1) : []
}

Comment on lines +168 to +176
row.reduce((acc, value, index) => {
const header = headers[index]
if (header) {
acc[header] = { value }
}
return acc
}, {})
)

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

Handle potential undefined headers in data mapping

In the data mapping, if a row has more values than there are headers, headers[index] may be undefined, resulting in data being dropped silently. Consider adding a warning or handling extra values explicitly.

Apply this diff to log a warning for rows with extra values:

 const data = rows.map((row) =>
   row.reduce((acc, value, index) => {
     const header = headers[index]
     if (header) {
       acc[header] = { value }
+    } else {
+      console.warn(\`No header found for column index \${index} in row \${JSON.stringify(row)}\`)
     }
     return acc
   }, {})
 )
📝 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
row.reduce((acc, value, index) => {
const header = headers[index]
if (header) {
acc[header] = { value }
}
return acc
}, {})
)
row.reduce((acc, value, index) => {
const header = headers[index]
if (header) {
acc[header] = { value }
} else {
console.warn(`No header found for column index ${index} in row ${JSON.stringify(row)}`)
}
return acc
}, {})
)

Copy link
Contributor

@damonbanks damonbanks left a comment

Choose a reason for hiding this comment

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

gtg 🚀

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

🧹 Nitpick comments (2)
plugins/xlsx-extractor/src/utils.spec.ts (2)

28-29: Document the asterisk removal behavior.

Consider adding a comment explaining why asterisks are removed from values. This seems like a specific requirement that future maintainers should understand.

+    // Asterisks are removed as they might be used for special notation in Excel
     it('should remove asterisks from values', () => {

42-43: LGTM! Consider documenting case sensitivity.

The test correctly verifies case-sensitive behavior. Consider adding a brief comment explaining why case sensitivity is important for header values.

+    // Headers maintain their original case to preserve Excel formatting
     it('should handle case sensitivity correctly', () => {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6c02197 and c3c213e.

📒 Files selected for processing (1)
  • plugins/xlsx-extractor/src/utils.spec.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Setup
  • GitHub Check: Nullify Dependencies
🔇 Additional comments (5)
plugins/xlsx-extractor/src/utils.spec.ts (5)

14-15: LGTM! Good test coverage for duplicate values.

The test case effectively verifies the deduplication logic with clear expected outcomes.


35-36: LGTM! Comprehensive test for mixed scenarios.

Good coverage of combined cases ensuring consistent behavior across different value types.


21-22: Add test coverage for null values.

While the test handles empty strings well, consider adding explicit test cases for null values to ensure both empty strings and nulls are handled consistently.

Example:

const input = [null, 'value', null]
const expected = ['empty', 'value', 'empty_1']

7-8: Add test coverage for trailing null cells.

While this test case correctly verifies unique value handling, consider adding test cases that specifically verify the removal of trailing null header cells to align with the PR objective (issue #1699).

Example:

const input = ['value1', 'value2', null, null]
const expected = ['value1', 'value2']

Line range hint 1-47: Add dedicated test suite for trailing null cells.

To fully validate the PR's objective (issue #1699), consider adding a dedicated describe block for trailing null cell scenarios:

describe('trailing null cell handling', () => {
  it('should remove trailing null cells', () => {
    const input = ['header1', 'header2', null, null]
    const expected = ['header1', 'header2']
    expect(prependNonUniqueHeaderColumns(input)).toEqual(expected)
  })

  it('should preserve null cells between valid headers', () => {
    const input = ['header1', null, 'header2', null, null]
    const expected = ['header1', 'empty', 'header2']
    expect(prependNonUniqueHeaderColumns(input)).toEqual(expected)
  })
})

@carlbrugger carlbrugger merged commit 62d2bf3 into main Jan 8, 2025
36 checks passed
@carlbrugger carlbrugger deleted the fix-issue-1699 branch January 8, 2025 20:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants