Syncing forecast views
This page is the recipe for keeping a copy of your forecast in another system, for example a planning
dashboard or a data warehouse that refreshes every hour. You configure the numbers as saved
forecast views in Logistified, and your sync reads each view with one call to
GET /api/v1/forecast-views/{id}/rows.
Set up the views
Section titled “Set up the views”- Use dedicated standard views for the sync, and leave the ones people work with alone, so an edit in the app doesn’t change your feed by surprise. Sort them by SKU where you can: that sort is computed in the database, is the cheapest to read, and keeps the rows in a stable order while stock changes.
- One view per location gives demand per store or channel: a view’s location filter decides which locations its rows sum. Rows carry no location id, so the view is the location.
- Locations that only mirror another store’s sales (multi-store partner locations) have demand but hold no stock. Use their views for demand, not for stock or coverage.
- ERP planning views (Settings → ERP) work the same way when your shop has an ERP connection.
- Supply views sync the same way. They are the heaviest views to read, because their period columns need each item’s full stock projection.
Keep a small view map next to your sync, so that anyone can check what a feed is supposed to be:
| View id | Location scope | Use |
|---|---|---|
a1b2… |
all locations | stock, coverage, reorder |
c3d4… |
Store 1 | demand only |
e5f6… |
Store 2 | demand only |
GET /api/v1/forecast-views lists the views with their ids.
Identify rows
Section titled “Identify rows”A row is identified by (view id, variantId). The sku is for display: it can be blank, and two
variants can share one.
- One call per view, with
limit=4000. A view with up to 4,000 rows comes back complete, withcursor: null. Behind the call, Logistified reads the view in pages of 1,000 rows, one after another and seconds apart, and returns them together. The call checks the pages against each other: if the view’s configuration, its row count or its columns change between two pages, or a row appears twice or goes missing, the call fails and you pull again. A variant that enters or leaves the view between two pages while the row count stays the same is not caught: it can be missing or stale until the next pull. - Split a larger view. A view with more than 4,000 rows answers with a non-null
cursor. Don’t continue it: split its products into disjoint views (for example by a product filter) and read each with one call. Store and channel views are usually far smaller than the whole catalogue. - Views one after another, never in parallel: each call recomputes the view, costs
15 tokens and runs alone per shop. A call above 1,000 rows reads its pages one by one and
lets go in between, so a heavy call that starts between two pages makes the rest of the call answer
429too. A heavy call that finds another one running gets429withdata.codeSHOP_BUSY; waitRetry-Afterand send the whole call again. - Plan the cycle. One key’s bucket holds 60 tokens and refills 1 token per second, so it allows four pulls at once and then one every 15 seconds: eight views take at least about 1 minute, plus their computation and any backoff. Spread the views across the hour if your schedule is tight. See Rate limits.
Every answer carries two fields for your bookkeeping:
computedAt: when the first page of the answer finished. In a view above 1,000 rows the later pages can read stock after it, so it is not one moment for the whole answer.viewRevision: a digest of the view’s configuration. It changes when the view’s columns, filters, locations, sort, display mode or forecast settings change; starring or collapsing things in the table doesn’t change it.
Accept a pull only when it is complete
Section titled “Accept a pull only when it is complete”Accept an answer only if all of these hold:
- HTTP
200 - no
erpUnavailable cursorisnullrows.lengthequalstotalCount- no
variantIdappears twice
Then stage the rows and replace that view’s data in one transaction. Never mix rows of two pulls.
Accept one answer at a time: a pull is always one call, never several calls put together.
When a pull is not accepted
Section titled “When a pull is not accepted”Keep the last accepted data, and:
erpUnavailable(a200with stock-dependent rows withheld): retry afterretryAfterMswhenretryableistrue.- A non-null
cursor: the view has more than 4,000 rows. Split it into disjoint views (see Pull); don’t continue with the cursor. 413 OUTPUT_TOO_LARGE: remove columns from the view. If it is still too large, split its products into disjoint views (for example by a product filter).400 INVALID_INPUTwithdata.codeVIEW_CHANGED_DURING_READ(retryable: true): the view changed while its pages were read, for example an edit or a stock change that moved a row. Pull the view again afterRetry-After.429(RATE_LIMITED, orSHOP_BUSYwhile another heavy call runs): waitRetry-After, then pull the view again.- Never stitch calls. Only one complete answer replaces a view’s data.
When viewRevision changes
Section titled “When viewRevision changes”After the setup, a new viewRevision means somebody edited the view. Keep the last accepted data
until a person has compared the view’s columns and its location and filter scope with your view
map, then accept the new revision.
How fresh each number is
Section titled “How fresh each number is”| What | Freshness |
|---|---|
| The forecast itself | Computed by every call |
| ERP stock (shops with an ERP connection) | Read live by every call, usually again for each 1,000-row page, so later pages can be newer than computedAt; some connections reuse one read for the whole call |
| Shopify stock and orders | Arrive by Shopify webhook, usually after a short delay; no guaranteed time |
| Demand history | Through the last complete day (UTC) |
| ERP master data and work orders | Synced daily at 08:15 UTC |
predictedSales |
The total over each row’s forecastHorizon days, not a daily rate |
| Supply period columns | Projected stock at the end of each period |
Sales that exist only in your ERP count as demand only for the ERP data your connection is set up to read; ask support which that is for your shop.
Example
Section titled “Example”A complete client in TypeScript: it pulls the views one after another, waits Retry-After on a 429, and
applies the acceptance rules above. It never stores anything itself; persist an accepted feed with
your own staging and swap.
// Pull whole forecast views from the Logistified REST API (server-side only: the key is a secret).//// One call per view with limit=4000, views one after another. A pull is ONE response, accepted only when it is// complete: HTTP 200, no `erpUnavailable`, `cursor === null`, `rows.length === totalCount` and unique `variantId`s.// A cursor is never continued: a view with more than 4,000 rows keeps the last accepted data, and the advice is to// split it into disjoint product-filtered views. Anything else keeps the last accepted data and is retried later.// Store an accepted feed by staging it and replacing that view's data in one transaction; identify rows by// (viewId, variantId).
/** The REST API's ceiling for `limit`: a view of up to this many rows comes back in one call. */export const PULL_LIMIT = 4000;
export interface ForecastColumn { id: string; displayName: string; type: "string" | "number" | "boolean" | "date"; unit?: string; period?: { start: string; end: string; type: "week" | "month" | "quarter" };}
export interface ForecastRow { variantId: string; productId: string; [columnId: string]: unknown;}
/** One view's last accepted data. */export interface ForecastViewFeed { viewId: string; viewRevision: string; computedAt: string; columns: ForecastColumn[]; rows: ForecastRow[];}
export type KeepReason = | "erp-unavailable" | "view-changed" | "incomplete" | "duplicate-ids" | "too-large" | "revision-changed" | "rate-limited" | "error";
export type PullResult = | { status: "accepted"; feed: ForecastViewFeed } | { status: "kept"; reason: KeepReason; /** The last accepted data, unchanged (null before the first accepted pull). */ feed: ForecastViewFeed | null; advice: string; retryAfterSeconds?: number; /** A person should compare the view's columns and location/filter scope with the view map. */ scopeReview?: boolean; /** The new revision the scope review is about. */ viewRevision?: string; };
export interface PullOptions { /** e.g. https://prod.logistified.app */ baseUrl: string; /** An `lstk_` key with the read scope. */ apiKey: string; fetch?: typeof fetch;}
interface RowsAnswer { data?: { erpUnavailable?: { retryable?: boolean; retryAfterMs?: number }; columns: ForecastColumn[]; rows: ForecastRow[]; totalCount: number; cursor: string | null; computedAt: string; viewRevision: string; }; error?: { code: string; message: string; retryable?: boolean; retryAfterMs?: number; data?: { code?: string } };}
/** Pull one view with one call and decide whether that one response may replace the last data. */export async function pullForecastView( options: PullOptions & { viewId: string; lastGood: ForecastViewFeed | null; /** A revision a person has checked after a change; it is accepted. */ approvedRevision?: string; }): Promise<PullResult> { const { viewId, lastGood } = options; const fetchFn = options.fetch ?? fetch; const keep = ( reason: KeepReason, advice: string, extra: { retryAfterSeconds?: number; scopeReview?: boolean; viewRevision?: string } = {} ): PullResult => ({ status: "kept", reason, feed: lastGood, advice, ...extra });
const url = `${options.baseUrl.replace(/\/+$/, "")}/api/v1/forecast-views/${encodeURIComponent(viewId)}/rows?limit=${PULL_LIMIT}`; let response: Response; try { response = await fetchFn(url, { headers: { Authorization: `Bearer ${options.apiKey}`, Accept: "application/json" } }); } catch (error) { // A network failure belongs to this view only: keep its last data and let the other views run. const reason = error instanceof Error ? error.message : String(error); return keep("error", `The request failed (${reason}); pull the view again later.`); } const body = (await response.json().catch(() => ({}))) as RowsAnswer;
const retryAfterSeconds = Number(response.headers.get("Retry-After")) || (body.error?.retryAfterMs ? Math.ceil(body.error.retryAfterMs / 1000) : undefined); if (response.status === 429) { return keep("rate-limited", "Wait Retry-After seconds, then pull the view again.", { retryAfterSeconds: retryAfterSeconds ?? 15 }); } if (response.status === 400 && body.error?.data?.code === "VIEW_CHANGED_DURING_READ") { return keep("view-changed", "The view changed while it was read; pull it again later.", { retryAfterSeconds }); } if (response.status === 413) { return keep("too-large", "Remove columns from the view; if it is still too large, split its products into disjoint views."); } if (response.status !== 200 || !body.data) { return keep("error", `HTTP ${response.status} ${body.error?.code ?? ""}: ${body.error?.message ?? "no data"}`.trim()); }
const data = body.data; if (data.erpUnavailable) { const wait = data.erpUnavailable.retryable ? Math.ceil((data.erpUnavailable.retryAfterMs ?? 30000) / 1000) : undefined; return keep("erp-unavailable", "Fishbowl stock could not be read; retry later.", wait ? { retryAfterSeconds: wait } : {}); } // Never continue with the cursor: a pull is one response. if (data.cursor !== null) { return keep( "incomplete", `The view has more than ${PULL_LIMIT.toLocaleString("en-US")} rows: split its products into disjoint views (for example by a product filter) and pull each one.` ); } if (data.rows.length !== data.totalCount) { return keep("incomplete", "The rows do not add up to totalCount; pull the view again later."); } if (new Set(data.rows.map((row) => row.variantId)).size !== data.rows.length) { return keep("duplicate-ids", "A variant appears twice; keep the last data and report the request id."); } if (lastGood && data.viewRevision !== lastGood.viewRevision && data.viewRevision !== options.approvedRevision) { return keep("revision-changed", "The view was edited: check its columns and location/filter scope, then approve the revision.", { scopeReview: true, viewRevision: data.viewRevision, }); } return { status: "accepted", feed: { viewId, viewRevision: data.viewRevision, computedAt: data.computedAt, columns: data.columns, rows: data.rows }, };}
/** Pull several views one after another (never in parallel), waiting Retry-After on 429 before trying the view again. */export async function pullForecastViews( viewIds: string[], options: PullOptions & { lastGood: Record<string, ForecastViewFeed>; approvedRevisions?: Record<string, string>; sleep?: (ms: number) => Promise<void>; maxAttempts?: number; }): Promise<Record<string, PullResult>> { const sleep = options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))); const results: Record<string, PullResult> = {}; for (const viewId of viewIds) { for (let attempt = 1; ; attempt++) { const result = await pullForecastView({ ...options, viewId, lastGood: options.lastGood[viewId] ?? null, approvedRevision: options.approvedRevisions?.[viewId], }); results[viewId] = result; if (result.status === "kept" && result.reason === "rate-limited" && attempt < (options.maxAttempts ?? 3)) { await sleep((result.retryAfterSeconds ?? 15) * 1000); continue; } break; } } return results;}Support and keys
Section titled “Support and keys”- Every response has an
X-Request-Idheader. Quote it when you contact support: the call is recorded with its duration. - A key reads every view of the shop; there are no per-view keys. Keep it on your server, never in a browser or an app.
- AI / Agent access uses the same keys and keeps its 1,000-row pages; whole-view reads are a REST feature.