Build a single-page Orders Manager application powered by the DataDoe REST API. Use when the user asks to create, scaffold, or build an orders manager, orders dashboard, orders table, or order management app using DataDoe.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Create Orders Manager?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/deltologic-create-orders-manager)
---
name: create-orders-manager
description: >-
Build a single-page Orders Manager application powered by the DataDoe REST API.
Use when the user asks to create, scaffold, or build an orders manager, orders
dashboard, orders table, or order management app using DataDoe.
metadata:
author: DataDoe
check-more-skills-at: https://app.datadoe.com/hub/ai-agents-and-skills
title: Orders Manager Builder
access: read
category: Reporting
interface: api
output: app
---
# Orders Manager
Build a complete, working single-page Orders Manager app using the DataDoe REST API. Deliver a working app with server authentication or a synthetic-data preview.
API docs: https://api.datadoe.com/api/v1/docs
Data scheme: https://api.datadoe.com/api/v1/spec/data-scheme
## Agent Type Detection
Determine your agent type before starting:
- **Low-level agent** (Cursor, Claude Code, Codex, Aider, etc.): follow the **Default Tech Stack** below.
- **High-level vibe coding assistant** (Lovable, Base44, Bolt, v0, etc.): ignore the tech stack section entirely; use whatever the platform provides. Implement **Auth & Config** with backend features or a separate server. Use synthetic data when server secrets or sessions are unavailable.
## App Features
### 1. Seller/Vendor Picker
- On load, fetch connected sellers and vendors from the API.
- Show a dropdown to select one. Orders cannot be loaded without a selection.
- Only sellers with `sellerCentralConnection !== null` are valid (Order Line Items source is `SELLER_CENTRAL`).
### 2. Orders Table
- Display orders in a table with expandable nested rows for line items.
- Parent row: `amazon_order_id`, `date`, `amazon_order_status`, `fulfillment_channel`, `sales_channel`, total item count, total price.
- Child rows (expanded): `sku`, `child_asin`, `product_name`, `quantity`, `item_price_value`, `item_price_currency`, `item_status` — keyed by `amazon_order_item_id` (`sku` can repeat within an order).
- Client-side pagination with configurable page size (10/25/50).
### 3. Filters
- **Date range**: date-from / date-to inputs. Default: last 30 days.
- **Order status**: multi-select checkboxes. Values documented by the DataDoe scheme: `Pending`, `Unshipped`, `Shipped`, `Canceled`. Some marketplaces return `Shipped` / `Unshipped` with a marketplace-specific prefix (`Shipped*` / `Unshipped*`), so filter those two with `beginsWith` (never `=`); `Pending` and `Canceled` can use `=`.
- Applying filters triggers a new export.
### 4. Order Tagging (Local)
- Tags are NOT part of the DataDoe API — they are stored in `localStorage`.
- Each order (`amazon_order_id`) can have zero or more text tags.
- UI: inline tag chips with "add tag" button + text input.
- Prefix all localStorage keys with `datadoe-orders-manager::` for collision safety.
- Enforce via TypeScript branded type:
```typescript
type StorageKey = `datadoe-orders-manager::${string}`;
```
### 5. Loading & Error States
- Show a spinner/skeleton during export creation and polling.
- Show user-friendly error messages for API failures (network errors, 429 rate limits, 4xx/5xx).
- On 429: auto-retry after `Retry-After` header value.
## DataDoe API Integration
### Auth & Config
The browser calls its own origin under `/api`. The backend calls
`https://api.datadoe.com/api/v1` with `datadoe-api-key` from a runtime
`DATADOE_API_KEY` server secret. Provision a dedicated key scoped to the
permitted seller accounts and Order Line Items exports.
Choose a platform that supports both server secrets and authenticated
sessions. If either is unavailable, build a synthetic-data preview. For
shared deployments, use an `HttpOnly`, `Secure`, `SameSite=Lax` session cookie.
Verify the session and seller permissions on every request. Bind development
servers to loopback and require same-origin requests. For export creation,
verify the origin or a CSRF token, validate the request body, and apply
per-user quotas and timeouts.
Implement these app routes with fixed upstream paths and methods:
| Method | App route | Server authorization |
| --- | --- | --- |
| GET | `/api/v1/util/sellers-and-vendors` | Filter the response to sellers assigned to the current session. |
| GET | `/api/v1/exports/sources` | Check the seller and return the Order Line Items source. |
| POST | `/api/v1/exports` | Check the seller, source, columns and filters. Record the returned export ID with its owner and seller. |
| GET | `/api/v1/exports/:id` and `/api/v1/exports/:id/raw` | Require the session owner of the export to still have access to its seller. |
Use server-generated upstream headers. For redirects, fetch from the
deployment's approved storage hosts in a separate request without the DataDoe
key. Bound the response size and stream it through the authenticated backend.
Send `Cache-Control: no-store` with order data. Omit keys, redirect URLs and
order rows from telemetry. Return a sanitized error and `Retry-After` when the
upstream API rate limits a request.
### Anti-Rate-Limit Guardrails (Mandatory)
1. **Global client-side pacing**: cap all DataDoe requests to **max 1 request every 600ms** (<= ~1.67 req/s), leaving headroom under 2 req/s.
2. **Single in-flight flow per seller**: never run multiple export flows in parallel for the same seller.
3. **No parallel polling**: only one active poll loop per export; cancel/replace stale loops before starting new ones.
4. **Debounce filter-triggered exports**: wait **400-800ms** after filter changes before creating a new export.
5. **Serialize bursty steps**: when chaining create → poll → raw download, avoid extra background fetches in parallel.
6. **Respect `Retry-After` exactly** on `429`, then add incremental delay for subsequent retries.
If these constraints conflict with UI responsiveness, prioritize staying below rate limits.
### Export Flow (5 steps)
**1. Fetch sellers**
```
GET /api/v1/util/sellers-and-vendors
→ { items: [{ id, name, sellerCentralConnection, vendorCentralConnection, amazonAdsConnection }] }
```
Filter to items where `sellerCentralConnection` is not null.
**2. Fetch export sources (get source ID)**
```
GET /api/v1/exports/sources?sellerOrVendorIds=<sellerId>
```
Find the source named `Order Line Items` (type `SELLER_CENTRAL`) and use the `id` it returns — **always prefer the resolved id**.
Never hardcode the source id: resolve it at runtime from `GET /api/v1/exports/sources` by matching `tableName == "amazon_order_items_with_cogs"` (the id format can differ between the REST and MCP surfaces).
**3. Create export**
```
POST /api/v1/exports
```
Request body:
```json
{
"sellerOrVendorIds": ["<sellerId>"],
"sourceId": "<id of amazon_order_items_with_cogs from GET /exports/sources>",
"columns": [
"amazon_order_id",
"amazon_order_item_id",
"date",
"amazon_order_status",
"fulfillment_channel",
"sales_channel",
"sku",
"line_item_number",
"child_asin",
"product_name",
"item_status",
"quantity",
"item_price_value",
"item_price_currency"
],
"from": "2025-01-01T00:00:00.000Z",
"to": "2025-01-31T23:59:59.999Z",
"outputType": "JSON",
"sendToAllOrganizationMembers": false
}
```
To filter by status, add `filters`. Use `beginsWith` for `Shipped` and `Unshipped` so marketplace-prefixed variants (`Shipped*` / `Unshipped*`) are included; `=` is safe only for `Pending` and `Canceled`:
```json
{
"filters": {
"combinator": "or",
"rules": [
{
"field": "amazon_order_status",
"operator": "beginsWith",
"value": "Shipped",
"not": false
},
{
"field": "amazon_order_status",
"operator": "=",
"value": "Pending",
"not": false
}
]
}
}
```
Response: `{ id, status: "PENDING", ... }`.
**4. Poll status** (every 5s, timeout 2min)
```
GET /api/v1/exports/<exportId>
→ { status: "PENDING" | "PROCESSING" | "COMPLETED" | "ERROR" }
```
**5. Download data**
When `status` is `COMPLETED`, download. If `ERROR`, show error.
```
GET /api/v1/exports/<exportId>/raw
```
- `200`: redirects (302) to a pre-signed S3 URL — the app backend validates and fetches the storage URL, then streams the result to the browser.
- `204`: still processing — retry after a few seconds.
- `404`: export not found.
Example row returned in the flat array:
```json
{
"seller_or_vendor_id": "3f2a9c1e-5b7d-4e8a-9c21-7d4e5f6a8b90",
"seller_or_vendor_name": "DataDoe UK",
"marketplace_country_name": "United Kingdom",
"amazon_order_id": "203-5492174-4518714",
"amazon_order_item_id": "12345678901234",
"sku": "341_SDA12D_117_FBA",
"line_item_number": 0,
"date": "2025-01-12",
"amazon_order_status": "Shipped",
"fulfillment_channel": "Amazon",
"sales_channel": "Amazon.co.uk",
"child_asin": "ABCDEFGHIJ",
"product_name": "xyz",
"item_status": "Shipped",
"quantity": 2,
"item_price_value": 14.76,
"item_price_currency": "GBP"
}
```
For the full column reference, see: https://api.datadoe.com/api/v1/spec/data-scheme
### Raw Data Shape & Client-Side Grouping Logic
The `/raw` endpoint returns a **flat array of line items**. Each element is one order item (`amazon_order_item_id`) within one order. An order with N order items produces N rows all sharing the same `amazon_order_id`; the same `sku` can appear on more than one of them.
**CRITICAL — `columns: []` (empty array) does NOT return all columns.** It returns only seller-context metadata columns (seller id / name, marketplace, connection ids) and none of the Order Line Items fields (`amazon_order_id`, `sku`, `amazon_order_status`, etc.). Always specify the required columns explicitly. Every response also **prepends those utility columns** before your requested fields, so read values by **key/name, never by column position**.
**Field roles:**
| Field | Level | Notes |
| --------------------- | --------- | ----------------------------------------------------------------- |
| `amazon_order_id` | Order | Grouping key — unique per order |
| `amazon_order_item_id` | Line item | Amazon's order-item id — unique per line, never null. **Use it as the row key** (TanStack `getRowId`). |
| `amazon_order_status` | Order | Consistent across all rows for the same order. `Pending` / `Unshipped` / `Shipped` / `Canceled`; some marketplaces prefix `Shipped*` / `Unshipped*` |
| `fulfillment_channel` | Order | Consistent across all rows for the same order |
| `date` | Order | Purchase date. Marketplace orders use the marketplace local date. Off-Amazon lines use the kept connection's country time zone. Use this for display and sorting. `order_date` duplicates `date`. |
| `sales_channel` | Order | Amazon's supplied channel. A marketplace order uses an Amazon marketplace domain, such as Amazon.com. Any other non-empty value, including Non-Amazon, is off-Amazon Multi-Channel Fulfillment. That value does not name the external store. A blank channel is not off-Amazon. |
| `sku` | Line item | Seller SKU of the line. **Not unique within an order** — the same SKU can be a separate order item more than once, so never key rows by it |
| `line_item_number` | Line item | Occurrence index of the same SKU within the order (`0` for the first line of each SKU; increments only when that SKU repeats). **Not** the line's position in the order — do not use it to order or key lines |
| `child_asin` | Line item | Amazon ASIN |
| `product_name` | Line item | Full product name |
| `item_status` | Line item | Can differ from `amazon_order_status` |
| `quantity` | Line item | Units for this SKU only |
| `item_price_value` | Line item | **Line-item total value — already includes quantity; use as-is, do NOT multiply by `quantity`.** **Null on cancelled lines** (and on orders <4h old): coalesce to `0` and render "—" with a "cancelled" badge, never `NaN`. On an off-Amazon line this is the order-report amount, not verified sales. |
| `item_price_currency` | Line item | Consistent across the priced rows of an order; **null on cancelled lines** — take it from another line of the same order, else fall back to the marketplace currency |
**How to build the parent (order) row from the flat array:**
```typescript
// Group by amazon_order_id. Sort parent rows by date (purchase date).
// item_price_value is already the line TOTAL - sum it as-is, never multiply by quantity.
// item_price_value and item_price_currency are NULL on cancelled lines (and on orders <4h old):
// coalesce the price to 0 and take the currency from the first line that has one, so a
// cancelled line can never turn the order total into NaN.
const ordersMap = new Map<string, OrderRow>();
for (const item of lineItems) {
const linePrice = item.item_price_value ?? 0; // null on cancelled lines -> 0, never NaN
const existing = ordersMap.get(item.amazon_order_id);
if (existing) {
existing.lineItems.push(item); // child rows are keyed by amazon_order_item_id, not sku
existing.totalPrice += linePrice; // line total, NOT × quantity
existing.itemCount += item.quantity ?? 0;
existing.currency ??= item.item_price_currency ?? null; // first non-null currency wins
} else {
ordersMap.set(item.amazon_order_id, {
amazon_order_id: item.amazon_order_id,
amazon_order_status: item.amazon_order_status, // order-level, consistent
fulfillment_channel: item.fulfillment_channel, // order-level, consistent
sales_channel: item.sales_channel, // order-level, consistent
date: item.date, // local date in the kept connection's country time zone
currency: item.item_price_currency ?? null, // null on cancelled lines; filled from a later line
totalPrice: linePrice, // line total, NOT × quantity
itemCount: item.quantity ?? 0,
lineItems: [item],
});
}
}
const orders = Array.from(ordersMap.values());
// Sort by date descending. date is the purchase date. order_date is the same value.
// If currency is still null (every line cancelled), fall back to the seller's marketplace
// currency (e.g. GBP for Amazon.co.uk) and render the total as "—" with a "cancelled" badge.
```
**Parent row columns to display:**
| Column | Source | Display |
| ---------- | ------------------------------------- | ---------------------- |
| Order ID | `amazon_order_id` | Monospace, full string |
| Order Date | `date` | Purchase date |
| Status | `amazon_order_status` (first item) | Coloured badge |
| Channel | `fulfillment_channel` (first item) | Badge |
| Sales channel | `sales_channel` (first item) | Amazon domain, or the supplied off-Amazon value |
| Items | `sum(quantity)` across all line items | Number |
| Total | `sum(item_price_value ?? 0)` (already line totals; null on cancelled lines) | Formatted currency; "—" + "cancelled" badge when every line is null. For an off-Amazon order, label it as a declared amount, not sales revenue. |
| Tags | localStorage only | Tag chips |
**Child (line item) row columns to display** (row key: `amazon_order_item_id` via TanStack `getRowId` — not `sku`, not the array index):
| Column | Source |
| ----------- | ------------------------------------------ |
| SKU | `sku` |
| ASIN | `child_asin` |
| Product | `product_name` |
| Qty | `quantity` |
| Price | `item_price_value` + `item_price_currency` ("—" when null, i.e. cancelled line) |
| Item Status | `item_status` |
An order is off-Amazon when `sales_channel` is non-empty and, after trim and lowercasing, is not an Amazon marketplace domain: `amazon.ae`, `amazon.ca`, `amazon.co.jp`, `amazon.co.uk`, `amazon.co.za`, `amazon.com`, `amazon.com.au`, `amazon.com.be`, `amazon.com.br`, `amazon.com.mx`, `amazon.com.tr`, `amazon.de`, `amazon.eg`, `amazon.es`, `amazon.fr`, `amazon.ie`, `amazon.in`, `amazon.it`, `amazon.nl`, `amazon.pl`, `amazon.sa`, `amazon.se`, or `amazon.sg`. Keep the row and the supplied channel. A blank channel stays a marketplace order. Do not name an external store from a generic value such as Non-Amazon.
**CRITICAL — API parameter formats discovered through testing:**
- `GET /exports/sources` uses **bare** query param `sellerOrVendorIds=<uuid>` — **not** `sellerOrVendorIds[]=<uuid>` and **not** `sellerOrVendorIds[0]=<uuid>`. The bracket syntax is rejected with 400.
- `POST /exports` **`columns` must be an explicit list** of the field names you need — never pass `[]` (empty). An empty array returns only seller-context metadata with no order fields, causing the table to display empty rows.
- Date range uses **top-level** `from` and `to` fields (ISO 8601 datetime strings like `2025-01-01T00:00:00.000Z`) — **not** inside `filters`.
- `filters` uses `combinator` with **lowercase** values: `"and"` or `"or"` (not `"AND"` / `"OR"`).
- Each filter rule **must** include the `not` field (boolean): `{ "field": "...", "operator": "...", "value": "...", "not": false }`.
- If no filter rules are needed, either omit `filters` entirely or pass `{ "combinator": "and", "rules": [] }`.
## Default Tech Stack (Low-Level Agents Only)
Skip this section if you are a high-level assistant.
| Tool | Version / Notes |
| -------------- | -------------------------------------------------------------- |
| Vite | Latest, React + TypeScript template (`npm create vite@latest`) |
| React | 18+ with TypeScript strict mode |
| axios | **1.13.6 only** (security requirement) |
| TanStack Table | `@tanstack/react-table` latest |
| day.js | Latest, for date formatting and manipulation |
| Lucide React | Latest, for icons |
| CSS Modules | Native CSS, no Tailwind or component libraries |
| Google Sans | Font via Google Fonts CDN |
### Setup
Vite creates a nested directory. Move all files up to the workspace root so the project lives at the top level:
```bash
npm create vite@latest orders-manager -- --template react-ts
shopt -s dotglob && mv orders-manager/* . && rmdir orders-manager
npm install axios@1.13.6 @tanstack/react-table dayjs lucide-react
```
### Required Execution Order
1. Scaffold Vite app in `orders-manager`.
2. Move generated files/folders to workspace root.
3. Install dependencies.
4. Add `.env` to `.gitignore`.
5. Create `.env.example`.
6. Implement the server routes and verify the session and credential boundary.
7. Implement app code using exact snippets from the **Mandatory Code Snippets** section.
8. Run build/lint checks.
### File Structure (Feature-Based)
Every component lives in its own directory containing exactly two files: the component file and its CSS Module. No component files sit loose in a parent folder.
```
src/
├── main.tsx
├── App.tsx
├── App.module.css
├── shared/
│ ├── styles/
│ │ ├── global.css # imports tokens, typography, palette
│ │ ├── tokens.css # CSS custom properties: colors, spacing
│ │ ├── typography.css # font families, sizes, weights
│ │ ├── colors.css # color palette utility classes
│ │ └── spacing.css # margin/padding utility classes
│ ├── components/
│ │ ├── DataTable/
│ │ │ ├── DataTable.tsx # generic TanStack Table wrapper
│ │ │ └── DataTable.module.css
│ │ ├── Spinner/
│ │ │ ├── Spinner.tsx
│ │ │ └── Spinner.module.css
│ │ └── ErrorMessage/
│ │ ├── ErrorMessage.tsx
│ │ └── ErrorMessage.module.css
│ ├── hooks/
│ │ └── useLocalStorage.ts
│ ├── utils/
│ │ └── localStorage.ts # branded StorageKey type, get/set helpers
│ └── api/
│ └── client.ts # axios instance + 429 retry interceptor
├── features/
│ └── orders/
│ ├── OrdersManager/
│ │ ├── OrdersManager.tsx
│ │ └── OrdersManager.module.css
│ ├── OrdersTable/
│ │ ├── OrdersTable.tsx
│ │ └── OrdersTable.module.css
│ ├── OrderFilters/
│ │ ├── OrderFilters.tsx
│ │ └── OrderFilters.module.css
│ ├── OrderTags/
│ │ ├── OrderTags.tsx
│ │ └── OrderTags.module.css
│ ├── SellerPicker/
│ │ ├── SellerPicker.tsx
│ │ └── SellerPicker.module.css
│ ├── hooks/
│ │ ├── useOrders.ts
│ │ ├── useExport.ts
│ │ └── useSellers.ts
│ ├── types.ts
│ └── utils.ts
```
### Styling Rules
- Define design tokens as CSS custom properties in `tokens.css`.
- Import Google Sans in `global.css`: `@import url('https://fonts.googleapis.com/css2?family=Google+Sans:wght@400;500;700&display=swap');`
- Each component gets its own `.module.css` file.
- No inline styles. No Tailwind. No component libraries.
### Generic DataTable Component
Create a generic `DataTable<T>` component that:
- Accepts `columns: ColumnDef<T>[]`, `data: T[]`, and optional `renderSubComponent`.
- Handles pagination (page size selector: 10/25/50).
- Uses `getExpandedRowModel()` for nested row expansion.
- Renders via CSS Modules — the orders feature passes its own column definitions.
### localStorage Key Safety
```typescript
type StorageKey = `datadoe-orders-manager::${string}`;
function getItem(key: StorageKey): string | null {
return localStorage.getItem(key);
}
function setItem(key: StorageKey, value: string): void {
localStorage.setItem(key, value);
}
```
## Mandatory API Connectivity Check (before UI)
**Never edit `.env` automatically — treat it as a protected secrets file.**
Use synthetic data or a dedicated read-only server key to verify:
- The local app returns a permitted seller list from its own origin.
- The deployed API returns `401` without a session and denies another user's sellers or exports.
- The browser can create, poll and download an export for a permitted seller.
- The browser asset bundles, requests and storage contain no DataDoe credential. Check a synthetic sentinel value in the built assets.
## Mandatory Code Snippets
Use the app routes above for both development and production. In Vite, route
the relative `/api` prefix to the app's loopback backend during development.
Serve `/api` on the same origin as the browser bundle in production.
### `src/api/client.ts` — Axios Instance with Pacing & 429 Retry
```typescript
import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
const MIN_REQUEST_INTERVAL_MS = 600;
let lastRequestTime = 0;
async function waitForPacing(): Promise<void> {
const now = Date.now();
const elapsed = now - lastRequestTime;
if (elapsed < MIN_REQUEST_INTERVAL_MS) {
await new Promise((resolve) =>
setTimeout(resolve, MIN_REQUEST_INTERVAL_MS - elapsed)
);
}
lastRequestTime = Date.now();
}
const instance: AxiosInstance = axios.create({
baseURL: "/api",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
instance.interceptors.request.use(async (config) => {
await waitForPacing();
return config;
});
instance.interceptors.response.use(
(response) => response,
async (error) => {
const response = error.response as AxiosResponse | undefined;
if (response?.status === 429) {
const retryAfter = parseInt(response.headers["retry-after"] || "1", 10);
const delay = retryAfter * 1000 + 200;
await new Promise((resolve) => setTimeout(resolve, delay));
return instance.request(error.config as AxiosRequestConfig);
}
return Promise.reject(error);
}
);
export default instance;
```
**Critical details:**
- The browser sends its same-origin session cookie on each request.
- The pacing interceptor enforces 600ms minimum between requests (< 2 req/s limit).
- The 429 interceptor reads `Retry-After`, waits, and retries once.
### `src/api/datadoe.ts` — API Functions with Correct Request Shapes
```typescript
import client from "./client";
// The Order Line Items source id is resolved at runtime from GET /exports/sources
// by table name. Never hardcode it: ids differ between the REST and MCP surfaces and
// can change; a stale id fails the export with FIELD/SOURCE errors.
const ORDER_LINE_ITEMS_TABLE = "amazon_order_items_with_cogs";
export async function fetchSellersAndVendors() {
const response = await client.get<{ items: any[] }>(
"/v1/util/sellers-and-vendors"
);
return response.data.items;
}
// IMPORTANT: query param is sellerOrVendorIds=<uuid> (no brackets)
export async function fetchOrderLineItemsSourceId(
sellerId: string
): Promise<string> {
try {
const response = await client.get<any[]>(
`/v1/exports/sources?sellerOrVendorIds=${sellerId}`
);
const orderSource = response.data.find(
(s: any) =>
s.tableName === ORDER_LINE_ITEMS_TABLE ||
(s.name === "Order Line Items" && s.type === "SELLER_CENTRAL")
);
if (!orderSource?.id) {
throw new Error(
`Source ${ORDER_LINE_ITEMS_TABLE} not found for seller ${sellerId} - check the connection and the Data settings.`
);
}
return orderSource.id;
} catch (error) {
// Surface the failure in the UI; do not fall back to a hardcoded id.
throw error;
}
}
// Required columns for the Order Line Items source.
// NEVER pass columns: [] — an empty array returns only seller-context metadata
// (seller_or_vendor_id, seller_or_vendor_name, marketplace_country_name, etc.) with NO order fields,
// which causes the table to display empty rows.
const ORDER_LINE_ITEMS_COLUMNS = [
"amazon_order_id",
"amazon_order_item_id", // unique per line - the row key (sku can repeat within an order)
"date",
"amazon_order_status",
"fulfillment_channel",
"sales_channel",
"sku",
"line_item_number",
"child_asin",
"product_name",
"item_status",
"quantity",
"item_price_value",
"item_price_currency",
];
// IMPORTANT: export creation request shape — all fields are mandatory.
// - from/to are TOP-LEVEL ISO datetime strings (not inside filters).
// - columns must be an EXPLICIT list of field names (never empty []).
// - sendToAllOrganizationMembers is required (use false).
// - filters.combinator is lowercase: "and" or "or".
// - each filter rule must have a "not" boolean field.
export async function createExport(
sellerId: string,
sourceId: string,
dateFrom: string,
dateTo: string,
orderStatusFilters: string[] = []
) {
const body: Record<string, unknown> = {
sourceId,
sellerOrVendorIds: [sellerId],
outputType: "JSON",
columns: ORDER_LINE_ITEMS_COLUMNS,
sendToAllOrganizationMembers: false,
from: `${dateFrom}T00:00:00.000Z`,
to: `${dateTo}T23:59:59.999Z`,
};
if (orderStatusFilters.length > 0) {
body.filters = {
combinator: "or",
rules: orderStatusFilters.map((status) => ({
field: "amazon_order_status",
// Shipped / Unshipped have marketplace-prefixed variants (Shipped*, Unshipped*):
// match them with beginsWith. Pending / Canceled are exact values.
operator:
status === "Shipped" || status === "Unshipped" ? "beginsWith" : "=",
value: status,
not: false,
})),
};
}
const response = await client.post<any>("/v1/exports", body);
return response.data;
}
export async function pollExport(exportId: string) {
const response = await client.get<any>(`/v1/exports/${exportId}`);
return response.data;
}
export async function fetchExportRaw(exportId: string) {
const response = await client.get(`/v1/exports/${exportId}/raw`, {
validateStatus: (status) => status === 200 || status === 204,
});
if (response.status === 204) return null;
return response.data;
}
```
### Server `.env.example`
```dotenv
DATADOE_API_KEY=
```
Load the value from server configuration at runtime.
## Implementation Rules
1. **Single run**: deliver the working mode selected in **Auth & Config**.
2. **Test API calls first**: before coding the full UI, verify the export flow works by running the mandatory connectivity checks.
3. **Group line items by order**: the API returns flat rows. Group by `amazon_order_id` before rendering.
4. **Handle empty states**: no sellers, no orders, export still loading — all need UI.
5. **Date defaults**: from = 30 days ago, to = today.
6. **Use `outputType: "JSON"`** for exports.
7. **Poll interval**: 5 seconds between status checks. Timeout after 2 minutes with an error message.
8. **Retry on 429**: auto-retry with the `Retry-After` value, with incrementally increasing delays.
9. **Use the exact code snippets** from the Mandatory Code Snippets section for `src/api/client.ts` and `src/api/datadoe.ts`.
10. **Run build and lint** before finalizing.
11. **Leave dev server running** in background after implementation.
12. **Report local URL, proxy check result**, and any residual risk explicitly.
## Protected Files
**Never modify `.env`.**
- Use `.env.example` as reference and documentation target.
- Never print `.env` secrets in output.
## Post-Implementation Startup
Always run dev server in background:
```bash
npm run dev
```
## Verification Checklist
After implementation, verify:
- App starts without errors (`npm run dev`).
- Seller picker loads and shows sellers.
- Selecting a seller and clicking "Load Orders" triggers the export flow.
- Orders appear in the table grouped by `amazon_order_id`.
- Expanding a row shows line items.
- Date filter changes trigger new exports.
- Status filter with checkboxes works.
- Tags can be added, removed, and persist across page reloads.
- Loading spinner shows during export polling.
- Error messages display on API failure.
- Pagination controls work (10/25/50 per page).