Skip to content

feat: quick order upload integration - #3158

Merged
eduardoformiga merged 53 commits into
vtex:feat/quick-order-by-file-feature-branchfrom
cubos-vtex:feat/quick-order-integration
Mar 27, 2026
Merged

eduardoformiga merged 53 commits into
vtex:feat/quick-order-by-file-feature-branchfrom
cubos-vtex:feat/quick-order-integration

Conversation

@BrunaCubos

@BrunaCubos BrunaCubos commented Dec 17, 2025 •

Copy link
Copy Markdown
Collaborator

What's the purpose of this pull request?

This pull request improves the Quick Order drawer experience by fixing CSV file upload error handling, removing leftover debug code, and ensuring the attachment button behavior is fully driven by CMS configuration.

How it works?

  • The FileUploadCard component now reacts to the hasError prop from its parent via a useEffect.

  • When CSV parsing fails, the upload state is automatically set to error.

  • Parsing errors are mapped to the invalid-structure error type, displaying the message:
    "Invalid structure. Check missing headers or columns and try again."

  • Selecting a new file automatically clears the previous error state.

  • The SearchInput component now uses the attachmentButton configuration provided by CMS instead of hardcoded values.

  • The attachment button respects the enabled flag from the Navbar section configuration.

  • Icon and aria-label values are passed dynamically from CMS (attachmentButtonIcon and attachmentButtonAriaLabel).

  • Removed the hardcoded showAttachmentButton={true} and replaced it with a CMS-driven prop.

How to test it?

  • Navigate to the store homepage
  • Click the attachment button in the search input (if enabled)
  • Upload an invalid CSV file (missing headers, wrong format, corrupted file)
  • Expected: The FileUploadStatus component displays an error state
  • Expected: Error message shows
    "Invalid structure. Check missing headers or columns and try again."
  • Select a new file
    Expected: The error state is cleared

Starters Deploy Preview

References

Checklist

You may erase this after checking them all 😉

PR Title and Commit Messages

  • PR title and commit messages follow the Conventional Commits specification
    • Available prefixes: feat, fix, chore, docs, style, refactor, ci and test

PR Description

  • Added a label according to the PR goal - breaking change, bug, contributing, performance, documentation..

Dependencies

  • Committed the pnpm-lock.yaml file when there were changes to the packages

Documentation

-[ x] PR description

  • For documentation changes, ping @Mariana-Caetano to review and update (Or submit a doc request)

Summary by CodeRabbit

  • New Features

    • CSV and Excel (.xls/.xlsx) file upload for bulk product search and quick ordering
    • Attachment/upload button in search input to trigger file flow
    • Quick Order Drawer: loading state, provider-driven config, improved empty-state and product handling
  • Improvements

    • Automatic CSV delimiter detection and more tolerant header/column parsing
    • Expanded, clearer file-upload error messages (including "no-products-found") and CMS-configurable texts/limits
    • Accessibility tweaks: optional ariaLabel handling and better ARIA for upload/dropzone
  • Style

    • Theming tokens, styles and CSS variables for Quick Order Drawer visuals and compatibility

@BrunaCubos
BrunaCubos requested a review from a team as a code owner December 17, 2025 14:39
@BrunaCubos
BrunaCubos requested review from hellofanny and renatamottam and removed request for a team December 17, 2025 14:39
@BrunaCubos BrunaCubos changed the title Feat/quick order integration feat: quick order upload integration Dec 17, 2025
@codesandbox-ci

codesandbox-ci Bot commented Dec 17, 2025 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Comment thread REGRA.MD Outdated
@@ -0,0 +1,167 @@
B2B Faststore - Quick Order by File

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Remover

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Removido!

Comment thread Untitled Outdated
@@ -0,0 +1,2 @@
packages:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Acredito que isso tb deve ser removido

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Ajustado!

@BrunaCubos

Copy link
Copy Markdown
Collaborator Author

Planilha usada para integraçao:
FastStore Starter Template.csv

@coderabbitai

coderabbitai Bot commented Feb 13, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds CSV and Excel file upload and parsing (delimiter detection), maps parsed SKUs to a bulk product fetcher, wires results into a QuickOrder drawer, exposes CMS config for file upload, updates related UI, styles, exports, and SDK hooks.

Changes

Cohort / File(s) Summary
Parsing & Hooks
packages/components/src/hooks/useCSVParser.ts, packages/components/src/hooks/useFileUpload.ts, packages/components/package.json
CSV parser: automatic delimiter detection (;, \t, ,), improved header matching, chunk/error handling; added Excel MIME types to accepted file types; dependency @koale/useworker added.
File Upload UI & Status
packages/components/src/molecules/Dropzone/Dropzone.tsx, packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx, packages/components/src/molecules/FileUploadStatus/FileUploadStatus.tsx, packages/ui/src/components/molecules/FileUploadCard/styles.scss
Dropzone ariaLabel made optional and DropzoneState added; FileUploadCard: optional title, errorType/errorMessage props and sync logic; FileUploadErrorType converted from enum→string union and gained 'no-products-found'; FileUploadStatus enhanced message resolution and props.
SearchInput & Upload Dropdown
packages/core/src/components/search/SearchInput/SearchInput.tsx, packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx
Integrates attachment button + upload flow into SearchInput; CMS-driven labels; CSV/XLSX parsing (xlsx lib); maps CSV→SKUs→bulk product fetch; toasts, processing states, and drawer trigger added.
QuickOrderDrawer & Provider
packages/components/src/organisms/QuickOrderDrawer/..., packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss
Provider adds isLoading and totalRequestedSkus, synchronizes initialProducts, computes alert messages; footer button async loading; products table attrs renamed to data-fs-qod-*, empty-state and skeleton adjustments, new QOD tokens and styling.
SDK: Bulk Fetch & Conversion
packages/core/src/sdk/product/useBulkProductsQuery.ts, packages/core/src/sdk/product/convertProductToQuickOrder.ts
New useBulkProductsQuery batches SKU requests (10 per batch, 100ms delay) and aggregates results; convertProductToQuickOrder maps API product→QuickOrder product with inventory/availability and quantity logic.
CMS & Global Settings
packages/core/cms/faststore/content-types.json, packages/core/cms/faststore/sections.json, packages/core/src/utils/globalSettings.ts
Adds fileUpload CMS schema (accepted types, max size, error messages, labels) and attachmentButton config for searchInput; exposes fileUpload type in global settings.
Navbar & Integration
packages/core/src/components/navigation/Navbar/Navbar.tsx, packages/core/src/components/sections/Navbar/Navbar.tsx, packages/core/src/components/sections/Navbar/section.module.scss
Wires attachmentButton config into SearchInput props (enabled/icon/ariaLabel) for desktop and mobile; imports QOD styles into Navbar section module.
Public Exports & Types
packages/components/src/index.ts, packages/components/src/hooks/index.ts, packages/ui/src/index.ts
Exports updated to include CSV parser types and useCSVParser, file upload types (FileRejectionCode, FileUploadCardProps), QuickOrder Product and provider props; hook re-exports cleaned.
Styling & SearchInputField
packages/ui/src/components/molecules/SearchInputField/styles.scss, packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss
Removed legacy attachment/separator styles; added --fs-qod-* tokens with backward aliases and expanded QuickOrderDrawer styling.
Package & Storybook
packages/core/package.json, packages/storybook/package.json, packages/storybook/.storybook/main.js
Added xlsx dependency in core; Storybook SWC addon added; storybook deps set to workspace.
Fragments & ProductDetails
packages/core/src/components/sections/ProductDetails/ProductDetails.tsx
Adds quantity field to offers in ProductDetails GraphQL fragment to support inventory-aware QuickOrder mapping.
Changelogs & Misc
packages/components/CHANGELOG.md, packages/core/CHANGELOG.md, packages/cli/CHANGELOG.md, packages/storybook/stories/*
Changelog conflict cleanups and story updates (error types → string literals, CSV filename).

Sequence Diagram

sequenceDiagram
    actor User
    participant SearchInput
    participant FileUploadCard
    participant Parser
    participant BulkFetcher
    participant QuickOrderDrawer

    User->>SearchInput: Click attachment / drop file
    SearchInput->>FileUploadCard: open upload UI
    User->>FileUploadCard: select CSV/XLSX
    FileUploadCard->>Parser: parse file (detect delimiter / parse XLSX→CSV)
    Parser-->>FileUploadCard: CSVData or parse error
    alt parsed SKUs
        FileUploadCard->>SearchInput: return SKUs
        SearchInput->>BulkFetcher: fetch SKUs (batched)
        BulkFetcher-->>SearchInput: product details (with quantity)
        SearchInput->>QuickOrderDrawer: populate products (isLoading=true)
        QuickOrderDrawer-->>User: show skeleton (loading)
        Note over SearchInput: artificial delay + processing
        SearchInput->>QuickOrderDrawer: update products (isLoading=false)
        User->>QuickOrderDrawer: adjust quantities & add to cart
    else parse/error
        FileUploadCard-->>User: show error message (mapped error type)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • hellofanny
  • ArthurTriis1

Poem

📂 A file dropped, delimiters hum,
Parsers dance and SKUs come,
Batches fetch and drawers glow bright,
Quick orders bloom from CSV night. 🎉

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: quick order upload integration' directly summarizes the main change—integrating CSV file upload functionality into the Quick Order drawer workflow.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 10

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

🤖 Fix all issues with AI agents
In `@packages/components/src/hooks/useCSVParser.ts`:
- Around line 106-337: The current useCSVParser implementation uses an async
Promise executor (awaiting detectDelimiter inside the new Promise), which can
cause unhandled rejections; refactor by making the outer function (useCSVParser)
async and call await detectDelimiter() before creating the new Promise that
wraps Papa.parse so the executor is synchronous; keep helper functions
(detectDelimiter, findColumnIndex, validateAndTransformRow, estimateRows) and
the Papa.parse call (chunk/complete/error handlers) largely unchanged, but move
detectedDelimiter determination out of the Promise executor and then return new
Promise((resolve,reject) => { Papa.parse(...) }) that uses the same
reject/resolve logic. Ensure any early rejects (missing SKU/Quantity) call
parser.abort() and reject inside the synchronous executor.

In `@packages/components/src/hooks/useFileUpload.ts`:
- Line 31: The function useFileUpload currently requires a full
Required<FileUploadOptions> default which blocks partial overrides; change the
parameter to accept Partial<FileUploadOptions> (e.g., options:
Partial<FileUploadOptions> = {}) and inside useFileUpload merge with
DEFAULT_FILE_UPLOAD_OPTIONS (e.g., const merged = {
...DEFAULT_FILE_UPLOAD_OPTIONS, ...options }) so callers can pass only fields
they want to override; update any internal uses of the old parameter to read
from the merged object and adjust typing accordingly while keeping
DEFAULT_FILE_UPLOAD_OPTIONS and the useFileUpload name intact.

In `@packages/components/src/molecules/Dropzone/Dropzone.tsx`:
- Around line 141-151: The spread order currently lets consumer props in
otherProps override critical handlers from getRootProps(), breaking Dropzone
behavior; update the return JSX in Dropzone.tsx to ensure {...getRootProps()} is
spread last (after {...otherProps}) or explicitly merge event handlers (e.g.,
onClick, onDragEnter, onKeyDown) so handlers from getRootProps() are preserved
while still allowing otherProps to provide non-conflicting props; modify the
element that uses ref and data-* attributes accordingly to apply this change.

In `@packages/components/src/molecules/SearchInputField/SearchInputField.tsx`:
- Around line 128-135: Replace the hardcoded aria-label on the IconButton inside
SearchInputField with a CMS-driven prop: add an explicit prop (e.g.,
attachmentButtonAriaLabel) to SearchInputField and pass it to the IconButton as
the aria-label (falling back to a sensible default if undefined), and keep
attachmentButtonProps spread but do not rely on it to override aria-label;
update usages of IconButton, the attachmentButtonProps spread, and the component
props interface/type to include attachmentButtonAriaLabel so the accessible
label is driven explicitly by CMS config.

In
`@packages/components/src/organisms/QuickOrderDrawer/provider/QuickOrderDrawerProvider.tsx`:
- Around line 152-162: The context `value` object (typed as
QuickOrderDrawerContextValue) is recreated each render causing unnecessary
re-renders of `useQuickOrderDrawer` consumers; wrap the `value` creation in
`useMemo` (imported from React) and return useMemo(() => ({ products,
totalPrice, itemsCount, alertMessage, isLoading, setAlertMessage,
onChangeQuantityItem, onDelete, onAddToCart }), [products, totalPrice,
itemsCount, alertMessage, isLoading, setAlertMessage, onChangeQuantityItem,
onDelete, onAddToCart]) so the object identity only changes when one of those
dependencies changes.

In `@packages/core/package.json`:
- Line 97: Remove the unused and vulnerable "xlsx" dependency from
packages/core/package.json and either implement proper .xlsx parsing or remove
".xlsx" from the accepted file types list in the file upload hook; specifically,
delete the "xlsx" entry in package.json and update the supported types
array/constant referenced in packages/components/src/hooks/useFileUpload.ts (the
code that currently lists ".xlsx" at or around the supported file types
declaration) so it no longer advertises unsupported .xlsx handling, or replace
that entry with a working parser integration if you choose to add real support.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx`:
- Around line 343-388: The hardcoded 2s test delay in the quick order flow (the
setTimeout call using timeoutId and setIsLoadingWithDelay) should not ship;
either remove the artificial delay entirely or replace the magic number with a
named constant (e.g., QUICK_ORDER_DELAY) and default it to 0 for production.
Update the logic around the timeoutId cleanup (clearTimeout in the return)
accordingly, and remove the "for testing" comment; ensure calls to
setQuickOrderProducts, setIsQuickOrderDrawerOpen, setFileUploadVisible, and
setNoProductsError behave the same when the delay is removed or controlled by
the new constant.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`:
- Around line 35-40: In UploadFileDropdown, the call to useCSVParser currently
hardcodes delimiter: ',' which prevents auto-detection of semicolons/tabs;
update the options passed to useCSVParser in UploadFileDropdown (the
useCSVParser(...) invocation) to set delimiter: '' so the parser can auto-detect
delimiters (matching the behavior used in SearchInput's useCSVParser usage);
keep the other options (skipEmptyLines, skuColumnNames, quantityColumnNames)
unchanged.

In `@packages/core/src/sdk/product/useBulkProductsQuery.ts`:
- Around line 43-129: The effect in useBulkProductsQuery spawns fetchProducts
without cancelling stale runs, so when skusKey/channel/locale changes an earlier
fetch can overwrite state; modify the useEffect to create a cancellation guard
(either an AbortController passed to request or a local "cancelled" boolean) and
check it before calling setProducts, setError, and setIsLoading; ensure
fetchProducts listens to the AbortController signal for request() or checks the
cancelled flag after each await (and in the batch loop), and call
controller.abort() or set cancelled = true in the effect cleanup so only the
latest invocation updates state.

In `@packages/ui/src/components/molecules/SearchInputField/styles.scss`:
- Around line 94-98: The transition shorthand in the SearchInputField styles
(the transition declaration using --fs-search-input-field-transition-timing and
--fs-search-input-field-transition-function) mistakenly uses the timing token
for both duration and easing/delay for box-shadow; update the box-shadow entry
so its third value is the easing token
(--fs-search-input-field-transition-function) instead of the timing token,
ensuring the shorthand reads "box-shadow [duration] [timing-function], border
[duration] [timing-function]" so box-shadow uses duration then easing (not a
duplicate delay).
🟡 Minor comments (21)
packages/core/CHANGELOG.md-6-11 (1)

6-11: ⚠️ Potential issue | 🟡 Minor

Changelog entry missing version header and links.

The new entries at the top don't follow the established format in this file — they lack a version number/heading (e.g., # X.Y.Z) and commit/PR links. This also triggers a markdownlint MD001 warning (h3 without preceding h2). If versioning is handled by CI/lerna, these entries should be placed under a placeholder like # Unreleased to maintain structure.

packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawer.tsx-31-31 (1)

31-31: ⚠️ Potential issue | 🟡 Minor

formatter prop is declared but never used.

formatter is accepted in QuickOrderDrawerProps (Line 31) but is not forwarded to the provider, children, or any other consumer. Either pass it through providerProps/context so descendant components (e.g., QuickOrderDrawerProducts) can access it, or remove it from the props to avoid a misleading API surface.

Also applies to: 39-63

packages/ui/src/components/molecules/FileUploadStatus/styles.scss-74-75 (1)

74-75: ⚠️ Potential issue | 🟡 Minor

Stylelint error: use currentcolor (lowercase) instead of currentColor.

The project's Stylelint config enforces value-keyword-case. This appears in 6 places across the loading, completed, and error icon blocks. A quick find-and-replace will fix all.

Fix
-    fill: currentColor;
-    stroke: currentColor;
+    fill: currentcolor;
+    stroke: currentcolor;

Apply to Lines 74–75, 102–103, and 119–120.

Also applies to: 102-103, 119-120

packages/components/src/hooks/useFileUpload.ts-37-39 (1)

37-39: ⚠️ Potential issue | 🟡 Minor

Wrap const declaration in a block to fix switch-case scoping.

Biome correctly flags that const sizeMB is accessible from other case branches. Wrap it in a block.

Fix
-        case 'file-too-large':
-          const sizeMB = Math.round(maxSize / (1024 * 1024))
-          return `File is too large. Maximum size is ${sizeMB}MB.`
+        case 'file-too-large': {
+          const sizeMB = Math.round(maxSize / (1024 * 1024))
+          return `File is too large. Maximum size is ${sizeMB}MB.`
+        }
packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawer.tsx-57-59 (1)

57-59: ⚠️ Potential issue | 🟡 Minor

Duplicate data-fs-qod attribute on both SlideOver and the inner div.

Both the <SlideOver> (Line 57) and the child <div> (Line 59) carry data-fs-qod. This will cause CSS selectors to match both elements unintentionally. Likely only one should have it.

Proposed fix
       overlayProps={overlayProps}
       data-fs-slide-over
-      data-fs-qod
     >
       <div data-fs-qod>{children}</div>
packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx-231-233 (1)

231-233: ⚠️ Potential issue | 🟡 Minor

Add colSpan to TableCell props to eliminate type assertion workaround.

The cast to React.HTMLAttributes<HTMLTableCellElement> works around TableCellProps not explicitly declaring colSpan. While the interface extends HTMLAttributes<HTMLTableCellElement>, TypeScript doesn't automatically infer colSpan support without explicit declaration. Add colSpan?: number to TableCellProps in packages/components/src/molecules/Table/TableCell.tsx to allow direct usage without assertion.

packages/core/src/styles/global/index.scss-7-8 (1)

7-8: ⚠️ Potential issue | 🟡 Minor

Drop the .scss extension from the @import path.

Stylelint (scss/load-partial-extension) flags this. SCSS partials should be imported without the file extension to follow convention and satisfy the linter.

Proposed fix
-@import "@faststore/ui/src/styles/components.scss";
+@import "@faststore/ui/src/styles/components";
packages/ui/src/components/molecules/Dropzone/styles.scss-191-207 (1)

191-207: ⚠️ Potential issue | 🟡 Minor

Use modern range notation for the media query.

Stylelint (media-feature-range-notation) expects the context/range syntax.

Proposed fix
-@media (max-width: 768px) {
+@media (width <= 768px) {
packages/ui/src/components/molecules/Dropzone/styles.scss-178-188 (1)

178-188: ⚠️ Potential issue | 🟡 Minor

Replace deprecated clip with clip-path.

The clip property is deprecated per the CSS spec. The standard visually-hidden pattern now uses clip-path.

Proposed fix
-    clip: rect(0, 0, 0, 0);
+    clip-path: inset(50%);
packages/core/src/components/search/UploadFileDropdown/section.module.scss-1-2 (1)

1-2: ⚠️ Potential issue | 🟡 Minor

Stylelint errors: @import position and .scss extension.

Two lint violations flagged:

  1. @import inside a selector block is flagged by no-invalid-position-at-import-rule.
  2. The .scss extension triggers scss/load-partial-extension.

If scoping the import inside .section is intentional (CSS Modules pattern), consider suppressing with // stylelint-disable-next-line or migrating to @use with a mixin approach. Otherwise, move the import to the file's top level and drop the extension.

packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerHeader.tsx-16-21 (1)

16-21: ⚠️ Potential issue | 🟡 Minor

Truncation breaks for small titleCharLimit values (< 6).

When titleCharLimit is, say, 5: leftOffset = floor(2.5) - 3 = -1. title.slice(0, -1) removes the last character instead of keeping the first N characters, producing garbled output.

Also, minor typo: titleFormmated → titleFormatted.

🛡️ Proposed safeguard
- const leftOffset = Math.floor(titleCharLimit / 2) - 3
- const rightOffset = Math.floor(titleCharLimit / 2)
- const titleFormmated =
+ const leftOffset = Math.max(0, Math.floor(titleCharLimit / 2) - 3)
+ const rightOffset = Math.floor(titleCharLimit / 2)
+ const titleFormatted =
    title.length > titleCharLimit
      ? `${title.slice(0, leftOffset)}...${title.slice(-rightOffset)}`
      : title
packages/components/src/molecules/Dropzone/Dropzone.tsx-56-66 (1)

56-66: ⚠️ Potential issue | 🟡 Minor

JSDoc descriptions for noClick, noKeyboard, and noDrag are swapped/incorrect.

These don't match what react-dropzone actually does:

  • noClick: currently says "Whether to show the file input" — should describe disabling click-to-open.
  • noKeyboard: currently says "Whether to prevent drag events on the document body" — should describe disabling keyboard interaction.
  • noDrag: currently says "Whether to prevent dropping on the document body" — should describe disabling drag-and-drop.

Incorrect JSDoc on a public API will mislead consumers.

📝 Proposed fix
   /**
-   * Whether to show the file input (hidden by default).
+   * Whether to disable click-to-open file dialog.
    */
   noClick?: boolean
   /**
-   * Whether to prevent drag events on the document body.
+   * Whether to disable opening the file dialog via keyboard interaction.
    */
   noKeyboard?: boolean
   /**
-   * Whether to prevent dropping on the document body.
+   * Whether to disable drag-and-drop interaction.
    */
   noDrag?: boolean
