# Sales Overview

> The home analytics page of a store admin. Handles stores with no sales yet, today’s unfinished numbers and reports that fail or come back incomplete.

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

## Overview

Sales Overview is the page a merchant opens first: six KPI cards, a sales chart, a live view and three breakdowns, under a date range picker with a compare-to control. You pass loaders that take a query and return data, and the block owns loading, refreshing, errors and retries for each card on its own.

Every KPI card shows its value, a change chip and the period it’s compared with, like “vs Aug 23–Sep 21”. The chip colors by whether up is good for that metric, reads New when the previous period was zero instead of a meaningless ∞%, and shows a dash when there is nothing to compare. When the range changes, only the digits that changed roll; nothing counts up on first load.

Today is never a finished number. Its point on the chart and every sparkline is drawn dotted, the tooltip says “so far”, and the Today preset compares with yesterday at the same time instead of the whole day. Hovering any chart moves one crosshair across all six sparklines and the main chart at once, and the card captions show the hovered day’s values.

The chart picks hours for a single day, days up to two months and weeks beyond that. It can switch between sales, orders and average order value, and View as table shows the same numbers as an accessible table. An empty store shows zeros with a Share your store button, a failed report shows its error with Try again in its own card, and a metric your source can’t provide says so rather than showing a zero.

## 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/sales-overview
```

## Usage

### From Shopify analytics

Run one ShopifyQL query per range through the Admin API, grouped by the granularity the query asks for, and map each row to a SalesPoint. Sessions and returning customers come from the same query, so every card fills from one request.

```tsx
"use client"

import { money } from "../price/money"
import type { SalesPoint, SalesQuery } from "@/components/blocks/sales-overview/sales"
import { SalesOverview } from "@/components/blocks/sales-overview/sales-overview"

type ShopifyqlResponse = {
  data: {
    shopifyqlQuery: {
      tableData: { columns: { name: string }[]; rows: Record<string, string>[] } | null
      parseErrors: string[]
    }
  }
}

const groupBy = { hour: "hour", day: "day", week: "week" } as const

async function shopifyql(query: string, signal: AbortSignal) {
  const response = await fetch("/api/shopify/graphql", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      query: `query Sales($q: String!) { shopifyqlQuery(query: $q) { tableData { columns { name } rows } parseErrors } }`,
      variables: { q: query },
    }),
    signal,
  })
  if (!response.ok) throw new Error("Shopify analytics didn’t respond. Try again in a minute.")
  const { data } = (await response.json()) as ShopifyqlResponse
  if (data.shopifyqlQuery.parseErrors.length) throw new Error(data.shopifyqlQuery.parseErrors[0])
  return data.shopifyqlQuery.tableData?.rows ?? []
}

function toPoints(rows: Record<string, string>[], currencyCode: string): SalesPoint[] {
  return rows.map((row) => ({
    date: row.hour ? row.hour.slice(0, 13) : (row.day ?? row.week).slice(0, 10),
    sales: money(row.total_sales, currencyCode),
    orders: Number(row.orders),
    sessions: row.sessions === undefined ? undefined : Number(row.sessions),
    customers: Number(row.customers),
    returningCustomers: Number(row.returning_customers),
  }))
}

async function loadSeries(query: SalesQuery, signal: AbortSignal) {
  const select = "SHOW total_sales, orders, sessions, customers, returning_customers"
  const range = (start: string, end: string) =>
    `FROM sales, sessions ${select} SINCE ${start} UNTIL ${end} TIMESERIES ${groupBy[query.granularity]}`
  const [current, previous] = await Promise.all([
    shopifyql(range(query.range.start, query.range.end), signal),
    query.comparison
      ? shopifyql(range(query.comparison.start, query.comparison.end), signal)
      : Promise.resolve(null),
  ])
  return {
    current: toPoints(current, "USD"),
    previous: previous ? toPoints(previous, "USD") : null,
  }
}

