# Inventory

> A stock table where merchants edit quantities in place and save adjustments. Handles live orders, edits from another device and oversold or untracked stock.

Canonical: https://hextaui.com/blocks/inventory
Last updated: 2026-10-29

## Overview

Inventory is the stock table for one location. Each row is a variant with its thumbnail, title and SKU. The columns follow Shopify: Unavailable, Committed, Available, On hand and Incoming. On hand is always Available plus Committed plus Unavailable, so editing one of them moves the other by the same amount.

Click a quantity, press Enter or start typing to open the editor. Adjust by adds or removes stock and Set to enters a count, with a live preview such as 42 → 47. The arrow keys step by 1, or by 10 with Shift. Enter keeps the change in a draft and moves down a row, and Escape cancels. Edited cells get a dot and show their delta, and a save bar collects the batch with one reason, such as Received or Cycle count.

Saving sends adjustments, not overwrites. Each one carries its delta, the quantity it was based on and the result, so an order placed while you were typing isn’t lost. A row the server rejects stays in the draft with its message, such as “Quantity changed to 40 by another device”, and Reapply sends it again on top of the new quantity.

When new items arrive, changed numbers roll digit by digit and flash briefly. Rows don’t re-sort while you’re working in the table. The toolbar has search by title or SKU, Low stock, Out of stock and Incoming filters, sorting by Available, and bulk Set to 0 or Adjust by for selected rows. Loading, an empty location, no results, untracked variants, oversold stock and an all-locations read-only view are covered too, and every row has its adjustment history in a sheet.

## Installation

### Step 1: Get HextaUI Pro