packages/core/src/sdk/product/convertProductToQuickOrder.ts-25-31 (1)

25-31: ⚠️ Potential issue | 🟡 Minor

Extract magic number and address unsafe type assertion for missing quantity field.

  1. The quantity field is not included in the ProductDetailsFragment GraphQL query, but the code casts offer to access it anyway. Either add quantity to the fragment or handle its absence without a type assertion.

  2. Extract 999999 as a named constant—it represents the default high inventory fallback and belongs at the module level for clarity and maintainability.

♻️ Suggested fix
+const DEFAULT_IN_STOCK_INVENTORY = 999999
+
 export const convertProductToQuickOrder = (
   product: ProductDetailsFragment_ProductFragment,
   requestedQuantity: number
 ): Product | null => {
   ...
-  const offerQuantity = (offer as { quantity?: number | null }).quantity
   const inventory =
     offerQuantity != null
       ? offerQuantity
       : isInStock
-        ? 999999
+        ? DEFAULT_IN_STOCK_INVENTORY
         : 0

For the quantity field: either update ProductDetailsFragment to query it from the API, or use optional chaining without casting if the field is intentionally excluded.

packages/components/src/hooks/useCSVParser.ts-122-143 (1)

122-143: ⚠️ Potential issue | 🟡 Minor

\r\n fallback in delimiter detection is dead code.

const firstLine = text.split('\n')[0] || text.split('\r\n')[0] || ''

If the file uses \r\n line endings, split('\n') still splits correctly — it just leaves a trailing \r on the first element, which is non-empty. The || never reaches the split('\r\n') branch.

Proposed fix
-const firstLine = text.split('\n')[0] || text.split('\r\n')[0] || ''
+const firstLine = (text.split(/\r?\n/)[0] || '').trim()
packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx-48-64 (1)

48-64: ⚠️ Potential issue | 🟡 Minor

CSV errors are surfaced both as a toast and inline — double notification.

The useEffect on lines 48-64 pushes a toast when csvError changes, and lines 224-229 render the same error inline. The user sees the error message twice. Pick one approach — toast for transient feedback or inline for persistent display — not both.

Also applies to: 224-229

packages/storybook/stories/fileupload.stories.tsx-84-93 (1)

84-93: ⚠️ Potential issue | 🟡 Minor

FileUploadStatusAllErrorTypes is missing 'no-products-found'.

The FileUploadErrorType union includes 7 values, but only 6 are listed here. Add 'no-products-found' for complete story coverage.

packages/ui/src/components/molecules/SearchInputField/styles.scss-14-16 (1)

14-16: ⚠️ Potential issue | 🟡 Minor

Stylelint violation: unexpected empty line before custom property (line 15).

Static analysis flagged this. Remove the blank line before --fs-search-input-field-transition-timing to satisfy custom-property-empty-line-before.

packages/core/src/components/search/SearchInput/SearchInput.tsx-244-257 (1)

244-257: ⚠️ Potential issue | 🟡 Minor

Promise.race timeout doesn't cancel the losing parse operation.

If the 30-second timeout wins, onParseFile (and its Web Worker) continues running in the background. The resolved result may later update state unexpectedly. Consider using an AbortController-style mechanism or at minimum setting a flag to discard late results.

packages/storybook/stories/fileupload.stories.tsx-6-6 (1)

6-6: ⚠️ Potential issue | 🟡 Minor

Fragile deep import into dist path.

@faststore/components/dist/esm/molecules/FileUploadStatus will break if the build output structure changes. FileUploadErrorType is already exported from the package root:

Proposed fix
-import type { FileUploadErrorType } from '@faststore/components/dist/esm/molecules/FileUploadStatus'
+import type { FileUploadErrorType } from '@faststore/components'
packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx-126-130 (1)

126-130: ⚠️ Potential issue | 🟡 Minor

isValidFileType hardcodes .csv while accept is a configurable prop.

If a consumer passes a different accept value (e.g., .xlsx), the validation will still reject anything that isn't .csv. Either derive the valid extensions from the accept prop or document that only CSV is supported and remove the accept prop flexibility.

packages/components/src/organisms/QuickOrderDrawer/index.ts-13-17 (1)

13-17: ⚠️ Potential issue | 🟡 Minor

Rename Product to avoid namespace collision at the package level.

This type is exported from the package's top-level index.ts and competes with other Product* types (ProductCard, ProductPrice, ProductTitle, etc.). Renaming to QuickOrderDrawerProduct or QuickOrderProduct makes the scope explicit and reduces collision risk for consumers.

Note: QuickOrderDrawerProvider is intentionally not exported—the QuickOrderDrawer component wraps the provider internally, so consumers don't need direct access to it.

🧹 Nitpick comments (26)
packages/core/src/utils/utilities.ts (1)

148-156: formatFileSize doesn't guard against negative or extremely large values.

Negative bytes will produce NaN from Math.log, and values ≥ 1 TB will index past the sizes array yielding "1024 undefined". Neither is likely for a 10 MB file upload cap, but a small guard keeps it robust.

🛡️ Suggested defensive guard
 export const formatFileSize = (bytes: number): string => {
-  if (bytes === 0) return '0 Bytes'
+  if (bytes <= 0) return '0 Bytes'

   const k = 1024
   const sizes = ['Bytes', 'KB', 'MB', 'GB']
-  const i = Math.floor(Math.log(bytes) / Math.log(k))
+  const i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length - 1)

   return Number.parseFloat((bytes / k ** i).toFixed(2)) + ' ' + sizes[i]
 }
packages/ui/src/components/molecules/FileUploadCard/styles.scss (2)

17-18: Hardcoded hex colors bypass the design token system.

Several hex values (#0366dd, #ffffff, #bfdbfe, #d6d6d6, #f0f7ff, #f5f5f5) are used directly instead of referencing existing --fs-* design tokens. This breaks theming consistency and makes future palette changes harder to propagate.

Consider replacing these with appropriate design tokens (e.g., var(--fs-color-primary-bkg), var(--fs-color-neutral-0), etc.) where equivalents exist.

Also applies to: 117-118, 172-172, 200-207, 219-219, 242-242


61-62: Fixed height: 285px is fragile.

The card's open state uses a fixed 285px height, which may clip content or leave excess space if labels/fonts vary across locales or CMS configurations. Consider using min-height instead, or letting the content drive the height with a max-height + overflow strategy.

packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss (3)

2-3: Nested @import rules flagged by Stylelint (no-invalid-position-at-import-rule).

Importing Tooltip and Alert styles inside the [data-fs-qod] selector is a valid SCSS scoping technique, but it triggers Stylelint errors. Consider using @use with namespacing or moving these to a top-level import if compatible with the build setup.


238-251: Remove commented-out border-color lines.

Lines 241 and 249 contain commented-out border-color declarations — leftover debug/exploration code. Per the PR objectives about removing leftover debug code, these should be cleaned up.

♻️ Suggested fix
       [data-fs-badge-variant="success"] {
         color: var(--fs-badge-success-text-color);

         [data-fs-badge-wrapper] {
           background-color: var(--fs-qod-badge-success-bkg-color);
-
-          /* border-color: var(--fs-badge-success-border-color); */
         }
       }

       [data-fs-badge-variant="warning"] {
         [data-fs-badge-wrapper] {
           background-color: var(--fs-qod-badge-warning-bkg-color);
-
-          /* border-color: var(--fs-badge-success-border-color); */
         }
       }

113-114: Use overflow shorthand per Stylelint.

Stylelint flags the longhand overflow-x/overflow-y pair. Use the shorthand instead:

♻️ Suggested fix
-    overflow-x: hidden;
-    overflow-y: auto;
+    overflow: hidden auto;
packages/ui/src/components/molecules/FileUploadStatus/styles.scss (2)

13-15: Hardcoded hex colors bypass design tokens.

Colors like #08a822, #d31a15, #fdf6f5, #ffdfd9, #0366dd, #0252b8, and #d6d6d6 are scattered throughout. Consider mapping these to design tokens (or adding new tokens) so theming and dark-mode work consistently across the system.

Also applies to: 48-49, 198-199, 220-226


29-29: Remove commented-out code.

// height: 188px; — leftover debug/exploration code.

packages/components/src/organisms/QuickOrderDrawer/provider/QuickOrderDrawerProvider.tsx (2)

105-111: Redundant else if (isLoading) — simplify to else.

Since the if checks !isLoading, the else branch necessarily means isLoading is truthy.

Fix
   useEffect(() => {
     if (!isLoading) {
       setAlertMessage(getAlertMessage(products, totalRequestedSkus))
-    } else if (isLoading) {
+    } else {
       setAlertMessage('')
     }
   }, [products, isLoading, totalRequestedSkus])

73-95: getAlertMessage is recreated every render — consider useCallback or move it outside the component.

Since it's a pure function that only depends on its arguments, it can be hoisted to module scope, which also avoids the stale-closure risk in the effect on Line 105.

packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx (2)

219-219: Hardcoded color on the delete icon.

color="#1F1F1F" bypasses design tokens. Use a CSS variable or token-based approach consistent with the rest of the design system.


44-44: Unnecessary variable alias.

const showSkeleton = isLoading adds no clarity — just use isLoading directly on Line 90.

packages/ui/src/styles/components.scss (1)

67-67: Dropzone import is out of alphabetical order.

Other molecule imports are alphabetically sorted. Dropzone (Line 67) should be between Dropdown (Line 31) and FileUploadCard (Line 32) to stay consistent.

packages/core/src/components/navigation/Navbar/Navbar.tsx (1)

157-167: Simplify the redundant ternary for attachmentButtonIcon.

searchInput?.attachmentButton?.icon already evaluates to undefined when the chain is nullish — the explicit ternary adds noise. Same pattern is duplicated for the mobile instance (Lines 199-203).

Proposed fix (apply to both desktop and mobile)
-              attachmentButtonIcon={
-                searchInput?.attachmentButton?.icon
-                  ? searchInput.attachmentButton.icon
-                  : undefined
-              }
+              attachmentButtonIcon={searchInput?.attachmentButton?.icon}
packages/ui/src/components/molecules/Dropzone/styles.scss (1)

7-7: Misleading CSS custom property name.

--fs-modal-bg-color suggests modal context, but this is the Dropzone component. Rename to something like --fs-dropzone-bg-color to avoid confusion.

Proposed fix
-  --fs-modal-bg-color: var(--fs-color-neutral-0);
+  --fs-dropzone-bg-color: var(--fs-color-neutral-0);

Also update the reference on line 22:

-  background-color: var(--fs-modal-bg-color);
+  background-color: var(--fs-dropzone-bg-color);
packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerFooter.tsx (1)

26-26: Hardcoded English strings limit i18n.

"{itemsCount} items" and "Add to Cart" (line 36) are hardcoded. If this library supports localization, these should be externalized or accepted as props.

packages/core/src/components/search/UploadFileDropdown/section.module.scss (1)

77-92: Hardcoded max-width: 500px may not be responsive.

[data-fs-upload-result-file-name] and [data-fs-upload-result-file-rows] use a fixed max-width: 500px. On viewports narrower than ~500px this won't clip as expected, and on wider layouts it may feel constrained. Consider max-width: 100% with a container constraint or a relative unit.

packages/core/src/sdk/product/useBulkProductsQuery.ts (1)

38-41: skusKey derivation on a potentially unstable skus reference is fine, but consider stabilizing upstream.

useMemo(() => skus.join(','), [skus]) recomputes whenever the skus array reference changes, even if the content is identical. This won't cause incorrect behavior (the resulting string equality prevents effect re-runs), but it does run the join on every new reference. If the caller frequently creates new arrays with the same content, consider memoizing skus at the call site.

packages/storybook/stories/quick-order-drawer.stories.tsx (1)

37-46: Unnecessary Fragment wrapper in Default story.

The <>...</> wrapper on lines 38/45 is redundant since QuickOrderDrawer already accepts children. The other stories don't use this wrapper — keep it consistent.

♻️ Proposed fix
       <QuickOrderDrawer isOpen={isOpen}>
-        <>
-          <QuickOrderDrawerHeader
-            title="order-file.csv"
-            onCloseDrawer={() => setIsOpen(false)}
-          />
-          <QuickOrderDrawerProducts columns={columns} />
-          <QuickOrderDrawerFooter />
-        </>
+        <QuickOrderDrawerHeader
+          title="order-file.csv"
+          onCloseDrawer={() => setIsOpen(false)}
+        />
+        <QuickOrderDrawerProducts columns={columns} />
+        <QuickOrderDrawerFooter />
       </QuickOrderDrawer>
packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx (1)

126-156: Duplicated file-processing logic between handleFileChange and handleDrop.

Both handlers perform identical validation → state update → callback sequences. Extract a shared helper like processFile(files: File[]) to consolidate the logic and avoid divergence if one path is updated without the other.

♻️ Suggested refactor
+ const processFiles = (files: File[]) => {
+   if (files.length === 0) return
+   const file = files[0]
+   setSelectedFile(file)
+
+   if (!isValidFileType(file)) {
+     setUploadState('error')
+     setErrorType('unsupported')
+     return
+   }
+
+   setErrorType(undefined)
+   setUploadState(isUploading ? 'uploading' : 'completed')
+   onFileSelect?.(files)
+ }
+
  const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
-   const files = Array.from(e.target.files || [])
-   if (files.length > 0) {
-     const file = files[0]
-     setSelectedFile(file)
-     ...
-   }
+   processFiles(Array.from(e.target.files || []))
  }

  const handleDrop = (e: DragEvent<HTMLDivElement>) => {
    if (!isOpen) return
    e.preventDefault()
    e.stopPropagation()
    setDragActive(false)
-   if (e.dataTransfer.files && e.dataTransfer.files[0]) {
-     const files = Array.from(e.dataTransfer.files)
-     ...
-   }
+   if (e.dataTransfer.files?.length) {
+     processFiles(Array.from(e.dataTransfer.files))
+   }
  }

Also applies to: 169-198

packages/components/src/molecules/FileUploadStatus/FileUploadStatus.tsx (1)

190-204: getErrorMessage() called twice in the error rendering path.

Each call reconstructs the object. Destructure once for clarity and to avoid redundant work:

