Skip to content

feat: Add Quick Order Full Feature - #3197

Merged
eduardoformiga merged 7 commits into
devfrom
feat/quick-order-by-file-feature-branch
Mar 27, 2026
Merged

eduardoformiga merged 7 commits into
devfrom
feat/quick-order-by-file-feature-branch

Conversation

@ArthurTriis1

@ArthurTriis1 ArthurTriis1 commented Feb 3, 2026 •

Copy link
Copy Markdown
Collaborator

Add Quick Order Full Feature

Summary by CodeRabbit

  • New Features
    • Quick Order Drawer (header, product list, footer) with add‑to‑cart flow and provider.
    • File Upload UI: File Upload Card and File Upload Status with template download, progress, and error states.
    • Dropzone for drag‑and‑drop file selection with reject handling.
    • CSV parsing and file‑upload hooks for client‑side validation and template generation.
    • Search attachment button to launch upload/quick‑order flow; Storybook stories and new UI styles.

@ArthurTriis1
ArthurTriis1 requested a review from a team as a code owner February 3, 2026 18:22
@ArthurTriis1
ArthurTriis1 requested review from eduardoformiga and lucasfp13 and removed request for a team February 3, 2026 18:22
@coderabbitai

coderabbitai Bot commented Feb 3, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ace6e932-3118-4234-93b8-dfe2676e056d

📥 Commits

Reviewing files that changed from the base of the PR and between 93d2534 and 153ba0f.

📒 Files selected for processing (3)
  • packages/core/cypress/tsconfig.json
  • packages/core/jest.config.js
  • packages/core/test/tsconfig.json
✅ Files skipped from review due to trivial changes (2)
  • packages/core/test/tsconfig.json
  • packages/core/cypress/tsconfig.json

Walkthrough

Adds a CSV-driven quick-order flow: new QuickOrderDrawer (provider, header, products, footer), FileUploadCard/FileUploadStatus and Dropzone components, useCSVParser and useFileUpload hooks, bulk SKU fetching and conversion utilities, SearchInput integration, Storybook stories, SCSS styles, and updated public exports and package deps.

Changes

Cohort / File(s) Summary
QuickOrder Drawer & Provider
packages/components/src/organisms/QuickOrderDrawer/..., packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss
New QuickOrderDrawer component, Header/Products/Footer subcomponents, QuickOrderDrawerProvider hook/context, provider types, and SlideOver-based UI with styles.
File Upload UI & Dropzone
packages/components/src/molecules/FileUploadCard/..., packages/components/src/molecules/FileUploadStatus/..., packages/components/src/molecules/Dropzone/..., packages/ui/src/components/molecules/{FileUploadCard,FileUploadStatus,Dropzone}/styles.scss
Introduces FileUploadCard, FileUploadStatus (enums/types/actions), Dropzone component, index barrels, and related SCSS styles.
CSV & File hooks
packages/components/src/hooks/useCSVParser.ts, packages/components/src/hooks/useFileUpload.ts, packages/components/src/hooks/index.ts
Adds useCSVParser (PapaParse worker, chunked parsing, template gen) and useFileUpload (rejection mapping/error state); re-exports added in hooks barrel.
SearchInput & core integration
packages/core/src/components/search/SearchInput/SearchInput.tsx, packages/core/src/components/sections/Navbar/*, packages/core/cms/faststore/sections.json
SearchInput gains attachment/upload flow, CSV parsing + timeout, FileUploadCard/QuickOrderDrawer wiring, SKU aggregation, bulk product fetch integration, and extended Navbar props + CMS schema.
Bulk product fetching & conversion
packages/core/src/sdk/product/useBulkProductsQuery.ts, packages/core/src/sdk/product/convertProductToQuickOrder.ts
New batched/throttled useBulkProductsQuery hook and convertProductToQuickOrder util to normalize product → quick-order shape (inventory, availability, selectedCount).
Storybook & tooling
packages/storybook/stories/*, packages/storybook/.storybook/main.js, packages/storybook/package.json
Adds stories for QuickOrderDrawer, Dropzone, FileUpload components; registers SWC compiler addon and adjusts storybook deps to workspace:.
Exports, typings & small refactors
packages/components/src/index.ts, packages/components/src/.../index.tsx, packages/components/src/atoms/{Link,List}/*, packages/components/src/molecules/Accordion/*, packages/components/src/hooks/index.ts, packages/ui/src/index.ts
Updated public barrels to expose new components/types, reordered some type exports, and tightened forwardRef generics in atoms/molecules.
Styles & globals
packages/ui/src/styles/components.scss, packages/core/src/styles/global/index.scss, multiple SCSS files
Imported new component styles into global bundles and added SCSS for Dropzone, FileUploadCard, FileUploadStatus, QuickOrderDrawer, plus SearchInputField style tweaks.
Utilities, deps, changelogs & configs
packages/core/src/utils/utilities.ts, packages/components/package.json, packages/ui/package.json, packages/*/CHANGELOG.md, packages/core/*/tsconfig/jest
Adds formatFileName/formatFileSize utilities, papaparse/react-dropzone deps and types, workspace: dependency adjustments, changelog fixes, and test/tsconfig/jest config additions.
sequenceDiagram
  autonumber
  actor User
  participant SearchInput
  participant FileUploadCard
  participant CSVParser as useCSVParser
  participant BulkAPI as useBulkProductsQuery
  participant QuickOrderProvider
  participant QuickOrderDrawer
  participant Cart

  User->>SearchInput: trigger attachment / upload
  SearchInput->>FileUploadCard: open with handlers
  FileUploadCard->>CSVParser: parse file (worker, chunked)
  CSVParser-->>FileUploadCard: parsed CSV data (skus + qty)
  FileUploadCard->>SearchInput: return CSVData
  SearchInput->>BulkAPI: fetch products for SKUs (batched)
  BulkAPI-->>SearchInput: product results
  SearchInput->>QuickOrderProvider: initialize with products
  QuickOrderDrawer->>User: render products via provider
  User->>QuickOrderDrawer: change qty / add to cart
  QuickOrderDrawer->>QuickOrderProvider: compute purchasable items
  QuickOrderProvider->>Cart: onAddToCart callback with items
  Cart-->>QuickOrderDrawer: confirm -> drawer closes
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • lemagnetic
  • icaroov
  • lariciamota
  • raabelo

🐇 A CSV sailed in on a drop and landed near,
Files turned to SKUs, quick orders soon appear,
Drawer unfurled, products aligned in rows,
From parser to cart the tiny pipeline flows,
🎉 QuickOrder shipped — hooray, go steer!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.46% 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: Add Quick Order Full Feature' accurately describes the main change in the changeset—introducing a complete Quick Order feature with components, hooks, provider context, and integration.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/quick-order-by-file-feature-branch

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.

@ArthurTriis1 ArthurTriis1 changed the title feat: Criaçao do Quick Order Drawer (#3140) Add Quick Order Full Feature Feb 3, 2026
@ArthurTriis1
ArthurTriis1 marked this pull request as draft February 3, 2026 18:24
@codesandbox-ci

codesandbox-ci Bot commented Feb 3, 2026 •

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.

@ArthurTriis1
ArthurTriis1 changed the base branch from dev to main February 3, 2026 18:27

@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: 4

🤖 Fix all issues with AI agents
In
`@packages/components/src/organisms/QuickOrderDrawer/provider/QuickOrderDrawerProvider.tsx`:
- Around line 120-130: The context `value` object in QuickOrderDrawerProvider is
recreated every render which triggers unnecessary consumer re-renders; wrap the
`value: QuickOrderDrawerContextValue` creation in React.useMemo and return the
memoized object, using a dependency array that includes products, totalPrice,
itemsCount, alertMessage, setAlertMessage, onChangeQuantityItem, onDelete,
onAddToCart, and formatter so consumers only update when those actual values
change.

In `@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawer.tsx`:
- Around line 12-42: Add an onAddToCart callback to QuickOrderDrawerProps and
forward it through QuickOrderDrawer to the provider: declare onAddToCart?:
(items: Product[] | /* match existing provider signature */ any) => void on the
QuickOrderDrawerProps type, accept that prop in the QuickOrderDrawer component
and pass it into QuickOrderDrawerProvider so QuickOrderDrawerFooter can invoke
it; ensure the prop name matches QuickOrderDrawerProvider's expected callback
and update any prop passthrough logic (QuickOrderDrawer ->
QuickOrderDrawerProvider) accordingly.

In `@packages/storybook/package.json`:
- Around line 19-20: Update the "@types/react-dom" dependency in the components
package.json to "^18.2.42" so it matches "@types/react" and other workspace
packages; locate the "@types/react-dom" entry in the components package.json
(currently "^18.2.17") and change its version string to "^18.2.42".

In `@packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss`:
- Around line 2-3: Remove the nested `@import` "../../molecules/Tooltip/styles";
and `@import` "../../molecules/Alert/styles"; from QuickOrderDrawer's styles.scss
to avoid duplicating Tooltip and Alert rules already pulled in by the global
components.scss; locate the imports inside the [data-fs-quick-order-drawer]
scoped styles and delete them (or alternatively, if you intended scoped-only
inclusion, remove those same imports from packages/ui/src/styles/components.scss
instead) so the styles are only imported once.
🧹 Nitpick comments (10)
packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss (2)

11-15: Consider using design tokens instead of hardcoded colors for theming consistency.