export function ShopifyHome({ shopTimeZone }: { shopTimeZone: string }) {
  return (
    <SalesOverview
      loaders={{ series: loadSeries }}
      currencyCode="USD"
      now={new Date().toISOString()}
      timeZone={shopTimeZone}
      title="Home"
    />
  )
}
```

### From Stripe charges

List succeeded charges for the range and let bucketize sum them into hours, days or weeks in the shop’s time zone. Stripe has no sessions, so those cards show Not available instead of a fake zero.

```tsx
"use client"

import { fromMinorUnits } from "../price/money"
import { bucketize, zonedNow, type SalesPoint, type SalesQuery } from "@/components/blocks/sales-overview/sales"
import { SalesOverview } from "@/components/blocks/sales-overview/sales-overview"

type StripeCharge = {
  id: string
  amount: number
  amount_refunded: number
  currency: string
  created: number
  status: "succeeded" | "pending" | "failed"
}

const timeZone = "America/New_York"

async function listCharges(start: string, end: string, signal: AbortSignal) {
  const params = new URLSearchParams({ start, end, timeZone })
  const response = await fetch(`/api/stripe/charges?${params}`, { signal })
  if (!response.ok) throw new Error("Couldn’t load charges from Stripe.")
  return (await response.json()) as StripeCharge[]
}

function chargesToRows(charges: StripeCharge[]): SalesPoint[] {
  return charges
    .filter((charge) => charge.status === "succeeded")
    .map((charge) => {
      const local = zonedNow(new Date(charge.created * 1000), timeZone)
      return {
        date: `${local.day}T${String(local.hour).padStart(2, "0")}`,
        sales: fromMinorUnits(charge.amount - charge.amount_refunded, charge.currency),
        orders: 1,
      }
    })
}

async function loadSeries(query: SalesQuery, signal: AbortSignal) {
  const current = await listCharges(query.range.start, query.range.end, signal)
  const previous = query.comparison
    ? await listCharges(query.comparison.start, query.comparison.end, signal)
    : null
  return {
    current: bucketize(chargesToRows(current), query.buckets, "USD"),
    previous: previous ? bucketize(chargesToRows(previous), query.comparisonBuckets, "USD") : null,
  }
}

export function StripeRevenue() {
  return (
    <SalesOverview
      loaders={{ series: loadSeries }}
      currencyCode="USD"
      now={new Date().toISOString()}
      timeZone={timeZone}
      metrics={["sales", "orders", "averageOrderValue"]}
      title="Revenue"
    />
  )
}
```

### Your own SQL endpoint

Point the loaders at a route that runs one GROUP BY per range. The query carries the start, end, comparison range and granularity, and the abort signal cancels a request when the merchant picks another range.

```tsx
"use client"

import type { SalesChannelRow, TopProductRow } from "@/components/blocks/sales-overview/breakdowns"
import type { SalesQuery, SalesSeries } from "@/components/blocks/sales-overview/sales"
import { SalesOverview } from "@/components/blocks/sales-overview/sales-overview"