Proposed fix
          {state === 'error' ? (
-           <>
-             <p data-fs-file-upload-status-text-error>
-               {getErrorMessage().title}
-             </p>
-             <p data-fs-file-upload-status-text-error>
-               {getErrorMessage().description}
-             </p>
-           </>
+           (() => {
+             const { title, description } = getErrorMessage()
+             return (
+               <>
+                 <p data-fs-file-upload-status-text-error>{title}</p>
+                 {description && (
+                   <p data-fs-file-upload-status-text-error>{description}</p>
+                 )}
+               </>
+             )
+           })()

Or extract it above the JSX:

+  const errorInfo = state === 'error' ? getErrorMessage() : null
+
   return (
     ...
           {state === 'error' ? (
             <>
-              <p ...>{getErrorMessage().title}</p>
-              <p ...>{getErrorMessage().description}</p>
+              <p ...>{errorInfo?.title}</p>
+              {errorInfo?.description && <p ...>{errorInfo.description}</p>}
             </>
packages/core/src/components/search/SearchInput/SearchInput.tsx (2)

116-129: 14+ useState declarations — this component is doing too much.

SearchInput now manages search query, search dropdown, file upload card visibility, upload modal, CSV parsing, bulk product fetching, quick order drawer, and cart operations. Consider extracting the file-upload + quick-order workflow into a custom hook (e.g., useQuickOrderUpload) to reduce cognitive load and improve testability.

Also applies to: 137-140


325-403: Massive useEffect with three conditional branches and a nested setTimeout.

This effect handles loading state, data conversion, and empty-state detection, all in one block. The branching is hard to follow and the conditions overlap subtly (e.g., skusToFetch.length > 0 appears in every branch). Consider splitting into smaller, focused effects or moving the conversion logic into a callback triggered after useBulkProductsQuery completes.

packages/components/src/hooks/useCSVParser.ts (2)

44-65: useCallback depends on [options] — unstable object reference.

If the caller passes an inline object literal (which both UploadFileDropdown.tsx and SearchInput.tsx do), onParseFile is recreated every render, defeating useCallback. Either destructure the options into primitives for the dependency array, or document that callers must memoize the options object.

Proposed fix — use a stable ref
+const optionsRef = useRef(options)
+optionsRef.current = options
+
 const onParseFile = useCallback(
   async (file: File): Promise<CSVData | null> => {
     try {
       setError(null)
       setIsProcessing(true)
-      const result = await parseCSVFile(file, options)
+      const result = await parseCSVFile(file, optionsRef.current)
       return result
     } catch (err) { ... }
     finally { setIsProcessing(false) }
   },
-  [options]
+  []
 )

253-253: Mutating PapaParse's chunk results.data directly.

results.data = results.data.slice(1) reassigns a property on PapaParse's internal results object. While this works today, it's fragile — use a local variable instead:

-           results.data = results.data.slice(1)
+           const dataRows = results.data.slice(1)
            isHeaderProcessed = true
          }

-         results.data.forEach((row: any, index: number) => {
+         const rows = isHeaderProcessed ? (dataRows ?? results.data) : results.data
+         rows.forEach((row: any, index: number) => {

Actually, a simpler approach: just skip index 0 in the forEach when processing the first chunk's header.

packages/components/src/index.ts (1)

403-415: Dropzone exports break the co-location of SKUMatrix exports.

The Dropzone block (lines 409–410) splits the SKUMatrix value exports (lines 403–407) from their type exports (lines 411–415). Every other component in this file keeps its value and type exports adjacent. This looks like a rebase artifact.

♻️ Suggested reordering
 export {
   default as SKUMatrix,
   SKUMatrixSidebar,
   SKUMatrixTrigger,
 } from './organisms/SKUMatrix'
-
-export { default as Dropzone } from './molecules/Dropzone'
-export type { DropzoneProps, DropzoneState } from './molecules/Dropzone'
 export type {
   SKUMatrixProps,
   SKUMatrixSidebarProps,
   SKUMatrixTriggerProps,
 } from './organisms/SKUMatrix'
+
+export { default as Dropzone } from './molecules/Dropzone'
+export type { DropzoneProps, DropzoneState } from './molecules/Dropzone'

Comment on lines +106 to +337
return new Promise(async (resolve, reject) => {
const defaultOptions = {
skuColumnNames: ['sku', 'id', 'product', 'productid', 'item'],
quantityColumnNames: ['quantity', 'qty', 'amount', 'count'],
delimiter: '',
skipEmptyLines: true,
chunkSize: 1024 * 1024,
}

const config = { ...defaultOptions, ...options }

const detectDelimiter = (): Promise<string> => {
if (config.delimiter) {
return Promise.resolve(config.delimiter)
}

return new Promise((resolveDelimiter) => {
const reader = new FileReader()
reader.onload = (e) => {
const text = e.target?.result as string
const firstLine = text.split('\n')[0] || text.split('\r\n')[0] || ''

const commaCount = (firstLine.match(/,/g) || []).length
const semicolonCount = (firstLine.match(/;/g) || []).length
const tabCount = (firstLine.match(/\t/g) || []).length

if (semicolonCount > 0 && semicolonCount >= commaCount) {
resolveDelimiter(';')
} else if (tabCount > commaCount && tabCount > semicolonCount) {
resolveDelimiter('\t')
} else {
resolveDelimiter(',')
}
}
reader.onerror = () => resolveDelimiter(',')
reader.readAsText(file.slice(0, 1024))
})
}

const detectedDelimiter = await detectDelimiter()

let headers: string[] = []
let skuIndex = -1
let quantityIndex = -1
let isHeaderProcessed = false

const transformedData: Array<{ SKU: string; Quantity: number }> = []
const errors: string[] = []
let processedRows = 0
let totalEstimatedRows = 0

const findColumnIndex = (
headers: string[],
columnNames: string[]
): number => {
return headers.findIndex((header) =>
columnNames.some((name) =>
header.toLowerCase().trim().includes(name.toLowerCase())
)
)
}

const validateAndTransformRow = (row: unknown[], rowIndex: number) => {
try {
const sku = row[skuIndex]
const quantity = row[quantityIndex]

if (!sku || sku === '' || quantity === undefined || quantity === '') {
return null
}

const trimmedSku = String(sku).trim()
const numericQuantity = Number(quantity)

if (!trimmedSku) {
throw new Error('Empty SKU found')
}

if (Number.isNaN(numericQuantity) || numericQuantity < 0) {
throw new Error(
`Invalid quantity value: ${quantity} for SKU: ${trimmedSku}`
)
}

return {
SKU: trimmedSku,
Quantity: numericQuantity,
}
} catch (err) {
const errorMessage =
err instanceof Error ? err.message : 'Unknown error'
errors.push(`Row ${rowIndex + 2}: ${errorMessage}`)

if (errors.length > 1000) {
errors.splice(0, 500)
}

return null
}
}

const estimateRows = (fileSize: number) => {
const avgBytesPerRow = 50
return Math.floor(fileSize / avgBytesPerRow)
}

totalEstimatedRows = estimateRows(file.size)

Papa.parse(file, {
header: false,
dynamicTyping: false,
skipEmptyLines: config.skipEmptyLines,
delimiter: detectedDelimiter,

worker: true,

chunk: (
results: { data: unknown[][] },
parser: { abort: () => void }
) => {
try {
if (!isHeaderProcessed && results.data.length > 0) {
headers = results.data[0] as string[]

skuIndex = findColumnIndex(headers, config.skuColumnNames)
quantityIndex = findColumnIndex(headers, config.quantityColumnNames)

if (skuIndex === -1) {
parser.abort()
reject(
new Error(
`SKU column not found. Expected one of: ${config.skuColumnNames.join(', ')}`
)
)
return
}

if (quantityIndex === -1) {
parser.abort()
reject(
new Error(
`Quantity column not found. Expected one of: ${config.quantityColumnNames.join(', ')}`
)
)
return
}

results.data = results.data.slice(1)
isHeaderProcessed = true
}

results.data.forEach((row: any, index: number) => {
const globalRowIndex = processedRows + index
const transformedRow = validateAndTransformRow(row, globalRowIndex)

if (transformedRow) {
transformedData.push(transformedRow)
}
})

processedRows += results.data.length

if (config.onProgress) {
const percentage = Math.min(
100,
Math.round((processedRows / totalEstimatedRows) * 100)
)
config.onProgress({
processed: processedRows,
total: totalEstimatedRows,
percentage,
})
}
} catch (err) {
parser.abort()
reject(err)
}
},

complete: () => {
try {
if (transformedData.length === 0) {
if (errors.length > 0) {
reject(
new Error(
`No valid data found. First few errors:\n${errors.slice(0, 5).join('\n')}`
)
)
} else {
reject(new Error('No valid data found in file'))
}
return
}

if (errors.length > 0) {
console.warn(
`CSV parsing completed with ${errors.length} warnings. Sample:`,
errors.slice(0, 10)
)
}

if (config.onProgress) {
config.onProgress({
processed: processedRows,
total: processedRows,
percentage: 100,
})
}

resolve({
data: transformedData,
fileName: file.name,
totalRows: transformedData.length,
fileSize: file.size,
})
} catch (err) {
reject(err)
}
},

error: (error: unknown) => {
const errorMessage =
error instanceof Error ? error.message : 'Unknown parsing error'
reject(new Error(`PapaParse error: ${errorMessage}`))
},

fastMode: false,
chunkSize: config.chunkSize,
preview: 0,
encoding: 'UTF-8',
})
})

ghost Feb 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Async Promise executor — anti-pattern with real risk.

Biome correctly flags this. If detectDelimiter() rejects or any await throws before the first try/catch, the rejection goes to the async function's implicit return promise, not the outer new Promise, causing an unhandled rejection.

Refactor to async function that returns a promise directly:

Proposed fix (simplified structure)
-const parseCSVFile = (
+const parseCSVFile = async (
   file: File,
   options: WorkerCSVOptions = {}
 ): Promise<WorkerCSVData> => {
-  return new Promise(async (resolve, reject) => {
     const defaultOptions = { ... }
     const config = { ...defaultOptions, ...options }
+    const detectedDelimiter = await detectDelimiter(file, config.delimiter)
 
-    const detectDelimiter = (): Promise<string> => { ... }
-    const detectedDelimiter = await detectDelimiter()
-
-    // ... setup variables ...
-
-    Papa.parse(file, {
-      // ... callbacks using resolve/reject ...
-    })
-  })
+    return new Promise((resolve, reject) => {
+      // ... setup variables ...
+      Papa.parse(file, {
+        // ... callbacks using resolve/reject ...
+      })
+    })
 }

This separates the async setup (detectDelimiter) from the callback-based PapaParse promise, keeping the executor synchronous.

🧰 Tools
🪛 Biome (2.3.14)

[error] 106-337: Promise executor functions should not be async.

(lint/suspicious/noAsyncPromiseExecutor)

🤖 Prompt for AI Agents
In `@packages/components/src/hooks/useCSVParser.ts` around lines 106 - 337, The
current useCSVParser implementation uses an async Promise executor (awaiting
detectDelimiter inside the new Promise), which can cause unhandled rejections;
refactor by making the outer function (useCSVParser) async and call await
detectDelimiter() before creating the new Promise that wraps Papa.parse so the
executor is synchronous; keep helper functions (detectDelimiter,
findColumnIndex, validateAndTransformRow, estimateRows) and the Papa.parse call
(chunk/complete/error handlers) largely unchanged, but move detectedDelimiter
determination out of the Promise executor and then return new
Promise((resolve,reject) => { Papa.parse(...) }) that uses the same
reject/resolve logic. Ensure any early rejects (missing SKU/Quantity) call
parser.abort() and reject inside the synchronous executor.

Comment on lines +141 to +151
return (
<div
ref={ref}
data-fs-dropzone
data-fs-dropzone-drag-active={isDragActive}
data-fs-dropzone-drag-accept={isDragAccept}
data-fs-dropzone-drag-reject={isDragReject}
data-fs-dropzone-disabled={disabled}
data-testid={testId}
{...getRootProps()}
{...otherProps}

ghost Feb 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

otherProps spread after getRootProps() can silently override dropzone event handlers.

{...getRootProps()} sets up critical handlers (onClick, onDragEnter, onKeyDown, etc.). Spreading {...otherProps} after it means any consumer-passed handler with the same name will clobber them, breaking dropzone behavior without warning.

Consider spreading getRootProps() last, or merging handlers explicitly.

🛡️ Proposed fix — spread getRootProps last
       <div
         ref={ref}
         data-fs-dropzone
         data-fs-dropzone-drag-active={isDragActive}
         data-fs-dropzone-drag-accept={isDragAccept}
         data-fs-dropzone-drag-reject={isDragReject}
         data-fs-dropzone-disabled={disabled}
         data-testid={testId}
-        {...getRootProps()}
         {...otherProps}
+        {...getRootProps()}
       >
📝 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
return (
<div
ref={ref}
data-fs-dropzone
data-fs-dropzone-drag-active={isDragActive}
data-fs-dropzone-drag-accept={isDragAccept}
data-fs-dropzone-drag-reject={isDragReject}
data-fs-dropzone-disabled={disabled}
data-testid={testId}
{...getRootProps()}
{...otherProps}
return (
<div
ref={ref}
data-fs-dropzone
data-fs-dropzone-drag-active={isDragActive}
data-fs-dropzone-drag-accept={isDragAccept}
data-fs-dropzone-drag-reject={isDragReject}
data-fs-dropzone-disabled={disabled}
data-testid={testId}
{...otherProps}
{...getRootProps()}
>
🤖 Prompt for AI Agents
In `@packages/components/src/molecules/Dropzone/Dropzone.tsx` around lines 141 -
151, The spread order currently lets consumer props in otherProps override
critical handlers from getRootProps(), breaking Dropzone behavior; update the
return JSX in Dropzone.tsx to ensure {...getRootProps()} is spread last (after
{...otherProps}) or explicitly merge event handlers (e.g., onClick, onDragEnter,
onKeyDown) so handlers from getRootProps() are preserved while still allowing
otherProps to provide non-conflicting props; modify the element that uses ref
and data-* attributes accordingly to apply this change.

Comment on lines +152 to +162
const value: QuickOrderDrawerContextValue = {
products,
totalPrice,
itemsCount,
alertMessage,
isLoading,
setAlertMessage,
onChangeQuantityItem,
onDelete,
onAddToCart,
}

ghost Feb 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Memoize the context value to avoid unnecessary consumer re-renders.

A new value object is created every render, causing all useQuickOrderDrawer consumers to re-render even when nothing changed. Wrap it in useMemo.

Fix
-  const value: QuickOrderDrawerContextValue = {
+  const value: QuickOrderDrawerContextValue = useMemo(() => ({
     products,
     totalPrice,
     itemsCount,
     alertMessage,
     isLoading,
     setAlertMessage,
     onChangeQuantityItem,
     onDelete,
     onAddToCart,
-  }
+  }), [products, totalPrice, itemsCount, alertMessage, isLoading, setAlertMessage, onChangeQuantityItem, onDelete, onAddToCart])

As per coding guidelines: "Check rendering performance (avoid heavy operations on render, use memo/useMemo/useCallback when appropriate)".

📝 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
const value: QuickOrderDrawerContextValue = {
products,
totalPrice,
itemsCount,
alertMessage,
isLoading,
setAlertMessage,
onChangeQuantityItem,
onDelete,
onAddToCart,
}
const value: QuickOrderDrawerContextValue = useMemo(() => ({
products,
totalPrice,
itemsCount,
alertMessage,
isLoading,
setAlertMessage,
onChangeQuantityItem,
onDelete,
onAddToCart,
}), [products, totalPrice, itemsCount, alertMessage, isLoading, setAlertMessage, onChangeQuantityItem, onDelete, onAddToCart])
🤖 Prompt for AI Agents
In
`@packages/components/src/organisms/QuickOrderDrawer/provider/QuickOrderDrawerProvider.tsx`
around lines 152 - 162, The context `value` object (typed as
QuickOrderDrawerContextValue) is recreated each render causing unnecessary
re-renders of `useQuickOrderDrawer` consumers; wrap the `value` creation in
`useMemo` (imported from React) and return useMemo(() => ({ products,
totalPrice, itemsCount, alertMessage, isLoading, setAlertMessage,
onChangeQuantityItem, onDelete, onAddToCart }), [products, totalPrice,
itemsCount, alertMessage, isLoading, setAlertMessage, onChangeQuantityItem,
onDelete, onAddToCart]) so the object identity only changes when one of those
dependencies changes.

Comment thread packages/core/package.json Resolved
Comment on lines +343 to +388
// Add artificial delay to test loading state
setIsLoadingWithDelay(true)

const timeoutId = setTimeout(() => {
const convertedProducts: Product[] = []

fetchedProducts.forEach((productData) => {
if (productData.product && !productData.error) {
const csvItem = csvData.data.find(
(item: { SKU: string; Quantity: number }) =>
item.SKU === productData.sku ||
item.SKU?.trim() === productData.sku?.trim()
)
const requestedQuantity = csvItem?.Quantity ?? 1

const convertedProduct = convertProductToQuickOrder(
productData.product,
requestedQuantity
)

if (convertedProduct) {
convertedProducts.push(convertedProduct)
}
}
})

setQuickOrderProducts(convertedProducts)
setIsLoadingWithDelay(false)

if (convertedProducts.length > 0) {
setIsQuickOrderDrawerOpen(true)
setFileUploadVisible(false)
setNoProductsError(false)
} else {
// Keep drawer open to show empty state message
setQuickOrderProducts([])
setIsQuickOrderDrawerOpen(true)
setFileUploadVisible(false)
setNoProductsError(true)
}
}, 2000) // 2 second delay for testing

return () => {
clearTimeout(timeoutId)
}
}

ghost Feb 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Hardcoded 2-second delay labeled "for testing" will ship to production.

Line 383: }, 2000) // 2 second delay for testing — This artificially delays every quick order flow by 2 seconds after products are fetched. If intentional for UX (e.g., skeleton display), remove the "for testing" comment and add a constant. If it's debug scaffolding, remove it before merging.

Proposed fix (if the delay is not needed)
-       const timeoutId = setTimeout(() => {
          const convertedProducts: Product[] = []
          // ... conversion logic ...
          setQuickOrderProducts(convertedProducts)
          setIsLoadingWithDelay(false)
          // ... state updates ...
-       }, 2000) // 2 second delay for testing
-
-       return () => {
-         clearTimeout(timeoutId)
-       }
🤖 Prompt for AI Agents
In `@packages/core/src/components/search/SearchInput/SearchInput.tsx` around lines
343 - 388, The hardcoded 2s test delay in the quick order flow (the setTimeout
call using timeoutId and setIsLoadingWithDelay) should not ship; either remove
the artificial delay entirely or replace the magic number with a named constant
(e.g., QUICK_ORDER_DELAY) and default it to 0 for production. Update the logic
around the timeoutId cleanup (clearTimeout in the return) accordingly, and
remove the "for testing" comment; ensure calls to setQuickOrderProducts,
setIsQuickOrderDrawerOpen, setFileUploadVisible, and setNoProductsError behave
the same when the delay is removed or controlled by the new constant.

Comment on lines +35 to +40
} = useCSVParser({
delimiter: ',',
skipEmptyLines: true,
skuColumnNames: ['sku', 'id', 'product', 'productid', 'item'],
quantityColumnNames: ['quantity', 'qty', 'amount', 'count'],
})

ghost Feb 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Hardcoded delimiter: ',' prevents auto-detection.

useCSVParser auto-detects the delimiter (comma, semicolon, tab) when delimiter is ''. Setting it to ',' here forces comma-only parsing and breaks semicolon/tab-delimited files. Use '' for auto-detection, matching the behavior in SearchInput.tsx (line 149).

Proposed fix
   } = useCSVParser({
-    delimiter: ',',
+    delimiter: '',
     skipEmptyLines: true,
     skuColumnNames: ['sku', 'id', 'product', 'productid', 'item'],
     quantityColumnNames: ['quantity', 'qty', 'amount', 'count'],
   })
📝 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
} = useCSVParser({
delimiter: ',',
skipEmptyLines: true,
skuColumnNames: ['sku', 'id', 'product', 'productid', 'item'],
quantityColumnNames: ['quantity', 'qty', 'amount', 'count'],
})
} = useCSVParser({
delimiter: '',
skipEmptyLines: true,
skuColumnNames: ['sku', 'id', 'product', 'productid', 'item'],
quantityColumnNames: ['quantity', 'qty', 'amount', 'count'],
})
🤖 Prompt for AI Agents
In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`
around lines 35 - 40, In UploadFileDropdown, the call to useCSVParser currently
hardcodes delimiter: ',' which prevents auto-detection of semicolons/tabs;
update the options passed to useCSVParser in UploadFileDropdown (the
useCSVParser(...) invocation) to set delimiter: '' so the parser can auto-detect
delimiters (matching the behavior used in SearchInput's useCSVParser usage);
keep the other options (skipEmptyLines, skuColumnNames, quantityColumnNames)
unchanged.

Comment on lines +43 to +129
useEffect(() => {
if (skus.length === 0) {
setProducts([])
setIsLoading(false)
return
}

const fetchProducts = async () => {
setIsLoading(true)
setError(null)

try {
if (!channel) {
throw new Error(
`useBulkProductsQuery: 'channel' from session is an empty string.`
)
}

// Process SKUs in batches to avoid overwhelming the server
// This matches the RFC recommendation to divide requests into smaller batches
const results: BulkProductData[] = []

for (let i = 0; i < skus.length; i += BATCH_SIZE) {
const batch = skus.slice(i, i + BATCH_SIZE)

// Fetch each product individually using the same query as useProductQuery
// This matches exactly how products are fetched elsewhere in the codebase
const batchPromises = batch.map(
async (sku): Promise<BulkProductData> => {
try {
const variables: ClientProductQueryQueryVariables = {
locator: [
{ key: 'id', value: sku },
{ key: 'channel', value: channel },
{ key: 'locale', value: locale },
],
}

// Use POST method to avoid URL length issues with GET
const data = await request<
ClientProductQueryQuery,
ClientProductQueryQueryVariables
>(query, variables, {
fetchOptions: {
method: 'POST',
},
})

return {
sku,
product: data.product,
}
} catch (err) {
console.error(`Failed to fetch product ${sku}:`, err)
return {
sku,
error:
err instanceof Error
? err
: new Error(`Failed to fetch product: ${sku}`),
}
}
}
)

const batchResults = await Promise.all(batchPromises)
results.push(...batchResults)

// Add a small delay between batches to avoid rate limiting
if (i + BATCH_SIZE < skus.length) {
await new Promise((resolve) => setTimeout(resolve, BATCH_DELAY_MS))
}
}

setProducts(results)
} catch (err) {
setError(
err instanceof Error ? err : new Error('Failed to fetch products')
)
setProducts([])
} finally {
setIsLoading(false)
}
}

fetchProducts()
}, [skusKey, channel, locale, skus.length])

ghost Feb 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Race condition: no cancellation guard when dependencies change.

If skusKey changes while a fetch is in-flight, the stale request continues and can overwrite the state set by the newer request. Add a cleanup flag (or AbortController) to discard results from superseded fetches.

🛡️ Proposed fix — stale closure guard
   useEffect(() => {
+    let cancelled = false
+
     if (skus.length === 0) {
       setProducts([])
       setIsLoading(false)
       return
     }

     const fetchProducts = async () => {
       setIsLoading(true)
       setError(null)

       try {
         // ... batching logic unchanged ...

-        setProducts(results)
+        if (!cancelled) {
+          setProducts(results)
+        }
       } catch (err) {
-        setError(
-          err instanceof Error ? err : new Error('Failed to fetch products')
-        )
-        setProducts([])
+        if (!cancelled) {
+          setError(
+            err instanceof Error ? err : new Error('Failed to fetch products')
+          )
+          setProducts([])
+        }
       } finally {
-        setIsLoading(false)
+        if (!cancelled) {
+          setIsLoading(false)
+        }
       }
     }

     fetchProducts()
+
+    return () => {
+      cancelled = true
+    }
-  }, [skusKey, channel, locale, skus.length])
+  }, [skusKey, channel, locale])
📝 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
useEffect(() => {
if (skus.length === 0) {
setProducts([])
setIsLoading(false)
return
}
const fetchProducts = async () => {
setIsLoading(true)
setError(null)
try {
if (!channel) {
throw new Error(
`useBulkProductsQuery: 'channel' from session is an empty string.`
)
}
// Process SKUs in batches to avoid overwhelming the server
// This matches the RFC recommendation to divide requests into smaller batches
const results: BulkProductData[] = []
for (let i = 0; i < skus.length; i += BATCH_SIZE) {
const batch = skus.slice(i, i + BATCH_SIZE)
// Fetch each product individually using the same query as useProductQuery
// This matches exactly how products are fetched elsewhere in the codebase
const batchPromises = batch.map(
async (sku): Promise<BulkProductData> => {
try {
const variables: ClientProductQueryQueryVariables = {
locator: [
{ key: 'id', value: sku },
{ key: 'channel', value: channel },
{ key: 'locale', value: locale },
],
}
// Use POST method to avoid URL length issues with GET
const data = await request<
ClientProductQueryQuery,
ClientProductQueryQueryVariables
>(query, variables, {
fetchOptions: {
method: 'POST',
},
})
return {
sku,
product: data.product,
}
} catch (err) {
console.error(`Failed to fetch product ${sku}:`, err)
return {
sku,
error:
err instanceof Error
? err
: new Error(`Failed to fetch product: ${sku}`),
}
}
}
)
const batchResults = await Promise.all(batchPromises)
results.push(...batchResults)
// Add a small delay between batches to avoid rate limiting
if (i + BATCH_SIZE < skus.length) {
await new Promise((resolve) => setTimeout(resolve, BATCH_DELAY_MS))
}
}
setProducts(results)
} catch (err) {
setError(
err instanceof Error ? err : new Error('Failed to fetch products')
)
setProducts([])
} finally {
setIsLoading(false)
}
}
fetchProducts()
}, [skusKey, channel, locale, skus.length])
useEffect(() => {
let cancelled = false
if (skus.length === 0) {
setProducts([])
setIsLoading(false)
return
}
const fetchProducts = async () => {
setIsLoading(true)
setError(null)
try {
if (!channel) {
throw new Error(
`useBulkProductsQuery: 'channel' from session is an empty string.`
)
}
// Process SKUs in batches to avoid overwhelming the server
// This matches the RFC recommendation to divide requests into smaller batches
const results: BulkProductData[] = []
for (let i = 0; i < skus.length; i += BATCH_SIZE) {
const batch = skus.slice(i, i + BATCH_SIZE)
// Fetch each product individually using the same query as useProductQuery
// This matches exactly how products are fetched elsewhere in the codebase
const batchPromises = batch.map(
async (sku): Promise<BulkProductData> => {
try {
const variables: ClientProductQueryQueryVariables = {
locator: [
{ key: 'id', value: sku },
{ key: 'channel', value: channel },
{ key: 'locale', value: locale },
],
}
// Use POST method to avoid URL length issues with GET
const data = await request<
ClientProductQueryQuery,
ClientProductQueryQueryVariables
>(query, variables, {
fetchOptions: {
method: 'POST',
},
})
return {
sku,
product: data.product,
}
} catch (err) {
console.error(`Failed to fetch product ${sku}:`, err)
return {
sku,
error:
err instanceof Error
? err
: new Error(`Failed to fetch product: ${sku}`),
}
}
}
)
const batchResults = await Promise.all(batchPromises)
results.push(...batchResults)
// Add a small delay between batches to avoid rate limiting
if (i + BATCH_SIZE < skus.length) {
await new Promise((resolve) => setTimeout(resolve, BATCH_DELAY_MS))
}
}
if (!cancelled) {
setProducts(results)
}
} catch (err) {
if (!cancelled) {
setError(
err instanceof Error ? err : new Error('Failed to fetch products')
)
setProducts([])
}
} finally {
if (!cancelled) {
setIsLoading(false)
}
}
}
fetchProducts()
return () => {
cancelled = true
}
}, [skusKey, channel, locale])
🤖 Prompt for AI Agents
In `@packages/core/src/sdk/product/useBulkProductsQuery.ts` around lines 43 - 129,
The effect in useBulkProductsQuery spawns fetchProducts without cancelling stale
runs, so when skusKey/channel/locale changes an earlier fetch can overwrite
state; modify the useEffect to create a cancellation guard (either an
AbortController passed to request or a local "cancelled" boolean) and check it
before calling setProducts, setError, and setIsLoading; ensure fetchProducts
listens to the AbortController signal for request() or checks the cancelled flag
after each await (and in the batch loop), and call controller.abort() or set
cancelled = true in the effect cleanup so only the latest invocation updates
state.

Giuliana Rigaud and others added 5 commits February 23, 2026 18:30
This PR refers to the creation of the Quick Order Drawer, a new
component developed for the Quick Order By File functionality.

The main advantage of the Quick Order functionality is the ability to
add products directly to the cart from the search, which significantly
reduces the number of clicks and browsing time.

<!--- Considering the context, what is the problem we'll solve? Where in
VTEX's big picture our issue fits in? Write a tweet about the context
and the problem itself. --->

<!--- Tell us the role of the new feature, or component, in its context.
Provide details about what you have implemented and screenshots if
applicable. --->
Creating the Quick Order Drawer layout according to Figma.

<img width="1912" height="966" alt="image (3)"
src="https://github.com/user-attachments/assets/65a66428-8db2-45f4-86f5-c28f4236a2e4"
/>

<!--- Describe the steps with bullet points. Is there any external link
that can be used to better test it or an example? --->

	•	The user uploads the file in the Quick Order interface.
	•	After the upload is completed, the Search button becomes enabled.
	•	The user clicks the Search button to start processing.
	•	The system begins processing the file data.
	•	The Dropdown enters a loading state.
• Even while loading, the Dropdown can be closed without interrupting
the processing.
• Once processing is finished, the system automatically opens the Quick
Order Drawer.

<!--- Add a link to a deploy preview from `starter.store` with this
branch being used. --->

<!--- Tip: You can get an installable version of this branch from the
CodeSandbox generated when this PR is created. --->

[Figma](https://www.figma.com/design/0c3DOaXs6rS25LyDWi7uap/Cubos-%C2%B7-FastStore-Features-(H2-2024)?node-id=1-23&node-type=canvas&t=EiFoKx4kFwgKhNEP-0)

<!--- Spread the knowledge: is there any content you used to create this
PR that is worth sharing? --->

<!--- Extra tip: adding references to related issues or mentioning
people important to this PR may be good for the documentation and
reviewing process --->

<em>You may erase this after checking them all 😉</em>

**PR Title and Commit Messages**

- [x] PR title and commit messages follow the [Conventional
Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification
- Available prefixes: `feat`, `fix`, `chore`, `docs`, `style`,
`refactor`, `ci` and `test`

**PR Description**

- [ ] Added a label according to the PR goal - `breaking change`, `bug`,
`contributing`, `performance`, `documentation`..

**Dependencies**

- [ ] Committed the `pnpm-lock.yaml` file when there were changes to the
packages

**Documentation**

- [x] PR description
- [ ] For documentation changes, ping `@Mariana-Caetano` to review and
update (Or submit a doc request)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

* **New Features**
* Added Quick Order Drawer component enabling streamlined product
ordering with header, product selection table, quantity adjustments, and
checkout from a side panel.

* **Documentation**
* Added Storybook examples demonstrating Quick Order Drawer with
multiple configuration scenarios.

* **Chores**
* Updated TypeScript React type definitions to latest compatible
versions.

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: renato <[email protected]>
Co-authored-by: Bruna Santos <[email protected]>
Co-authored-by: Arthur Andrade <[email protected]>
Tasks
[https://vtex-dev.atlassian.net/jira/software/projects/BE/boards/2868?selectedIssue=BE-69](https://vtex-dev.atlassian.net/jira/software/projects/BE/boards/2868?selectedIssue=BE-69)
[BE-70](https://vtex-dev.atlassian.net/jira/software/projects/BE/boards/2868?selectedIssue=BE-70)

Here's the completed PR description in English:

- Introduced `FileUploadCard` for file selection and upload
functionality, including drag-and-drop support.
- Added `FileUploadStatus` to display upload progress and error
handling.
- Updated index files to export new components and types.
- Enhanced `SearchInputField` to include an attachment button that
triggers the file upload card.
- Added styles for both new components to ensure proper UI integration.

## What's the purpose of this pull request?

This PR introduces a new file upload feature that allows users to
perform bulk searches by uploading CSV files. The feature provides a
modern, user-friendly interface with drag-and-drop support, real-time
upload status tracking, and comprehensive error handling to guide users
through the file upload process.

## How it works?

### FileUploadCard Component
- **File Selection**: Users can either click "Select file" button or
drag-and-drop files into the dropzone
- **Drag & Drop**: Visual feedback with border color and background
changes when dragging files
- **File Input**: Hidden file input that's always present in the DOM to
ensure file picker works in all states
- **Download Template**: Provides a CSV template download option for
users who need guidance on file format
- **Validation**: Only accepts CSV files (`.csv` extension)
- **States**: Manages upload states (uploading, completed, error) with
appropriate UI updates

### FileUploadStatus Component
Displays the current status of the uploaded file with three distinct
states:

1. **Uploading State**
   - Shows spinning CircleNotch icon
   - Displays "Uploading your file..." message
   - Shows filename

2. **Completed State**
   - Shows Table icon in green background
   - Displays filename and file size
   - Shows "Search" button to proceed with the uploaded file

3. **Error State**
   - Shows WarningOctagon icon in red background
- Special styling: light pink background (#FDF6F5) with red border
(#FFDFD9)
   - Displays error title and description in two lines
   - Shows two action buttons: "Download template" and "Select file"

### Error Types
The component handles six different error scenarios:
- **Unsupported**: Wrong file type (non-CSV files)
- **Unreadable**: File can't be parsed or is corrupted
- **Invalid Structure**: Missing headers or incorrect columns
- **Empty**: File has no data
- **Too Large**: File exceeds size limit
- **Unexpected**: Generic error for unknown issues

### Integration
- Added attachment icon button to `SearchInputField` component
- Clicking the attachment button toggles the `FileUploadCard` visibility
- Card appears as a dropdown below the search input
- Smooth animations for show/hide transitions

### Key Features
- **File validation**: Automatically checks file type on selection/drop
- **Error recovery**: Users can easily select a new file or download
template when errors occur
- **Responsive design**: Components adapt to container width
- **Accessibility**: Proper ARIA labels and keyboard navigation support
- **Visual feedback**: Icons, colors, and animations provide clear
status indication

## How to test it?

### Basic File Upload Flow
1. Navigate to a page with the search input
2. Click the attachment icon button (Paperclip icon)
3. The FileUploadCard should appear below the search input
4. Click "Select file" or drag-and-drop a CSV file
5. Observe the uploading state with spinning icon
6. After 2 seconds, see the completed state with "Search" button
7. Click the X button to remove the file and return to initial state

### Drag and Drop
1. Open the FileUploadCard
2. Drag a CSV file over the dropzone
3. Observe the visual feedback (border and background color change)
4. Drop the file to upload

### Error Handling - Unsupported File Type
1. Open the FileUploadCard
2. Select or drop a non-CSV file (e.g., .txt, .pdf, .xlsx)
3. Observe error state with red icon and pink background
4. Read error message: "Unsupported file type." / "Upload a CSV or use
the template provided."
5. Click "Download template" to get a sample CSV
6. Click "Select file" to try uploading again

### File Removal
1. Upload a file successfully
2. Click the X button in the top-right of the file status
3. Component should return to initial dropzone state


### Starters Deploy Preview

<!-- Add your deploy preview link here -->

## References

- [Phosphor Icons](https://phosphoricons.com/) - Icon library used for
UI elements
- [Conventional Commits](https://www.conventionalcommits.org/) - Commit
message format

## Checklist

<em>You may erase this after checking them all 😉</em>

**PR Title and Commit Messages**

- [ ] PR title and commit messages follow the [Conventional
Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification
- Available prefixes: `feat`, `fix`, `chore`, `docs`, `style`,
`refactor`, `ci` and `test`

**PR Description**

- [ ] Added a label according to the PR goal - `breaking change`, `bug`,
`contributing`, `performance`, `documentation`..

**Dependencies**

- [ ] Committed the `pnpm-lock.yaml` file when there were changes to the
packages

**Documentation**

- [ ] PR description


[BE-70]:
https://vtex-dev.atlassian.net/browse/BE-70?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

## Release Notes

* **New Features**
* File upload card component enabling file selection via drag-and-drop
or file picker with status indicators
* File upload status component displaying upload progress, success, and
error states with customizable error handling
  * Attachment button in search input for quick file upload access

* **Chores**
  * Added component styling and Storybook demonstrations

<sub>✏️ Tip: You can customize this high-level summary in your review
settings.</sub>

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Bruna Santos <[email protected]>
Co-authored-by: Arthur Andrade <[email protected]>
## What's the purpose of this pull request?

This pull request introduces a new file upload and CSV parsing feature
to the `components` package, including reusable hooks and UI components.
The main changes are the addition of a `FileUploadCard` component for
uploading files, a `useCSVParser` hook for parsing CSV files in a web
worker, and a `useFileUpload` hook for managing file upload errors and
validation. These new utilities are exported for use in other parts of
the application.

This PR it was created from vtex#3109 

## How it works?

**New hooks and utilities:**

* Added `useCSVParser` hook for parsing CSV files in a web worker, with
error handling and CSV template generation.
* Added `useFileUpload` hook to manage file upload errors, validation,
and rejection reasons.
* Exported new hooks from the hooks index for easier consumption.
* Added type exports for CSV parsing to the main index file.

**New UI components:**

* Added `FileUploadCard` component for file selection, drag-and-drop,
and template download, with error state and file validation.
* Added exports for `FileUploadCard` and `FileUploadStatus` components
and their types.

**Dependency updates:**

* Added `papaparse` to dependencies for running CSV parsing in a web
worker.

## How to test it?

![Nov-12-2025
14-49-47](https://github.com/user-attachments/assets/6aaf4cbd-4b2e-45ea-9a36-1278b8c2dc88)


### Starters Deploy Preview

<!--- Add a link to a deploy preview from `starter.store` with this
branch being used. --->

<!--- Tip: You can get an installable version of this branch from the
CodeSandbox generated when this PR is created. --->

## References

- [Card](https://vtex-dev.atlassian.net/browse/BE-71)
-
[Figma](https://www.figma.com/design/YjU7SKqgLar3oxCP3SwagX/B2B-%C2%B7-Order-entry?node-id=53-3753&t=khUOMzHdN5djYyKo-0)

## Checklist

<em>You may erase this after checking them all 😉</em>

**PR Title and Commit Messages**

- [x] PR title and commit messages follow the [Conventional
Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification
- Available prefixes: `feat`, `fix`, `chore`, `docs`, `style`,
`refactor`, `ci` and `test`

**PR Description**

- [ ] Added a label according to the PR goal - `breaking change`, `bug`,
`contributing`, `performance`, `documentation`..

**Dependencies**

- [ ] Committed the `pnpm-lock.yaml` file when there were changes to the
packages

**Documentation**

- [ ] PR description
- [ ] For documentation changes, ping `@Mariana-Caetano` to review and
update (Or submit a doc request)


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* CSV parsing with worker-backed parsing, template generation, Dropzone
upload UI and an Upload File dropdown; file-based search integration.

* **Enhancements**
* New file upload hooks, FileUploadCard and FileUploadStatus props for
richer status, customizable labels, and improved file name/size
formatting.
  * Template download and clearer upload error handling.

* **Refactor**
* Tightened public type signatures and expanded component/hook exports.

* **Style**
  * Added Dropzone and upload-related styles and Storybook stories.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Giuliana Rigaud <[email protected]>
Co-authored-by: renato <[email protected]>
Co-authored-by: Bruna Santos <[email protected]>
Co-authored-by: Arthur Andrade <[email protected]>
Co-authored-by: BrunaCubos <[email protected]>
Co-authored-by: Bruna Santos <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Everton Ataide <[email protected]>
@ataideverton
ataideverton changed the base branch from main to feat/quick-order-by-file-feature-branch February 25, 2026 13:07
Bruna Santos and others added 7 commits March 4, 2026 10:19
- Introduced `FileUploadCard` for file selection and upload functionality, including drag-and-drop support.
- Added `FileUploadStatus` to display upload progress and error handling.
- Updated index files to export new components and types.
- Enhanced `SearchInputField` to include an attachment button that triggers the file upload card.
- Added styles for both new components to ensure proper UI integration.

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 8

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx (1)

185-189: ⚠️ Potential issue | 🟠 Major

Validate against the configured accept prop, not a hardcoded .csv.

The component input accepts accept, but isValidFileType only allows .csv, which can produce false "unsupported" errors for configured extensions.

💡 Proposed fix
   const isValidFileType = (file: File): boolean => {
     const fileName = file.name.toLowerCase()
-    const validExtensions = ['.csv']
+    const validExtensions = accept
+      .split(',')
+      .map((ext) => ext.trim().toLowerCase())
+      .filter((ext) => ext.startsWith('.'))
+
+    if (validExtensions.length === 0) {
+      return true
+    }
+
     return validExtensions.some((ext) => fileName.endsWith(ext))
   }

Also applies to: 197-200, 239-242

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx` around
lines 185 - 189, isValidFileType currently hardcodes ['.csv']; update it to
validate against the component's accept prop in FileUploadCard by parsing the
accept string (e.g. ".csv,.txt,image/*,text/csv") into allowed extensions and
MIME patterns, then check the file by matching file.name endings for extensions
and file.type for MIME patterns; replace any other hardcoded checks (the other
occurrences of file-type validation in this component) to call the new
isValidFileType so validation honors the accept prop across FileUploadCard.
packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx (1)

22-24: ⚠️ Potential issue | 🟠 Major

ACCEPTED_FILE_TYPES excludes Excel files.

The dropzone only accepts text/csv, but the component handles Excel files via isExcelFile(). Users dragging .xlsx files will see a rejection toast. Update accepted types to include Excel MIME types.

Fix
 const ACCEPTED_FILE_TYPES = {
   'text/csv': ['.csv'],
+  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['.xlsx'],
+  'application/vnd.ms-excel': ['.xls'],
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`
around lines 22 - 24, ACCEPTED_FILE_TYPES currently only lists 'text/csv' so
Excel files are rejected even though UploadFileDropdown uses isExcelFile() to
handle them; update the ACCEPTED_FILE_TYPES constant to include Excel MIME types
(e.g. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' and
'application/vnd.ms-excel') mapped to the corresponding extensions ('.xlsx',
'.xls') so the dropzone will accept Excel files; keep the existing isExcelFile()
logic and any downstream Excel handling unchanged.
♻️ Duplicate comments (4)
packages/core/package.json (1)

104-104: ⚠️ Potential issue | 🔴 Critical

Avoid introducing xlsx@^0.18.5 without a security-approved plan.

If Excel parsing is not strictly required in this PR, removing this runtime dependency is the safer path.

💡 Minimal safe change (if Excel parsing is not needed yet)
-    "tsx": "^4.6.2",
-    "xlsx": "^0.18.5"
+    "tsx": "^4.6.2"
What are the current security advisories affecting npm package "xlsx" version "0.18.5", and is there a patched npm release available?
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/package.json` at line 104, The PR added a runtime dependency
"xlsx": "^0.18.5" in package.json without a security-approved plan; either
remove this dependency if Excel parsing isn't needed yet (delete the "xlsx"
entry) or, if needed, replace it with a security-reviewed version – run an npm
audit / check advisories for "[email protected]" and upgrade to the patched release
(or add a vetted alternative) and document the approval; look for the "xlsx"
dependency string in package.json to make the change and update the PR
description with the security advisory check results.
packages/components/src/molecules/Dropzone/Dropzone.tsx (1)

194-197: ⚠️ Potential issue | 🟠 Major

Preserve dropzone handlers by changing spread order.

otherProps is currently spread after getRootProps(), so consumer handlers can silently override critical drag/drop and click handlers.

💡 Proposed fix
-      {...rootProps}
-      {...accessibilityProps}
-      {...otherProps}
+      {...otherProps}
+      {...rootProps}
+      {...accessibilityProps}
       ref={mergedRef}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/components/src/molecules/Dropzone/Dropzone.tsx` around lines 194 -
197, Consumer event handlers in Dropzone are being able to override critical
drag/drop and click handlers because {...otherProps} is spread after
{...rootProps} and {...accessibilityProps}; move the spread order so
{...otherProps} is applied before the handlers returned by getRootProps (i.e.,
spread otherProps first, then spread rootProps and accessibilityProps) so that
the dropzone's root handlers (rootProps/accessibilityProps) take precedence over
consumer props; update the JSX where {...rootProps}, {...accessibilityProps},
{...otherProps}, ref={mergedRef} are used accordingly in Dropzone.tsx.
packages/core/src/sdk/product/useBulkProductsQuery.ts (1)

43-129: ⚠️ Potential issue | 🟠 Major

Add cancellation guards for async batches and fully reset state on empty input.

Without a cancellation guard, stale in-flight runs can overwrite fresh results. Also, the empty-SKU branch should clear previous error state.

💡 Proposed fix
   useEffect(() => {
+    let cancelled = false
+
     if (skus.length === 0) {
       setProducts([])
+      setError(null)
       setIsLoading(false)
       return
     }
@@
-        setProducts(results)
+        if (!cancelled) {
+          setProducts(results)
+        }
       } catch (err) {
-        setError(
-          err instanceof Error ? err : new Error('Failed to fetch products')
-        )
-        setProducts([])
+        if (!cancelled) {
+          setError(
+            err instanceof Error ? err : new Error('Failed to fetch products')
+          )
+          setProducts([])
+        }
       } finally {
-        setIsLoading(false)
+        if (!cancelled) {
+          setIsLoading(false)
+        }
       }
     }
 
     fetchProducts()
-  }, [skusKey, channel, locale, skus.length])
+    return () => {
+      cancelled = true
+    }
+  }, [skusKey, channel, locale])
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/sdk/product/useBulkProductsQuery.ts` around lines 43 - 129,
The effect lacks cancellation guards and doesn't clear previous error when skus
is empty; add a cancellation flag (e.g., let cancelled = false) at the top of
the useEffect and return a cleanup that sets cancelled = true, then before every
state write in fetchProducts (setIsLoading, setError, setProducts) check if
cancelled and skip updates to avoid stale in-flight overwrites; also in the
early-return branch for skus.length === 0 call setError(null) in addition to
setProducts([]) and setIsLoading(false) so prior errors are cleared; reference
functions/variables useEffect, fetchProducts, BATCH_SIZE, BATCH_DELAY_MS,
setProducts, setError, setIsLoading, skus.length, skusKey when applying the
changes.
packages/core/src/components/search/SearchInput/SearchInput.tsx (1)

412-453: ⚠️ Potential issue | 🟠 Major

Remove the hardcoded 2s post-fetch delay before rendering results.

Line 452 introduces a fixed wait that slows every successful quick-order flow and looks like debug/test scaffolding.

Suggested simplification
-        // Add artificial delay to test loading state
-        setIsLoadingWithDelay(true)
-
-        const timeoutId = setTimeout(() => {
           const convertedProducts: Product[] = []
@@
-          setQuickOrderProducts(convertedProducts)
-          setIsLoadingWithDelay(false)
+          setQuickOrderProducts(convertedProducts)
+          setIsLoadingWithDelay(false)
@@
-        }, 2000) // 2 second delay for testing
-
-        return () => {
-          clearTimeout(timeoutId)
-        }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx` around lines
412 - 453, The artificial 2s setTimeout wrapper around the post-fetch processing
should be removed so results render immediately: inline the code currently
inside the timeout and call it immediately after fetch; remove the timeoutId and
the hardcoded delay, ensure setIsLoadingWithDelay(true) is not left toggled
(setIsLoadingWithDelay(false) after processing or remove this test-only flag
entirely), and keep the existing logic that builds convertedProducts via
convertProductToQuickOrder and updates setQuickOrderProducts,
setIsQuickOrderDrawerOpen, setFileUploadVisible, and setNoProductsError without
the artificial delay.
🧹 Nitpick comments (6)
packages/components/src/molecules/Dropzone/Dropzone.tsx (1)

96-104: Remove the duplicated DropzoneState declaration.

DropzoneState is declared twice with the same shape; keep a single declaration to avoid accidental divergence.

💡 Proposed cleanup
 export interface DropzoneState {
   acceptedFiles: File[]
   fileRejections: FileRejection[]
 }
-
-export interface DropzoneState {
-  acceptedFiles: File[]
-  fileRejections: FileRejection[]
-}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/components/src/molecules/Dropzone/Dropzone.tsx` around lines 96 -
104, There are two identical DropzoneState interface declarations; remove the
duplicate so only one DropzoneState interface remains to prevent divergence.
Locate the repeated declarations of DropzoneState in Dropzone.tsx and delete one
of them (keeping the single declaration that defines acceptedFiles: File[] and
fileRejections: FileRejection[]), then run a type-check to ensure no references
break.
packages/components/src/molecules/FileUploadStatus/FileUploadStatus.tsx (1)

224-231: Minor: getErrorMessage() called twice.

The function is called on both lines 227 and 230, executing the logic twice per render. Consider storing the result in a variable.

Optimization
+          const errorMsg = getErrorMessage()
           {state === FileUploadState.Error ? (
             <>
               <p data-fs-file-upload-status-text-error>
-                {getErrorMessage().title}
+                {errorMsg.title}
               </p>
               <p data-fs-file-upload-status-text-error>
-                {getErrorMessage().description}
+                {errorMsg.description}
               </p>
             </>
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/components/src/molecules/FileUploadStatus/FileUploadStatus.tsx`
around lines 224 - 231, When rendering the error state in FileUploadStatus
(where state === FileUploadState.Error), avoid calling getErrorMessage() twice;
compute const error = getErrorMessage() once at the top of the FileUploadStatus
render (or inside the Error branch) and use error.title and error.description
for the two <p> elements so the message logic runs only once per render.
packages/core/src/sdk/product/convertProductToQuickOrder.ts (1)

25-31: Type assertion and magic number.

The type assertion on line 25 indicates quantity isn't in the GraphQL type definition. This is now correct since ProductDetailsFragment was updated to include quantity. Consider removing the assertion if the generated types are updated.

The 999999 fallback is a reasonable default but could be extracted as a named constant for clarity.

Optional improvement
+const DEFAULT_HIGH_INVENTORY = 999999
+
 // ...
 
-      ? 999999 // Default to high inventory when InStock but quantity not provided
+      ? DEFAULT_HIGH_INVENTORY // Default to high inventory when InStock but quantity not provided
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/sdk/product/convertProductToQuickOrder.ts` around lines 25
- 31, The code uses a manual type assertion for offer.quantity and a magic
number fallback; update convertProductToQuickOrder to remove the unnecessary
cast by using offer.quantity directly (the GraphQL ProductDetailsFragment now
includes quantity) and extract the 999999 fallback into a named constant (e.g.,
DEFAULT_IN_STOCK_QUANTITY) at module scope, then use that constant when
computing inventory so the intent is clear and types come from the generated
fragment.
packages/components/src/hooks/useCSVParser.ts (1)

44-65: Unstable options reference may cause unnecessary re-renders.

The useCallback depends on options, which is an object. If the caller doesn't memoize options, onParseFile will be recreated on every render. Consider destructuring the needed options or documenting that callers should memoize.

Alternative: destructure needed values
-export function useCSVParser(options: CSVParserOptions = {}) {
+export function useCSVParser({
+  delimiter,
+  skipEmptyLines,
+  skuColumnNames,
+  quantityColumnNames,
+  chunkSize,
+  onProgress,
+}: CSVParserOptions = {}) {
   // ...
   const onParseFile = useCallback(
     async (file: File): Promise<CSVData | null> => {
       // ...
-      const result = await parseCSVFile(file, options)
+      const result = await parseCSVFile(file, {
+        delimiter,
+        skipEmptyLines,
+        skuColumnNames,
+        quantityColumnNames,
+        chunkSize,
+        onProgress,
+      })
       // ...
     },
-    [options]
+    [delimiter, skipEmptyLines, skuColumnNames, quantityColumnNames, chunkSize, onProgress]
   )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/components/src/hooks/useCSVParser.ts` around lines 44 - 65,
onParseFile's useCallback currently depends on the whole options object causing
unnecessary re-creations when callers pass a new options reference; fix by
either destructuring the specific option fields you need from options (e.g.,
delimiter, hasHeader, encoding) and use those primitives in the dependency array
of the callback, or document/require that callers pass a memoized options object
and add a comment to that effect; update the dependency array of the useCallback
in useCSVParser.ts to list the exact option properties used (or replace options
with a memoizedOptions variable) and keep references to parseCSVFile and
setError/setIsParsing unchanged.
packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx (1)

214-214: Replace readAsBinaryString with readAsArrayBuffer and update the XLSX parsing type. readAsBinaryString is deprecated and less performant than ArrayBuffer. Use readAsArrayBuffer with type: "array" for XLSX.read() to improve performance and future-proof the code.

Proposed fix
-    reader.readAsBinaryString(file)
+    reader.readAsArrayBuffer(file)

And update the read call:

-        const workbook = XLSX.read(data, { type: 'binary' })
+        const workbook = XLSX.read(data, { type: 'array' })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`
at line 214, In UploadFileDropdown (reader usage), replace the deprecated
reader.readAsBinaryString(file) with reader.readAsArrayBuffer(file) and when
calling XLSX.read(...) pass the ArrayBuffer result with type: "array" (use
reader.result as the ArrayBuffer) so the XLSX.parse receives an ArrayBuffer
instead of a binary string; update any downstream handling that assumes a string
to handle an ArrayBuffer accordingly (look for reader.readAsBinaryString and the
XLSX.read(...) call in UploadFileDropdown.tsx).
packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx (1)

275-277: Remove unnecessary cast and use colSpan directly.

TableCellProps extends HTMLAttributes<HTMLTableCellElement>, which already includes colSpan. The cast bypasses this type safety unnecessarily.

Suggested change
-                  {...({
-                    colSpan: 5,
-                  } as React.HTMLAttributes<HTMLTableCellElement>)}
+                  colSpan={5}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`
around lines 275 - 277, In QuickOrderDrawerProducts (the JSX returning the table
row/cell), remove the unnecessary type cast around the spreaded object and pass
colSpan directly (replace {...({ colSpan: 5 } as
React.HTMLAttributes<HTMLTableCellElement>)} with colSpan={5}); TableCellProps
already extends HTMLAttributes<HTMLTableCellElement> so the cast is redundant
and bypasses type safety—use the direct prop on the TableCell element.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/components/src/hooks/useCSVParser.ts`:
- Around line 257-259: Remove the leftover debug statement console.log('')
inside the CSV parsing loop: in the block where results.data.forEach((row: any,
index: number) => { ... }) (which computes globalRowIndex using processedRows +
index), delete the console.log('') line and ensure no other stray debug console
calls remain in useCSVParser (e.g., console.log/debug) so parsing runs without
spurious output.

In `@packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx`:
- Around line 175-183: The effect in FileUploadCard should handle the
isUploading=true transition and the file-type validator should respect the
component's accept prop: update the useEffect that currently checks
hasError/selectedFile/isUploading to include an explicit branch when isUploading
is true that calls setUploadState(FileUploadState.Uploading) and clears any
error via setErrorType(undefined); also update the isValidFileType function to
derive accepted extensions/MIME types from the accept prop (falling back to the
existing ".csv" check only if accept is undefined), and use that parsed list to
validate selectedFile.type and selectedFile.name so the validator matches what
the input allows.

In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`:
- Around line 126-133: The skeleton rows in QuickOrderDrawerProducts currently
render 4 TableCell skeletons per TableRow which misaligns with the table's 5
headers; update the skeleton rendering in the component (the Array.from(...) map
that returns TableRow with TableCell skeletons) to render the same number of
cells as the table headers—either change the hardcoded length from 4 to 5 or
derive the count from the headers/columns array used by the table so TableRow
and TableCell skeletons match the real column count.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx`:
- Around line 197-204: Move the usePage hook call out of the try/catch so it’s
invoked at the top-level of the SearchInput component; call const pageContext =
usePage<{ globalSettings?: { fileUpload?: any } }>() unconditionally, then
derive fileUploadConfig from pageContext with a safeguarded expression (e.g.,
fileUploadConfig = pageContext?.globalSettings?.fileUpload ?? undefined) and
keep any try/catch only around operations that may throw (not the hook). Update
the code around fileUploadConfig in SearchInput/SearchInput.tsx to reference the
top-level usePage result and remove the hook from the try block to satisfy React
Rules of Hooks.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`:
- Around line 176-187: The current map callback in UploadFileDropdown (the .map
that reads skuIndex/quantityIndex) throws on the first invalid quantity,
aborting the whole import; change it to validate each row without throwing: for
each row parse sku and quantity, if quantity is invalid push an error entry into
a local errors array (include row number and offending value) and skip adding
that row to the results, otherwise push the { sku, quantity } into the results
array; after processing all rows return/emit both the valid results and the
collected errors (or surface them to the existing CSV parser error-handling
path) so a single bad row doesn’t reject the entire file.

In `@packages/core/src/sdk/product/convertProductToQuickOrder.ts`:
- Around line 73-76: The image mapping in convertProductToQuickOrder.ts assumes
product.image[0] exists; add a defensive check for an empty or missing
product.image array inside the convertProductToQuickOrder function (or the scope
where image is constructed) and handle it explicitly — either return null/skip
creating the quick-order product early or set the image field to null and emit a
warning/log via the same logger used elsewhere; reference product.image, the
image object construction (url/alternateName) and convertProductToQuickOrder to
locate where to add this guard.

In `@packages/core/src/styles/global/index.scss`:
- Around line 7-8: The import in packages/core/src/styles/global/index.scss uses
a disallowed `.scss` extension; update the `@import`
"@faststore/ui/src/styles/components.scss"; statement to remove the extension so
it reads `@import` "@faststore/ui/src/styles/components"; ensuring it follows the
project's Stylelint rule against explicit .scss extensions.

In `@packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss`:
- Line 111: The CSS rule uses the nonstandard casing "currentColor" for the fill
property which fails Stylelint; update the value in
packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss by replacing
fill: currentColor; with the lowercase variant fill: currentcolor; so the
declaration (in the selector that sets fill) conforms to Stylelint expectations.

---

Outside diff comments:
In `@packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx`:
- Around line 185-189: isValidFileType currently hardcodes ['.csv']; update it
to validate against the component's accept prop in FileUploadCard by parsing the
accept string (e.g. ".csv,.txt,image/*,text/csv") into allowed extensions and
MIME patterns, then check the file by matching file.name endings for extensions
and file.type for MIME patterns; replace any other hardcoded checks (the other
occurrences of file-type validation in this component) to call the new
isValidFileType so validation honors the accept prop across FileUploadCard.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`:
- Around line 22-24: ACCEPTED_FILE_TYPES currently only lists 'text/csv' so
Excel files are rejected even though UploadFileDropdown uses isExcelFile() to
handle them; update the ACCEPTED_FILE_TYPES constant to include Excel MIME types
(e.g. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' and
'application/vnd.ms-excel') mapped to the corresponding extensions ('.xlsx',
'.xls') so the dropzone will accept Excel files; keep the existing isExcelFile()
logic and any downstream Excel handling unchanged.

---

Duplicate comments:
In `@packages/components/src/molecules/Dropzone/Dropzone.tsx`:
- Around line 194-197: Consumer event handlers in Dropzone are being able to
override critical drag/drop and click handlers because {...otherProps} is spread
after {...rootProps} and {...accessibilityProps}; move the spread order so
{...otherProps} is applied before the handlers returned by getRootProps (i.e.,
spread otherProps first, then spread rootProps and accessibilityProps) so that
the dropzone's root handlers (rootProps/accessibilityProps) take precedence over
consumer props; update the JSX where {...rootProps}, {...accessibilityProps},
{...otherProps}, ref={mergedRef} are used accordingly in Dropzone.tsx.

In `@packages/core/package.json`:
- Line 104: The PR added a runtime dependency "xlsx": "^0.18.5" in package.json
without a security-approved plan; either remove this dependency if Excel parsing
isn't needed yet (delete the "xlsx" entry) or, if needed, replace it with a
security-reviewed version – run an npm audit / check advisories for
"[email protected]" and upgrade to the patched release (or add a vetted alternative)
and document the approval; look for the "xlsx" dependency string in package.json
to make the change and update the PR description with the security advisory
check results.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx`:
- Around line 412-453: The artificial 2s setTimeout wrapper around the
post-fetch processing should be removed so results render immediately: inline
the code currently inside the timeout and call it immediately after fetch;
remove the timeoutId and the hardcoded delay, ensure setIsLoadingWithDelay(true)
is not left toggled (setIsLoadingWithDelay(false) after processing or remove
this test-only flag entirely), and keep the existing logic that builds
convertedProducts via convertProductToQuickOrder and updates
setQuickOrderProducts, setIsQuickOrderDrawerOpen, setFileUploadVisible, and
setNoProductsError without the artificial delay.

In `@packages/core/src/sdk/product/useBulkProductsQuery.ts`:
- Around line 43-129: The effect lacks cancellation guards and doesn't clear
previous error when skus is empty; add a cancellation flag (e.g., let cancelled
= false) at the top of the useEffect and return a cleanup that sets cancelled =
true, then before every state write in fetchProducts (setIsLoading, setError,
setProducts) check if cancelled and skip updates to avoid stale in-flight
overwrites; also in the early-return branch for skus.length === 0 call
setError(null) in addition to setProducts([]) and setIsLoading(false) so prior
errors are cleared; reference functions/variables useEffect, fetchProducts,
BATCH_SIZE, BATCH_DELAY_MS, setProducts, setError, setIsLoading, skus.length,
skusKey when applying the changes.

---

Nitpick comments:
In `@packages/components/src/hooks/useCSVParser.ts`:
- Around line 44-65: onParseFile's useCallback currently depends on the whole
options object causing unnecessary re-creations when callers pass a new options
reference; fix by either destructuring the specific option fields you need from
options (e.g., delimiter, hasHeader, encoding) and use those primitives in the
dependency array of the callback, or document/require that callers pass a
memoized options object and add a comment to that effect; update the dependency
array of the useCallback in useCSVParser.ts to list the exact option properties
used (or replace options with a memoizedOptions variable) and keep references to
parseCSVFile and setError/setIsParsing unchanged.

In `@packages/components/src/molecules/Dropzone/Dropzone.tsx`:
- Around line 96-104: There are two identical DropzoneState interface
declarations; remove the duplicate so only one DropzoneState interface remains
to prevent divergence. Locate the repeated declarations of DropzoneState in
Dropzone.tsx and delete one of them (keeping the single declaration that defines
acceptedFiles: File[] and fileRejections: FileRejection[]), then run a
type-check to ensure no references break.

In `@packages/components/src/molecules/FileUploadStatus/FileUploadStatus.tsx`:
- Around line 224-231: When rendering the error state in FileUploadStatus (where
state === FileUploadState.Error), avoid calling getErrorMessage() twice; compute
const error = getErrorMessage() once at the top of the FileUploadStatus render
(or inside the Error branch) and use error.title and error.description for the
two <p> elements so the message logic runs only once per render.

In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`:
- Around line 275-277: In QuickOrderDrawerProducts (the JSX returning the table
row/cell), remove the unnecessary type cast around the spreaded object and pass
colSpan directly (replace {...({ colSpan: 5 } as
React.HTMLAttributes<HTMLTableCellElement>)} with colSpan={5}); TableCellProps
already extends HTMLAttributes<HTMLTableCellElement> so the cast is redundant
and bypasses type safety—use the direct prop on the TableCell element.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`:
- Line 214: In UploadFileDropdown (reader usage), replace the deprecated
reader.readAsBinaryString(file) with reader.readAsArrayBuffer(file) and when
calling XLSX.read(...) pass the ArrayBuffer result with type: "array" (use
reader.result as the ArrayBuffer) so the XLSX.parse receives an ArrayBuffer
instead of a binary string; update any downstream handling that assumes a string
to handle an ArrayBuffer accordingly (look for reader.readAsBinaryString and the
XLSX.read(...) call in UploadFileDropdown.tsx).

In `@packages/core/src/sdk/product/convertProductToQuickOrder.ts`:
- Around line 25-31: The code uses a manual type assertion for offer.quantity
and a magic number fallback; update convertProductToQuickOrder to remove the
unnecessary cast by using offer.quantity directly (the GraphQL
ProductDetailsFragment now includes quantity) and extract the 999999 fallback
into a named constant (e.g., DEFAULT_IN_STOCK_QUANTITY) at module scope, then
use that constant when computing inventory so the intent is clear and types come
from the generated fragment.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9902da27-66b2-4bc7-9920-bd9b6b1e8cc0

📥 Commits

Reviewing files that changed from the base of the PR and between 6a0093d and 609f9f5.

⛔ Files ignored due to path filters (5)
  • package.json is excluded by none and included by none
  • packages/core/@generated/gql.ts is excluded by !**/@generated/**, !**/@generated/** and included by packages/**
  • packages/core/@generated/graphql.ts is excluded by !**/@generated/**, !**/@generated/** and included by packages/**
  • packages/core/public/icons.svg is excluded by !**/*.svg and included by packages/**
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (36)
  • packages/components/package.json
  • packages/components/src/hooks/index.ts
  • packages/components/src/hooks/useCSVParser.ts
  • packages/components/src/hooks/useFileUpload.ts
  • packages/components/src/index.ts
  • packages/components/src/molecules/Dropzone/Dropzone.tsx
  • packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx
  • packages/components/src/molecules/FileUploadStatus/FileUploadStatus.tsx
  • packages/components/src/molecules/SearchInputField/SearchInputField.tsx
  • packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawer.tsx
  • packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerFooter.tsx
  • packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerHeader.tsx
  • packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx
  • packages/components/src/organisms/QuickOrderDrawer/index.ts
  • packages/components/src/organisms/QuickOrderDrawer/provider/QuickOrderDrawerProvider.tsx
  • packages/core/cms/faststore/content-types.json
  • packages/core/cms/faststore/sections.json
  • packages/core/package.json
  • packages/core/src/components/navigation/Navbar/Navbar.tsx
  • packages/core/src/components/search/SearchInput/SearchInput.tsx
  • packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx
  • packages/core/src/components/search/UploadFileDropdown/section.module.scss
  • packages/core/src/components/sections/Navbar/Navbar.tsx
  • packages/core/src/components/sections/Navbar/section.module.scss
  • packages/core/src/components/sections/ProductDetails/ProductDetails.tsx
  • packages/core/src/sdk/product/convertProductToQuickOrder.ts
  • packages/core/src/sdk/product/useBulkProductsQuery.ts
  • packages/core/src/styles/global/index.scss
  • packages/core/src/utils/globalSettings.ts
  • packages/core/src/utils/utilities.ts
  • packages/storybook/stories/fileupload.stories.tsx
  • packages/storybook/stories/quick-order-drawer.stories.tsx
  • packages/ui/src/components/molecules/FileUploadCard/styles.scss
  • packages/ui/src/components/molecules/SearchInputField/styles.scss
  • packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss
  • packages/ui/src/index.ts
💤 Files with no reviewable changes (1)
  • packages/ui/src/components/molecules/SearchInputField/styles.scss
🚧 Files skipped from review as they are similar to previous changes (10)
  • packages/core/cms/faststore/sections.json
  • packages/ui/src/components/molecules/FileUploadCard/styles.scss
  • packages/core/src/components/navigation/Navbar/Navbar.tsx
  • packages/components/src/molecules/SearchInputField/SearchInputField.tsx
  • packages/storybook/stories/quick-order-drawer.stories.tsx
  • packages/core/src/utils/utilities.ts
  • packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerFooter.tsx
  • packages/components/src/hooks/useFileUpload.ts
  • packages/components/src/organisms/QuickOrderDrawer/index.ts
  • packages/components/src/hooks/index.ts

Everton Ataide added 2 commits March 4, 2026 20:57

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

♻️ Duplicate comments (6)
packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx (1)

126-133: ⚠️ Potential issue | 🟡 Minor

Skeleton columns still don’t match the table shape.

On Line 119 there are 5 table headers, but Line 130 renders only 4 skeleton cells. This keeps loading rows visually misaligned.

Proposed fix
- {Array.from({
-   length: 4,
- }).map((_, cellIndex) => {
+ {Array.from({
+   length: 5,
+ }).map((_, cellIndex) => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`
around lines 126 - 133, The skeleton row rendering in
QuickOrderDrawerProducts.tsx uses Array.from({ length: 4 }) to generate 4
TableCell skeletons while the table header (rendered around Line 119) has 5
headers; update the skeleton generation to match the header count (make the
inner Array.from length equal to 5 or derive it from the headers array) so each
TableRow in the skeleton renders the same number of TableCell elements as the
table headers (adjust the map that creates TableCell with key
`table-cell-skeleton-${cellIndex}` accordingly).
packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx (1)

175-183: ⚠️ Potential issue | 🟡 Minor

A single invalid quantity still aborts the full XLSX import.

This is still all-or-nothing due to throwing inside .map; one bad row discards all valid rows. Consider collecting row-level errors and continuing transformation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`
around lines 175 - 183, In UploadFileDropdown (inside the .map callback that
reads skuIndex and quantityIndex) stop throwing on invalid quantity; instead
create a local errors array (e.g., rowErrors) and for each row validate
quantity, pushing a descriptive error (row id/number, SKU, invalid value) when
isNaN or quantity < 0 and skip adding that row to the output; continue
transforming valid rows into the resulting payload (e.g., validRows) and after
the map/transform, surface rowErrors (set component state or return them to the
caller / show a toast) while proceeding with importing validRows so a single bad
row no longer aborts the whole XLSX import.
packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx (2)

185-189: ⚠️ Potential issue | 🟠 Major

File type validation should honor the accept prop.

Line 187 hardcodes ['.csv'], which can disagree with the input accept (Line 311) and reject files the UI allows.

Suggested adjustment
 const isValidFileType = (file: File): boolean => {
   const fileName = file.name.toLowerCase()
-  const validExtensions = ['.csv']
-  return validExtensions.some((ext) => fileName.endsWith(ext))
+  const allowed = (accept || '.csv')
+    .split(',')
+    .map((v) => v.trim().toLowerCase())
+    .filter(Boolean)
+
+  return allowed.some((rule) => {
+    if (rule.startsWith('.')) return fileName.endsWith(rule)
+    if (rule.endsWith('/*')) return file.type.toLowerCase().startsWith(rule.slice(0, -1))
+    return file.type.toLowerCase() === rule
+  })
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx` around
lines 185 - 189, The file-type check in isValidFileType currently hardcodes
validExtensions = ['.csv'], which can conflict with the component prop accept
used by the file input; update isValidFileType (in FileUploadCard) to derive
allowed extensions/types from the component's accept prop (falling back to
current behavior if accept is empty), parse accept into a list of
extensions/MIME types, and validate the incoming File by comparing
file.name/file.type against that parsed list so the validation matches what the
UI input allows.

175-183: ⚠️ Potential issue | 🟠 Major

Sync effect should handle isUploading=true and not override local unsupported errors.

On Line 179, the Completed branch can clobber a locally set unsupported error, and there is no explicit transition for parent-driven isUploading=true.

Suggested adjustment
 useEffect(() => {
-  if (hasError && selectedFile) {
-    setUploadState(FileUploadState.Error)
-    setErrorType(errorTypeProp ?? 'invalid-structure')
-  } else if (!hasError && selectedFile && !isUploading) {
-    setUploadState(FileUploadState.Completed)
-    setErrorType(undefined)
-  }
-}, [hasError, selectedFile, isUploading, errorTypeProp])
+  if (!selectedFile) return
+
+  if (hasError) {
+    setUploadState(FileUploadState.Error)
+    setErrorType(errorTypeProp ?? 'invalid-structure')
+    return
+  }
+
+  if (isUploading) {
+    setUploadState(FileUploadState.Uploading)
+    setErrorType(undefined)
+    return
+  }
+
+  if (errorType === 'unsupported') return
+
+  setUploadState(FileUploadState.Completed)
+  setErrorType(undefined)
+}, [hasError, selectedFile, isUploading, errorTypeProp, errorType])
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx` around
lines 175 - 183, The effect in useEffect that synchronizes parent-driven props
currently sets Completed and clears errorType even when a local 'unsupported'
error exists and doesn't handle the case when isUploading becomes true; update
the effect so: if isUploading && selectedFile =>
setUploadState(FileUploadState.Uploading) and do not clear errorType; if
hasError && selectedFile => setUploadState(FileUploadState.Error) and
setErrorType(errorTypeProp ?? 'invalid-structure'); otherwise if !hasError &&
selectedFile && !isUploading => only set Completed and clear errorType when the
current errorType (or errorTypeProp) is not 'unsupported' (preserve local
'unsupported'); use the existing functions setUploadState, setErrorType and
props hasError, selectedFile, isUploading, errorTypeProp, and enum
FileUploadState to locate and implement the checks.
packages/core/src/components/search/SearchInput/SearchInput.tsx (2)

417-458: ⚠️ Potential issue | 🟠 Major

Remove the hardcoded 2s delay from quick-order product hydration.

Line 457 introduces an artificial delay in the main flow, which adds avoidable latency and leaves test scaffolding in production code.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx` around lines
417 - 458, The code introduces an artificial 2s setTimeout in the quick-order
hydration flow (see setIsLoadingWithDelay, timeoutId, setQuickOrderProducts,
setIsQuickOrderDrawerOpen) which causes unnecessary production latency; remove
the hardcoded setTimeout and run the hydration logic immediately (or replace it
with a configurable/test-only hook) so fetchedProducts are converted and state
(setQuickOrderProducts, setIsQuickOrderDrawerOpen, setFileUploadVisible,
setNoProductsError, setIsLoadingWithDelay) is updated without the fixed delay.

198-205: ⚠️ Potential issue | 🔴 Critical

Call usePage at top level; current try/catch placement violates Hooks rules.

Line 201 invokes a hook inside try, which breaks hook ordering guarantees and matches the lint error.

Suggested adjustment
-    let fileUploadConfig
-    try {
-      const pageContext = usePage<{ globalSettings?: { fileUpload?: any } }>()
-      fileUploadConfig = pageContext?.globalSettings?.fileUpload
-    } catch {
-      fileUploadConfig = undefined
-    }
+    const pageContext = usePage<{ globalSettings?: { fileUpload?: unknown } }>()
+    const fileUploadConfig = pageContext?.globalSettings?.fileUpload
#!/bin/bash
# Verify hook placement and surrounding control flow
rg -n -C4 'try \{|usePage<|catch \{' packages/core/src/components/search/SearchInput/SearchInput.tsx

As per coding guidelines "Ensure React hooks follow rules of hooks (no conditional hooks, proper dependencies)".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx` around lines
198 - 205, The hook usePage must be called at the top level to respect React
Hooks rules: move the call out of the try/catch so that const pageContext =
usePage<{ globalSettings?: { fileUpload?: any } }>() is executed unconditionally
(e.g., at the start of the SearchInput component function), then derive
fileUploadConfig from pageContext (fileUploadConfig =
pageContext?.globalSettings?.fileUpload) and remove the try/catch around
usePage; ensure the symbol fileUploadConfig and the usePage invocation in
SearchInput are updated accordingly and any necessary null/undefined checks
remain after the top-level hook call.
🧹 Nitpick comments (2)
packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx (2)

124-142: Flatten the nested JSX conditional for table body states.

Line 124 currently starts a nested ternary (loading -> products -> empty), which is harder to scan and maintain. A flat branch (early-return helper or precomputed bodyContent) would read cleaner.

As per coding guidelines, packages/**/*.{ts,tsx} should “Prefer flat conditionals over nested ifs: combine conditions with && or use early returns to avoid deep nesting and improve readability.”

Also applies to: 271-298

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`
around lines 124 - 142, The JSX currently nests a ternary at the table body
using showSkeleton ? ... : products.length > 0 ? ... : ...; refactor
QuickOrderDrawerProducts to compute a flat bodyContent (or return early) before
the JSX render: evaluate showSkeleton first to render the skeleton rows (using
TableRow/TableCell/Skeleton), else check products.length to render product rows,
else render the empty-state row; then use the single {bodyContent} in the table
body to remove the nested ternary and improve readability.

276-278: Remove the unnecessary as React.HTMLAttributes<...> type assertion.

TableCellProps already extends HTMLAttributes<HTMLTableCellElement>, so colSpan is natively supported. Use colSpan={5} directly instead of the spread cast.

Proposed fix
- {...({
-   colSpan: 5,
- } as React.HTMLAttributes<HTMLTableCellElement>)}
+ colSpan={5}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`
around lines 276 - 278, In QuickOrderDrawerProducts.tsx remove the unnecessary
type assertion spread and set the colspan directly: replace the JSX spread
{...({ colSpan: 5 } as React.HTMLAttributes<HTMLTableCellElement>)} with a
direct prop colSpan={5} on the TableCell element (the component/render block
where colSpan is applied inside QuickOrderDrawerProducts), since TableCellProps
already includes HTMLAttributes and colSpan is supported natively.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/components/CHANGELOG.md`:
- Around line 18-20: The changelog has an invalid heading jump (MD001): the top
heading "[3.98.0-dev.0] (2026-02-24)" is level-1 while the subsequent "###
Features" is level-3; change the release heading "[3.98.0-dev.0] (2026-02-24)"
from a single "#" to "##" so the "### Features" is a valid child heading,
ensuring consistent Markdown heading hierarchy in CHANGELOG.md.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx`:
- Around line 577-603: The prop fileUploadCardProps is optional but is being
dereferenced directly (e.g., fileUploadCardProps.title,
fileUploadCardProps.fileInputAriaLabel) which can throw if undefined; fix by
reading from a safe merged object (e.g., create a local
mergedFileUploadCardProps = { ...DEFAULT_FILE_UPLOAD_CARD_PROPS,
...(fileUploadCardProps ?? {}) } or use optional
chaining/fileUploadCardProps?.title everywhere) and then use
mergedFileUploadCardProps.title, mergedFileUploadCardProps.fileInputAriaLabel,
etc., for the JSX props (keep the final spread but replace direct dereferences
with values from the merged object) so the component never dereferences
undefined.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`:
- Around line 286-311: The Excel parsing branch (isExcelFile -> parseXLSXFile)
is never reached because the dropzone/file picker still only accepts CSV; update
the file acceptance configuration so .xls and .xlsx (and appropriate MIME types)
are allowed. Locate the component that configures accepted file types for the
upload (the accept prop or Dropzone configuration used alongside
onParseFile/isExcelFile) and add the Excel extensions/MIME types alongside CSV;
ensure isExcelFile and parseXLSXFile remain unchanged so Excel files flow into
the existing Excel parsing branch and non-Excel files still go to onParseFile.
- Around line 141-153: The header-detection in UploadFileDropdown (skuIndex and
quantityIndex) is too permissive because it uses
header?.toLowerCase().includes('id'|'product'|'amount'), which can match
unrelated columns; replace these includes checks with normalized exact matching
against explicit alias lists (e.g., skuAliases and quantityAliases) by
normalizing each header (trim, toLowerCase, collapse non-alphanumeric to a
canonical token) and using aliases.includes(normalizedHeader) or a whole-word
regex match per header; update the skuIndex and quantityIndex findIndex calls to
use that normalized-equals check and keep an explicit fallback/validation path
if no header is found.
- Line 16: Remove the top-level import of XLSX and instead lazy-load it inside
the Excel parsing path: make parseXLSXFile async (or ensure callers await it)
and do a dynamic import like const XLSX = await import('xlsx') (or const {
default: XLSX } = await import('xlsx') if required) inside parseXLSXFile before
any XLSX.* calls, so the heavy module is only loaded when parseXLSXFile is
invoked; update UploadFileDropdown usages that call parseXLSXFile to await the
result if necessary.

---

Duplicate comments:
In `@packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx`:
- Around line 185-189: The file-type check in isValidFileType currently
hardcodes validExtensions = ['.csv'], which can conflict with the component prop
accept used by the file input; update isValidFileType (in FileUploadCard) to
derive allowed extensions/types from the component's accept prop (falling back
to current behavior if accept is empty), parse accept into a list of
extensions/MIME types, and validate the incoming File by comparing
file.name/file.type against that parsed list so the validation matches what the
UI input allows.
- Around line 175-183: The effect in useEffect that synchronizes parent-driven
props currently sets Completed and clears errorType even when a local
'unsupported' error exists and doesn't handle the case when isUploading becomes
true; update the effect so: if isUploading && selectedFile =>
setUploadState(FileUploadState.Uploading) and do not clear errorType; if
hasError && selectedFile => setUploadState(FileUploadState.Error) and
setErrorType(errorTypeProp ?? 'invalid-structure'); otherwise if !hasError &&
selectedFile && !isUploading => only set Completed and clear errorType when the
current errorType (or errorTypeProp) is not 'unsupported' (preserve local
'unsupported'); use the existing functions setUploadState, setErrorType and
props hasError, selectedFile, isUploading, errorTypeProp, and enum
FileUploadState to locate and implement the checks.

In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`:
- Around line 126-133: The skeleton row rendering in
QuickOrderDrawerProducts.tsx uses Array.from({ length: 4 }) to generate 4
TableCell skeletons while the table header (rendered around Line 119) has 5
headers; update the skeleton generation to match the header count (make the
inner Array.from length equal to 5 or derive it from the headers array) so each
TableRow in the skeleton renders the same number of TableCell elements as the
table headers (adjust the map that creates TableCell with key
`table-cell-skeleton-${cellIndex}` accordingly).

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx`:
- Around line 417-458: The code introduces an artificial 2s setTimeout in the
quick-order hydration flow (see setIsLoadingWithDelay, timeoutId,
setQuickOrderProducts, setIsQuickOrderDrawerOpen) which causes unnecessary
production latency; remove the hardcoded setTimeout and run the hydration logic
immediately (or replace it with a configurable/test-only hook) so
fetchedProducts are converted and state (setQuickOrderProducts,
setIsQuickOrderDrawerOpen, setFileUploadVisible, setNoProductsError,
setIsLoadingWithDelay) is updated without the fixed delay.
- Around line 198-205: The hook usePage must be called at the top level to
respect React Hooks rules: move the call out of the try/catch so that const
pageContext = usePage<{ globalSettings?: { fileUpload?: any } }>() is executed
unconditionally (e.g., at the start of the SearchInput component function), then
derive fileUploadConfig from pageContext (fileUploadConfig =
pageContext?.globalSettings?.fileUpload) and remove the try/catch around
usePage; ensure the symbol fileUploadConfig and the usePage invocation in
SearchInput are updated accordingly and any necessary null/undefined checks
remain after the top-level hook call.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`:
- Around line 175-183: In UploadFileDropdown (inside the .map callback that
reads skuIndex and quantityIndex) stop throwing on invalid quantity; instead
create a local errors array (e.g., rowErrors) and for each row validate
quantity, pushing a descriptive error (row id/number, SKU, invalid value) when
isNaN or quantity < 0 and skip adding that row to the output; continue
transforming valid rows into the resulting payload (e.g., validRows) and after
the map/transform, surface rowErrors (set component state or return them to the
caller / show a toast) while proceeding with importing validRows so a single bad
row no longer aborts the whole XLSX import.

---

Nitpick comments:
In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`:
- Around line 124-142: The JSX currently nests a ternary at the table body using
showSkeleton ? ... : products.length > 0 ? ... : ...; refactor
QuickOrderDrawerProducts to compute a flat bodyContent (or return early) before
the JSX render: evaluate showSkeleton first to render the skeleton rows (using
TableRow/TableCell/Skeleton), else check products.length to render product rows,
else render the empty-state row; then use the single {bodyContent} in the table
body to remove the nested ternary and improve readability.
- Around line 276-278: In QuickOrderDrawerProducts.tsx remove the unnecessary
type assertion spread and set the colspan directly: replace the JSX spread
{...({ colSpan: 5 } as React.HTMLAttributes<HTMLTableCellElement>)} with a
direct prop colSpan={5} on the TableCell element (the component/render block
where colSpan is applied inside QuickOrderDrawerProducts), since TableCellProps
already includes HTMLAttributes and colSpan is supported natively.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 48675320-8147-4611-b492-fe70b6141e6f

📥 Commits

Reviewing files that changed from the base of the PR and between 609f9f5 and 2d5835f.

⛔ Files ignored due to path filters (5)
  • CHANGELOG.md is excluded by none and included by none
  • package.json is excluded by none and included by none
  • packages/core/@generated/gql.ts is excluded by !**/@generated/**, !**/@generated/** and included by packages/**
  • packages/core/@generated/graphql.ts is excluded by !**/@generated/**, !**/@generated/** and included by packages/**
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (13)
  • packages/cli/CHANGELOG.md
  • packages/components/CHANGELOG.md
  • packages/components/package.json
  • packages/components/src/index.ts
  • packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx
  • packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx
  • packages/core/CHANGELOG.md
  • packages/core/package.json
  • packages/core/src/components/search/SearchInput/SearchInput.tsx
  • packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx
  • packages/storybook/.storybook/main.js
  • packages/storybook/package.json
  • packages/storybook/stories/fileupload.stories.tsx
💤 Files with no reviewable changes (2)
  • packages/cli/CHANGELOG.md
  • packages/core/CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/components/package.json
  • packages/components/src/index.ts
  • packages/core/package.json

Comment thread packages/components/CHANGELOG.md Resolved
type DropzoneState,
} from '@faststore/ui'

import * as XLSX from 'xlsx'

ghost Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check the UploadFileDropdown.tsx file content
cat -n packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx | head -80

Repository: vtex/faststore

Length of output: 3639


🏁 Script executed:

#!/bin/bash
# Search for all xlsx imports and usages in the file
rg "xlsx|XLSX|parseXLSXFile" packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx -n -C 3

Repository: vtex/faststore

Length of output: 1227


🏁 Script executed:

#!/bin/bash
# Check file length
wc -l packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx

Repository: vtex/faststore

Length of output: 139


🏁 Script executed:

#!/bin/bash
# Check if XLSX is used anywhere besides parseXLSXFile and its references
rg "XLSX\\.|\bXLSX\b" packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx -n

Repository: vtex/faststore

Length of output: 221


🏁 Script executed:

#!/bin/bash
# Check other component files in the same directory to see if xlsx pattern is used elsewhere
fd . packages/core/src/components/search/UploadFileDropdown/ -type f -name "*.tsx" -o -name "*.ts"

Repository: vtex/faststore

Length of output: 228


🏁 Script executed:

#!/bin/bash
# List files in the UploadFileDropdown directory
ls -la packages/core/src/components/search/UploadFileDropdown/

Repository: vtex/faststore

Length of output: 378


Lazy-load xlsx to avoid inflating the initial search bundle.

xlsx is heavy and only used in the Excel parsing path. Move the import inside parseXLSXFile:

Proposed fix
-import * as XLSX from 'xlsx'
@@
 const parseXLSXFile = async (file: File): Promise<CSVData> => {
+  const XLSX = await import('xlsx')
   return new Promise((resolve, reject) => {
📝 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 * as XLSX from 'xlsx'
const parseXLSXFile = async (file: File): Promise<CSVData> => {
const XLSX = await import('xlsx')
return new Promise((resolve, reject) => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`
at line 16, Remove the top-level import of XLSX and instead lazy-load it inside
the Excel parsing path: make parseXLSXFile async (or ensure callers await it)
and do a dynamic import like const XLSX = await import('xlsx') (or const {
default: XLSX } = await import('xlsx') if required) inside parseXLSXFile before
any XLSX.* calls, so the heavy module is only loaded when parseXLSXFile is
invoked; update UploadFileDropdown usages that call parseXLSXFile to await the
result if necessary.

ghost Mar 6, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

O resto do projeto não usa lazy-load pra bibliotecas, não sei se essa inclusão quebraria algum pattern interno @lariciamota

ghost Mar 6, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

ghost Mar 6, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Não acho que quebraria, mas podemos deixar assim, aqui eu só tiraria o * para deixar explícito o que ta sendo usado

ghost Mar 6, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@ataideverton mas uma dúvida que fiquei agora, em outro momento tinha sido decidido apenas suportar csv e ai outras extensões foram excluídas, algo mudou nessa decisão ou esse PR não foi atualizado com isso?

ghost Mar 9, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Eu não tava atualizado nessa decisão e esse PR tinha código pra outros formatos.

Vou trocar uma ideia com o Arthur e ver qual é o caminho que tinham decidido seguir, ai atualizo esse PR e o comentário de acordo

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (4)
packages/core/src/components/search/SearchInput/SearchInput.tsx (2)

198-205: ⚠️ Potential issue | 🔴 Critical

Move usePage out of try/catch (Line 201).

Hook calls must be top-level and unconditional. This currently violates Rules of Hooks and matches the Biome error.

Proposed fix
-    let fileUploadConfig
-    try {
-      const pageContext = usePage<{ globalSettings?: { fileUpload?: any } }>()
-      fileUploadConfig = pageContext?.globalSettings?.fileUpload
-    } catch {
-      fileUploadConfig = undefined
-    }
+    const pageContext = usePage<{
+      globalSettings?: { fileUpload?: unknown }
+    }>()
+    const fileUploadConfig =
+      (pageContext?.globalSettings?.fileUpload as
+        | {
+            acceptedFileTypes?: string
+            labels?: Record<string, string>
+            errorMessages?: Record<string, { title: string; description: string }>
+          }
+        | undefined) ?? undefined

As per coding guidelines, React hooks must follow rules of hooks (no conditional hooks).

#!/bin/bash
# Verify there is no usePage call inside try/catch blocks
rg -n -C3 "try\\s*\\{|usePage<|catch\\s*\\{" packages/core/src/components/search/SearchInput/SearchInput.tsx
# Expected after fix: usePage call appears at top-level component scope, outside try/catch.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx` around lines
198 - 205, The usePage hook is being called inside a try/catch which violates
the Rules of Hooks; move the usePage<{ globalSettings?: { fileUpload?: any }
}>() call to the top-level of the SearchInput component (unconditional) and
assign its result to pageContext, then derive fileUploadConfig from
pageContext?.globalSettings?.fileUpload; if you need to guard against runtime
errors keep only the property access or any risky logic inside the try/catch but
ensure the usePage invocation itself is always called unconditionally (refer to
usePage, pageContext, fileUploadConfig in SearchInput).

417-457: ⚠️ Potential issue | 🟠 Major

Remove the hardcoded 2s test delay from successful quick-order processing.

This forces unnecessary latency on every successful bulk flow. If a delay is needed, use a named constant defaulting to 0 in production.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx` around lines
417 - 457, The code currently hardcodes a 2000ms test delay in the quick-order
success path (the setTimeout that sets timeoutId and toggles
setIsLoadingWithDelay, setQuickOrderProducts, setIsQuickOrderDrawerOpen,
setFileUploadVisible, setNoProductsError after convertProductToQuickOrder).
Replace the magic number with a named constant like QUICK_ORDER_DELAY_MS
(default 0 in production) and use that constant in the setTimeout call so
production has no artificial latency; ensure the logic still uses
convertedProducts and state setters unchanged, and keep/implement
clearTimeout(timeoutId) on cleanup/unmount if not already present to avoid
dangling timers.
packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx (2)

171-190: ⚠️ Potential issue | 🟡 Minor

Do not fail the entire file on the first invalid row.

Current .map throws on one bad quantity and rejects the whole import. Collect row-level errors and keep valid rows, then surface aggregated errors.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`
around lines 171 - 190, The current transformation in UploadFileDropdown.tsx
(the transformedData mapping that iterates over rows using skuIndex and
quantityIndex) throws on the first invalid quantity and aborts the entire
import; change this to collect per-row validation errors instead: iterate rows,
validate each row's sku and quantity, for invalid rows push a descriptive error
(include row identifier/index, raw value, and SKU) into a local errors array and
skip adding that row to the validRows list, for valid rows push { sku, quantity
} into validRows; after iteration, use the existing handler/state path (e.g.,
where transformedData was used) to proceed with validRows and surface the
aggregated errors (errors array) to the user via the component's error state or
the import result object rather than throwing inside the map.

145-157: ⚠️ Potential issue | 🟠 Major

Header matching is too permissive and can bind wrong columns.

Using includes('id'|'product'|'amount') can match unrelated headers (e.g. order id). Normalize headers and match explicit aliases exactly.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`
around lines 145 - 157, The header matching in UploadFileDropdown (variables
skuIndex and quantityIndex) is too permissive because headers.findIndex uses
header?.toLowerCase().includes(...) which can match unrelated names like "order
id"; change the logic to normalize headers (trim and toLowerCase) and match
against an explicit set of allowed aliases (e.g., exact equality to 'sku',
'product_sku', 'productid' for skuIndex and 'quantity', 'qty', 'amount' for
quantityIndex) instead of using includes, and update the findIndex predicates to
check equality against that alias set so only exact normalized matches are
selected.
🧹 Nitpick comments (1)
packages/core/src/components/search/SearchInput/SearchInput.tsx (1)

87-91: Avoid over-narrowing attachmentButtonIcon in the public prop contract.

UISearchInputFieldProps accepts ReactNode; restricting to { icon, alt } reduces compatibility for existing callers. Consider a union type and normalize internally.

As per coding guidelines, TypeScript files should ensure type safety and avoid unnecessary contract restrictions.

Also applies to: 122-122, 533-540

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx` around lines
87 - 91, The prop type attachmentButtonIcon is currently over-narrowed to an
object shape ({ icon, alt }) in UISearchInputFieldProps; change the prop to
accept ReactNode | { icon: string; alt?: string } (or a similar union) so
callers can pass JSX or the object form, then normalize inside the SearchInput
component (e.g., in renderAttachmentButton or normalizeAttachmentIcon helper) to
produce the expected object/element; update all related usages and type
annotations (including the attachmentButtonIcon references around the other
occurrences) to use the new union without widening internal implementation
types.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@packages/core/src/components/search/SearchInput/SearchInput.tsx`:
- Around line 198-205: The usePage hook is being called inside a try/catch which
violates the Rules of Hooks; move the usePage<{ globalSettings?: { fileUpload?:
any } }>() call to the top-level of the SearchInput component (unconditional)
and assign its result to pageContext, then derive fileUploadConfig from
pageContext?.globalSettings?.fileUpload; if you need to guard against runtime
errors keep only the property access or any risky logic inside the try/catch but
ensure the usePage invocation itself is always called unconditionally (refer to
usePage, pageContext, fileUploadConfig in SearchInput).
- Around line 417-457: The code currently hardcodes a 2000ms test delay in the
quick-order success path (the setTimeout that sets timeoutId and toggles
setIsLoadingWithDelay, setQuickOrderProducts, setIsQuickOrderDrawerOpen,
setFileUploadVisible, setNoProductsError after convertProductToQuickOrder).
Replace the magic number with a named constant like QUICK_ORDER_DELAY_MS
(default 0 in production) and use that constant in the setTimeout call so
production has no artificial latency; ensure the logic still uses
convertedProducts and state setters unchanged, and keep/implement
clearTimeout(timeoutId) on cleanup/unmount if not already present to avoid
dangling timers.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`:
- Around line 171-190: The current transformation in UploadFileDropdown.tsx (the
transformedData mapping that iterates over rows using skuIndex and
quantityIndex) throws on the first invalid quantity and aborts the entire
import; change this to collect per-row validation errors instead: iterate rows,
validate each row's sku and quantity, for invalid rows push a descriptive error
(include row identifier/index, raw value, and SKU) into a local errors array and
skip adding that row to the validRows list, for valid rows push { sku, quantity
} into validRows; after iteration, use the existing handler/state path (e.g.,
where transformedData was used) to proceed with validRows and surface the
aggregated errors (errors array) to the user via the component's error state or
the import result object rather than throwing inside the map.
- Around line 145-157: The header matching in UploadFileDropdown (variables
skuIndex and quantityIndex) is too permissive because headers.findIndex uses
header?.toLowerCase().includes(...) which can match unrelated names like "order
id"; change the logic to normalize headers (trim and toLowerCase) and match
against an explicit set of allowed aliases (e.g., exact equality to 'sku',
'product_sku', 'productid' for skuIndex and 'quantity', 'qty', 'amount' for
quantityIndex) instead of using includes, and update the findIndex predicates to
check equality against that alias set so only exact normalized matches are
selected.

---

Nitpick comments:
In `@packages/core/src/components/search/SearchInput/SearchInput.tsx`:
- Around line 87-91: The prop type attachmentButtonIcon is currently
over-narrowed to an object shape ({ icon, alt }) in UISearchInputFieldProps;
change the prop to accept ReactNode | { icon: string; alt?: string } (or a
similar union) so callers can pass JSX or the object form, then normalize inside
the SearchInput component (e.g., in renderAttachmentButton or
normalizeAttachmentIcon helper) to produce the expected object/element; update
all related usages and type annotations (including the attachmentButtonIcon
references around the other occurrences) to use the new union without widening
internal implementation types.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6fd81892-ff56-46d5-8420-73db074dd546

📥 Commits

Reviewing files that changed from the base of the PR and between 2d5835f and fbad99d.

📒 Files selected for processing (2)
  • packages/core/src/components/search/SearchInput/SearchInput.tsx
  • packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

♻️ Duplicate comments (1)
packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx (1)

194-197: ⚠️ Potential issue | 🟠 Major

Make local file validation follow the accept prop.

isValidFileType() still hardcodes .csv, so the component can reject files that the input itself allows. That mismatch is user-visible now that SearchInput forwards CMS-driven accepted types on Line 598, so .xls/.xlsx or any custom allowlist will still land in the unsupported state here.

Proposed fix
   const isValidFileType = (file: File): boolean => {
     const fileName = file.name.toLowerCase()
-    const validExtensions = ['.csv']
-    return validExtensions.some((ext) => fileName.endsWith(ext))
+    const acceptedTypes = accept
+      .split(',')
+      .map((value) => value.trim().toLowerCase())
+      .filter(Boolean)
+
+    if (acceptedTypes.length === 0) {
+      return fileName.endsWith('.csv')
+    }
+
+    return acceptedTypes.some((value) =>
+      value.startsWith('.')
+        ? fileName.endsWith(value)
+        : file.type.toLowerCase() === value
+    )
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx` around
lines 194 - 197, The local validator is hardcoding '.csv' in isValidFileType,
causing a mismatch with the input's accept prop; update isValidFileType to use
the component's accept prop (or default) instead of the fixed array so it
validates against the same allowed extensions/types that SearchInput forwards.
Locate isValidFileType in FileUploadCard.tsx and change it to parse the accept
string/array (supporting MIME types and extensions like '.xls'/.xlsx') and check
the File's name/type against that parsed list, keeping existing
lowercase/endsWith logic and fallback behavior for backward compatibility.
🧹 Nitpick comments (5)
packages/components/src/hooks/useCSVParser.ts (1)

257-257: Prefer unknown[] over any for type safety.

The chunk callback already types results.data as unknown[][], so row should match.

Proposed fix
-          results.data.forEach((row: any, index: number) => {
+          results.data.forEach((row: unknown[], index: number) => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/components/src/hooks/useCSVParser.ts` at line 257, In useCSVParser,
the callback for results.data.forEach currently types the row as any; change the
parameter type to unknown[] (since results.data is unknown[][]) to improve type
safety—update the forEach signature from (row: any, index: number) to (row:
unknown[], index: number) and adjust any downstream usages that assume specific
element types by narrowing/casting them locally.
packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx (2)

273-278: Avoid type assertion for colSpan.

The spread with type assertion is a workaround. If TableCell doesn't support colSpan natively, consider extending its props to include standard <td> attributes.

♻️ Suggested approach

If TableCell wraps a <td>, it should ideally forward all standard HTML attributes:

// In TableCell component definition
export type TableCellProps = React.TdHTMLAttributes<HTMLTableCellElement> & {
  // existing custom props
}

Then usage simplifies to:

-                  {...({
-                    colSpan: 5,
-                  } as React.HTMLAttributes<HTMLTableCellElement>)}
+                  colSpan={5}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`
around lines 273 - 278, The TableCell usage currently uses a type assertion hack
to pass colSpan; update the TableCell component to accept standard td attributes
so callers can pass colSpan directly. Modify the TableCell props type (e.g.,
export type TableCellProps) to extend
React.TdHTMLAttributes<HTMLTableCellElement> (preserving existing custom props)
and ensure the component forwards remaining props to the underlying <td>; then
remove the spread/type assertion around colSpan in QuickOrderDrawerProducts and
pass colSpan={5} directly to TableCell.

124-142: Consider flattening the nested ternary for readability.

The three-state ternary (showSkeleton ? ... : products.length > 0 ? ... : ...) works but can be flattened using a helper function or early-return pattern for easier scanning.

♻️ Optional: extract render logic
const renderTableBody = () => {
  if (showSkeleton) {
    return <>{/* skeleton rows */}</>
  }
  
  if (products.length > 0) {
    return <>{/* product rows */}</>
  }
  
  return <>{/* empty state */}</>
}

As per coding guidelines: "Prefer flat conditionals over nested ifs: combine conditions with && or use early returns to avoid deep nesting."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`
around lines 124 - 142, The JSX currently uses a nested ternary around
showSkeleton and products.length to choose table body markup; extract that logic
into a helper like renderTableBody (or use early returns) to return the three
states (skeleton rows, product rows, empty state) instead of the nested ternary.
Update the component to call renderTableBody() where the current ternary is,
keeping the same rendering of TableRow/TableCell/Skeleton and the product
mapping logic so identifiers like showSkeleton, products, TableRow, TableCell
remain unchanged.
packages/core/src/sdk/product/convertProductToQuickOrder.ts (1)

25-31: Drop the local casts and rely on the generated types.

Line 25 widens offer.quantity to optional/null, and Line 78 re-asserts availability even though both types are already known here. That weakens the compiler checks in a shared SDK mapper.

Suggested refactor
-  const offerQuantity = (offer as { quantity?: number | null }).quantity
+  const offerQuantity = offer.quantity
@@
-  const availability = isInStock ? 'available' : 'outOfStock'
+  const availability: Product['availability'] =
+    isInStock ? 'available' : 'outOfStock'
@@
-    availability: availability as 'available' | 'outOfStock',
+    availability,

As per coding guidelines, "Ensure type safety and avoid type assertions when possible."

Also applies to: 78-78

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/sdk/product/convertProductToQuickOrder.ts` around lines 25
- 31, The code widens types with a local cast and re-asserts availability,
weakening compiler checks; remove the local cast and redundant assertions and
rely on the generated Offer types instead: use offer.quantity directly
(null/undefined check) when computing inventory and keep using the typed
isInStock/availability from the Offer model rather than re-asserting them;
update the logic around offer, offer.quantity, isInStock (and any use in
convertProductToQuickOrder) so the compiler enforces the correct
nullable/defined types without (offer as ...) or extra availability casts.
packages/core/src/components/search/SearchInput/SearchInput.tsx (1)

200-202: Type fileUploadConfig instead of any.

This code now reads acceptedFileTypes, labels, and errorMessages from CMS. Keeping the payload as any means typos in those keys degrade to runtime behavior instead of a compile-time failure. Please reuse the typed global settings contract here.

As per coding guidelines: packages/**/*.{ts,tsx}: Ensure type safety and avoid type assertions when possible.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx` around lines
200 - 202, Replace the untyped any payload by using the project's typed global
settings contract when deriving fileUploadConfig: update the usePage call and
the fileUploadConfig declaration to use the GlobalSettings type (or the specific
exported type used for CMS global settings) instead of any so TypeScript
validates keys like acceptedFileTypes, labels, and errorMessages; reference the
existing usePage hook and the fileUploadConfig variable to locate the change and
ensure the type import (e.g., GlobalSettings / AppGlobalSettings) is added and
applied to pageContext and fileUploadConfig.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/components/src/hooks/useCSVParser.ts`:
- Line 126: The line-break detection in useCSVParser computing firstLine is
wrong because text.split('\n')[0] will capture '\r\n' lines with a trailing
'\r', making the '\r\n' branch unreachable; update the logic in useCSVParser to
correctly detect CRLF before LF (e.g., check text.includes('\r\n') first or
split using a regex like /\r?\n/ and then trim '\r' from the first line) so
firstLine contains the actual header without leftover carriage returns; adjust
any downstream trimming/normalization that relies on firstLine accordingly.

In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`:
- Around line 289-293: The empty-state message in QuickOrderDrawerProducts
currently says "CSV file" which is inaccurate because uploads also support
Excel; update the UI text to use a neutral term like "spreadsheet file" or wire
this string to the component's messages prop so it can be configured via CMS.
Locate the JSX elements (e.g., the <p> with data-fs-qod-empty-state-message
inside QuickOrderDrawerProducts) and either replace the hard-coded "CSV file"
wording with "spreadsheet file" or read the text from messages.emptyStateMessage
(or similar messages prop) so the message becomes configurable.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx`:
- Around line 371-390: The CSV-import path currently pushes every row SKU into
skus and later uses csvData.data.find(...) to get requestedQuantity, which
returns only the first row for duplicate SKUs; update the SearchInput component
to aggregate duplicates when building skus by creating a normalized map (e.g.,
skuQuantityMap: Record<string, number>) that sums requestedQuantity per SKU and
setSkusToFetch to the unique SKU keys (instead of repeated SKUs), then modify
the fetch-completion effect that currently reads csvData.data.find(...) to read
requestedQuantity from skuQuantityMap for the SKU; persist skuQuantityMap in
state (e.g., setSkuQuantityMap) or pass it into the effect so the
drawer/add-to-cart flow uses the summed quantities.

In
`@packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx`:
- Around line 142-157: Headers from sheet_to_json(header: 1) may be non-strings;
normalize each header before calling toLowerCase() to avoid runtime errors. In
UploadFileDropdown.tsx, update the logic that computes skuIndex and
quantityIndex to map/normalize the headers array (e.g., coerce each header via
String(header ?? '') or (header ?? '').toString()) and then run the existing
includes checks; ensure headers is reassigned or use the normalized value when
calling headers.findIndex so that skuIndex and quantityIndex checks behave
safely.

In `@packages/core/src/sdk/product/convertProductToQuickOrder.ts`:
- Around line 41-56: Normalize the parsed requestedQuantity at the top of
convertProductToQuickOrder before the branch that sets selectedCount: coerce to
an integer (use Math.floor or Math.trunc to drop decimals), if the value is
null/undefined treat as 1, and clamp any non-positive values to 1 and any values
above inventory to inventory (or leave further capping to the existing inventory
branch). Update references from requestedQuantity to the normalized variable
(e.g., normalizedRequestedQuantity) in the existing conditions (isOutOfStock,
inventory, offerQuantity, selectedCount, quantityUpdated) so decimals, zeros or
negatives no longer produce invalid selectedCount.

---

Duplicate comments:
In `@packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx`:
- Around line 194-197: The local validator is hardcoding '.csv' in
isValidFileType, causing a mismatch with the input's accept prop; update
isValidFileType to use the component's accept prop (or default) instead of the
fixed array so it validates against the same allowed extensions/types that
SearchInput forwards. Locate isValidFileType in FileUploadCard.tsx and change it
to parse the accept string/array (supporting MIME types and extensions like
'.xls'/.xlsx') and check the File's name/type against that parsed list, keeping
existing lowercase/endsWith logic and fallback behavior for backward
compatibility.

---

Nitpick comments:
In `@packages/components/src/hooks/useCSVParser.ts`:
- Line 257: In useCSVParser, the callback for results.data.forEach currently
types the row as any; change the parameter type to unknown[] (since results.data
is unknown[][]) to improve type safety—update the forEach signature from (row:
any, index: number) to (row: unknown[], index: number) and adjust any downstream
usages that assume specific element types by narrowing/casting them locally.

In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`:
- Around line 273-278: The TableCell usage currently uses a type assertion hack
to pass colSpan; update the TableCell component to accept standard td attributes
so callers can pass colSpan directly. Modify the TableCell props type (e.g.,
export type TableCellProps) to extend
React.TdHTMLAttributes<HTMLTableCellElement> (preserving existing custom props)
and ensure the component forwards remaining props to the underlying <td>; then
remove the spread/type assertion around colSpan in QuickOrderDrawerProducts and
pass colSpan={5} directly to TableCell.
- Around line 124-142: The JSX currently uses a nested ternary around
showSkeleton and products.length to choose table body markup; extract that logic
into a helper like renderTableBody (or use early returns) to return the three
states (skeleton rows, product rows, empty state) instead of the nested ternary.
Update the component to call renderTableBody() where the current ternary is,
keeping the same rendering of TableRow/TableCell/Skeleton and the product
mapping logic so identifiers like showSkeleton, products, TableRow, TableCell
remain unchanged.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx`:
- Around line 200-202: Replace the untyped any payload by using the project's
typed global settings contract when deriving fileUploadConfig: update the
usePage call and the fileUploadConfig declaration to use the GlobalSettings type
(or the specific exported type used for CMS global settings) instead of any so
TypeScript validates keys like acceptedFileTypes, labels, and errorMessages;
reference the existing usePage hook and the fileUploadConfig variable to locate
the change and ensure the type import (e.g., GlobalSettings / AppGlobalSettings)
is added and applied to pageContext and fileUploadConfig.

In `@packages/core/src/sdk/product/convertProductToQuickOrder.ts`:
- Around line 25-31: The code widens types with a local cast and re-asserts
availability, weakening compiler checks; remove the local cast and redundant
assertions and rely on the generated Offer types instead: use offer.quantity
directly (null/undefined check) when computing inventory and keep using the
typed isInStock/availability from the Offer model rather than re-asserting them;
update the logic around offer, offer.quantity, isInStock (and any use in
convertProductToQuickOrder) so the compiler enforces the correct
nullable/defined types without (offer as ...) or extra availability casts.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1fccc42c-aa8a-4425-ada4-831fa0c2575d

📥 Commits

Reviewing files that changed from the base of the PR and between fbad99d and ec99799.

📒 Files selected for processing (7)
  • packages/components/src/hooks/useCSVParser.ts
  • packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx
  • packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx
  • packages/core/src/components/search/SearchInput/SearchInput.tsx
  • packages/core/src/components/search/UploadFileDropdown/UploadFileDropdown.tsx
  • packages/core/src/sdk/product/convertProductToQuickOrder.ts
  • packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss

Comment thread package.json Resolved
Comment thread packages/ui/src/index.ts Outdated
CSVParserError,
CSVParserOptions,
} from '@faststore/components'
// Explicitly re-export FileUploadCardProps to ensure TypeScript resolves it

ghost Mar 10, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Não entendi esses comentários 🤔 Pq exatamente esses exports são necessários msm já tendo o export * from '@faststore/components'? Rolou algum erro?

ghost Mar 10, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

A cubos precisou adicionar isso para os componentes serem lidos, mas já estou removendo

Comment thread packages/components/package.json Resolved
Comment thread packages/components/src/index.ts Resolved

ghost Mar 10, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Esses não deveriam ser adicionados ao CMS nesse PR? Os que estão em DEFAULT_FILE_UPLOAD_CARD_PROPS também

ghost Mar 10, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Sim, fiz essa integração e removi os valores default de labels no core, pode conferir?

Comment on lines -45 to -49
const mergedOptions = useMemo(
() => ({ ...defaultOptions, ...options }),
[options]
)

ghost Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Para checar: essa remoção foi intencional ou foi algo do merge? Achava que isso tinha sido introduzido em alguma review

): number => {
return headers.findIndex((header) =>
columnNames.some(
(name) => header.toLowerCase().trim() === name.toLowerCase()

ghost Mar 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Aqui também


// Skip header row — use only data rows
rows = rows.slice(1)
results.data = results.data.slice(1)

ghost Mar 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Acho que várias partes desse arquivo voltaram para uma versão antiga :/

Comment on lines +119 to +120
dragActiveText = 'Drop the files here...',
text = 'Drag and drop files here, or click to select files',

ghost Mar 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Remover texto hardcoded, precisamos receber tudo do CMS por conta do multilanguage da faststore

<Card
ref={containerRef}
title={title}
title={title ?? 'File Upload'}

ghost Mar 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
title={title ?? 'File Upload'}
title={title}

}
return { title: '', description: '' }

switch (errorType) {

ghost Mar 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Aqui também deve ter tido alguma regressão... não tá usando o FileUploadErrorType e mensagens hardcoded

ghost Mar 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Se for necessário, podemos colocar para importar apenas o QuickOrderDrawer

Suggested change
@import "@faststore/ui/src/components/molecules/Dropdown/styles.scss";
@import "@faststore/ui/src/components/organisms/QuickOrderDrawer/styles.scss";

export type GlobalCmsData = {
regionalization?: RegionalizationCmsData
deliveryPromise?: DeliveryPromiseCmsData
fileUpload?: FileUploadCmsData

ghost Mar 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caso meu questionamento no cms/content-types.json seja válido, podemos remover as mudanças nesse arquivo tb

Comment thread packages/ui/src/index.ts Outdated
@@ -1,8 +1,17 @@
export * from '@faststore/components'

export { useCSVParser } from '@faststore/components'

ghost Mar 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Vai precisar desses exports mesmo com export * from '@faststore/components'?

Comment on lines +61 to +62
// Process SKUs in batches to avoid overwhelming the server
// This matches the RFC recommendation to divide requests into smaller batches

ghost Mar 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Já tem outro comentário relacionado a tamanho de batch, então não precisa desses

Suggested change
// Process SKUs in batches to avoid overwhelming the server
// This matches the RFC recommendation to divide requests into smaller batches

Comment on lines +68 to +69
// Fetch each product individually using the same query as useProductQuery
// This matches exactly how products are fetched elsewhere in the codebase

ghost Mar 13, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Aqui tb, no início do arquivo já tem outro comentário similar

Suggested change
// Fetch each product individually using the same query as useProductQuery
// This matches exactly how products are fetched elsewhere in the codebase

@ArthurTriis1
ArthurTriis1 force-pushed the feat/quick-order-integration branch from 276c429 to 7cfab73 Compare March 13, 2026 19:22

ghost left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I left some comments, but let's do some pair programming afterward 😉

Comment on lines +119 to +135
const [isQuickOrderDrawerOpen, setIsQuickOrderDrawerOpen] = useState(false)
const [quickOrderProducts, setQuickOrderProducts] = useState<Product[]>([])
const [noProductsError, setNoProductsError] = useState<boolean>(false)

const searchRef = useRef<HTMLDivElement>(null)
const { addToSearchHistory } = useSearchHistory()
const router = useRouter()
const priceFormatter = usePriceFormatter()
const { pushToast } = useUI()

const [csvData, setCsvData] = useState<CSVData | null>(null)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [skusToFetch, setSkusToFetch] = useState<string[]>([])
const [skuQuantityMap, setSkuQuantityMap] = useState<
Record<string, number>
>({})
const [isLoadingWithDelay, setIsLoadingWithDelay] = useState(false)

ghost Mar 26, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe in the future refactor to useReduce instead of all these setState

setFileUploadVisible(false)
setNoProductsError(true)
}
}, 2000) // 2 second delay for testing

ghost Mar 26, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Conseguiram checar esse comentário acima?

product: data.product,
}
} catch (err) {
console.error(`Failed to fetch product ${sku}:`, err)

ghost Mar 26, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Should we keep this console here?

- Move all aria-labels and text strings from QuickOrderDrawerProducts
  to messages prop with defaults in sections.json
- Replace global CSS custom properties with local design tokens
  in QuickOrderDrawer styles for easier theming
- Remove temporary dev simulation code from SearchInput

Made-with: Cursor
@eduardoformiga
eduardoformiga merged commit 862c393 into vtex:feat/quick-order-by-file-feature-branch Mar 27, 2026
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.

10 participants