Multiple hardcoded color values are used throughout the stylesheet (e.g., black, #ffffff, #5c5c5c, green, #0366dd, #f1f8fd, #f5f5f5). This makes theming and dark mode support difficult. Consider defining these as CSS custom properties at the top of the file alongside existing tokens, or referencing existing design system variables.

Examples:

  • Line 11: --fs-quick-order-drawer-primary-text-color: black; → could reference a token like var(--fs-color-text)
  • Line 77: color: green; → should use --fs-quick-order-drawer-badge-success-bkg-color or similar
  • Lines 289-290: Footer button colors are hardcoded

Also applies to: 24-24, 63-63, 77-77, 100-100, 148-148, 157-157, 289-291


56-59: Fixed percentage heights may cause layout issues.

The header (8%), content (80%), and footer (12%) use percentage-based heights that total 100%. This assumes the parent container has a defined height. If the SlideOver doesn't enforce a height, these percentages won't work as expected. Consider using flex-grow with min/max constraints for more robust layout.

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

182-183: Hardcoded user-facing strings should be configurable.

Strings like "Quantity updated to match our inventory", "Out of stock", and "Available" are hardcoded. For internationalization (i18n) support and CMS flexibility, these should be part of the messages prop similar to invalidQuantityTitle and invalidQuantityMessage.

♻️ Suggested approach

Extend QuickOrderDrawerProductsProps.messages to include these strings:

  messages?: {
    invalidQuantityTitle?: string
    invalidQuantityMessage?: (
      min: number,
      max: number,
      quantity: number
    ) => string
+   quantityUpdatedTooltip?: string
+   outOfStockLabel?: string
+   availableLabel?: string
  }

Also applies to: 203-205


25-31: Consider sharing ImageComponentType to avoid duplication.

This type is also defined in ProductComparisonSidebar.tsx. Extracting it to a shared types file would improve maintainability.


122-146: Skeleton loading state shows fixed 5 rows regardless of expected product count.

The skeleton renders exactly 5 rows. If the actual product list is significantly larger or smaller, this may create a jarring visual transition. Consider accepting an optional skeletonRowCount prop or deriving from initialProducts length passed to the provider.

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

73-73: Document that initialProducts is only read on mount.

The useState(initialProducts) pattern means changes to initialProducts after initial render won't update the internal state. This is a valid pattern but should be documented in the JSDoc for QuickOrderDrawerProviderProps.initialProducts to set clear expectations for consumers.

📝 Suggested documentation
 export interface QuickOrderDrawerProviderProps {
   children: ReactNode
+  /**
+   * Initial products to populate the drawer. Only read on mount;
+   * subsequent changes to this prop will not update the internal state.
+   */
   initialProducts?: Product[]
packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerHeader.tsx (1)

31-31: Minor: Arrow function wrapper creates new reference on each render.

The () => onCloseDrawer?.() wrapper creates a new function reference on every render. While this is unlikely to cause issues here, you could simplify it:

♻️ Optional simplification
-      onClose={() => onCloseDrawer?.()}
+      onClose={onCloseDrawer}

Note: This assumes SlideOverHeader handles undefined gracefully for onClose.

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

54-75: Type the mock data properly instead of using double cast.

The as unknown as any[] cast bypasses TypeScript's type checking. This could hide mismatches between mock data and the actual Product interface. Import and use the Product type directly.

♻️ Proposed fix
+import type { Product } from '@faststore/components'
+
 // Mock products for storybook testing only
-const mockProducts = [
+const mockProducts: Product[] = [
   ...Array.from({ length: 4 }, (_, i) => ({
     id: `SGS23U-256GRN-EU${i}`,
     price: 1249.9,
     quantityUpdated: i % 3 === 0,
-    availability: i % 4 ? 'available' : 'outOfStock',
+    availability: (i % 4 ? 'available' : 'outOfStock') as const,
     inventory: 100,
     name: `Business Smartphone X5 256GB/8GB ${['Green', 'Phantom Black', 'Lavender', 'Cream'][i]}`,
     selectedCount: i % 4 ? [18, 20, 20, 12][i] : 0,
     image: { url: '/image.png', alternateName: 'Business Smartphone' },
   })),
   // ...
 ]

Then remove the casts from usage:

-        initialProducts={mockProducts as unknown as any[]}
+        initialProducts={mockProducts}

83-96: Stories don't demonstrate onAddToCart callback handling.

None of the stories provide an onAddToCart handler. Once the missing prop is added to QuickOrderDrawer (per earlier comment), update stories to demonstrate the callback, e.g., logging or showing an alert when "Add to Cart" is clicked.

packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerFooter.tsx (1)

6-16: Consider adding testId prop for testing consistency.

Other components in this library (Button, Price, Overlay, etc.) expose a testId prop for testing tools. Consider adding this for consistency with the established component patterns.

♻️ Optional: Add testId prop
 export type QuickOrderDrawerFooterProps = {
+  /**
+   * ID to find this component in testing tools (e.g.: cypress, testing library, and jest).
+   */
+  testId?: string
   formatter?: PriceFormatter
   /**
    * Text labels for CMS configuration
    */
   labels?: {
     itemsLabel?: string
     addToCartLabel?: string
     addToCartAriaLabel?: string
   }
 }

Then use it in the render:

   return (
-    <div data-fs-quick-order-drawer-footer>
+    <div data-fs-quick-order-drawer-footer data-testid={testId}>

Comment on lines +120 to +130
const value: QuickOrderDrawerContextValue = {
products,
totalPrice,
itemsCount,
alertMessage,
setAlertMessage,
onChangeQuantityItem,
onDelete,
onAddToCart,
formatter,
}

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

Context value object should be memoized to prevent unnecessary re-renders.

The value object is recreated on every render, which will cause all context consumers to re-render even when the actual values haven't changed. Wrap it in useMemo.

♻️ Proposed fix
-  const value: QuickOrderDrawerContextValue = {
-    products,
-    totalPrice,
-    itemsCount,
-    alertMessage,
-    setAlertMessage,
-    onChangeQuantityItem,
-    onDelete,
-    onAddToCart,
-    formatter,
-  }
+  const value: QuickOrderDrawerContextValue = useMemo(
+    () => ({
+      products,
+      totalPrice,
+      itemsCount,
+      alertMessage,
+      setAlertMessage,
+      onChangeQuantityItem,
+      onDelete,
+      onAddToCart,
+      formatter,
+    }),
+    [
+      products,
+      totalPrice,
+      itemsCount,
+      alertMessage,
+      onChangeQuantityItem,
+      onDelete,
+      onAddToCart,
+      formatter,
+    ]
+  )
📝 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,
setAlertMessage,
onChangeQuantityItem,
onDelete,
onAddToCart,
formatter,
}
const value: QuickOrderDrawerContextValue = useMemo(
() => ({
products,
totalPrice,
itemsCount,
alertMessage,
setAlertMessage,
onChangeQuantityItem,
onDelete,
onAddToCart,
formatter,
}),
[
products,
totalPrice,
itemsCount,
alertMessage,
onChangeQuantityItem,
onDelete,
onAddToCart,
formatter,
]
)
🤖 Prompt for AI Agents
In
`@packages/components/src/organisms/QuickOrderDrawer/provider/QuickOrderDrawerProvider.tsx`
around lines 120 - 130, The context `value` object in QuickOrderDrawerProvider
is recreated every render which triggers unnecessary consumer re-renders; wrap
the `value: QuickOrderDrawerContextValue` creation in React.useMemo and return
the memoized object, using a dependency array that includes products,
totalPrice, itemsCount, alertMessage, setAlertMessage, onChangeQuantityItem,
onDelete, onAddToCart, and formatter so consumers only update when those actual
values change.

Comment on lines +12 to +42
export type QuickOrderDrawerProps = {
/**
* ID to find this component in testing tools (e.g.: cypress, testing library, and jest).
*/
testId?: string

/**
* Controls the state
*/
isOpen: boolean

/**
* Props forwarded to the `Overlay` component.
*/
overlayProps?: OverlayProps

/**
* Formatter function that transforms the raw price value and render the result.
*/
formatter?: PriceFormatter

/**
* Initial alert message for CMS configuration
*/
initialAlertMessage?: string

/**
* Initial products for the Quick Order Drawer
*/
initialProducts?: Product[]
}

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

Missing onAddToCart prop prevents consumers from handling add-to-cart actions.

QuickOrderDrawerProvider accepts an onAddToCart callback, but QuickOrderDrawer doesn't expose this prop. Consumers have no way to handle the add-to-cart action triggered by QuickOrderDrawerFooter.

🐛 Proposed fix
+import type { Product } from './provider/QuickOrderDrawerProvider'
+
 export type QuickOrderDrawerProps = {
   // ... existing props
+
+  /**
+   * Callback fired when user clicks "Add to Cart" button.
+   */
+  onAddToCart?: (
+    products: Product[],
+    totalPrice: number,
+    itemsCount: number
+  ) => void
 }

 const QuickOrderDrawer = ({
   testId = 'fs-quick-order-drawer',
   isOpen,
   overlayProps,
   formatter,
   initialAlertMessage,
   initialProducts,
+  onAddToCart,
   children,
 }: PropsWithChildren<QuickOrderDrawerProps>) => {
   const { fade } = useFadeEffect()
   return (
     <QuickOrderDrawerProvider
       formatter={formatter}
       initialAlertMessage={initialAlertMessage}
       initialProducts={initialProducts}
+      onAddToCart={onAddToCart}
     >

Also applies to: 55-59

🤖 Prompt for AI Agents
In `@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawer.tsx`
around lines 12 - 42, Add an onAddToCart callback to QuickOrderDrawerProps and
forward it through QuickOrderDrawer to the provider: declare onAddToCart?:
(items: Product[] | /* match existing provider signature */ any) => void on the
QuickOrderDrawerProps type, accept that prop in the QuickOrderDrawer component
and pass it into QuickOrderDrawerProvider so QuickOrderDrawerFooter can invoke
it; ensure the prop name matches QuickOrderDrawerProvider's expected callback
and update any prop passthrough logic (QuickOrderDrawer ->
QuickOrderDrawerProvider) accordingly.

Comment thread packages/storybook/package.json Resolved
Comment on lines +2 to +3
@import "../../molecules/Tooltip/styles";
@import "../../molecules/Alert/styles";

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 | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# Check if Tooltip and Alert styles are imported in the global components.scss
rg -n "Tooltip/styles|Alert/styles" packages/ui/src/styles/components.scss

Repository: vtex/faststore

Length of output: 161


🏁 Script executed:

# Also check the context of the QuickOrderDrawer imports
cat -n packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss | head -20

Repository: vtex/faststore

Length of output: 934


🏁 Script executed:

# Check the structure of components.scss to understand the import pattern
cat -n packages/ui/src/styles/components.scss | head -50

Repository: vtex/faststore

Length of output: 2775


Remove the nested @import statements to avoid style duplication.

Tooltip and Alert styles are already imported globally in packages/ui/src/styles/components.scss (lines 64 and 23 respectively). The nested imports within [data-fs-quick-order-drawer] cause these same CSS rules to be duplicated in the compiled output. Either remove these nested imports if the global scope is sufficient, or remove them from components.scss if scoped imports are intentional.

🤖 Prompt for AI Agents
In `@packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss` around
lines 2 - 3, Remove the nested `@import` "../../molecules/Tooltip/styles"; and
`@import` "../../molecules/Alert/styles"; from QuickOrderDrawer's styles.scss to
avoid duplicating Tooltip and Alert rules already pulled in by the global
components.scss; locate the imports inside the [data-fs-quick-order-drawer]
scoped styles and delete them (or alternatively, if you intended scoped-only
inclusion, remove those same imports from packages/ui/src/styles/components.scss
instead) so the styles are only imported once.

@ArthurTriis1
ArthurTriis1 force-pushed the feat/quick-order-by-file-feature-branch branch from 6a8e751 to c197935 Compare February 10, 2026 14:05
@ArthurTriis1
ArthurTriis1 changed the base branch from main to dev February 10, 2026 14:06
@ataideverton
ataideverton force-pushed the feat/quick-order-by-file-feature-branch branch from c197935 to 39812ab Compare February 23, 2026 21:33
giurigaud and others added 3 commits March 4, 2026 16:02
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]>
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 #3109

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

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

<!--- 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. --->

- [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)

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

* **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 force-pushed the feat/quick-order-by-file-feature-branch branch from a38c730 to 462fe6a Compare March 4, 2026 19:05
## 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

<!--- 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

<!--- 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 --->

## 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**

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

**Dependencies**

- [x] 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
-->
## 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
<!-- 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: Everton Ataide <[email protected]>
Co-authored-by: Ícaro Oliveira <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@ArthurTriis1
ArthurTriis1 marked this pull request as ready for review March 27, 2026 18:21

@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: 15

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/atoms/Link/Link.tsx (1)

32-62: ⚠️ Potential issue | 🟡 Minor

Add polymorphic type cast for type safety with as prop usage.

Link is missing the polymorphic type cast that similar components like List and AccordionItem use. With the explicit HTMLAnchorElement ref typing but no cast, TypeScript won't properly infer types when consumers use the as prop with different element types, reducing type safety.

🔧 Proposed fix
+type LinkComponent = <C extends LinkElementType = 'a'>(
+  props: LinkProps<C>
+) => React.ReactElement | null
+
 const Link = forwardRef<
   HTMLAnchorElement,
   Omit<LinkProps<LinkElementType>, 'ref'>
 >(function Link<C extends LinkElementType = 'a'>(
   {
     as,
     children,
     variant = 'default',
     size = 'regular',
     inverse,
     testId = 'fs-link',
     ...otherProps
   }: LinkProps<C>,
   ref?: PolymorphicRef<C>
 ) {
   const Component = as ?? 'a'

   return (
     <Component
       ref={ref}
       data-fs-link
       data-fs-link-variant={variant}
       data-fs-link-inverse={inverse}
       data-fs-link-size={size}
       data-testid={testId}
       {...otherProps}
     >
       {children}
     </Component>
   )
-})
+}) as LinkComponent

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

In `@packages/components/src/atoms/Link/Link.tsx` around lines 32 - 62, The Link
component's forwardRef call lacks the polymorphic type cast, so TypeScript can't
infer correct props when consumers use the as prop; fix by casting the
forwardRef result to the polymorphic signature used by other components: ensure
the exported Link is typed as a generic polymorphic component (e.g., a generic
<C extends LinkElementType = 'a'>(props: LinkProps<C>, ref?: PolymorphicRef<C>)
=> JSX.Element) by applying an explicit "as" cast to the forwardRef(...) result
and keeping references to LinkProps, LinkElementType and PolymorphicRef so the
as prop and ref types are preserved for different element types.
packages/components/src/molecules/SearchInputField/SearchInputField.tsx (1)

13-16: ⚠️ Potential issue | 🔴 Critical

Broaden ButtonProps to match what IconButton accepts.

The local ButtonProps type only allows onClick and testId, but SearchInput.tsx passes 'aria-label' through attachmentButtonProps when calling this component. This creates a type mismatch—the property is valid for IconButton but your type definition rejects it.

Update the type to reflect what the buttons actually need:

Suggested fix
 import type {
   AriaAttributes,
+  ComponentPropsWithoutRef,
   FormEvent,
   InputHTMLAttributes,
   ReactNode,
 } from 'react'

-type ButtonProps = {
-  onClick?: () => void
-  testId?: string
-}
+type ButtonProps = Omit<
+  ComponentPropsWithoutRef<typeof IconButton>,
+  'type' | 'icon' | 'size'
+>
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/components/src/molecules/SearchInputField/SearchInputField.tsx`
around lines 13 - 16, The ButtonProps type in SearchInputField.tsx is too narrow
(only onClick/testId) and rejects valid props passed from SearchInput.tsx via
attachmentButtonProps (e.g., 'aria-label'); update ButtonProps to include the
real IconButton props by extending the IconButton prop type (for example extend
React.ComponentProps<typeof IconButton> or import and extend IconButtonProps) so
attachmentButtonProps can accept aria-label and other IconButton attributes
while preserving onClick/testId.
♻️ Duplicate comments (2)
packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss (1)

2-12: ⚠️ Potential issue | 🟡 Minor

Nested @import statements cause duplicate styles and Stylelint errors.

These imports are nested inside the [data-fs-quick-order-drawer] selector, which:

  1. Violates Stylelint's no-invalid-position-at-import-rule (imports must be at root)
  2. Duplicates styles already imported globally in packages/ui/src/styles/components.scss

Move these imports to the top of the file or remove them entirely if global imports suffice.

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

In `@packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss` around
lines 2 - 12, The SCSS file currently places multiple `@import` statements inside
the [data-fs-quick-order-drawer] selector which causes Stylelint errors and
duplicated CSS; move all those `@import` lines (Badge, Button, Icon, Overlay,
Price, Skeleton, Alert, QuantitySelector, Table, Tooltip, SlideOver) to the top
of packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss (or remove
them if they are already included in the global components.scss), and ensure no
`@import` remains nested inside the [data-fs-quick-order-drawer] selector so
imports are at root level and duplicates are avoided.
packages/components/src/organisms/QuickOrderDrawer/provider/QuickOrderDrawerProvider.tsx (1)

175-186: 🛠️ Refactor suggestion | 🟠 Major

Context value object still not memoized.

This was flagged in a previous review. The value object is recreated on every render, causing all context consumers to re-render unnecessarily. Wrap in useMemo.

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

In
`@packages/components/src/organisms/QuickOrderDrawer/provider/QuickOrderDrawerProvider.tsx`
around lines 175 - 186, The context value object named `value` in
`QuickOrderDrawerProvider` is recreated on every render; wrap its creation in
`useMemo` so consumers don't rerender unnecessarily—create `const value =
useMemo(() => ({ products, totalPrice, itemsCount, alertMessage, isLoading,
setAlertMessage, onChangeQuantityItem, onDelete, onAddToCart, formatter }),
[products, totalPrice, itemsCount, alertMessage, isLoading, setAlertMessage,
onChangeQuantityItem, onDelete, onAddToCart, formatter])` and return that
memoized `value` from the provider.
🧹 Nitpick comments (14)
packages/ui/src/components/molecules/FileUploadCard/styles.scss (1)

17-18: Consider using design tokens for hardcoded colors.

Lines 17-18 and elsewhere (161-162) use hardcoded hex values (#0366dd, #ffffff, #bfdbfe). For theme consistency and maintainability, consider replacing these with existing CSS variables or defining new tokens.

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

In `@packages/ui/src/components/molecules/FileUploadCard/styles.scss` around lines
17 - 18, Replace the hardcoded hex colors in the FileUploadCard styles by using
existing design tokens or new CSS variables: swap
--fs-file-upload-card-badge-bg-color (`#0366dd`),
--fs-file-upload-card-shadow-color (`#bfdbfe`) and any other hex usages (e.g.,
`#ffffff`) with appropriate global theme variables (or define new tokens if none
exist), update the declarations in styles.scss to reference those token names,
and ensure any components consuming --fs-file-upload-card-* properties use the
new tokens for consistent theming.
packages/components/src/hooks/useFileUpload.ts (1)

67-77: Only first file's first error is shown — intentional simplification.

When multiple files are rejected or a file has multiple errors, only the first error is displayed. This is a reasonable UX choice for single-file uploads (the default), but if multi-file support grows, consider aggregating or listing multiple errors.

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

In `@packages/components/src/hooks/useFileUpload.ts` around lines 67 - 77, The
current onFilesRejected handler only reads the first FileRejection's first error
and sets a single message via setUploadError, so multiple rejected files or
multiple errors per file are dropped; update onFilesRejected to aggregate errors
from all fileRejections (iterate fileRejections and their errors), map each
error.code through getErrorMessage, and combine them into a single user-friendly
string or array before calling setUploadError (or adjust setUploadError to
accept an array) so all rejection reasons are surfaced; keep references to
onFilesRejected, FileRejection, getErrorMessage, and setUploadError when making
the change.
packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss (1)

62-63: Consider using design tokens for hardcoded footer colors.

#858585 and #f5f5f5 could be replaced with existing neutral color tokens for theme consistency.

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

In `@packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss` around
lines 62 - 63, Replace the two hardcoded CSS color values used for the quick
order drawer footer with the project's neutral design tokens: swap
--fs-quick-order-drawer-footer-icon-color (`#858585`) and
--fs-quick-order-drawer-footer-icon-bkg (`#f5f5f5`) to reference the existing
neutral tokens (for example use tokens like --color-neutral-500 for the icon
color and --color-neutral-100 for the background or whichever neutral tokens
match the design system). Update the variables in styles.scss so they use
var(--your-neutral-token) instead of the hex literals to ensure theme
consistency and theming support.
packages/core/src/utils/utilities.ts (1)

161-172: Consider handling NaN input for robustness.

If bytes is NaN, the function will return "NaN undefined" since NaN <= 0 is false, and subsequent calculations propagate NaN.

🛡️ Suggested defensive check
 export const formatFileSize = (bytes: number): string => {
-  if (bytes <= 0) return '0 Bytes'
+  if (!Number.isFinite(bytes) || bytes <= 0) return '0 Bytes'

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

In `@packages/core/src/utils/utilities.ts` around lines 161 - 172, The
formatFileSize function doesn't guard against NaN or non-finite inputs, causing
"NaN undefined" results; update formatFileSize to validate the input at the top
(e.g., use Number.isFinite or !Number.isNaN) and treat non-finite/NaN values the
same as non-positive values (return "0 Bytes" or another safe default), so add a
defensive check before computing k, sizes, and i to early-return for invalid
numbers.
packages/components/src/molecules/Dropzone/Dropzone.tsx (1)

173-184: Flatten accessibilityProps conditional for readability.

This nested conditional is harder to scan; a flat/early-return style is easier to maintain.

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

🤖 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 173 -
184, accessibilityProps is built with a nested ternary that reduces readability;
replace it with a flat conditional that first returns {} when ariaLabel is falsy
and otherwise builds the props object, setting role: 'button' and 'aria-label':
ariaLabel and adding 'aria-disabled': true only when disabled is truthy — update
the expression that defines accessibilityProps (references: accessibilityProps,
ariaLabel, disabled, role, 'aria-label', 'aria-disabled') to use a single-level
conditional or early-return style so the structure is easier to scan.
packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx (3)

134-151: Consider extracting skeleton rendering to reduce nesting.

The triple-nested ternary (showSkeleton ? ... : products.length > 0 ? ... : ...) increases cognitive load. Consider extracting to early returns or separate render functions for skeleton/products/empty states.

♻️ Optional refactor using early returns pattern
const renderTableContent = () => {
  if (showSkeleton) {
    return <SkeletonRows />
  }
  if (products.length > 0) {
    return <ProductRows products={products} ... />
  }
  return <EmptyStateRow ... />
}
🤖 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 134 - 151, The nested ternary that renders skeleton/products/empty
inside QuickOrderDrawerProducts is hard to read; extract the branches into a
small render helper or components: create a renderTableContent function (or
separate components like SkeletonRows, ProductRows and EmptyStateRow) and
replace the inline ternary using showSkeleton, products.length, and the existing
TableRow/TableCell/Skeleton rendering logic with early-return branches so each
case is isolated and easier to test and maintain.

275-282: Hardcoded color value reduces theme flexibility.

The color="#1F1F1F" on the trash icon bypasses the design token system. Consider using a CSS variable or removing the inline color to inherit from styles.

♻️ Suggested fix
-<Icon name="Thrash" color="#1F1F1F" />
+<Icon name="Thrash" />
🤖 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 - 282, The Trash icon is using a hardcoded color via the Icon
prop color="#1F1F1F" in the IconButton inside QuickOrderDrawerProducts (see
IconButton / Icon with name="Thrash" and onClick={() =>
onDelete(variantProduct.id)}); remove the inline hex color and instead allow the
icon to inherit styles from CSS/theme tokens (either remove the color prop or
replace it with a CSS variable or design token such as color="var(--color-icon)"
or the appropriate theme token) so the component respects the app theme.

244-270: Inline callback recreated on every render.

The onValidateBlur handler creates a new function reference on each render. While not critical for a table row, wrapping with useCallback at the component level or memoizing the row component would improve performance for larger product lists.

🤖 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 244 - 270, The inline onValidateBlur callback in
QuickOrderDrawerProducts is recreated on every render; move it out of the JSX
and memoize it with React.useCallback (e.g., create a const handleValidateBlur =
useCallback((min, maxValue, quantity) => { ...pushToast... }, [messages,
pushToast])) and pass that stable handleValidateBlur into the row prop instead
of the inline function so the function identity remains stable (ensure
dependencies include messages and pushToast and any other referenced values).
packages/core/src/components/search/SearchInput/SearchInput.tsx (2)

621-669: QuickOrderDrawer always renders even when closed.

The drawer component mounts regardless of isQuickOrderDrawerOpen. For bundle size and initial render performance, consider conditional rendering or lazy loading.

♻️ Conditional render suggestion
-<QuickOrderDrawer
-  isOpen={isQuickOrderDrawerOpen}
-  ...
->
+{isQuickOrderDrawerOpen && (
+  <QuickOrderDrawer
+    isOpen={isQuickOrderDrawerOpen}
+    ...
+  >
+    ...
+  </QuickOrderDrawer>
+)}

Or use dynamic import for the entire drawer.

🤖 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
621 - 669, QuickOrderDrawer is mounted regardless of isQuickOrderDrawerOpen
causing unnecessary bundle and render cost; wrap the QuickOrderDrawer JSX in a
conditional so it only renders when isQuickOrderDrawerOpen is true (or replace
with a dynamic import/React.lazy and Suspense to lazy-load the component) and
ensure any state-reset callbacks (setIsQuickOrderDrawerOpen,
setQuickOrderProducts, setSkusToFetch, setSkuQuantityMap) and child components
(QuickOrderDrawerHeader, QuickOrderDrawerProducts, QuickOrderDrawerFooter)
remain inside that conditional/lazy boundary so behavior is unchanged when
opened.

351-425: Complex state machine in useEffect is difficult to maintain.

This effect handles 4 different state transitions with nested conditions. Consider extracting to a custom hook or using a state machine library (e.g., XState) for clarity.

🤖 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
351 - 425, The useEffect in SearchInput.tsx has a complex state machine handling
multiple transitions; extract this logic into a focused custom hook (e.g.,
useQuickOrderState or useQuickOrderEffect) to improve readability and
testability: move the branching that inspects fetchedProducts, skusToFetch,
skuQuantityMap, and isLoadingProducts into the hook, keep the UI setters
(setQuickOrderProducts, setIsLoadingWithDelay, setIsQuickOrderDrawerOpen,
setFileUploadVisible, setNoProductsError) as effects/return values from the
hook, and encapsulate the timeout/cleanup and conversion via
convertProductToQuickOrder inside the hook so SearchInput only calls the hook
and applies its returned state/actions; preserve current behavior (including the
2s artificial delay and clearing timeout) and ensure the hook accepts inputs
fetchedProducts, skusToFetch, skuQuantityMap, and isLoadingProducts.
packages/components/src/molecules/FileUploadStatus/FileUploadStatus.tsx (1)

188-202: getErrorMessage() called twice in error state render.

Each call to getErrorMessage() recalculates the result. Extract to a variable for efficiency.

♻️ Suggested fix
 {state === FileUploadState.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>
+        <p data-fs-file-upload-status-text-error>{description}</p>
+      </>
+    )
+  })()

Or better, compute once before the return:

const errorInfo = state === FileUploadState.Error ? getErrorMessage() : null
🤖 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 188 - 202, The render calls getErrorMessage() twice when state ===
FileUploadState.Error which recomputes unnecessarily; compute it once before
returning (e.g., const errorInfo = state === FileUploadState.Error ?
getErrorMessage() : null) and replace both calls in the JSX with errorInfo.title
and errorInfo.description so FileUploadStatus uses the cached result; update
references to getErrorMessage() in the FileUploadStatus component accordingly.
packages/ui/src/components/molecules/SearchInputField/styles.scss (2)

99-105: Hardcoded fallback color should use design token.

The #e0e0e0 fallback bypasses the design system. If --fs-border-color-light isn't defined, consider using another existing token as fallback.

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

In `@packages/ui/src/components/molecules/SearchInputField/styles.scss` around
lines 99 - 105, The selector [data-fs-search-input-field-separator] currently
uses a hardcoded fallback color (`#e0e0e0`); replace that literal with a design
token fallback so the design system is preserved — update the background-color
declaration in styles for [data-fs-search-input-field-separator] to use
var(--fs-border-color-light, var(--fs-border-color)) (or another existing
neutral token used across the codebase) instead of `#e0e0e0` so it falls back to a
sanctioned design token.

107-113: Magic numbers for upload button positioning.

The 2.5rem and 3rem values would benefit from CSS variables or comments explaining the calculation (likely submit-button-width + gap).

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

In `@packages/ui/src/components/molecules/SearchInputField/styles.scss` around
lines 107 - 113, Replace the hardcoded magic numbers used to position the upload
button in the selector [data-fs-search-input-field]
[data-fs-search-input-field-upload-button] (currently 2.5rem and 3rem) with
named CSS variables or a calc expression (e.g. --upload-button-right or
calc(var(--submit-button-width) + var(--gap))) so the positioning is explicit
and maintainable; add the variable declarations (and a short comment describing
the formula, e.g. "submit-button-width + gap") in the relevant scope
(component/root) and update the media query to reference the same variable (e.g.
--upload-button-right-notebook) or adjust via calc so both desktop and notebook
values are expressed clearly.
packages/core/src/components/sections/Navbar/Navbar.tsx (1)

104-106: Narrow fileUploadCard.errorMessages keys for stronger type safety.

Partial<Record<string, ...>> allows arbitrary keys and weakens compile-time validation. Prefer a constrained union (or shared error-key type) so CMS config typos are caught at build time.

♻️ Suggested typing shape
+type QuickOrderFileUploadErrorKey =
+  // use the canonical keys from parser/upload flow
+  // e.g. 'invalidFileType' | 'missingHeaders' | ...
+  string

       errorMessages?: Partial<
-        Record<string, { title?: string; description?: string }>
+        Record<QuickOrderFileUploadErrorKey, { title?: string; description?: string }>
       >

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/sections/Navbar/Navbar.tsx` around lines 104 -
106, The prop typing for fileUploadCard.errorMessages in Navbar (errorMessages?:
Partial<Record<string, { title?: string; description?: string }>>) is too
permissive; replace the arbitrary string keys with a constrained union or shared
error-key type (e.g., define a FileUploadCardErrorKey union or reuse a central
ErrorKeys type) and use Partial<Record<FileUploadCardErrorKey, { title?: string;
description?: string }>> so misspelled CMS keys are caught at compile time;
update the Navbar prop/interface that declares errorMessages and any consumers
to use the new union type.
🤖 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 113: The Promise executor is async which can swallow synchronous throws
(e.g., from detectDelimiter); refactor by removing the async keyword from the
Promise executor in useCSVParser (the function that currently does return new
Promise(async (resolve, reject) => { ... } ). Instead create a synchronous
executor that starts an inner async function (e.g., async function run() { ...
}) and call run().catch(reject), or wrap the body in try/catch and use
.then/.catch for any async operations; ensure any call to detectDelimiter and
subsequent awaits are inside that inner async function and that all errors are
forwarded to reject.

In `@packages/components/src/molecules/Dropzone/Dropzone.tsx`:
- Around line 96-104: The file contains a duplicated TypeScript interface
declaration for DropzoneState (both declarations declare acceptedFiles: File[]
and fileRejections: FileRejection[]); remove the redundant declaration and keep
a single DropzoneState interface declaration (with acceptedFiles and
fileRejections) to avoid duplicate symbol errors and confusion, then run type
checks to ensure no other code depended on the duplicate.
- Around line 170-171: The Dropzone currently calls getRootProps() with no args
and then spreads otherProps after rootProps which allows user event handlers to
override internal handlers; update the code to pass custom props into
getRootProps(otherProps) (and similarly pass relevant props into getInputProps
when applicable) so react-dropzone composes handlers correctly, keep merging
refs via mergeRefs(ref, rootProps.ref) (or adjust to use the returned ref from
getRootProps), and remove the separate spread of otherProps after rootProps to
prevent handler overriding.

In `@packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx`:
- Around line 287-300: The fallback branch in handleDownloadTemplate (when
onDownloadTemplate is not provided) can throw if window.URL.createObjectURL is
unavailable; wrap the entire blob creation/download logic in a try-catch-finally
around the createObjectURL, anchor click, and revoke steps, log or surface the
caught error via console.error or a passed-in logger, and ensure
window.URL.revokeObjectURL(url) runs in finally only if url was created; keep
handleDownloadTemplate and onDownloadTemplate usage unchanged.
- Around line 212-236: handleFileChange and handleDrop duplicate the same
validation and state-setting logic; extract that logic into a shared helper
function (e.g., processSelectedFiles(files: File[])) that performs: select first
file and call setSelectedFile, validate via isValidFileType and set
FileUploadState.Error and FileUploadErrorType.Unsupported when invalid, clear
error with setErrorType(undefined) when valid, set upload state to
FileUploadState.Uploading or FileUploadState.Completed based on isUploading, and
invoke onFileSelect(files) if provided; then replace the body of both
handleFileChange and handleDrop to call this new helper to remove duplication
and keep behavior identical.
- Around line 175-192: The effect in FileUploadCard (useEffect watching
selectedFile, hasError, isUploading, errorTypeProp) causes duplicated/unsynced
state between the component and its parent (SearchInput); decide on a single
source of truth: either make FileUploadCard fully controlled by removing
internal uploadState and errorType (and instead render directly from props
hasError/isUploading/errorTypeProp), or lift the internal validation
(isValidFileType) into the parent so the parent controls hasError and
errorTypeProp; update/remove setUploadState and setErrorType usage accordingly
(and remove the useEffect that mirrors props into state) or, if choosing
controlled mode, update SearchInput to perform validation and pass the resulting
error/upload state into FileUploadCard.

In
`@packages/components/src/organisms/QuickOrderDrawer/provider/QuickOrderDrawerProvider.tsx`:
- Around line 125-131: The effect calling setAlertMessage uses getAlertMessage
but doesn't include it in dependencies; memoize getAlertMessage with useCallback
(e.g., wrap the existing getAlertMessage function in useCallback with
dependencies it uses) and then add getAlertMessage to the useEffect dependency
array, or alternatively move getAlertMessage outside the component if it has no
local state/props dependencies; ensure the getAlertMessage useCallback includes
only the necessary dependencies to avoid rerenders and prevent infinite loops.

In `@packages/core/cms/faststore/sections.json`:
- Around line 614-623: The NavbarProps fileUploadCard type is missing two schema
fields; update the fileUploadCard type in Navbar.tsx (the NavbarProps/interface
definition) to include dropzoneDragActiveText?: string and dropzoneText?: string
so the TypeScript contract matches the sections.json schema for the file upload
card configuration.

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx`:
- Around line 348-349: The call to useBulkProductsQuery currently ignores the
error return, so network/GraphQL failures are treated as empty results; update
the destructuring to also grab the error (e.g., const { products:
fetchedProducts, isLoading: isLoadingProducts, error: fetchError } =
useBulkProductsQuery(skusToFetch)), then handle fetchError in the effect that
consumes fetchedProducts (or show a user-facing toast/notification) so failures
are surfaced instead of silently returning no products; reference the
useBulkProductsQuery hook and the fetchedProducts/isLoadingProducts variables
when making the change.
- Around line 369-405: The artificial 2s timeout in the SearchInput flow (where
timeoutId is created, setIsLoadingWithDelay(true) is called and
convertedProducts is built using convertProductToQuickOrder) must not ship;
either remove the setTimeout completely and run the conversion synchronously
(then call setQuickOrderProducts, setIsQuickOrderDrawerOpen,
setFileUploadVisible, setNoProductsError immediately), or gate the delay behind
a configurable feature flag/env/prop (e.g., only use setTimeout(delay) when a
debug flag is true). Update the code around setIsLoadingWithDelay, timeoutId,
and the block that calls
setQuickOrderProducts/setIsQuickOrderDrawerOpen/setFileUploadVisible/setNoProductsError
so production builds do not include the hardcoded 2000ms delay.
- Around line 611-616: The conditional spread in SearchInput.tsx can still
access csvError.type when csvError is falsy (because the outer expression can be
true due to noProductsError); update the spread so csvError.type is only read
when csvError is non-null—e.g., compute errorType and errorMessage with a safe
guard: if noProductsError set errorType to FileUploadErrorType.NoProductsFound
and errorMessage undefined, otherwise (when csvError exists) call
mapCSVErrorToFileUploadErrorType(csvError.type) and use csvError.message; ensure
the object spread uses these precomputed values instead of directly referencing
csvError.type inside the conditional expression.

In `@packages/core/src/sdk/product/useBulkProductsQuery.ts`:
- Around line 43-125: The effect in useBulkProductsQuery can let stale batch
fetches overwrite newer state; fix by adding an abort/sequencing guard and
resetting error when skus is empty: create an AbortController or a requestId
counter inside the useEffect (used by fetchProducts and its inner batch map) and
check the controller.signal.aborted or compare requestId before calling
setProducts, setError or setIsLoading (and abort any in-flight requests and
clear pending timeouts between batches using the same controller/requestId), and
in the early-return branch where skus.length === 0 also call setError(null)
along with setProducts([]) and setIsLoading(false); ensure cleanup function
aborts the controller or increments the requestId to ignore in-flight results.

In `@packages/core/src/styles/global/index.scss`:
- Around line 14-15: Re-add the global Dropdown stylesheet import to
packages/core/src/styles/global/index.scss so Dropdown menus used by components
like MyAccountOrderActions
(packages/core/src/components/account/orders/.../MyAccountOrderActions.tsx)
remain styled; find the Dropdown styles file under the `@faststore/ui` package
(e.g. the component folder that contains Dropdown) and add an `@import` for its
styles.scss alongside the existing QuickOrderDrawer and SlideOver imports so the
dropdown styles are bundled globally.

In `@packages/storybook/stories/upload-file-dropdown.stories.tsx`:
- Around line 79-85: The formatFileSize function can misbehave for negative
bytes or when the computed index i goes outside sizes bounds; update
formatFileSize to first coerce/validate the input (treat negative or non-finite
bytes as 0 or throw), keep the existing zero check, then compute i and clamp it
between 0 and sizes.length - 1 (e.g., use Math.max/Math.min) before indexing
sizes so you never read out of bounds, and ensure the formatted value uses the
clamped divisor; reference the function name formatFileSize and the sizes/i
variables when making the change.

In `@packages/ui/src/components/molecules/FileUploadStatus/styles.scss`:
- Around line 74-75: Replace the CSS keyword casing for the SVG color properties
in packages/ui/src/components/molecules/FileUploadStatus/styles.scss: change all
occurrences of fill: currentColor; and stroke: currentColor; to use the
lowercase keyword currentcolor (affecting the three icon blocks around the
existing fill/stroke declarations noted at lines 74-75, 102-103, and 119-120).
Update every fill and stroke occurrence in the file to use currentcolor so
Stylelint no longer flags the casing rule.

---

Outside diff comments:
In `@packages/components/src/atoms/Link/Link.tsx`:
- Around line 32-62: The Link component's forwardRef call lacks the polymorphic
type cast, so TypeScript can't infer correct props when consumers use the as
prop; fix by casting the forwardRef result to the polymorphic signature used by
other components: ensure the exported Link is typed as a generic polymorphic
component (e.g., a generic <C extends LinkElementType = 'a'>(props:
LinkProps<C>, ref?: PolymorphicRef<C>) => JSX.Element) by applying an explicit
"as" cast to the forwardRef(...) result and keeping references to LinkProps,
LinkElementType and PolymorphicRef so the as prop and ref types are preserved
for different element types.

In `@packages/components/src/molecules/SearchInputField/SearchInputField.tsx`:
- Around line 13-16: The ButtonProps type in SearchInputField.tsx is too narrow
(only onClick/testId) and rejects valid props passed from SearchInput.tsx via
attachmentButtonProps (e.g., 'aria-label'); update ButtonProps to include the
real IconButton props by extending the IconButton prop type (for example extend
React.ComponentProps<typeof IconButton> or import and extend IconButtonProps) so
attachmentButtonProps can accept aria-label and other IconButton attributes
while preserving onClick/testId.

---

Duplicate comments:
In
`@packages/components/src/organisms/QuickOrderDrawer/provider/QuickOrderDrawerProvider.tsx`:
- Around line 175-186: The context value object named `value` in
`QuickOrderDrawerProvider` is recreated on every render; wrap its creation in
`useMemo` so consumers don't rerender unnecessarily—create `const value =
useMemo(() => ({ products, totalPrice, itemsCount, alertMessage, isLoading,
setAlertMessage, onChangeQuantityItem, onDelete, onAddToCart, formatter }),
[products, totalPrice, itemsCount, alertMessage, isLoading, setAlertMessage,
onChangeQuantityItem, onDelete, onAddToCart, formatter])` and return that
memoized `value` from the provider.

In `@packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss`:
- Around line 2-12: The SCSS file currently places multiple `@import` statements
inside the [data-fs-quick-order-drawer] selector which causes Stylelint errors
and duplicated CSS; move all those `@import` lines (Badge, Button, Icon, Overlay,
Price, Skeleton, Alert, QuantitySelector, Table, Tooltip, SlideOver) to the top
of packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss (or remove
them if they are already included in the global components.scss), and ensure no
`@import` remains nested inside the [data-fs-quick-order-drawer] selector so
imports are at root level and duplicates are avoided.

---

Nitpick comments:
In `@packages/components/src/hooks/useFileUpload.ts`:
- Around line 67-77: The current onFilesRejected handler only reads the first
FileRejection's first error and sets a single message via setUploadError, so
multiple rejected files or multiple errors per file are dropped; update
onFilesRejected to aggregate errors from all fileRejections (iterate
fileRejections and their errors), map each error.code through getErrorMessage,
and combine them into a single user-friendly string or array before calling
setUploadError (or adjust setUploadError to accept an array) so all rejection
reasons are surfaced; keep references to onFilesRejected, FileRejection,
getErrorMessage, and setUploadError when making the change.

In `@packages/components/src/molecules/Dropzone/Dropzone.tsx`:
- Around line 173-184: accessibilityProps is built with a nested ternary that
reduces readability; replace it with a flat conditional that first returns {}
when ariaLabel is falsy and otherwise builds the props object, setting role:
'button' and 'aria-label': ariaLabel and adding 'aria-disabled': true only when
disabled is truthy — update the expression that defines accessibilityProps
(references: accessibilityProps, ariaLabel, disabled, role, 'aria-label',
'aria-disabled') to use a single-level conditional or early-return style so the
structure is easier to scan.

In `@packages/components/src/molecules/FileUploadStatus/FileUploadStatus.tsx`:
- Around line 188-202: The render calls getErrorMessage() twice when state ===
FileUploadState.Error which recomputes unnecessarily; compute it once before
returning (e.g., const errorInfo = state === FileUploadState.Error ?
getErrorMessage() : null) and replace both calls in the JSX with errorInfo.title
and errorInfo.description so FileUploadStatus uses the cached result; update
references to getErrorMessage() in the FileUploadStatus component accordingly.

In
`@packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerProducts.tsx`:
- Around line 134-151: The nested ternary that renders skeleton/products/empty
inside QuickOrderDrawerProducts is hard to read; extract the branches into a
small render helper or components: create a renderTableContent function (or
separate components like SkeletonRows, ProductRows and EmptyStateRow) and
replace the inline ternary using showSkeleton, products.length, and the existing
TableRow/TableCell/Skeleton rendering logic with early-return branches so each
case is isolated and easier to test and maintain.
- Around line 275-282: The Trash icon is using a hardcoded color via the Icon
prop color="#1F1F1F" in the IconButton inside QuickOrderDrawerProducts (see
IconButton / Icon with name="Thrash" and onClick={() =>
onDelete(variantProduct.id)}); remove the inline hex color and instead allow the
icon to inherit styles from CSS/theme tokens (either remove the color prop or
replace it with a CSS variable or design token such as color="var(--color-icon)"
or the appropriate theme token) so the component respects the app theme.
- Around line 244-270: The inline onValidateBlur callback in
QuickOrderDrawerProducts is recreated on every render; move it out of the JSX
and memoize it with React.useCallback (e.g., create a const handleValidateBlur =
useCallback((min, maxValue, quantity) => { ...pushToast... }, [messages,
pushToast])) and pass that stable handleValidateBlur into the row prop instead
of the inline function so the function identity remains stable (ensure
dependencies include messages and pushToast and any other referenced values).

In `@packages/core/src/components/search/SearchInput/SearchInput.tsx`:
- Around line 621-669: QuickOrderDrawer is mounted regardless of
isQuickOrderDrawerOpen causing unnecessary bundle and render cost; wrap the
QuickOrderDrawer JSX in a conditional so it only renders when
isQuickOrderDrawerOpen is true (or replace with a dynamic import/React.lazy and
Suspense to lazy-load the component) and ensure any state-reset callbacks
(setIsQuickOrderDrawerOpen, setQuickOrderProducts, setSkusToFetch,
setSkuQuantityMap) and child components (QuickOrderDrawerHeader,
QuickOrderDrawerProducts, QuickOrderDrawerFooter) remain inside that
conditional/lazy boundary so behavior is unchanged when opened.
- Around line 351-425: The useEffect in SearchInput.tsx has a complex state
machine handling multiple transitions; extract this logic into a focused custom
hook (e.g., useQuickOrderState or useQuickOrderEffect) to improve readability
and testability: move the branching that inspects fetchedProducts, skusToFetch,
skuQuantityMap, and isLoadingProducts into the hook, keep the UI setters
(setQuickOrderProducts, setIsLoadingWithDelay, setIsQuickOrderDrawerOpen,
setFileUploadVisible, setNoProductsError) as effects/return values from the
hook, and encapsulate the timeout/cleanup and conversion via
convertProductToQuickOrder inside the hook so SearchInput only calls the hook
and applies its returned state/actions; preserve current behavior (including the
2s artificial delay and clearing timeout) and ensure the hook accepts inputs
fetchedProducts, skusToFetch, skuQuantityMap, and isLoadingProducts.

In `@packages/core/src/components/sections/Navbar/Navbar.tsx`:
- Around line 104-106: The prop typing for fileUploadCard.errorMessages in
Navbar (errorMessages?: Partial<Record<string, { title?: string; description?:
string }>>) is too permissive; replace the arbitrary string keys with a
constrained union or shared error-key type (e.g., define a
FileUploadCardErrorKey union or reuse a central ErrorKeys type) and use
Partial<Record<FileUploadCardErrorKey, { title?: string; description?: string
}>> so misspelled CMS keys are caught at compile time; update the Navbar
prop/interface that declares errorMessages and any consumers to use the new
union type.

In `@packages/core/src/utils/utilities.ts`:
- Around line 161-172: The formatFileSize function doesn't guard against NaN or
non-finite inputs, causing "NaN undefined" results; update formatFileSize to
validate the input at the top (e.g., use Number.isFinite or !Number.isNaN) and
treat non-finite/NaN values the same as non-positive values (return "0 Bytes" or
another safe default), so add a defensive check before computing k, sizes, and i
to early-return for invalid numbers.

In `@packages/ui/src/components/molecules/FileUploadCard/styles.scss`:
- Around line 17-18: Replace the hardcoded hex colors in the FileUploadCard
styles by using existing design tokens or new CSS variables: swap
--fs-file-upload-card-badge-bg-color (`#0366dd`),
--fs-file-upload-card-shadow-color (`#bfdbfe`) and any other hex usages (e.g.,
`#ffffff`) with appropriate global theme variables (or define new tokens if none
exist), update the declarations in styles.scss to reference those token names,
and ensure any components consuming --fs-file-upload-card-* properties use the
new tokens for consistent theming.

In `@packages/ui/src/components/molecules/SearchInputField/styles.scss`:
- Around line 99-105: The selector [data-fs-search-input-field-separator]
currently uses a hardcoded fallback color (`#e0e0e0`); replace that literal with a
design token fallback so the design system is preserved — update the
background-color declaration in styles for
[data-fs-search-input-field-separator] to use var(--fs-border-color-light,
var(--fs-border-color)) (or another existing neutral token used across the
codebase) instead of `#e0e0e0` so it falls back to a sanctioned design token.
- Around line 107-113: Replace the hardcoded magic numbers used to position the
upload button in the selector [data-fs-search-input-field]
[data-fs-search-input-field-upload-button] (currently 2.5rem and 3rem) with
named CSS variables or a calc expression (e.g. --upload-button-right or
calc(var(--submit-button-width) + var(--gap))) so the positioning is explicit
and maintainable; add the variable declarations (and a short comment describing
the formula, e.g. "submit-button-width + gap") in the relevant scope
(component/root) and update the media query to reference the same variable (e.g.
--upload-button-right-notebook) or adjust via calc so both desktop and notebook
values are expressed clearly.

In `@packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss`:
- Around line 62-63: Replace the two hardcoded CSS color values used for the
quick order drawer footer with the project's neutral design tokens: swap
--fs-quick-order-drawer-footer-icon-color (`#858585`) and
--fs-quick-order-drawer-footer-icon-bkg (`#f5f5f5`) to reference the existing
neutral tokens (for example use tokens like --color-neutral-500 for the icon
color and --color-neutral-100 for the background or whichever neutral tokens
match the design system). Update the variables in styles.scss so they use
var(--your-neutral-token) instead of the hex literals to ensure theme
consistency and theming support.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d8a5650f-0fd6-4033-8543-bd517ad47abf

📥 Commits

Reviewing files that changed from the base of the PR and between c76b34c and 862c393.

⛔ Files ignored due to path filters (5)
  • CHANGELOG.md 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 (47)
  • packages/cli/CHANGELOG.md
  • packages/components/CHANGELOG.md
  • packages/components/package.json
  • packages/components/src/atoms/Link/Link.tsx
  • packages/components/src/atoms/List/List.tsx
  • 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/Accordion/AccordionItem.tsx
  • packages/components/src/molecules/Dropzone/Dropzone.tsx
  • packages/components/src/molecules/Dropzone/index.ts
  • packages/components/src/molecules/FileUploadCard/FileUploadCard.tsx
  • packages/components/src/molecules/FileUploadCard/index.tsx
  • packages/components/src/molecules/FileUploadStatus/FileUploadStatus.tsx
  • packages/components/src/molecules/FileUploadStatus/index.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/CHANGELOG.md
  • packages/core/cms/faststore/sections.json
  • packages/core/src/components/search/SearchInput/SearchInput.tsx
  • 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/utilities.ts
  • packages/storybook/.storybook/main.js
  • packages/storybook/package.json
  • packages/storybook/stories/dropzone.stories.tsx
  • packages/storybook/stories/fileupload.stories.tsx
  • packages/storybook/stories/quick-order-drawer.stories.tsx
  • packages/storybook/stories/upload-file-dropdown.stories.tsx
  • packages/ui/package.json
  • packages/ui/src/components/molecules/Dropzone/styles.scss
  • packages/ui/src/components/molecules/FileUploadCard/styles.scss
  • packages/ui/src/components/molecules/FileUploadStatus/styles.scss
  • packages/ui/src/components/molecules/SearchInputField/styles.scss
  • packages/ui/src/components/organisms/QuickOrderDrawer/styles.scss
  • packages/ui/src/index.ts
  • packages/ui/src/styles/components.scss
💤 Files with no reviewable changes (1)
  • packages/cli/CHANGELOG.md
✅ Files skipped from review due to trivial changes (9)
  • packages/components/package.json
  • packages/components/src/molecules/Dropzone/index.ts
  • packages/ui/package.json
  • packages/ui/src/index.ts
  • packages/components/src/molecules/FileUploadStatus/index.tsx
  • packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerHeader.tsx
  • packages/ui/src/components/molecules/Dropzone/styles.scss
  • packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawerFooter.tsx
  • packages/components/src/organisms/QuickOrderDrawer/QuickOrderDrawer.tsx
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/ui/src/styles/components.scss
  • packages/storybook/package.json
  • packages/storybook/stories/quick-order-drawer.stories.tsx
  • packages/components/src/organisms/QuickOrderDrawer/index.ts

file: File,
options: WorkerCSVOptions = {}
): Promise<WorkerCSVData> => {
return new Promise(async (resolve, reject) => {

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

Async Promise executor is an anti-pattern.

Static analysis correctly flagged this. If the async function throws before the first await (e.g., during detectDelimiter), the error won't reject the promise—it'll be an unhandled rejection. Refactor to avoid async executor.

🐛 Proposed fix
 const parseCSVFile = (
   file: File,
   options: WorkerCSVOptions = {}
 ): Promise<WorkerCSVData> => {
-  return new Promise(async (resolve, reject) => {
+  return (async () => {
     const defaultOptions = { ... }
     const config = { ... }
-    const detectedDelimiter = await detectDelimiter()
+    const detectedDelimiter = await detectDelimiter(file, config.delimiter)
     
-    // ... rest of setup
-    
-    Papa.parse(file, {
-      // ...
-      complete: () => { resolve(...) },
-      error: (error) => { reject(...) },
-    })
-  })
+    return new Promise<WorkerCSVData>((resolve, reject) => {
+      // ... Papa.parse with resolve/reject
+    })
+  })()
 }
🧰 Tools
🪛 Biome (2.4.9)

[error] 113-346: Promise executor functions should not be async.

(lint/suspicious/noAsyncPromiseExecutor)

🤖 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 113, The Promise
executor is async which can swallow synchronous throws (e.g., from
detectDelimiter); refactor by removing the async keyword from the Promise
executor in useCSVParser (the function that currently does return new
Promise(async (resolve, reject) => { ... } ). Instead create a synchronous
executor that starts an inner async function (e.g., async function run() { ...
}) and call run().catch(reject), or wrap the body in try/catch and use
.then/.catch for any async operations; ensure any call to detectDelimiter and
subsequent awaits are inside that inner async function and that all errors are
forwarded to reject.

Comment on lines +96 to +104
export interface DropzoneState {
acceptedFiles: File[]
fileRejections: FileRejection[]
}

export interface DropzoneState {
acceptedFiles: File[]
fileRejections: FileRejection[]
}

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 | 🟡 Minor

Remove duplicated DropzoneState interface declaration.

DropzoneState is declared twice with identical members. Keep a single declaration to avoid confusion.

🧹 Suggested 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, The file contains a duplicated TypeScript interface declaration for
DropzoneState (both declarations declare acceptedFiles: File[] and
fileRejections: FileRejection[]); remove the redundant declaration and keep a
single DropzoneState interface declaration (with acceptedFiles and
fileRejections) to avoid duplicate symbol errors and confusion, then run type
checks to ensure no other code depended on the duplicate.

Comment on lines +170 to +171
const rootProps = getRootProps()
const mergedRef = mergeRefs(ref, rootProps.ref as React.Ref<HTMLDivElement>)

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

🌐 Web query:

In react-dropzone v14, is the recommended pattern to pass custom props/events into getRootProps(customProps) instead of spreading them after {...getRootProps()}?

💡 Result:

Yes, in react-dropzone v14, the recommended pattern is to pass custom props and events into getRootProps(customProps) rather than spreading them after {...getRootProps}. The official documentation explicitly states: "Note that whatever other props you want to add to the element where the props from getRootProps are set, you should always pass them through that function rather than applying them on the element itself. This is in order to avoid your props being overridden (or overriding the props returned by getRootProps)." Example from docs: <div {...getRootProps({ onClick: event => console.log(event), role: 'button', 'aria-label': 'drag and drop area', })} > <input {...getInputProps} />

Drag 'n' drop some files here, or click to select files.

In this pattern, custom props like onClick are merged correctly, with dropzone handlers taking precedence where needed (e.g., custom onClick is invoked before internal ones). Spreading custom props separately risks conflicts or overrides. This guidance has been consistent since before v14 and remains in the current docs (as of v14.4.0 and v15.0.0).

Citations:


🏁 Script executed:

cat -n packages/components/src/molecules/Dropzone/Dropzone.tsx | sed -n '160,210p'

Repository: vtex/faststore

Length of output: 1673


🏁 Script executed:

cat -n packages/components/src/molecules/Dropzone/Dropzone.tsx | sed -n '1,100p'

Repository: vtex/faststore

Length of output: 3188


🏁 Script executed:

cat -n packages/components/src/molecules/Dropzone/Dropzone.tsx | sed -n '100,170p'

Repository: vtex/faststore

Length of output: 1873


🏁 Script executed:

cd packages/components/src/molecules/Dropzone && grep -A 5 "getRootProps" Dropzone.tsx | head -20

Repository: vtex/faststore

Length of output: 349


🏁 Script executed:

# Search for getRootProps usage in the codebase to see if it's ever called with arguments
rg "getRootProps\(" packages/ -A 2

Repository: vtex/faststore

Length of output: 340


Pass custom props to getRootProps() to prevent overriding dropzone handlers.

Since otherProps spreads after rootProps, custom event handlers can override internal dropzone behaviors. Per react-dropzone's documented best practice, pass custom props directly into getRootProps(...) for proper handler composition.

🔧 Suggested fix
-  const rootProps = getRootProps()
+  const rootProps = getRootProps({
+    ...accessibilityProps,
+    ...otherProps,
+  })
   const mergedRef = mergeRefs(ref, rootProps.ref as React.Ref<HTMLDivElement>)

@@
       data-fs-dropzone-disabled={disabled}
       data-testid={testId}
       {...rootProps}
-      {...accessibilityProps}
-      {...otherProps}
       ref={mergedRef}

Also applies to: 194-197

🤖 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 170 -
171, The Dropzone currently calls getRootProps() with no args and then spreads
otherProps after rootProps which allows user event handlers to override internal
handlers; update the code to pass custom props into getRootProps(otherProps)
(and similarly pass relevant props into getInputProps when applicable) so
react-dropzone composes handlers correctly, keep merging refs via mergeRefs(ref,
rootProps.ref) (or adjust to use the returned ref from getRootProps), and remove
the separate spread of otherProps after rootProps to prevent handler overriding.

Comment on lines +175 to +192
useEffect(() => {
if (!selectedFile) return

if (hasError) {
setUploadState(FileUploadState.Error)
setErrorType(errorTypeProp ?? FileUploadErrorType.InvalidStructure)
return
}

if (isUploading) {
setUploadState(FileUploadState.Uploading)
setErrorType(undefined)
return
}

setUploadState(FileUploadState.Completed)
setErrorType(undefined)
}, [hasError, selectedFile, isUploading, errorTypeProp])

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

State synchronization may cause inconsistent UI.

This effect syncs external props (hasError, isUploading) to internal state, but both FileUploadCard and its parent (SearchInput) manage error/upload state independently. When isValidFileType() sets an internal error (lines 218-221), the parent won't know about it. Conversely, when the parent sets hasError=true, the internal state updates, but if the user selects a new file, the internal state resets while the parent's error state may persist.

Consider either:

  1. Making this a fully controlled component (remove internal uploadState/errorType)
  2. Or lifting isValidFileType validation to the parent
🤖 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 - 192, The effect in FileUploadCard (useEffect watching selectedFile,
hasError, isUploading, errorTypeProp) causes duplicated/unsynced state between
the component and its parent (SearchInput); decide on a single source of truth:
either make FileUploadCard fully controlled by removing internal uploadState and
errorType (and instead render directly from props
hasError/isUploading/errorTypeProp), or lift the internal validation
(isValidFileType) into the parent so the parent controls hasError and
errorTypeProp; update/remove setUploadState and setErrorType usage accordingly
(and remove the useEffect that mirrors props into state) or, if choosing
controlled mode, update SearchInput to perform validation and pass the resulting
error/upload state into FileUploadCard.

Comment on lines +212 to +236
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || [])
if (files.length > 0) {
const file = files[0]
setSelectedFile(file)

if (!isValidFileType(file)) {
setUploadState(FileUploadState.Error)
setErrorType(FileUploadErrorType.Unsupported)
return
}

setErrorType(undefined)

if (isUploading) {
setUploadState(FileUploadState.Uploading)
} else {
setUploadState(FileUploadState.Completed)
}

if (onFileSelect) {
onFileSelect(files)
}
}
}

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

Duplicate file handling logic between handleFileChange and handleDrop.

Both handlers share identical validation and state-setting logic. Extract to a shared helper to reduce duplication and ensure consistency.

♻️ Proposed refactor
+const processSelectedFile = (file: File) => {
+  setSelectedFile(file)
+
+  if (!isValidFileType(file)) {
+    setUploadState(FileUploadState.Error)
+    setErrorType(FileUploadErrorType.Unsupported)
+    return false
+  }
+
+  setErrorType(undefined)
+  setUploadState(isUploading ? FileUploadState.Uploading : FileUploadState.Completed)
+  return true
+}

 const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
   const files = Array.from(e.target.files || [])
   if (files.length > 0) {
-    const file = files[0]
-    setSelectedFile(file)
-    // ... duplicated logic
+    if (processSelectedFile(files[0]) && onFileSelect) {
+      onFileSelect(files)
+    }
   }
 }

Also applies to: 249-278

🤖 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 212 - 236, handleFileChange and handleDrop duplicate the same validation
and state-setting logic; extract that logic into a shared helper function (e.g.,
processSelectedFiles(files: File[])) that performs: select first file and call
setSelectedFile, validate via isValidFileType and set FileUploadState.Error and
FileUploadErrorType.Unsupported when invalid, clear error with
setErrorType(undefined) when valid, set upload state to
FileUploadState.Uploading or FileUploadState.Completed based on isUploading, and
invoke onFileSelect(files) if provided; then replace the body of both
handleFileChange and handleDrop to call this new helper to remove duplication
and keep behavior identical.

Comment on lines +611 to +616
{...((csvError || (noProductsError && !isLoadingProducts)) && {
errorType: noProductsError
? FileUploadErrorType.NoProductsFound
: mapCSVErrorToFileUploadErrorType(csvError.type),
errorMessage: noProductsError ? undefined : csvError?.message,
})}

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

Potential null dereference when accessing csvError.type.

When csvError is falsy but noProductsError is true, the conditional spread {...(csvError || ...) && { errorType: ... csvError.type }} still evaluates csvError.type inside. The outer condition csvError || (noProductsError && !isLoadingProducts) can be true when only noProductsError is true, then csvError.type throws.

🐛 Proposed fix
-{...((csvError || (noProductsError && !isLoadingProducts)) && {
-  errorType: noProductsError
-    ? FileUploadErrorType.NoProductsFound
-    : mapCSVErrorToFileUploadErrorType(csvError.type),
-  errorMessage: noProductsError ? undefined : csvError?.message,
-})}
+{...(csvError && {
+  errorType: mapCSVErrorToFileUploadErrorType(csvError.type),
+  errorMessage: csvError.message,
+})}
+{...(noProductsError && !isLoadingProducts && !csvError && {
+  errorType: FileUploadErrorType.NoProductsFound,
+})}
🤖 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
611 - 616, The conditional spread in SearchInput.tsx can still access
csvError.type when csvError is falsy (because the outer expression can be true
due to noProductsError); update the spread so csvError.type is only read when
csvError is non-null—e.g., compute errorType and errorMessage with a safe guard:
if noProductsError set errorType to FileUploadErrorType.NoProductsFound and
errorMessage undefined, otherwise (when csvError exists) call
mapCSVErrorToFileUploadErrorType(csvError.type) and use csvError.message; ensure
the object spread uses these precomputed values instead of directly referencing
csvError.type inside the conditional expression.

Comment on lines +43 to +125
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.`
)
}

const results: BulkProductData[] = []

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

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])

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
set -euo pipefail

printf '\n--- useBulkProductsQuery effect body ---\n'
sed -n '32,127p' packages/core/src/sdk/product/useBulkProductsQuery.ts

Repository: vtex/faststore

Length of output: 2972


Add abort/sequencing guard to prevent stale batch updates and reset error state when clearing products.

When skus, channel, or locale changes, the effect reruns but older batch fetches can still complete and overwrite state after newer ones finish. Add an abort controller or request ID to cancel in-flight fetches, and reset error in the empty-SKU branch alongside products and isLoading.

🤖 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 - 125,
The effect in useBulkProductsQuery can let stale batch fetches overwrite newer
state; fix by adding an abort/sequencing guard and resetting error when skus is
empty: create an AbortController or a requestId counter inside the useEffect
(used by fetchProducts and its inner batch map) and check the
controller.signal.aborted or compare requestId before calling setProducts,
setError or setIsLoading (and abort any in-flight requests and clear pending
timeouts between batches using the same controller/requestId), and in the
early-return branch where skus.length === 0 also call setError(null) along with
setProducts([]) and setIsLoading(false); ensure cleanup function aborts the
controller or increments the requestId to ignore in-flight results.

Comment on lines +14 to +15
@import "@faststore/ui/src/components/organisms/QuickOrderDrawer/styles.scss";
@import "@faststore/ui/src/components/organisms/SlideOver/styles.scss";

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

Re-add global Dropdown styles to avoid visual regressions.

Dropdown is actively used in core (e.g., packages/core/src/components/account/orders/MyAccountOrderDetails/MyAccountOrderActions/MyAccountOrderActions.tsx), but it is no longer imported here. This can leave those menus unstyled.

🎯 Suggested fix
 `@import` "@faststore/ui/src/components/organisms/QuickOrderDrawer/styles.scss";
 `@import` "@faststore/ui/src/components/organisms/SlideOver/styles.scss";
+@import "@faststore/ui/src/components/molecules/Dropdown/styles.scss";
📝 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 "@faststore/ui/src/components/organisms/QuickOrderDrawer/styles.scss";
@import "@faststore/ui/src/components/organisms/SlideOver/styles.scss";
`@import` "@faststore/ui/src/components/organisms/QuickOrderDrawer/styles.scss";
`@import` "@faststore/ui/src/components/organisms/SlideOver/styles.scss";
`@import` "@faststore/ui/src/components/molecules/Dropdown/styles.scss";
🧰 Tools
🪛 Stylelint (17.5.0)

[error] 14-14: Unexpected extension ".scss" in @import (scss/load-partial-extension)

(scss/load-partial-extension)


[error] 15-15: Unexpected extension ".scss" in @import (scss/load-partial-extension)

(scss/load-partial-extension)

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

In `@packages/core/src/styles/global/index.scss` around lines 14 - 15, Re-add the
global Dropdown stylesheet import to packages/core/src/styles/global/index.scss
so Dropdown menus used by components like MyAccountOrderActions
(packages/core/src/components/account/orders/.../MyAccountOrderActions.tsx)
remain styled; find the Dropdown styles file under the `@faststore/ui` package
(e.g. the component folder that contains Dropdown) and add an `@import` for its
styles.scss alongside the existing QuickOrderDrawer and SlideOver imports so the
dropdown styles are bundled globally.

Comment on lines +79 to +85
function formatFileSize(bytes: number): string {
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))
return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`
}

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 | 🟡 Minor

