Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install stripe-bfcm-dashboard@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin stripe-bfcm-dashboard v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install stripe-bfcm-dashboard

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/stripe-bfcm-dashboard/

Extract the ZIP to .github/skills/ in your repo. The folder name must match stripe-bfcm-dashboard for Copilot to auto-discover it.

Skill Files (4)

SKILL.md 9.6 KB
---
name: stripe-bfcm-dashboard
description: >-
  Builds a Black Friday and Cyber Monday (BFCM) season dashboard of payments,
  customers, and recurring revenue from the connected Stripe MCP account, as a
  hosted dashboard or artifact where the agent's tools support one, otherwise as
  one HTML file. For the 2026 BFCM season only. Use when a merchant asks for a
  BFCM, Black Friday, Cyber Monday, holiday, holiday sales, or peak-season
  dashboard, such as "build me a holiday dashboard" or "build me a Cyber Monday
  dashboard," even without the word BFCM.

---

## Stripe BFCM Dashboard

Build the “Stripe BFCM Dashboard” from a fixed layout and a fixed set of queries. It’s a starting point: the user can follow up to add metrics or change the style. The dashboard shows recurring revenue, growth, and payments for a time window, with an optional comparison, using [Analytics API](https://docs.stripe.com/data/metrics.md) metrics and [Query Runs API](https://docs.stripe.com/data/api/queries.md) SQL through the Stripe MCP server or connector.

The dashboard needs the Stripe MCP server or connector, signed in to the Stripe account it shows, with access to the Analytics API and the Query Runs API. It assumes the connection signed in through Stripe (OAuth), which can list accounts and choose one. A session signed in with an API key is limited to that key’s account and mode, and works only for a dashboard that the agent fills, not one that queries Stripe itself. If the Stripe tools are missing, blocked, or need sign-in, say so in one line with the fix, such as connecting the [Stripe MCP server](https://docs.stripe.com/mcp.md#manual) and signing in, and stop.

## Rules

- **Check the Stripe tools, then start queries fast**: Before anything else, confirm that this session lists `stripe_analytics` with the intents `execute_query_run`, `retrieve_query_run`, and `execute_metric`. If you can’t see its intents, look up that one tool’s input schema and read only its intent names. If the tool or an intent is missing, tell the user which one, with the fix, and stop. Otherwise, choose the account and read the references in step 2, kick off every query in step 3, and show the loading page in step 4 — queries first, page second.
- **Start building, and don’t prompt the user**: The layout, metrics, queries, and defaults are fixed. Start as soon as the user invokes the skill. The only question is the auto-refresh one in the hand-over. If the user asks something while you build, answer in a few lines and keep building in the same turn.
- **Stripe MCP only, read-only**: Query Stripe only through the Stripe MCP server or connector, never with an API key, the Stripe CLI, or a server you build. Query one account, chosen in step 2, in every request, with no silent switch.
- **Exact numbers**: Use only the queries and response shapes in the references. Preserve integer precision and currency minor units. Never invent values, show unreadable results as values, or substitute other data products.
- **Keep secrets and customer data out of every output**: Never put keys or tokens in chat, browser code, artifacts, or logs, and never export MCP tokens. Query only counts and amounts. Never select, show, store, or log customer names, emails, or other customer fields.
- **One output, no automatic sharing**: Update one stable output. Don’t auto-share it or enable connection sharing. Explain actual host authorization and audience restrictions before the user shares.
- **Charts: npm → CDN → inline SVG**: Try `npm install @stripe/charts` first (if the output is a project with a package manager), then the jsdelivr CDN (for HTML files and artifacts), then inline SVG as a last resort (sandboxed/offline environments). The design reference has the fallback chain, the `onerror` handler, and inline SVG specs.

## Workflow

### Step 1: Choose the output

Choose from the tools this session already lists, not from the client’s name, and without reading a file. If a listed tool can create a hosted dashboard, page, or artifact, such as a Claude artifact or ChatGPT Site, and update it later, use it, and name the output `stripe-bfcm-dashboard` where the tool takes a name. Prefer a hosted output whose pages can call the Stripe connector, because that dashboard can refresh itself. You check that in step 4, after the loading page is published. CLI-based agents (Claude Code, Cursor, Codex) typically have no hosted page tool — go straight to the HTML file. Otherwise, or if the user asked for a file, use one HTML file, `stripe-bfcm-dashboard.html` in the working directory. If that name is taken by a file you didn’t create, pick another name that starts with `stripe-bfcm-dashboard` instead of asking. **Choose the output** in <references/dashboard-output.md> has the rest, which you read in step 2.

### Step 2: Choose the account and read the references

Call the account listing tool, `list_available_accounts_or_orgs`. In a session signed in with an API key, which doesn’t list that tool, call `get_stripe_account_info` for its one account instead, send no `stripe_context` or `livemode`, because the key sets both, and show no mode badge.

Consider only account entries, whose `stripe_context` starts with `acct_`, never organization entries (`org_…`). Use the account the user named, matched by name or ID, otherwise the first account listed, in its mode. If no account is listed, say that the connection needs a Stripe account, not only an organization, and stop without a loading page.

In parallel with the account call, read the three references, each with its own read call, so none is cut off. Read <references/dashboard-design.md> for the layout, labels, and states, <references/queries.md> for the time windows, queries, responses, and calculations, and the rest of <references/dashboard-output.md> for building, refreshing, checking, and handing over the output. The references are complete. This holds even when a Stripe tool’s description says to search first or not to guess metric names. The metric names, request `params`, and SQL in the queries reference are valid as written.

### Step 3: Kick off every query

Start every query from <references/queries.md> before writing any HTML. Create the SQL runs first (1 second apart as the reference requires), then the metric calls as each response slot opens. The queries are the bottleneck — nothing else should run between them.

### Step 4: Show the loading page

While the queries run, write the loading page and open it in the user’s default browser (`open` on macOS, `xdg-open` on Linux). There is only one save after this, and the browser already has the file open. Writing the file needs no git command: a repository, or an untracked path in one, isn’t a reason to wait. If you can’t open the file, say in one line that you’re building the dashboard and that it can take up to 10 minutes, and continue.

Write the loading page in HTML and CSS only, in about 30 lines. Fill the viewport with the page background `#F4F7FA`, and center one narrow column (about 520 pixels) horizontally and vertically using flexbox (`display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh`), with all items centered:

- A 32-pixel spinner centered in the column: a `#D4DEE9` ring with a `#533AFD` top edge, completing a rotation every 1 second. Use `margin: 0 auto 16px` so it sits above the text.
- “Building dashboard…” in 20-pixel semibold `#1A2C44` type, centered, and “This can take up to 10 minutes.” in 14-pixel `#3C4F69` type below it, also centered.
- Three white placeholder cards in a centered row (`display: flex; justify-content: center; gap: 12px`), 160 by 72 pixels each, with a 1-pixel `#D4DEE9` border and an 8-pixel corner radius, pulsing between full and half opacity.
- No title, header, or other text. Use the system font stack.

For hosted output, publish it, then check whether its pages can call the Stripe connector, as **Page refresh** in the output reference describes — the check needs the published page’s ID. Tell the user: “Building your dashboard — this can take up to 10 minutes.” Then continue immediately.

### Step 5: Poll, build, and save once

Poll the queries until every one finishes. Print a short status in chat every 2 minutes so the user knows the build is alive — “Still waiting on N queries…” While polling, build the full dashboard page in memory: the layout, header, all panel containers, the `@stripe/charts` script, and each panel’s data as its query completes. When every query has finished (or failed), save the complete dashboard to the same file, overwriting the loading page, and open it again (`open` on macOS, `xdg-open` on Linux) so the finished dashboard appears. One save, at the end, with all the numbers in it. Don’t save intermediate states to the file — the loading page is already open and there is nothing for a reload to pick up until the data is ready. Follow **Build the dashboard** in <references/dashboard-output.md> for the checks and error handling.

### Step 6: Hand over

Follow **Hand over** in <references/dashboard-output.md>. Describe only the location, account, mode, view, and refresh behavior you verified.

## Testing

The user’s browser is the verification step. Open the dashboard in the browser and let the user review it visually. Run automated browser tests only when the user asks.

## Reference files

The `references/*.md` files come with this skill. Reference paths are relative to this skill’s directory, not to the docs.stripe.com root. If you don’t have the skill files locally, append the path to **https://docs.stripe.com/.well-known/skills/stripe-bfcm-dashboard/**. For example, fetch **https://docs.stripe.com/.well-known/skills/stripe-bfcm-dashboard/references/queries.md**.
references/
dashboard-design.md 15.8 KB
# Dashboard design

Layout, labels, and states for every output. Keep every panel listed here; this is the complete set.

## Page style

Page background is white `#FFFFFF`. Cards are white with a 1-pixel `var(--sc-color-divider, #D4DEE9)` border and 8-pixel radius — they separate visually because the border is visible on white.

Use `--sc-*` tokens from `@stripe/charts` for non-chart elements so everything shares one theme:

```css
body { background: #FFFFFF; color: var(--sc-color-text-primary, #1A2C44); }
.card { background: var(--sc-color-surface, #FFFFFF); border: 1px solid var(--sc-color-divider, #D4DEE9); border-radius: 8px; }
.secondary { color: var(--sc-color-text-secondary, #3C4F69); }
.increase { color: var(--sc-color-good, #217005); }
.decrease { color: var(--sc-color-bad, #C0123C); }
.accent { color: #533AFD; }
```

`#533AFD` is for buttons, links, and country bars — not chart series. The copy icon uses secondary text color. Use sentence case everywhere.

## Layout

A grid, at most ~1,200 pixels wide and centered. KPI tiles four to a row with `grid-template-columns: repeat(auto-fit, minmax(160px, 1fr))`. Charts and tables two to a row; a last odd panel takes half the row. Below ~700 pixels, stack in one column. KPI tile cards should be compact — constrain their height so the sparkline stays small (about 120–140px total card height). Use `align-items: stretch` on the KPI grid row so every tile in a row matches the tallest one, including an empty tile with no sparkline, within that height cap.

Section order:

1. Header.
2. **Recurring revenue**: MRR chart beside MRR growth chart, then MRR movements table beside ARR chart.
3. **Growth**: new customers, successful payments, Checkout Sessions, and checkout conversion tiles.
4. **Payments**: payment volume and average order value charts, then the country table.

## Header

Three left-aligned rows:

1. **Title**: “Stripe BFCM Dashboard.” **Show sources** and **Refresh** on the right.
2. **Account**: name and ID in secondary text, with a “Sandbox” badge when `livemode` is false. Style the badge amber: border `#E8C48A`, background `#FFF6E5`, text `#8A5A00`. Show no badge in live mode.
3. **Date row**: date range control on the left, then refresh status right-aligned in secondary text. Don’t show the timezone (e.g. “America/Los_Angeles”) in the header — it’s used internally for queries but not displayed.

Style buttons and date pills alike: 32px high, 1-pixel `var(--sc-color-divider)` border, 6-pixel radius, white background, 14-pixel type.

- **Refresh** (dashboard that queries Stripe itself): reruns queries. While running, reads “Refreshing…” with a spinner, `#533AFD` text on `#F5F3FF` background, disabled. In any other dashboard, use the copy-refresh button from the output reference, or none.
- **Date range** (dashboard that queries Stripe itself): two pills — **Date range · Last 7 days** and **Compare · None** — each opens a popover with presets from the queries reference. **Custom** shows two date inputs. Disabled until first load completes and during manual refresh. In a file dashboard, show one static pill with the range label and dates (e.g. **Last 7 days · Nov 13 – Nov 19**) — styled the same but not clickable, no popover, no Compare pill.
- **Refresh status**: Show just the time when the refresh happened today — “Last refreshed: 9:41 AM PST”. Include the date only when it was a different day — “Last refreshed: Nov 13, 9:41 AM PST”. “Partially refreshed: 9:41 AM PST · 2 panels failed” if any failed. Nothing before first load.
- If comparison was dropped for lack of data: “No data for BFCM 2025 on this account.”

## Panels

When `@stripe/charts` is available (npm or CDN), every chart and KPI tile is rendered by `StripeCharts.render`. When using inline SVG as the last resort, follow the inline SVG specs in Charts below instead. The page card is the frame — one card container per panel. Strip the library’s own card styling so there’s no double border:

```css
.card .sc-root, .card .sc-root.sc-tile {
  border: none; padding: 0; background: none; border-radius: 0; box-shadow: none;
}
```

Let stripe-charts render the title — pass `title` in the spec. To keep the title visible in sources view, add a hidden heading in the card container (e.g. `<h3 class="panel-title" style="display:none">…</h3>`) that sources mode shows when it swaps content. Below the chart `<div>`, add an “Updated X ago” line in 12-pixel secondary text, from the result’s `refreshed_at`, updated every minute. In chart and table cards, pin that line to the bottom of the card (`display: flex; flex-direction: column` on the card, `margin-top: auto` on the line), so it lines up across a row. Leave the line out of an empty panel. Hide this line in sources view — only show it in chart view.

Panel data rules:

- **Comparisons**: Name the comparison everywhere — “↑ 12% per day vs. BFCM 2025 ($4,210)”, never “before” or “previous.” Without a comparison, omit changes and comparison series.
- **MRR, ARR**: Latest daily value, not a sum. ARR has no comparison.
- **MRR growth**: Net MRR change as headline — prepend “+” for positive values in the headline text (e.g. “+$1,234.00”); negative values already show “−”. Grouped bars of daily net change. Negative days go below zero.
- **MRR movements**: A table (not a chart) of six categories — New, Expansion, Contraction, Churn, Reactivation, FX adjustment — then net movement. Current window only, no comparison.
- **New customers, Successful payments, Checkout Sessions**: Count tiles (`chart.type: 'kpi'`). Use `basis: 'total'`.
- **Checkout conversion**: `sessions_succeeded / sessions_loaded` as a percentage. Use `basis: 'custom'`.
- **Payment volume**: Bars for ≤14 days, lines for longer. A day with no rows is zero, not a gap.
- **Average order value**: Line chart. Plot every day in the window. A day with no payments is `y: null` (gap in the line). Headline is window amount / window count with `basis: 'custom'`.
- **Payment volume by country**: A table (not a chart) — top 10 countries by current amount, with proportional bars in accent `#533AFD`, current and comparison amounts. Only for windows ≤31 days.

## States

| State | What to use |
| --- | --- |
| Loading | stripe-charts: `{loading: true}` shows a skeleton. Update with `handle.update(fullSpec)` when data arrives. |
| Empty | As **Empty panels** below describes: stripe-charts’ empty state for charts, custom HTML for KPI tiles and tables. |
| Refreshing (manual) | stripe-charts: `handle.update({...spec, loading: true})` for charts and tables. KPI tiles: keep prior spec. |
| Refreshing (auto) | Keep prior spec in all panels — no loading states. |
| Failed | Custom HTML (stripe-charts has no error state): hide the chart `<div>`, show “Couldn’t load this panel.” with a **Retry** button in the card container. On retry success, hide the error, show the chart `<div>`, and call `handle.update(fullSpec)`. |

### Empty panels

A panel is empty only when it has no value to show, such as a rate or average with a zero denominator. A count or amount of zero is a value: show 0, not the empty state.

- **Charts**: stripe-charts’ own empty state: one series with empty data, `series: [{label: '…', data: []}]`, and `emptyMessage: 'No data yet'`. Add nothing to it.
- **Tables**: keep the title and show “No data yet” in secondary text.
- **KPI tiles**: stripe-charts ignores `emptyMessage` on KPI tiles, so render the title with `StripeCharts.render`, `chart.type: 'kpi'`, and `series: [{label: '…', data: []}]`, then add below it a muted em dash (`—`) where the value goes, in 28-pixel semibold secondary text, and one line saying why the tile is empty, in 14-pixel primary text. Don’t repeat the window’s dates: the header already shows them. Checkout conversion’s reason is “No checkout sessions.”

A panel pulses only while its query is still pending. After its result arrives (success or failure), the pulse stops. After all queries are done, no panel should pulse.

### No data for the range

When every current-window query succeeds with no rows or only zeros: keep the header, replace all sections with one centered card (~240px high):

**No data for this time range** — “Acme (acct_…, Sandbox) has no payments, customers, or subscriptions from Fri, Nov 6 – Fri, Nov 13, 2026.”

Then one line based on First activity query:

- **No activity yet**: “This account has no payments, customers, or subscriptions yet.” In sandbox, add “Create test payments to try it.”
- **First activity after range**: “First activity is on Mon, Sep 14, 2026.” Add **Show since Sep 14** button (capped at 92 days).
- **Latest activity before range**: “Latest activity is on Thu, Oct 2, 2026.” Add **Show Sep 3 – Oct 2** button (30 days ending that day).
- **Otherwise**: “Try a longer range from **Date range**.”

A dashboard that can’t query Stripe shows this card without buttons.

## Sources

**Show sources** toggles every panel to show its source in place of its content. In sources mode, hide the chart `<div>` and show the hidden `.panel-title` heading so the title stays visible. Each panel keeps its size.

Each source block shows:

1. **One-sentence description** of what the metric measures, in secondary text above the code area:

| Panel | Description |
| --- | --- |
| Payment volume | Succeeded payment intent volume, or attributed line-item volume for product or price queries. |
| Average order value | Average succeeded payment amount, or average line-item amount for product or price queries. |
| New customers | Count of customers created, by day. |
| Successful payments | Count of succeeded PaymentIntents, by day. |
| Checkout Sessions | Checkout sessions whose payment page was initialized, and those that completed successfully. |
| Payment volume by country | Succeeded payment intent volume grouped by country. |
| MRR | Monthly recurring revenue from active and past-due subscriptions. |
| ARR | Annual recurring revenue from active and past-due subscriptions. |
| MRR growth | Net change in MRR over time. |
| MRR movements | Net change in MRR over time, broken down by change type. |
| Checkout conversion | Succeeded session count divided by initiated session count for each aggregate bucket, in basis points. |

1. **The request** — the endpoint (`POST /v2/data/analytics/metric_query` or `POST /v2/data/query_runs`) and the params or SQL. Pretty-print JSON params (indented, one key per line) and format SQL with line breaks and indentation for readability. Show the code area with a gray background and rounded corners. In the top-right corner of the code area, a 16-pixel clipboard icon inside a 32-pixel button (no text label). When selected, copy the code text, swap the icon to a check mark, and show “Copied” for 4 seconds, then restore. If the clipboard isn’t available, select the text instead.

2. **Status** — whether stale or failed, if applicable.

Don’t show API keys, tokens, response IDs, raw rows, or customer data.

## Charts

Use `@stripe/charts` for every chart and KPI tile. Try loading in this order:

### 1. npm (preferred, when available)

If the output is a project with a package manager:

```bash
npm install @stripe/charts
```

```js
import {render} from '@stripe/charts';
render(el, spec);
```

If install fails (package not yet published), fall through to CDN.

### 2. CDN (default for HTML files and artifacts)

```html
<div id="sc-fallback" style="display:none;text-align:center;padding:40px;color:#3C4F69">
  Charts couldn't load — check your connection and reload the page.
</div>
<script src="https://cdn.jsdelivr.net/gh/stripe/charts@0.0.1-preview.1/dist/stripe-charts.min.js"
  onerror="document.getElementById('sc-fallback').style.display='block'"></script>
```

Works in browsers (local HTML), Claude artifacts, ChatGPT Sites, and Cursor. May not work in sandboxed environments (Codex containers) or offline.

### 3. Inline SVG (last resort)

Use when the environment blocks both npm and CDN. Build charts with one reusable `drawChart(el, spec)` function using inline SVG:

- **Line charts**: 2px stroke, no point markers. First palette color for primary, `#95A4BA` dashed for comparison.
- **Bar charts**: Grouped side by side, 2px rounded tops.
- **KPI tiles**: Title in 14px, value in 28px semibold, change with arrow below.
- **Y-axis**: Right side, 3–5 labels, compact format (“$2K”), light gridlines.
- **X-axis**: Hairline baseline, 3–4 date labels.
- **Tooltip**: On hover, show exact value and date.
- **Empty / loading**: Center “No data yet” text, or the **Empty panels** KPI layout for tiles / pulse animation on placeholder.

Note limitations (no sparklines, no incomplete-day markers, no accessibility) in the hand-over.

### stripe-charts API and series colors

`StripeCharts.render(element, spec)` returns a handle with `update(spec)` and `destroy()`.

**Do not set `color` on any series.** Let the library assign its palette. With one primary series per chart, every chart gets purple `#9966FF`. The full palette in order: purple `#9966FF`, blue `#0055BC`, cyan `#00A1C2`, orange `#ED6804`, magenta `#B3063D`, dark green `#1C5A0D`, pink `#FA4A67`, brown `#922700`, green `#3DA00B`. Comparison series are gray `#95A4BA`.

### Examples

**Payment volume** — currency bar chart with comparison:

```js
StripeCharts.render(el, {
  version: 1,
  title: 'Payment volume',
  format: {style: 'currency', currency: 'usd', unit: 'minor'},
  kpi: {value: 984200, basis: 'total', comparisonValue: 870100},
  chart: {
    type: 'bar', stacking: 'grouped',
    axes: {y: {notation: 'compact'}},
    incomplete: {from: '2026-11-13', message: 'Partial day'},
  },
  series: [
    {label: 'BFCM 2026', data: [{x: '2026-11-27', y: 312000}, ...]},
    {label: 'BFCM 2025', comparison: true, data: [{x: '2025-11-28', y: 290100}, ...]},
  ],
});
```

**MRR** — line chart, headline is latest value:

```js
StripeCharts.render(el, {
  version: 1,
  title: 'MRR',
  format: {style: 'currency', currency: 'usd', unit: 'minor'},
  kpi: {value: 1250000, basis: 'latest', comparisonValue: 1180000},
  chart: {type: 'line', axes: {y: {notation: 'compact'}}},
  series: [
    {label: 'Current', data: [...]},
    {label: 'BFCM 2025', comparison: true, data: [...]},
  ],
});
```

**KPI tile** — count with sparkline:

```js
StripeCharts.render(el, {
  version: 1,
  title: 'New customers',
  format: {style: 'number', maximumFractionDigits: 0},
  kpi: {value: 847, basis: 'total', comparisonValue: 612},
  chart: {type: 'kpi'},
  series: [{label: 'New customers', data: [{x: '2026-11-06', y: 120}, ...]}],
});
```

**Average order value** — line chart, null gaps for days with no payments:

```js
StripeCharts.render(el, {
  version: 1,
  title: 'Average order value',
  format: {style: 'currency', currency: 'usd', unit: 'minor'},
  kpi: {value: 4500, basis: 'custom'},
  chart: {type: 'line', axes: {y: {notation: 'compact'}}},
  series: [{label: 'AOV', data: [{x: '2026-11-12', y: 4500}, {x: '2026-11-13', y: null}, ...]}],
});
```

**Loading → populated**:

```js
const handle = StripeCharts.render(el, {version: 1, title: 'Payment volume', loading: true});
handle.update({version: 1, title: 'Payment volume', format: {...}, series: [...]});
```

### Panel-to-chart mapping

| Panel | `chart.type` | `format.style` | `kpi.basis` |
| --- | --- | --- | --- |
| Payment volume | `bar` (≤14d) or `line` | `currency` | `total` |
| MRR | `line` | `currency` | `latest` |
| ARR | `line` | `currency` | `latest` |
| MRR growth | `bar` grouped | `currency` | `total` |
| Average order value | `line` | `currency` | `custom` |
| New customers | `kpi` | `number` | `total` |
| Successful payments | `kpi` | `number` | `total` |
| Checkout Sessions | `kpi` | `number` | `total` |
| Checkout conversion | `kpi` | `percent`, `unit: 'ratio'` | `custom` |

Comparison series use `comparison: true` and align by position (index), not date. When the window includes today, set `chart.incomplete.from` to today’s date. All Stripe amounts are minor units — always set `unit: 'minor'`. Use `stacking: 'grouped'` only on bar charts — omit it when the chart type is `line`.
dashboard-output.md 13.3 KB
# Dashboard output requirements

Use this reference to choose the dashboard’s output, build it, refresh it, check it, and hand it over. The steps are the same in every agent. You run the queries through the connected Stripe MCP server or connector and write the results into one output: a hosted dashboard or artifact where this session’s tools support one, otherwise one HTML file.

## Choose the output

The skill’s step 1 makes this choice from the listed tools, before the loading page. Check it against these rules now.

1. **Inspect your tools**: Read the tools this session lists, and their schemas, for operations that create, edit, publish, or export a page or file, and for any that let a page refresh its own data. Use tool discovery if the session has it, for page and file tools only. The queries reference covers the Stripe tools, so don’t load their schemas here. If you find a hosted tool only now, and the user didn’t ask for a file, use it, and delete the loading file you wrote. Go by what’s listed, not by the client’s name, because the same client can list different tools in different sessions. Artifacts in Claude, Sites in ChatGPT, and file or artifact tools in Codex are examples, and no client is sure to have them. Never call a tool, operation, or parameter that the session doesn’t list.
2. **Prefer hosted output**: If a listed tool can create a hosted dashboard, page, or artifact, such as a Claude artifact, that holds the complete dashboard, with every panel and its inline script, and can update it later, use it.
3. **Otherwise, write one HTML file**: If no listed tool can do that, the user asked for a file, or creating or updating the hosted output fails, write the dashboard as one self-contained HTML file, `stripe-bfcm-dashboard.html` in the working directory. Export or attach it if a listed tool can. Never overwrite a file you didn’t create: pick another name that starts with `stripe-bfcm-dashboard` instead of asking.

Proceed with the best available output; fall through to an HTML file when no hosting tool is listed.

## Build the dashboard

The skill’s workflow starts queries before writing any HTML. This section covers the build after queries are running.

1. **Show the loading page (first build only)**: The skill’s step 4 writes the loading page and opens it. Skip this on a refresh — go straight to updating the existing dashboard in place.
2. **Poll and build in memory**: Poll the queries until every one finishes or fails. While polling, build the full dashboard page in memory: the layout, header, all panel containers, the `@stripe/charts` script (via the design reference’s fallback chain), and each panel’s data as its query completes. Print a short status in chat every 2 minutes so the user knows the build is alive — “Still waiting on N queries…” or “All queries complete — finalizing.”
3. **Save once**: When every query has finished (or failed), save the complete dashboard to the file or hosted output, overwriting the loading page. One save, at the end, with all the numbers in it. Don’t save intermediate states — there is nothing for the open loading page to pick up until the data is ready. Don’t add `<meta http-equiv="refresh">` to the file. A panel whose query succeeded gets its full spec; a panel whose query failed gets the failed state from the design reference.
4. **Open the finished dashboard**: For HTML files, open the file again (`open` on macOS, `xdg-open` on Linux) so the finished dashboard appears. For hosted output, the update is live. Run every check in Check before publishing. Store the account’s name, ID, mode, view boundaries, time zone, last successful query time, and any failures. Escape stored strings for their HTML context.

Treat the results this way:

- **Some queries failed**: Show the failed state in the affected panels only, as the dashboard design describes, and publish the rest.
- **No data**: Queries that succeed with no rows are results, not failures. Show the dashboard design’s no-data states.
- **Every query failed**: Don’t publish or hand over a dashboard. Replace any loading page with the error and its fix, say the same in the chat, and stop.

Build the page to these limits:

- **Small script**: Aim for about 300 lines. When `@stripe/charts` is available, use `StripeCharts.render` for all charts and KPI tiles — the page script handles data wiring, layout, refresh, and sources only. With inline SVG, follow the design reference’s inline SVG specs.
- **One page, one dependency**: Use `@stripe/charts` for all charts and KPI tiles, loaded via npm, CDN, or inline SVG as the design reference’s fallback chain describes. Load no other remote scripts, fonts, or images.
- **No extra storage**: Don’t add a database, a scheduled task, or a second data file. The results live in the page.

## Page behavior

- **Open with results**: On initial load, the page draws every panel from the query results the agent embedded — it loads `@stripe/charts` for rendering but makes no Stripe API calls. It computes totals, changes, and averages with the queries reference’s calculations, and shows the stored view’s dates, time zone, and refresh status.
- **Agent refresh**: The page can’t query Stripe itself unless the output environment says so, because your Stripe connection belongs to you, not to the browser. Its button reads **Copy refresh request**, copies “Refresh my Stripe BFCM Dashboard” to the clipboard, and reads “Copied. Paste it to your agent” for 4 seconds. If the clipboard isn’t available, it shows that text selected instead. If the viewer has no way to send you that request, leave the button out. The date range shows as text, as the dashboard design describes.
- **Page refresh**: For hosted output, check whether its pages can call the Stripe connector, and how. Read the hosting tool’s description and schema. If the session lists a tool that describes what the host’s pages can do, such as `describe_capabilities` in Claude, call it once, asking about the connector directly and passing the loading page’s ID where the tool takes one. If pages can call the connector, build a page that queries Stripe itself, as the next section describes. Use **Agent refresh** only when they can’t, when the output is a file, or in a session signed in with an API key, which can’t list accounts for the page’s account check.

### Pages that query Stripe themselves

Use the call the environment documents, with the tool and intent names you confirmed, and declare the page’s tools the way it requires. For example, where a Claude artifact offers it, `const mcp = await claude.use("mcp")` (it can be `null`), then `await mcp.callTool("Stripe", tool, input)`. Read `.payload`, which can be an object or JSON text. A failure rejects. The loading page is already published, so declare the same tools on it first, such as `{"mcp": {"servers": [{"server": "Stripe", "tools": ["stripe_analytics", "list_available_accounts_or_orgs"]}]}}`, then publish the dashboard over it. Don’t write this call into a page whose environment doesn’t offer it.

The page adds this behavior, with one metric queue and one polling helper:

1. **Account**: Before its first query, call `list_available_accounts_or_orgs` only to confirm that the written account is listed, and never pick another. The client can ask the viewer to allow the Stripe connector on this first call, so a failure usually means the viewer hasn’t answered yet: keep the embedded results and retry the call every 3 seconds. Show one message only when the call succeeds without the account, or still fails after 2 minutes: “Connect Stripe with access to Acme (acct_…), then select Try again,” naming the account, and a **Try again** button that starts the account check again.
2. **View**: Keep the embedded results under their stored dates and time zone until new results replace them. Before each refresh, compute the time zone and time windows from the queries reference. If their dates or time zone differ from the view on the page, such as on a later day, treat the refresh as a range change, as **Date range** describes.
3. **Refresh**: The **Refresh** button reruns the queries from the queries reference in its order, with its pacing, polling, and single retry. Each waiting chart and table shows its spinner as the dashboard design’s Refreshing state describes. If a query fails, its panels show their old values again with “Couldn’t refresh” and **Retry**, and the header reads “Partially refreshed,” as the dashboard design describes.
4. **Auto-refresh**: Off unless the user asks for it, as Hand over describes. When it’s on, refresh every 5 minutes while the page is visible, as **Refresh** does, but without panel spinners, as the dashboard design’s Refreshing state describes. Skip a turn while a refresh or a range change runs. The date range control stays enabled: choosing a range or a comparison during an auto-refresh stops it and discards its results. When a hidden page becomes visible after 5 minutes or more, refresh right away.
5. **Date range**: Enable the date range control from the dashboard design. Choosing a range or a comparison clears every result from the previous range, shows each panel’s loading state, and reruns the queries for the chosen range with the custom range rules in the queries reference. A query that fails shows its failed state, never the previous range’s values.

## Refresh or change the view

When the user asks, rerun the queries and update the same dashboard, artifact, or file. Never create a second one. If updating a hosted output fails, write the HTML file instead, and say that the earlier link is out of date.

- **Refresh, same view**: Keep each earlier result until its new one succeeds. Mark a query that fails as failed to refresh, so the page keeps its old values with a failure note.
- **Different period or time zone**: Rerun every query for the new view. Never keep a result from the previous view.

Then run the checks in Check before publishing again for the values and controls that changed. An HTML file that’s already open keeps showing its old figures, so after you write the file, open it again so the updated dashboard appears.

## Check before publishing

Check the filled-in dashboard before you publish, export, or hand it over:

- **Numbers**: Use only successful, complete Stripe results and calculations from those results. Never show failed or unreadable results as zeros. Mark retained values as stale after a failed refresh.
- **Account**: Show the selected account’s name and ID, and its verified Stripe mode as the dashboard design describes. Check that every result belongs to that account and mode. Never work out the mode from missing metadata.
- **Refresh mode**: Describe only the refresh behavior the output supports. Reloading saved results doesn’t retrieve new Stripe data. Make the refresh button’s label match its action — “Copy refresh request” if it only copies instructions, omitted if no refresh is supported.
- **Privacy**: Keep credentials, tokens, and customer-identifying data out of the page, embedded data, generated source, files, and URLs.

Fix failed checks before publishing. If you can’t verify a check, including the account or mode, explain what’s missing and stop. In a session signed in with an API key, the key sets the mode and no tool reports it: say in the hand-over that the mode is the key’s, without naming one. Apply the same checks to hosted output and HTML files.

## Hand over

Give the dashboard’s location on its own line: the URL or download that the publishing or export operation returned, or the file’s full path after you confirm the file exists. Never write a URL yourself. Then, in a few short lines:

- The view: the date range and dates, such as “Last 7 days plus today so far, Fri, Nov 6 – Fri, Nov 13, 2026.” Only mention a comparison if one is active — don’t say “with no comparison.” Keep it to what the dashboard actually shows.
- The headline payment volume, such as “$1,106.71 from 16 successful payments.” Include the change only if a comparison is active — don’t say “no change figure” or explain why there isn’t one. If the range has no data, say so, with the account’s first or latest activity and an offer to show the range the design reference’s no-data card gives.
- The account’s name, ID, and verified mode. If the connection lists other accounts, say how many, and that the user can ask for another one by name.
- The time zone, the time of the last successful retrieval, and any failed panels.
- How the dashboard refreshes, as built: either “Ask me to refresh it. It doesn’t update on its own,” adding for hosted output that its pages can’t query Stripe in this client, or, for a page that queries Stripe itself, “The page refreshes when you select Refresh,” and that the client may ask the viewer to allow the Stripe connector.
- Who can open it, as the host enforces it. A file isn’t a sharing link. Anyone who can open the dashboard or file can read its saved figures without a Stripe connection. In a page that queries Stripe itself, a viewer needs their own Stripe connection with access to the account only to retrieve new data.

For a page that queries Stripe itself, end with one question: “Do you want the page to refresh every 5 minutes while it’s open?” Don’t wait for the answer before handing over. If the user says yes, turn auto-refresh on in the same page, without rerunning the queries.

For any other dashboard, end with: “Would you like me to refresh the data, or add a comparison to the previous BFCM?” Don’t wait for the answer before handing over.
queries.md 27.6 KB
# Queries and calculations

Use this reference for every number on the dashboard. The general rules come first: the queries at a glance, their placeholders, time windows, how to run and read the queries, and the calculations. Then the queries follow in the order the dashboard runs them, each with its SQL or request. Use these queries and response shapes exactly, instead of designing new ones.

## Overview

The dashboard runs these queries, in this order. Read the fields as written, without interpreting them:

```json
[
  {"id": "new_customers", "type": "sql", "window": "both", "sql": "New customers"},
  {"id": "successful_payments", "type": "sql", "window": "both", "sql": "Successful payments"},
  {"id": "checkout_sessions", "type": "sql", "window": "both", "sql": "Checkout Sessions"},
  {"id": "payment_volume", "type": "sql", "window": "both", "sql": "Payment volume"},
  {"id": "average_order_value", "type": "sql", "window": "both", "sql": "Average order value"},
  {"id": "payment_volume_by_country", "type": "sql", "window": "both", "sql": "Payment volume by country", "skip_if_days_over": 31},
  {"id": "mrr", "type": "metric", "window": "current", "params": {"name": "revenue.mrr", "starts_at": "{CUR_START}", "ends_at": "{CUR_END_INCL}", "granularity": "day", "timezone": "{TZ}"}},
  {"id": "arr", "type": "metric", "window": "current", "params": {"name": "revenue.arr", "starts_at": "{CUR_START}", "ends_at": "{CUR_END_INCL}", "granularity": "day", "timezone": "{TZ}"}},
  {"id": "mrr_comparison", "type": "metric", "window": "comparison", "skip_without_comparison": true, "params": {"name": "revenue.mrr", "starts_at": "{CMP_START}", "ends_at": "{CMP_END_INCL}", "granularity": "day", "timezone": "{TZ}"}},
  {"id": "mrr_growth", "type": "metric", "window": "current", "params": {"name": "revenue_growth.mrr", "starts_at": "{CUR_START}", "ends_at": "{CUR_END_INCL}", "granularity": "day", "timezone": "{TZ}", "group_by": ["change_type"]}},
  {"id": "mrr_growth_comparison", "type": "metric", "window": "comparison", "skip_without_comparison": true, "params": {"name": "revenue_growth.mrr", "starts_at": "{CMP_START}", "ends_at": "{CMP_END_INCL}", "granularity": "day", "timezone": "{TZ}"}},
  {"id": "first_activity", "type": "sql", "window": "none", "only_if_no_data": true, "sql": "First activity"}
]
```

- **`id`**: The query’s ID in the page’s code, and the key its result is stored under.
- **`window`**: `both` covers the current and comparison windows in one request. `none` uses neither.
- **`sql`**: The heading under Queries that holds the query’s SQL. Send that SQL exactly, with the placeholders filled in.
- **`params`**: The metric request’s `params`, with the placeholders filled in.
- **`skip_without_comparison`**: Don’t send the query when there’s no comparison.
- **`skip_if_days_over`**: Don’t send the query when the current window is longer than this many days.
- **`only_if_no_data`**: Send the query only when the range has no data, as the design reference (`dashboard-design.md`) defines it, and once per account.

## Placeholders

Every query uses these placeholders. CUR is the current window and CMP is the comparison window. SQL takes UTC instants as `YYYY-MM-DD HH:MM:SS`, and metric requests take them as `YYYY-MM-DDTHH:MM:SSZ`.

| Placeholder | Value | Example |
| --- | --- | --- |
| `{CUR_START}` | The current window’s start | `2026-11-06 08:00:00` |
| `{CUR_END}` | The current window’s exclusive SQL end: now, or the next local midnight | `2026-11-14 00:27:04` |
| `{CUR_END_INCL}` | The current window’s inclusive metric end: now, or 1 second before the next local midnight | `2026-11-14T00:27:04Z` |
| `{CMP_START}` | The comparison window’s start | `2025-11-28 08:00:00` |
| `{CMP_END}` | The comparison window’s exclusive SQL end | `2025-12-02 08:00:00` |
| `{CMP_END_INCL}` | The comparison window’s inclusive metric end | `2025-12-02T07:59:59Z` |
| `{TZ}` | The IANA time zone | `America/Los_Angeles` |

The comparison must come before the current window, so the SQL’s `CASE` split works. With no comparison, set `{CMP_START}` and `{CMP_END}` to `{CUR_START}`, an empty range, so the SQL keeps one shape, and send no comparison metric request.

## Time windows

Every output shows the same view, unless the user asks for another period.

- **Time zone**: The IANA zone the user named, otherwise the viewer’s own zone. For the queries you run, that’s the zone your session reports for the user, or the system zone where you run on the user’s machine. Use Pacific time (`America/Los_Angeles`) only if neither is available, and say so in the hand-over. For the queries a dashboard runs itself, it’s the browser’s `Intl.DateTimeFormat().resolvedOptions().timeZone`. Every result is in this local time zone.
- **BFCM**: The 4 days from Black Friday, the day after US Thanksgiving (the fourth Thursday in November), through Cyber Monday.
- **Default view**: The last 7 complete local days plus today so far, with no comparison.
- **Comparison**: One of **None** or **Previous BFCM** (the most recent BFCM that ended before the current window starts). Choosing another range keeps the chosen comparison. If every comparison query has succeeded, every comparison SQL query has no rows, its Payment volume and MRR are zero on every day, and MRR growth comparison has no movements, the account has no data then: drop the comparison and say so, rather than showing zeros.
- **Presets**: **Last 7 days**, **Last 14 days**, and **Month to date** end with today so far, like the default view. **Month to date** starts at local midnight on the first of the current month in the selected time zone. **BFCM 2025** and **BFCM 2026** each cover those 4 days; **BFCM 2026** is available from Black Friday on and runs through today if BFCM is still in progress. **Custom** follows the custom range rules.
- **Custom range**: From **Custom** or the user’s request, the chosen local start and end dates, inclusive. End no later than today, and keep the range to at most 92 days. The comparison follows the boundary rules.
- **Boundaries**: Windows start and end at local midnights, each converted to UTC on its own date, so the windows follow daylight saving time. Every Analytics API request for a window that includes today ends at now, the time of the request, so it returns the latest data. A window that ended earlier, such as a comparison or a past custom range, ends 1 second before the next local midnight: metric ends are inclusive. SQL ends are exclusive: now, or the next local midnight.
- **Comparison boundaries**: **Previous BFCM** covers that BFCM’s 4 full days, except while this year’s BFCM is in progress: when the current window starts on this year’s Black Friday and ends today, on or before Cyber Monday, the comparison covers the same number of days from the previous Black Friday, day for day. When the current window includes today, a comparison that matches it day for day ends at the same local time on its matching day, so both windows cover the same hours. A full 4-day **Previous BFCM** ends 1 second before the local midnight after Cyber Monday.

For example, on Nov 13, 2026 in Pacific time, the current window is Fri, Nov 6 – Fri, Nov 13, from `2026-11-06T08:00:00Z` up to now, and no comparison. **Month to date** starts Sun, Nov 1, at `2026-11-01T07:00:00Z`, because daylight saving time ends only later that day, and its requests end at now. If the user picks **Previous BFCM**, the comparison is BFCM 2025, Fri, Nov 28 – Mon, Dec 1, 2025, from `2025-11-28T08:00:00Z` to `2025-12-02T07:59:59Z`, and its changes compare per day, because the windows have 8 and 4 days.

## Running the queries

- **Order**: On first load and on refresh, start the queries in the order they’re listed under Queries. Create the query runs back to back, without waiting for one to finish before the next. In a sandbox (`livemode` false), which allows 1 query run creation per second, send each creation at least 1 second after the previous one. Send the Analytics API metric calls one at a time, each at least 1 second after the previous metric response. Query runs and metric calls don’t wait for each other, and each panel fills as soon as its result arrives.
- **Agent turns**: Maximize what you do per turn — each turn costs wall-clock time. In one turn, create every query run that’s due (spaced ~1s apart in sandbox), send the next metric call, and retrieve every query run whose poll is due. Don’t serialize: never wait for one query’s result before creating the next query run. Build the page in memory as results arrive. Save the file once, after every query has finished or failed. Don’t sleep when the previous turn took longer than 1 second. Sleep only for the time still left until the next poll or creation is due.
- **Skips**: Follow each query’s skip fields in the Overview. With no comparison, give the SQL an empty comparison window.
- **One fetch**: Share each result across all panels that need it.
- **Limits**: Keep each daily metric window to at most 92 days, and use at most one `group_by` dimension.
- **Polling**: Poll a pending query run after 2 seconds, then 4, then every 5 seconds, for up to 5 minutes.
- **Failures**: Treat a call with no response after 60 seconds as a network error, so no query stays pending. Retry a rate limit, network, or server error once after about 2 seconds, holding new calls during a rate-limit wait. Never retry other errors unchanged. Show failures only in the affected panels.
- **Freshness**: Data isn’t real-time. Query-run tables can lag about 3 hours, and recurring metrics about 1 hour. Show each query’s `refreshed_at` as the design reference describes, and never promise live numbers.
- **More metrics**: Start with only the queries here. If the user asks for more charts, use the [supported metrics](https://docs.stripe.com/data/metrics/supported-metrics.md).

### Requests

Every `stripe_analytics` call takes `stripe_context` and `livemode` from the account, an `intent`, and `params`. In a session signed in with an API key, leave out `stripe_context` and `livemode`.

This skill expects `stripe_analytics`, with the intents `execute_query_run`, `retrieve_query_run`, and `execute_metric`, and `list_available_accounts_or_orgs`. The skill’s first rule already checked `stripe_analytics` and its intents against the session, so don’t read its schema again, or the rest of its description, a long manual that this skill replaces. Look at that one tool’s schema again only if a call fails on an unknown tool, intent, or field. If the session lists a different tool or intent for the same job, use the listed name everywhere, including any tool declaration the output needs, and mention it in the hand-over. If no listed tool runs a metric or a query run, say so and stop, as for missing Stripe tools.

- **Query Runs API SQL**: `"intent": "execute_query_run"` with `"params": {"sql": "…"}`. Poll with `"intent": "retrieve_query_run"` and `"params": {"query_run_id": "qryrun_…"}`, adding `page` and `limit` for later pages. Fill in the placeholders as the Placeholders section describes.
- **Analytics API metric**: `"intent": "execute_metric"` with the query’s `params`, such as `{"stripe_context": "acct_…", "livemode": true, "intent": "execute_metric", "params": {"name": "revenue.mrr", "starts_at": "2025-11-28T08:00:00Z", "ends_at": "2025-12-02T07:59:59Z", "granularity": "day", "timezone": "America/Los_Angeles"}}`. Fill in the placeholders as the Placeholders section describes. `{TZ}` makes the API bucket each day in local time.
- **From the dashboard**: Only in a dashboard that queries Stripe itself, as the output reference (`dashboard-output.md`) defines it. Write the tool and intent names you confirmed into one constant at the top of the script, and use only that constant in calls. Make the calls the way the output environment’s tools and schemas describe, never from a client’s name.

### Responses

These are the shapes the tools return as of this skill. Parse responses with these shapes. Anything else is unreadable: show the failed state with **Retry**, never guessed values. If a call succeeds but its response doesn’t match, say in the hand-over that the tool’s response format changed, so it doesn’t read as missing data.

- **Wrapper**: Every `stripe_analytics` response arrives as `{"tooltip": "…", "result": {…}}`. Unwrap `result`, and ignore `tooltip`.
- **`list_available_accounts_or_orgs`**: `{"accounts": [{"stripe_context": "acct_…", "livemode": true, "name": "…"}]}`.
- **`get_stripe_account_info`**: `{"account_id": "acct_…", "display_name": "…", "dashboard_api_keys_link": "…"}`, with no mode. Use `account_id` and `display_name`.
- **`execute_metric`**: `result.data[]` holds one row per bucket: `{"timestamp": "2026-10-01T07:00:00.000Z", "dimensions": {}, "results": [{"name": "revenue.mrr", "value": "1250000", "currency": "usd"}]}`. The value and currency are in `results[]`, matched by `name`, not on the row itself. `value` is an integer, sent as a string or a number. `timestamp` is the bucket’s start in UTC: convert it to the local day. A grouped row puts its group in `dimensions`, such as `{"change_type": "MRR_CHURN"}`. `result.refreshed_at` and `result.created` are top-level. Empty buckets come back as rows with zero values, except that a grouped query with no groups returns an empty `data`, which means no movements. The API doesn’t paginate: `next_page_url` is always `null`, and one response holds the whole series. If a non-empty result’s rows don’t reach the window’s last day, treat it as incomplete.
- **`execute_query_run` and `retrieve_query_run`**: `result.status` is `running`, `succeeded`, `failed`, or `canceled`. Rows are in `result.result.inline.rows[].data`, as objects keyed by column whose values are strings. Treat a cell shaped `{"string_value": "…"}` as its string. Follow `result.result.inline.next_page_url` by passing it as `params.page`, with the same `query_run_id` and `limit`. `result.result.row_count` is the total across all pages, not the size of one page. An identical cached run can come back from create as `succeeded` with only `result.result.file`. When that happens, call `retrieve_query_run` with `include: ["result.inline"]`. `result.refreshed_at` is the data watermark.
- **SQL values**: Every SQL value except `created` is cast to `varchar`, so 64-bit integers arrive as strings. Amounts are whole numbers of the default currency’s minor units, rounded once in the SQL. Payment volume and Average order value’s `created` is a timestamp of the local date at midnight, labeled UTC, such as `2026-11-06T00:00:00.000Z` for Nov 6: read its first 10 characters as the date, without converting it. The other daily queries return the local date as `day`.
- **Completeness**: Follow every inline result page before computing anything. A missing or incomplete result is a failure, never an empty success. After a complete SQL result, a day with no rows means zero.

## Calculations

Apply these rules in the page’s code, never by estimating in prose:

- **Precision**: Parse amounts and counts from strings without rounding through floating point. Format money using [Stripe minor units](https://docs.stripe.com/currencies.md#minor-units), including zero- and three-decimal currencies. Round only for display.
- **Currency**: The payments queries convert each payment to the account’s default currency at its UTC day’s average exchange rate, as the `payments.*` Analytics API metrics do, and return that currency in `currency`. Format their amounts with it, and never convert them again. Rows that report different currencies are unreadable. A payment with no exchange rate for its day adds nothing to the volume but still counts in the average’s denominator. Never group or filter payments by product or price: that changes the quantity to attributed pre-discount line-item amounts. Payment volume isn’t net revenue, recognized revenue, or profit.
- **Today**: Every total, change, average, rate, chart, table, and card includes today up to now. MRR and ARR use the latest daily bucket, which is today’s when the window includes today.
- **Changes**: Compare window totals. When the windows have different numbers of days, compare each additive total, such as a count, payment volume, or MRR movements, divided by its window’s days, and label the change “per day.” MRR and ARR are levels, not totals: compare their latest daily values directly, never per day. Averages and rates also compare directly, and checkout conversion’s change is in percentage points. Show a dash for the percentage change when the comparison is missing or zero. Never leave out a failed query to produce a total.
- **Averages and rates**: Never average daily averages. A zero denominator means no value, not zero.
- **Countries**: Rank the current window’s named countries by `succeeded_amount_in_merchant_default_currency`, and show the top 10, each with its comparison row from the same result. Show a null or empty country as one row, after them. Don’t build an overall total by adding country rows.

## Queries

Each heading matches a query in the Overview, which holds the metric requests’ `params`. Each SQL query covers both windows unless it says otherwise.

The Payment volume, Average order value, and Payment volume by country queries share three parts:

- **Window split**: The `CASE` labels each row `comparison` or `current`, so the comparison must end before the current window starts.
- **Local day**: In Payment volume and Average order value, the nested `DATE_TRUNC` and `DATE_ADD` shift each `created` by the `{TZ}` offset, then cut it to the day.
- **Currency conversion**: The `exchange_rate_daily_averages` join converts each payment at its UTC day’s average rate, and `ROUND(COALESCE(SUM(…), 0))` returns whole minor units.

### New customers

The count of customers created by day. The New customers card shows its total.

```sql
-- Daily new customers per window
SELECT CASE WHEN created < TIMESTAMP '{CMP_END}' THEN 'comparison' ELSE 'current' END AS win,
  date_format(from_unixtime(to_unixtime(created), '{TZ}'), '%Y-%m-%d') AS day,
  CAST(COUNT(*) AS varchar) AS customers
FROM customers
WHERE (created >= TIMESTAMP '{CMP_START}' AND created < TIMESTAMP '{CMP_END}') OR (created >= TIMESTAMP '{CUR_START}' AND created < TIMESTAMP '{CUR_END}')
GROUP BY 1, 2
ORDER BY 1, 2
```

### Successful payments

The count of succeeded PaymentIntents by day. The Successful payments card shows its total.

```sql
-- Daily succeeded PaymentIntent count per window
SELECT CASE WHEN created < TIMESTAMP '{CMP_END}' THEN 'comparison' ELSE 'current' END AS win,
  date_format(from_unixtime(to_unixtime(created), '{TZ}'), '%Y-%m-%d') AS day,
  CAST(COUNT(*) AS varchar) AS payments
FROM payment_intents
WHERE status = 'succeeded'
  AND ((created >= TIMESTAMP '{CMP_START}' AND created < TIMESTAMP '{CMP_END}') OR (created >= TIMESTAMP '{CUR_START}' AND created < TIMESTAMP '{CUR_END}'))
GROUP BY 1, 2
ORDER BY 1, 2
```

### Checkout Sessions

Checkout Sessions whose payment page loaded, as `sessions_loaded`, and those of them that succeeded, as `sessions_succeeded`, by the session’s creation day, for Checkout, Elements, and Payment Links only. The Checkout Sessions card shows the total of `sessions_loaded`. The checkout conversion card shows the total of `sessions_succeeded` divided by the total of `sessions_loaded`.

```sql
-- Daily Checkout Sessions loaded and succeeded per window, for Checkout, Elements, and Payment Links
SELECT CASE WHEN created_at < TIMESTAMP '{CMP_END}' THEN 'comparison' ELSE 'current' END AS win,
  date_format(from_unixtime(to_unixtime(created_at), '{TZ}'), '%Y-%m-%d') AS day,
  CAST(COUNT(checkout_session_id) AS varchar) AS sessions_loaded,
  CAST(COUNT(CASE WHEN succeeded_at IS NOT NULL THEN checkout_session_id END) AS varchar) AS sessions_succeeded
FROM checkout_session_interactions
WHERE first_initialized_at IS NOT NULL
  AND payment_surface IN ('hosted_checkout', 'embedded_checkout', 'elements', 'elements_2017', 'custom_checkout', 'payment_form_checkout', 'payment_links')
  AND ((created_at >= TIMESTAMP '{CMP_START}' AND created_at < TIMESTAMP '{CMP_END}') OR (created_at >= TIMESTAMP '{CUR_START}' AND created_at < TIMESTAMP '{CUR_END}'))
GROUP BY 1, 2
ORDER BY 1, 2
```

### Payment volume

Succeeded payment volume in the default currency by local day. The Payment volume chart plots each day, and its headline is the window’s total.

```sql
-- Daily succeeded payment volume in merchant default currency per window
SELECT CASE WHEN "payment_intents".created < TIMESTAMP '{CMP_END}' THEN 'comparison' ELSE 'current' END AS win, COALESCE("accounts".default_currency, 'usd') AS currency, CAST(DATE_TRUNC('DAY', CAST(DATE_ADD('MINUTE', CAST(TIMEZONE_MINUTE(AT_TIMEZONE(COALESCE("payment_intents".created, CAST(NULL AS TIMESTAMP)), '{TZ}')) AS BIGINT), DATE_ADD('HOUR', CAST(TIMEZONE_HOUR(AT_TIMEZONE(COALESCE("payment_intents".created, CAST(NULL AS TIMESTAMP)), '{TZ}')) AS BIGINT), COALESCE("payment_intents".created, CAST(NULL AS TIMESTAMP)))) AS TIMESTAMP)) AS TIMESTAMP) AS "created", CAST(CAST(ROUND(COALESCE(SUM( "payment_intents".amount * "exchange_rate_daily_averages".exchange_rate ), 0)) AS BIGINT) AS VARCHAR) AS "succeeded_amount_in_merchant_default_currency" FROM payment_intents AS "payment_intents" LEFT JOIN accounts AS "accounts" ON TRUE LEFT JOIN exchange_rate_daily_averages AS "exchange_rate_daily_averages" ON "exchange_rate_daily_averages".buy_currency = COALESCE("accounts".default_currency, 'usd') AND "exchange_rate_daily_averages".sell_currency = "payment_intents".currency AND CAST(DATE_TRUNC('DAY', "exchange_rate_daily_averages".date) AS TIMESTAMP) = CAST(DATE_TRUNC('DAY', "payment_intents".created) AS TIMESTAMP) WHERE (("payment_intents".created >= TIMESTAMP '{CMP_START}' AND "payment_intents".created < TIMESTAMP '{CMP_END}') OR ("payment_intents".created >= TIMESTAMP '{CUR_START}' AND "payment_intents".created < TIMESTAMP '{CUR_END}')) AND "payment_intents".status = 'succeeded' GROUP BY 1, 2, 3 ORDER BY 1, 3
```

### Average order value

Succeeded volume and count by local day, for Checkout, Elements, and Payment Links payments only. The chart plots each day’s `succeeded_amount_in_merchant_default_currency` divided by that day’s `succeeded_payment_count`. Its headline is the window’s total amount divided by its total count.

```sql
-- Daily succeeded average order value in merchant default currency per window, for Checkout, Elements, and Payment Links payments
SELECT CASE WHEN "payment_intents".created < TIMESTAMP '{CMP_END}' THEN 'comparison' ELSE 'current' END AS win, COALESCE("accounts".default_currency, 'usd') AS currency, CAST(DATE_TRUNC('DAY', CAST(DATE_ADD('MINUTE', CAST(TIMEZONE_MINUTE(AT_TIMEZONE(COALESCE("payment_intents".created, CAST(NULL AS TIMESTAMP)), '{TZ}')) AS BIGINT), DATE_ADD('HOUR', CAST(TIMEZONE_HOUR(AT_TIMEZONE(COALESCE("payment_intents".created, CAST(NULL AS TIMESTAMP)), '{TZ}')) AS BIGINT), COALESCE("payment_intents".created, CAST(NULL AS TIMESTAMP)))) AS TIMESTAMP)) AS TIMESTAMP) AS "created", CAST(CAST(ROUND(COALESCE(SUM( "payment_intents".amount * "exchange_rate_daily_averages".exchange_rate ), 0)) AS BIGINT) AS VARCHAR) AS "succeeded_amount_in_merchant_default_currency", CAST(COUNT("payment_intents".id) AS VARCHAR) AS "succeeded_payment_count" FROM payment_intents AS "payment_intents" LEFT JOIN payment_intents_with_attributed_sessions AS "payment_intents_with_attributed_sessions" ON "payment_intents".id = "payment_intents_with_attributed_sessions".payment_intent_id LEFT JOIN accounts AS "accounts" ON TRUE LEFT JOIN exchange_rate_daily_averages AS "exchange_rate_daily_averages" ON "exchange_rate_daily_averages".buy_currency = COALESCE("accounts".default_currency, 'usd') AND "exchange_rate_daily_averages".sell_currency = "payment_intents".currency AND CAST(DATE_TRUNC('DAY', "exchange_rate_daily_averages".date) AS TIMESTAMP) = CAST(DATE_TRUNC('DAY', "payment_intents".created) AS TIMESTAMP) WHERE (("payment_intents".created >= TIMESTAMP '{CMP_START}' AND "payment_intents".created < TIMESTAMP '{CMP_END}') OR ("payment_intents".created >= TIMESTAMP '{CUR_START}' AND "payment_intents".created < TIMESTAMP '{CUR_END}')) AND "payment_intents".status = 'succeeded' AND "payment_intents_with_attributed_sessions".payment_surface IN ('hosted_checkout', 'embedded_checkout', 'elements', 'elements_2017', 'custom_checkout', 'payment_form_checkout', 'payment_links') GROUP BY 1, 2, 3 ORDER BY 1, 3
```

### Payment volume by country

Succeeded payment volume by the IP-geocoded country of the payer’s session, for each whole window, for the country table.

```sql
-- Succeeded payment volume in merchant default currency per window and geocoded country
SELECT CASE WHEN "payment_intents".created < TIMESTAMP '{CMP_END}' THEN 'comparison' ELSE 'current' END AS win, COALESCE("accounts".default_currency, 'usd') AS currency, "payment_intents_with_attributed_sessions".geocoded_country AS "geocoded_country", CAST(CAST(ROUND(COALESCE(SUM( "payment_intents".amount * "exchange_rate_daily_averages".exchange_rate ), 0)) AS BIGINT) AS VARCHAR) AS "succeeded_amount_in_merchant_default_currency" FROM payment_intents AS "payment_intents" LEFT JOIN payment_intents_with_attributed_sessions AS "payment_intents_with_attributed_sessions" ON "payment_intents".id = "payment_intents_with_attributed_sessions".payment_intent_id LEFT JOIN accounts AS "accounts" ON TRUE LEFT JOIN exchange_rate_daily_averages AS "exchange_rate_daily_averages" ON "exchange_rate_daily_averages".buy_currency = COALESCE("accounts".default_currency, 'usd') AND "exchange_rate_daily_averages".sell_currency = "payment_intents".currency AND CAST(DATE_TRUNC('DAY', "exchange_rate_daily_averages".date) AS TIMESTAMP) = CAST(DATE_TRUNC('DAY', "payment_intents".created) AS TIMESTAMP) WHERE (("payment_intents".created >= TIMESTAMP '{CMP_START}' AND "payment_intents".created < TIMESTAMP '{CMP_END}') OR ("payment_intents".created >= TIMESTAMP '{CUR_START}' AND "payment_intents".created < TIMESTAMP '{CUR_END}')) AND "payment_intents".status = 'succeeded' GROUP BY 1, 2, 3 ORDER BY 1, 4 DESC
```

### MRR

Monthly recurring revenue for the current window, by day. The MRR chart plots each day, and its headline is the latest daily bucket, never a sum.

### ARR

Annual recurring revenue for the current window, by day. The ARR chart plots each day, and its headline is the latest daily bucket. It has no comparison.

### MRR comparison

MRR for the comparison window. Its latest daily bucket is the MRR headline’s comparison, and its days are the chart’s comparison line.

### MRR growth

MRR movements for the current window, by day and `change_type`. The MRR growth chart plots each day’s net change, the sum of that day’s rows, and its headline is the sum of every row. The MRR movements table maps each row’s `dimensions.change_type` to its category before summing: `MRR_NEW` to “New,” `MRR_EXPANSION` to “Expansion,” `MRR_CONTRACTION` to “Contraction,” `MRR_CHURN` to “Churn,” `MRR_REACTIVATION` to “Reactivation,” and `MRR_FX_ADJUSTMENT` to “FX adjustment.” Render exactly those six rows, in that order, with zero for a category that has no rows, then net movement: the six category totals added once each. Any other `change_type` value makes the result unreadable.

### MRR growth comparison

MRR movements for the comparison window. The MRR growth chart plots each day’s sum as the comparison’s bars. The sum of every row is its comparison value, shown without a percentage change, because either can be negative or zero.

### First activity

The account’s first and latest succeeded payment, customer, or subscription. A null or missing `first_day` means the account has no activity yet.

```sql
-- First and latest succeeded PaymentIntent, customer, or subscription
WITH events AS (
  SELECT created AS at FROM payment_intents WHERE status = 'succeeded'
  UNION ALL SELECT created FROM customers
  UNION ALL SELECT created FROM subscriptions
)
SELECT date_format(from_unixtime(to_unixtime(MIN(at)), '{TZ}'), '%Y-%m-%d') AS first_day,
  date_format(from_unixtime(to_unixtime(MAX(at)), '{TZ}'), '%Y-%m-%d') AS last_day
FROM events
```

License (MIT)

View full license text
The MIT License (MIT)

Copyright (c) 2024–2025 Stripe

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.