function report<T>(name: string) {
  return async (query: SalesQuery, signal: AbortSignal): Promise<T> => {
    const response = await fetch(`/api/reports/${name}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        start: query.range.start,
        end: query.range.end,
        compareStart: query.comparison?.start,
        compareEnd: query.comparison?.end,
        granularity: query.granularity,
        timeZone: query.timeZone,
      }),
      signal,
    })
    if (!response.ok) {
      const body = (await response.json().catch(() => null)) as { error?: string } | null
      throw new Error(body?.error ?? "This report didn’t load.")
    }
    return response.json() as Promise<T>
  }
}

const loaders = {
  series: report<SalesSeries>("sales"),
  channels: report<SalesChannelRow[]>("channels"),
  products: report<TopProductRow[]>("top-products"),
}

export function Dashboard({ now, timeZone }: { now: string; timeZone: string }) {
  return (
    <SalesOverview
      loaders={loaders}
      currencyCode="EUR"
      locale="de-DE"
      now={now}
      timeZone={timeZone}
      title="Overview"
    />
  )
}
```

## Anatomy

The parts you compose, from the outside in.

| Part | Description |
| --- | --- |
| `SalesOverview` | The whole page: header, range picker, KPI grid, chart, live view and breakdowns, with data loading built in. |
| `DateRangePicker` | Presets, a range calendar for custom dates and the compare-to select. |
| `KpiCard` | One metric with an info tooltip, rolling value, change chip, comparison caption and sparkline. |
| `DeltaChip` | The change between two periods, colored by whether up is good. |
| `Sparkline` | A small line with the comparison dashed and today dotted, synced to the shared crosshair. |
| `SalesChart` | The main chart with a metric switcher, comparison line, crosshair tooltip and table view. |
| `LiveView` | Visitors right now, orders and sales today and recent orders sliding in. |
| `ChannelBreakdown, TopProducts, DeviceBreakdown` | Breakdown cards with their own loading, empty and error states. |
| `SalesHoverProvider` | Shares the hovered point between charts. SalesOverview adds it for you. |
| `presetRange, comparisonRange, granularityFor, buildQuery, bucketize, getDelta` | Pure helpers for ranges, comparison periods, buckets and percent change. |

## API reference

### SalesOverview

Also takes div props. Dates are shop-local days like 2026-10-21.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `loaders` | `{ series, channels?, products?, devices? }` | – | Each is (query, signal) => Promise. series returns { current, previous?, unavailable? } as SalesPoint[]. Leave out a breakdown loader to hide its card. Throw to show the message in that card. |
| `currencyCode` | `string` | – | The shop currency, like "USD". |
| `now` | `string` | – | The current instant as ISO. Decides today, the incomplete point and future hours. |
| `timeZone` | `string` | `"UTC"` | The shop’s IANA time zone. Days and hours are counted in it. |
| `value` | `SalesRangeValue` | – | { preset, range: { start, end }, compare }. Controlled range. |
| `defaultValue` | `SalesRangeValue` | `last 30 days vs previous period` | The starting range when uncontrolled. |
| `onValueChange` | `(value: SalesRangeValue) => void` | – | Called when the range or comparison changes. |
| `title` | `ReactNode` | – | The page heading, like a greeting. |
| `description` | `ReactNode` | – | A line under the heading. |
| `actions` | `ReactNode` | – | Extra controls next to the range picker. |
| `metrics` | `SalesMetric[]` | `all six` | Which KPI cards to show, in order. |
| `chartMetrics` | `SalesMetric[]` | `["sales", "orders", "averageOrderValue"]` | Metrics the chart can switch between. |
| `metricDefinitions` | `Partial<Record<SalesMetric, { label, description, polarity }>>` | – | Rename a metric, change its tooltip, or set polarity to "down" when a fall is good. |
| `live` | `LiveViewProps \| "loading" \| null` | – | Data for the live view card. Leave out to hide it. |
| `onShareStore` | `() => void` | – | Shows Share your store on an empty chart. |
| `locale` | `Intl.LocalesArgument` | `"en-US"` | Locale for numbers and dates. |
| `labels` | `Partial<SalesOverviewLabels>` | – | Words for captions, card titles, the picker and the chart. |

### DateRangePicker

Also takes div props.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `today` | `string` | – | Today in the shop’s time zone. Later days can’t be picked. |
| `value` | `SalesRangeValue` | – | Controlled value. |
| `defaultValue` | `SalesRangeValue` | – | Uncontrolled starting value. |
| `onValueChange` | `(value: SalesRangeValue) => void` | – | Called with the new preset, range and comparison. |
| `presets` | `DateRangePreset[]` | `all` | today, yesterday, last_7_days, last_30_days, last_90_days, month_to_date and custom. |
| `compareOptions` | `CompareMode[]` | `["previous_period", "previous_year", "none"]` | Options in the compare-to select. |
| `timeZone` | `string` | – | Named in the picker so merchants know which day “today” is. |

### KpiCard

Also takes div props.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `label` | `string` | – | The metric name. |
| `description` | `string` | – | The definition shown in the info tooltip. |
| `value` | `number \| null` | – | The value for the period. |
| `previous` | `number \| null` | – | The comparison value. Leave out when not comparing. |
| `format` | `Intl.NumberFormatOptions` | – | How the rolling value is formatted. |
| `polarity` | `"up" \| "down" \| "neutral"` | `"up"` | Which direction is good. Sets the chip color. |
| `comparisonLabel` | `string \| null` | – | The caption, like “vs Aug 23–Sep 21”. |
| `points` | `KpiPoint[]` | – | { label, value, state?, previous?, previousLabel? } for the sparkline and hover caption. |
| `status` | `"ready" \| "loading" \| "unavailable" \| "error"` | `"ready"` | Loading shows a skeleton the same size. |
| `message` | `string` | – | Why the metric is unavailable or failed. |

### SalesChart

Also takes div props.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `model` | `SalesModel \| null` | – | From buildSalesModel(query, series, currencyCode). |
| `status` | `"loading" \| "ready" \| "error"` | `"ready"` | Loading shows a skeleton, error shows the message with Try again. |
| `onRetry` | `() => void` | – | Called by Try again. |
| `metric` | `SalesMetric` | – | Controlled metric. Also defaultMetric and onMetricChange. |
| `view` | `"chart" \| "table"` | – | Controlled view. Also defaultView and onViewChange. |
| `onShareStore` | `() => void` | – | Action in the empty state. |

### LiveView

Also takes div props.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `visitors` | `number` | – | Visitors right now. Changes roll gently. |
| `ordersToday` | `number` | – | Orders so far today. |
| `salesToday` | `Money` | – | Sales so far today. |
| `recentOrders` | `LiveOrder[]` | – | { id, name, customer, total, items, at, location? }. toLiveOrder(order) maps an Order. New ids slide in at the top. |
| `status` | `"live" \| "reconnecting"` | `"live"` | Shows Reconnecting… when your socket drops. |
| `now` | `string` | – | Used for “4 min ago”. |

### SalesPoint

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `date` | `string` | – | The bucket: 2026-10-21 for a day or week, 2026-10-21T14 for an hour. |
| `sales` | `Money` | – | Total sales in the bucket. |
| `orders` | `number` | – | Orders in the bucket. |
| `sessions` | `number` | – | Optional. Without it, conversion rate and sessions show Not available. |
| `customers, returningCustomers` | `number` | – | Optional. Drive the returning customer rate. |

## Keyboard

| Key | Action |
| --- | --- |
| `←` `→` | With the chart focused, move the crosshair to the previous or next point. Every sparkline follows. |
| `Home` `End` | Jump to the first or latest point. |
| `Esc` | Hide the crosshair. |
| `↑` `↓` | Move between presets in the date range picker. |

## Accessibility

- Each KPI card is a group named with its full reading, like “Total sales, $113,661.39, Up 5.5%, an improvement, vs Aug 23–Sep 21”. Sparklines are hidden from screen readers, and the change is never shown by color alone: an arrow and a word carry it.
- The chart is focusable. Arrow keys move point by point and a polite live region reads the date, the value and the comparison. View as table shows the same data as a real table.
- A polite announcement reads the new range and its total once data loads, failed cards use role="alert", and new live orders are announced as they arrive. Visitor counts aren’t announced, so screen readers aren’t flooded.
- Numbers roll only when they change and jump straight to the new value with reduced motion. Nothing pulses, and the live dot is static.

## Built with

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

- [Avatar](https://hextaui.com/docs/avatar) - User photos with an initials fallback, status badges and stacked groups that collapse into a count.
- [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.
- [Calendar](https://hextaui.com/docs/calendar) - A date grid for single, range and multiple selection, with sliding months, range previews and touch-sized days.
- [Card](https://hextaui.com/docs/card) - A surface for grouping content, with three variants, edge-to-edge media, concentric radii and whole-card links.
- [Chart](https://hextaui.com/docs/chart) - Recharts charts with themed colors, a tooltip and legend that read labels from one config, and keyboard navigation with a visible focus ring.
- [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.
- [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.
- [Tooltip](https://hextaui.com/docs/tooltip) - A short hint on hover or keyboard focus that opens after a brief rest, switches instantly between neighbours and shows shortcuts.

## Code

11 files, added to components/blocks/sales-overview.