Potential edge case in formatFileSize.

When bytes is negative or the calculated index exceeds the sizes array bounds, this could produce unexpected results. Consider adding bounds checking.

🛡️ Safer implementation
 function 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))
-  return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`
+  const clampedIndex = Math.min(i, sizes.length - 1)
+  return `${Number.parseFloat((bytes / k ** clampedIndex).toFixed(2))} ${sizes[clampedIndex]}`
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/storybook/stories/upload-file-dropdown.stories.tsx` around lines 79
- 85, The formatFileSize function can misbehave for negative bytes or when the
computed index i goes outside sizes bounds; update formatFileSize to first
coerce/validate the input (treat negative or non-finite bytes as 0 or throw),
keep the existing zero check, then compute i and clamp it between 0 and
sizes.length - 1 (e.g., use Math.max/Math.min) before indexing sizes so you
never read out of bounds, and ensure the formatted value uses the clamped
divisor; reference the function name formatFileSize and the sizes/i variables
when making the change.

Comment on lines +74 to +75
fill: currentColor;
stroke: currentColor;

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 | 🟡 Minor

Use lowercase currentcolor here.

Stylelint is already flagging these declarations, so the new stylesheet won't pass lint until the keyword casing matches the repo rule.

Suggested fix
-    fill: currentColor;
-    stroke: currentColor;
+    fill: currentcolor;
+    stroke: currentcolor;