One payment unlocks every block, including future ones. [See pricing](https://hextaui.com/pricing).

### Step 2: Add the Pro registry to components.json

```json title="components.json"
{
  "registries": {
    "@hextaui-pro": {
      "url": "https://hextaui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
      }
    }
  }
}
```

### Step 3: Add your token

Create a token on your [account page](https://hextaui.com/account) and put it in `.env.local` as `HEXTAUI_PRO_TOKEN`.

### Step 4: Add the block

```bash
npx shadcn@latest add @hextaui-pro/inventory
```

## Usage

### Save to Shopify

Send each batch to inventoryAdjustQuantities with the delta and changeFromQuantity. Shopify rejects a change when the quantity moved since you loaded it, and those user errors come back as failed rows that the merchant can reapply.

```tsx
"use client"

import { InventoryTable } from "@/components/blocks/inventory/inventory-table"
import type {
  InventoryAdjustment,
  InventoryItem,
  InventoryReason,
  InventorySaveResult,
} from "@/components/blocks/inventory/inventory"

const reasons: Record<InventoryReason, string> = {
  correction: "correction",
  received: "received",
  damaged: "damaged",
  theft_or_loss: "theft_or_loss",
  returned: "restock",
  cycle_count: "cycle_count_available",
}

const mutation = `
  mutation Adjust($input: InventoryAdjustQuantitiesInput!) {
    inventoryAdjustQuantities(input: $input) {
      userErrors { field message }
    }
  }
`

async function adjustOnShopify(
  locationId: string,
  adjustments: InventoryAdjustment[]
): Promise<InventorySaveResult> {
  const failed: InventorySaveResult["failed"] = []
  const groups = new Map<InventoryReason, InventoryAdjustment[]>()
  for (const adjustment of adjustments) {
    groups.set(adjustment.reason, [...(groups.get(adjustment.reason) ?? []), adjustment])
  }
  for (const [reason, group] of groups) {
    const response = await fetch("/api/shopify/graphql", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        query: mutation,
        variables: {
          input: {
            name: "available",
            reason: reasons[reason],
            changes: group.map((adjustment) => ({
              inventoryItemId: adjustment.itemId,
              locationId,
              delta: adjustment.delta,
              changeFromQuantity: adjustment.compareQuantity,
            })),
          },
        },
      }),
    })
    const { data } = await response.json()
    const errors: { field: string[] | null; message: string }[] =
      data.inventoryAdjustQuantities.userErrors
    for (const error of errors) {
      const index = Number(error.field?.[2])
      const itemId = group[index]?.itemId
      if (itemId) failed.push({ itemId, message: error.message })
    }
  }
  return { failed }
}

export function ShopifyInventory({
  items,
  locationId,
  locationName,
  refresh,
}: {
  items: InventoryItem[]
  locationId: string
  locationName: string
  refresh: () => Promise<void>
}) {
  return (
    <InventoryTable
      items={items}
      locationName={locationName}
      onSave={async (adjustments) => {
        const result = await adjustOnShopify(locationId, adjustments)
        await refresh()
        return result
      }}
    />
  )
}
```

### Medusa inventory levels

Map Medusa location levels to items: stocked minus reserved is Available, and reserved is Committed. Each adjustment posts the new stocked quantity for that inventory item and location.

```tsx
"use client"

import * as React from "react"

import { InventoryTable } from "@/components/blocks/inventory/inventory-table"
import type { InventoryItem } from "@/components/blocks/inventory/inventory"

type MedusaLevel = {
  inventory_item_id: string
  location_id: string
  stocked_quantity: number
  reserved_quantity: number
  incoming_quantity: number
}

type MedusaVariant = {
  id: string
  title: string
  sku: string | null
  manage_inventory: boolean
  product: { title: string; thumbnail: string | null }
  inventory_items: { inventory_item_id: string }[]
}

function toItem(variant: MedusaVariant, level: MedusaLevel | undefined): InventoryItem {
  const stocked = level?.stocked_quantity ?? 0
  const reserved = level?.reserved_quantity ?? 0
  return {
    id: variant.inventory_items[0]?.inventory_item_id ?? variant.id,
    productTitle: variant.product.title,
    variantTitle: variant.title,
    sku: variant.sku ?? undefined,
    image: variant.product.thumbnail ? { src: variant.product.thumbnail } : undefined,
    tracked: variant.manage_inventory,
    available: stocked - reserved,
    committed: reserved,
    incoming: level?.incoming_quantity
      ? [{ id: "incoming", quantity: level.incoming_quantity }]
      : [],
  }
}

export function MedusaInventory({
  variants,
  levels,
  locationId,
}: {
  variants: MedusaVariant[]
  levels: MedusaLevel[]
  locationId: string
}) {
  const [current, setCurrent] = React.useState(levels)
  const items = variants.map((variant) =>
    toItem(
      variant,
      current.find(
        (level) =>
          level.location_id === locationId &&
          level.inventory_item_id === variant.inventory_items[0]?.inventory_item_id
      )
    )
  )

  return (
    <InventoryTable
      items={items}
      onSave={async (adjustments) => {
        const failed = []
        for (const adjustment of adjustments) {
          const response = await fetch(
            `/admin/inventory-items/${adjustment.itemId}/location-levels/${locationId}`,
            {
              method: "POST",
              credentials: "include",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ stocked_quantity: adjustment.compareQuantity + adjustment.delta }),
            }
          )
          if (!response.ok) {
            failed.push({ itemId: adjustment.itemId, message: "Medusa didn’t accept this change" })
            continue
          }
          const { inventory_item } = await response.json()
          setCurrent((levels) =>
            levels.map((level) =>
              level.inventory_item_id === adjustment.itemId && level.location_id === locationId
                ? { ...level, ...inventory_item.location_levels[0] }
                : level
            )
          )
        }
        return { failed }
      }}
    />
  )
}
```

### Map a CSV import

previewCsvImport matches rows to variants by SKU and turns each count into an adjustment against the current quantity. It also lists unknown SKUs and bad rows so you can show them before anything is saved.

```tsx
import {
  fieldValue,
  parseQuantity,
  type InventoryAdjustment,
  type InventoryItem,
  type InventoryReason,
} from "@/components/blocks/inventory/inventory"

type CsvMapping = {
  sku: string
  quantity: string
  field?: "available" | "onHand"
}

type CsvPreview = {
  adjustments: InventoryAdjustment[]
  unknownSkus: string[]
  invalidRows: number[]
}

function parseCsv(text: string) {
  const [header, ...lines] = text.trim().split(/\r?\n/)
  const columns = header.split(",").map((cell) => cell.trim().replace(/^"|"$/g, ""))
  return lines.map((line) => {
    const cells = line.split(",").map((cell) => cell.trim().replace(/^"|"$/g, ""))
    return Object.fromEntries(columns.map((column, index) => [column, cells[index] ?? ""]))
  })
}

export function previewCsvImport(
  text: string,
  items: InventoryItem[],
  mapping: CsvMapping,
  reason: InventoryReason = "cycle_count"
): CsvPreview {
  const field = mapping.field ?? "available"
  const bySku = new Map(items.map((item) => [item.sku?.toLowerCase(), item]))
  const preview: CsvPreview = { adjustments: [], unknownSkus: [], invalidRows: [] }

  parseCsv(text).forEach((row, index) => {
    const sku = row[mapping.sku]?.toLowerCase()
    const item = sku ? bySku.get(sku) : undefined
    const quantity = parseQuantity(row[mapping.quantity] ?? "")
    if (!item) {
      if (sku) preview.unknownSkus.push(row[mapping.sku])
      return
    }
    if (quantity === null || Number.isNaN(quantity) || quantity < 0) {
      preview.invalidRows.push(index + 2)
      return
    }
    const current = fieldValue(item, field)
    if (quantity === current || item.tracked === false) return
    preview.adjustments.push({
      itemId: item.id,
      field,
      delta: quantity - current,
      quantity,
      compareQuantity: current,
      reason,
    })
  })

  return preview
}
```

## Anatomy

The parts you compose, from the outside in.

| Part | Description |
| --- | --- |
| `InventoryTable` | Toolbar, editable grid, quantity editor, history sheet and save bar. |
| `QuantityEditor` | The Adjust by / Set to popover with a stepper and a before → after preview. |
| `InventoryHistorySheet` | A side sheet listing who changed a row, when, why, by how much and the resulting quantity. |
| `buildAdjustments, draftDelta, onHand, stockStatus` | Pure helpers for adjustments, deltas, on-hand math and stock states. They work on the server too. |

## API reference

### InventoryTable

Also takes div props.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `items` | `InventoryItem[]` | – | Variants at the current location. Pass new arrays as orders come in, and changed numbers roll and flash in place. |
| `onSave` | `(adjustments: InventoryAdjustment[]) => Promise<InventorySaveResult \| void>` | – | Apply the batch, update items, then resolve. Return { failed } to keep those rows in the draft with a message, or throw to fail the whole batch. |
| `loading` | `boolean` | `false` | Shows skeleton rows. |
| `locationName` | `string` | – | Used in the empty state, the history sheet and labels. |
| `readOnly` | `boolean` | `false` | Turns off editing and selection, for example when showing all locations. |
| `lowStockThreshold` | `number` | `5` | Available at or below this counts as low stock. |
| `defaultReason` | `InventoryReason` | `"correction"` | The reason preselected in the save bar. |
| `onTrack` | `(item: InventoryItem) => Promise<void>` | – | Shows a Track button on untracked rows. |
| `onLoadHistory` | `(item: InventoryItem) => Promise<InventoryHistoryEntry[]>` | – | Loads the adjustment history when the sheet opens. Throw to show a retry state. |
| `onDirtyChange` | `(dirty: boolean) => void` | – | Called when unsaved changes appear or clear, for navigation guards. |
| `locale` | `Intl.LocalesArgument` | `"en-US"` | Locale for numbers and dates. |
| `labels` | `Partial<InventoryTableLabels>` | – | Column names, filters, save bar and empty-state words. |

### InventoryItem

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `id` | `string` | – | Your inventory item or variant id. It comes back in each adjustment. |
| `productTitle, variantTitle, sku, image` | `string, string, string, { src; alt? }` | – | What the row shows. Search matches the title, variant and SKU. |
| `available` | `number` | – | Sellable stock. Can be negative when overselling is allowed. |
| `committed` | `number` | – | Stock in unfulfilled orders. |
| `unavailable` | `{ damaged?; qualityControl?; safetyStock?; reserved? }` | – | Counted in On hand but not sellable, with a breakdown popover. |
| `incoming` | `{ id; quantity; expectedOn?; source? }[]` | – | Transfers and purchase orders on the way. Past dates show as overdue. |
| `tracked` | `boolean` | `true` | false shows Not tracked instead of numbers. |

### InventoryAdjustment

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `itemId` | `string` | – | The row that changed. |
| `field` | `"available" \| "onHand"` | – | Which quantity was edited. Both move by the same delta. |
| `delta` | `number` | – | The change to apply. Send this to the server, not the result. |
| `compareQuantity` | `number` | – | The quantity the change was based on, for compare-and-set checks. |
| `quantity` | `number` | – | The expected result. |
| `reason` | `InventoryReason` | – | correction, received, damaged, theft_or_loss, returned or cycle_count. |

## Keyboard

| Key | Action |
| --- | --- |
| `ArrowUp` `ArrowDown` `ArrowLeft` `ArrowRight` | Moves between cells like a spreadsheet. In the editor, Up and Down step the quantity. |
| `Shift` `ArrowUp` | Steps the quantity by 10 in the editor. |
| `Enter` | Opens the editor on a quantity. In the editor, keeps the change and moves down a row. |
| `0-9` | Starts editing with that digit. + and − start an Adjust by. |
| `Escape` | Cancels the editor, or clears the selection in the grid. |
| `Backspace` | Removes the unsaved change on the focused row. |
| `Space` | Selects or clears the row when its checkbox has focus. |
| `Mod` `S` | Saves the draft. |

## Accessibility

- The grid uses one tab stop that moves with the arrow keys. Every cell has a name such as “Available for Ring Vase, Sand / Medium, 47, changed by +5, not saved”.
- A polite live region announces each change kept in the draft, selection counts and “Saved 3 changes”. Save failures go to an alert region, and the failed row links to its message.
- Stock states are never shown by color alone. Low stock, Out of stock and Oversold are written out, oversold numbers get a warning icon, and edited cells show their delta as text.
- Rows don’t move while focus is in the table or a popover is open, so live updates never pull the row out from under a screen reader or keyboard user. Number rolls and flashes are turned off for reduced motion.

## Built with

The free HextaUI components Inventory is made from. Each one installs on its own.

- [Badge](https://hextaui.com/docs/badge) - Status labels with colored dots, removable tags that slide closed and counts that roll to their new value.
- [Button](https://hextaui.com/docs/button) - Buttons in every variant and size, with a built-in loading, success and error flow that skips the spinner for fast requests.
- [Checkbox](https://hextaui.com/docs/checkbox) - A checkbox whose check draws in, with indeterminate parents, groups and labels that share its hover.
- [Drawer](https://hextaui.com/docs/drawer) - A panel that slides in from any edge and follows your finger, with snap points, a working handle and nested drawers that stack.
- [Empty](https://hextaui.com/docs/empty) - A placeholder for screens with nothing to show yet, with an icon, a message and the next action.
- [Input group](https://hextaui.com/docs/input-group) - An input with icons, text, buttons or a keyboard hint attached, sharing one border and focus ring.
- [Kbd](https://hextaui.com/docs/kbd) - Key caps for shortcuts that show the right symbols on every platform, read them out properly and press down with the real keys.
- [Number flow](https://hextaui.com/docs/number-flow) - Animated numbers where only the changed digits spin, with any Intl format and locale.
- [Popover](https://hextaui.com/docs/popover) - A floating panel anchored to a trigger that resizes smoothly with its content and follows the trigger’s direction.
- [Select](https://hextaui.com/docs/select) - Pick one or more options from a list that opens on the current value, with typeahead, groups and form support.
- [Sheet](https://hextaui.com/docs/sheet) - A panel that slides in from any edge, with swipe-to-dismiss, scroll lock and stacked nesting.
- [Skeleton](https://hextaui.com/docs/skeleton) - Placeholders that wait 150ms before showing, take the exact size of the content they wrap, and fade it in without moving anything.
- [Table](https://hextaui.com/docs/table) - A responsive table with a surface style, wrapping or compact cells, sticky headers, pinned columns and scroll hints.
- [Toggle group](https://hextaui.com/docs/toggle-group) - A row of toggles for one choice or many, with a fill that slides to the picked item, joined or spaced items and arrow-key focus.

## Code

9 files, added to components/blocks/inventory.