Apply the same replacement in all three icon blocks.

Also applies to: 102-103, 119-120

🧰 Tools
🪛 Stylelint (17.5.0)

[error] 74-74: Expected "currentColor" to be "currentcolor" (value-keyword-case)

(value-keyword-case)


[error] 75-75: Expected "currentColor" to be "currentcolor" (value-keyword-case)

(value-keyword-case)

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

In `@packages/ui/src/components/molecules/FileUploadStatus/styles.scss` around
lines 74 - 75, Replace the CSS keyword casing for the SVG color properties in
packages/ui/src/components/molecules/FileUploadStatus/styles.scss: change all
occurrences of fill: currentColor; and stroke: currentColor; to use the
lowercase keyword currentcolor (affecting the three icon blocks around the
existing fill/stroke declarations noted at lines 74-75, 102-103, and 119-120).
Update every fill and stroke occurrence in the file to use currentcolor so
Stylelint no longer flags the casing rule.

- Removed specific version overrides for webpack, allowing for a broader range of compatible versions.
- Updated various package dependencies to support webpack versions 4 and 5, enhancing compatibility and flexibility in the project.
@eduardoformiga eduardoformiga changed the title Add Quick Order Full Feature feat: Add Quick Order Full Feature Mar 27, 2026
- Introduced a new `tsconfig.json` for Cypress to extend the base configuration and include Cypress and Node types.
- Added a new `tsconfig.json` for testing with Jest, specifying Jest types and including TypeScript files.
- Updated Jest configuration to use `ts-jest` for transforming TypeScript files during testing.
@eduardoformiga
eduardoformiga merged commit f5518d7 into dev Mar 27, 2026
3 checks passed
@eduardoformiga
eduardoformiga deleted the feat/quick-order-by-file-feature-branch branch March 27, 2026 19:21
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.

5 participants