# Shopify Price and Availability Anomaly Desk (`practical_ai_lab_jp/pal-shopify-price-availability-anomaly-desk`) Actor

Paste one Shopify store URL to baseline its public product feed, then compare repeat runs to find severity-ranked price and stock anomalies grouped by product family, with before-after records and JSON/CSV reports.

- **URL**: https://apify.com/practical_ai_lab_jp/pal-shopify-price-availability-anomaly-desk.md
- **Developed by:** [Practical AI Lab](https://apify.com/practical_ai_lab_jp) (community)
- **Categories:** E-commerce, Developer tools
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $20.00 / 1,000 anomaly reports

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Shopify Price and Availability Anomaly Desk

Give this Actor **one public Shopify store URL**. The first run saves a baseline of the store's public product feed. Every later run compares the store with the previous run and returns **severity-ranked price and availability anomalies**, grouped by product family, with before-and-after values and ready-to-share JSON and CSV reports.

It is built for ecommerce operations analysts who need to answer: *"What changed on this storefront since last time, and which changes need a human right now?"*

### What makes it different from a product scraper

A product scraper returns a catalog. This Actor returns **decisions** from changes between runs:

- **Multi-factor scoring.** Signals that move together on the same variant are stacked into one finding. A price drop combined with a stockout scores higher than either alone.
- **Product-family roll-ups.** Findings are grouped by product type (falling back to vendor) and ranked, with a pattern label such as `BROAD_PRICE_DROP` when most compared variants in a family moved the same way.
- **Four buyer outcomes** in one run: pricing error triage, stock disruption watch, promotion and markdown audit, and catalog integrity drift.
- **Reproducible output.** Every report carries the thresholds used, snapshot hashes and timestamps for the two runs compared.

### Quick start (one URL)

1. Open the Actor and enter only **Shopify store URL**, for example `https://www.allbirds.com` (an example storefront with no affiliation; use a store you are permitted to monitor).
2. Click **Start**. The run finishes with status `BASELINE_CREATED`. No anomalies are reported on a first run, because there is nothing to compare with yet. You get a sample of the products that were captured so you can confirm the right store was read.
3. Run the Actor again later with the same input. The run now compares the store with the previous run and returns anomalies.

Minimal input:

```json
{
    "storeUrl": "https://www.allbirds.com"
}
```

Input with every option (values shown are the defaults except `minSeverity`):

```json
{
    "storeUrl": "https://www.allbirds.com",
    "maxProducts": 250,
    "maxPages": 4,
    "priceChangeThresholdPercent": 10,
    "minSeverity": "medium",
    "maxAnomalies": 300,
    "requestDelaySecs": 1.5,
    "requestTimeoutSecs": 15,
    "stateStoreName": "pal-shopify-anomaly-desk-state"
}
```

### Scheduling later runs

This Actor does not run itself and sends no alerts. Without a schedule it is a one-off comparison against whatever run came before.

To monitor a store over time:

1. Save the input above as an Apify **Task**.
2. Create an Apify **Schedule** for that Task (for example once a day, or every few hours for fast-moving stores).
3. Read each run's dataset, `OUTPUT` or CSV files. Apify integrations or webhooks that you configure yourself can forward results; they are not enabled by this Actor.

Each run is compared with the **previous** run, so the schedule interval is the comparison window. Use a different `stateStoreName` if you want an independent baseline for the same domain (for example, one daily schedule and one weekly schedule).

### What you get

#### Dataset (one table, `recordType` tells the rows apart)

| recordType | When | Content |
|---|---|---|
| `RUN_SUMMARY` | Every successful run | Status (`BASELINE_CREATED`, `ANOMALIES_FOUND` or `NO_ANOMALIES_FOUND`), sample size, counts by severity, thresholds, snapshot hashes, caveats and next step |
| `BASELINE_SAMPLE` | First run only | Up to 10 captured products (title, family, price range, availability count) so you can confirm what is being monitored |
| `FAMILY_RISK` | Repeat runs | One row per affected product family, ranked, with severity, pattern, share of compared variants affected and suggested action |
| `ANOMALY` | Repeat runs | One row per affected variant or removed product, ranked, with signals, before and after price, compare-at price, availability, evidence text, buyer outcomes and suggested action |

Rows are pushed in that order: summary, families (most severe first), then anomalies (most severe first). Each anomaly carries `familyRank`, so findings and families join without extra work.

#### Key-value store (run's default store)

- `OUTPUT` – the summary plus the four buyer-outcome sections (top 10 items each) and billing status.
- `REPORT_JSON` – the full report: summary, outcomes, families and all reported anomalies.
- `ANOMALIES_CSV` and `FAMILIES_CSV` – the same data as flat CSV. Text that starts with `=`, `+`, `-` or `@` is prefixed with `'` so store-controlled titles cannot become spreadsheet formulas.

#### Illustrative record (made-up placeholder values, not real store data)

```json
{
    "recordType": "ANOMALY",
    "rank": 1,
    "severity": "critical",
    "severityScore": 100,
    "family": "Example family",
    "anomalyType": "SUSPECTED_PRICING_ERROR",
    "signals": ["PRICE_DROP", "SUSPECTED_PRICING_ERROR", "WENT_OUT_OF_STOCK"],
    "productTitle": "Example product",
    "variantTitle": "Example variant",
    "beforePrice": "100.00",
    "afterPrice": "20.00",
    "priceChangePercent": -80.0,
    "beforeAvailable": true,
    "afterAvailable": false,
    "buyerOutcomes": ["pricing_error_triage", "stock_disruption_watch", "promotion_audit"],
    "evidence": "Price 100.00 -> 20.00 (-80.0%). Went out of stock.",
    "recommendedAction": "Verify this price in the store admin now; if unintended, correct it and review any orders placed at the new price."
}
```

### The four buyer outcomes

| Outcome | Question it answers | Included findings |
|---|---|---|
| `pricing_error_triage` | Which price moves look like mistakes or need a margin check now? | Suspected pricing errors, and price moves scoring 35 or more |
| `stock_disruption_watch` | What went out of stock or came back, and did the price move too? | Availability changes |
| `promotion_audit` | Which markdowns or compare-at discounts started, deepened or ended? | Price drops and discount changes |
| `catalog_integrity_drift` | What disappeared from the public feed? | Removed products and variants |

### How severity is scored

Each variant is compared with its previous state. Signals add points, combinations add a bonus, and the total is capped at 100.

| Signal | Points |
|---|---|
| Price change at or above the threshold | 15 plus 0.6 per percent changed (max 45) |
| Suspected pricing error (drop of 70% or more, rise of 400% or more, or a price of zero) | +30 |
| Went out of stock | +20 |
| Back in stock | +10 |
| Compare-at discount started, deepened (15 points or more) or ended | +10 / +10 / +5 |
| Price drop together with a stockout / price rise with a stockout / price change with a restock | bonus +20 / +15 / +10 |
| Price change together with a discount change | bonus +5 |
| Two or more variants of the same product changed (at least half of them) | +10 |
| Variant or product removed | 25 / 30, plus 10 if it was in stock |

Severity levels: `critical` 75 and above, `high` 55 to 74, `medium` 35 to 54, `low` below 35. Family scores take the top finding, add a small bonus for the number of findings and +10 for a broad pattern. The thresholds are fixed rules, not a learned model; tune the price threshold and `minSeverity` for your store.

### Safety and compliance

- Reads only the public `/products.json` product feed of the single store you provide. It never logs in, uses no proxies, and collects no customer or personal data.
- **robots.txt is checked before every storefront request** using the user agent `PALShopifyAnomalyDesk`. A disallow rule stops the run. If robots.txt cannot be retrieved reliably (HTTP 401, 403, 429, 5xx or a network failure) access is treated as unknown and the run is refused. A missing robots.txt (HTTP 404 or 410) means no restrictions. A `Crawl-delay` is honored up to 10 seconds.
- **SSRF protection.** HTTPS only, no credentials or custom ports, no IP-address hosts, no local or internal names. Every resolved address must be public, and the connection is pinned to the validated address. Redirects are followed only within the same site and are checked again, including robots.txt.
- **Bounded work.** At most 8 pages, 1,000 products and 6,000 variants per run, a request budget, response size limits, per-request timeouts and a delay between requests (at least 1 second).
- Refused or failed runs write the reason to `OUTPUT` and the run status, push no dataset rows and are never billed.

### State and storage

Baselines are kept in a **named key-value store** (`stateStoreName`, default `pal-shopify-anomaly-desk-state`), because a run's default store is new on every run and cannot carry state between scheduled runs. Each domain has one compact snapshot (size-checked, below 3 MB). At most 50 domains are tracked per store; the least recently updated one is deleted when that limit is exceeded. A stored baseline that cannot be read is replaced by a new baseline, and the summary says so. The baseline moves forward after each complete run. A run that ends early because a later page failed does not overwrite the baseline.

### Billing behavior

The code defines one custom pay-per-event charge, `anomaly-report`, and raises it **at most once per run**, only for a complete (non-partial) repeat run that reports at least one anomaly, after the results are saved. Baseline runs, runs without anomalies, partial runs, refused runs and failed runs are not charged. Pricing itself is configured separately in Apify Console; this repository does not set a price.

### Limitations and sample-size caveats

- **Only public feed data.** Inventory quantities, orders, sales and discounts applied at checkout are not visible. Availability is a true/false flag.
- **No currency in the feed.** Prices are compared as published for the store's default market. Multi-market or multi-currency stores can show differences that are not real changes.
- **Sampling, not a census.** Products are read in feed order up to `maxProducts` and `maxPages`. If the catalog is larger, only that part is monitored, removals are not assessed, and results do not describe the whole catalog. The summary reports whether the sample was complete and why it was capped.
- **Small samples are noisy.** With fewer than 30 products, percentages and family patterns are indicative only. Family patterns need at least 3 compared variants; families with fewer than 5 carry a sample note.
- **Previous run only.** A price that changed and changed back between two runs is invisible, and slow drift across many runs is not flagged. Use a shorter schedule interval for fast-moving stores.
- **New products are counted, not judged.** Products absent from the previous sample are listed in the summary count only.
- **Reordered feeds.** The feed order is controlled by the store. If it is reordered while the sample is capped, some products may fall in or out of the sample between runs.
- **Family labels come from the store.** Stores with empty product types fall back to the vendor name, or `Uncategorized`.
- **Stores can block or disable the feed.** Some stores restrict `/products.json`, add a password page or disallow it in robots.txt. These runs fail with an explanatory status and are not billed.
- Limited to 50 variants per product and 6,000 variants per run.

### Development

The core logic does not import the Apify SDK, so the test suite runs fully offline with standard-library `unittest`:

```
python -m unittest discover -s tests -t .
```

Tests use fake HTTP, storage and SDK objects only; they never touch the network.

# Actor input Schema

## `storeUrl` (type: `string`):

One public HTTPS storefront URL, for example https://www.allbirds.com (example only, no affiliation). Only the origin is used; paths and query strings are ignored. Use a store you are permitted to monitor.

## `maxProducts` (type: `integer`):

Upper bound on products read from the public product feed, in feed order. Larger catalogs are sampled, not fully covered.

## `maxPages` (type: `integer`):

Upper bound on product-feed pages requested (up to 250 products per page).

## `priceChangeThresholdPercent` (type: `number`):

Minimum absolute price change per variant, between two runs, that counts as a price signal. Drops of 70% or more and rises of 400% or more are always flagged as suspected pricing errors.

## `minSeverity` (type: `string`):

Findings below this level are counted in the summary but not returned.

## `maxAnomalies` (type: `integer`):

Caps the number of variant-level anomaly records returned (highest severity first).

## `requestDelaySecs` (type: `number`):

Minimum pause between requests to the store. A longer Crawl-delay in the store's robots.txt overrides this.

## `requestTimeoutSecs` (type: `integer`):

Timeout for each request to the store.

## `stateStoreName` (type: `string`):

Name of the named key-value store that keeps one compact baseline per store domain between runs. Use a different name to keep independent baselines (for example, one per schedule). Lowercase letters, digits and hyphens only.

## Actor input object example

```json
{
  "storeUrl": "https://www.allbirds.com",
  "maxProducts": 250,
  "maxPages": 4,
  "priceChangeThresholdPercent": 10,
  "minSeverity": "low",
  "maxAnomalies": 300,
  "requestDelaySecs": 1.5,
  "requestTimeoutSecs": 15,
  "stateStoreName": "pal-shopify-anomaly-desk-state"
}
```

# Actor output Schema

## `results` (type: `string`):

Download rows from the latest run in JSON/CSV.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "storeUrl": "https://www.allbirds.com"
};

// Run the Actor and wait for it to finish
const run = await client.actor("practical_ai_lab_jp/pal-shopify-price-availability-anomaly-desk").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "storeUrl": "https://www.allbirds.com" }

# Run the Actor and wait for it to finish
run = client.actor("practical_ai_lab_jp/pal-shopify-price-availability-anomaly-desk").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "storeUrl": "https://www.allbirds.com"
}' |
apify call practical_ai_lab_jp/pal-shopify-price-availability-anomaly-desk --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,practical_ai_lab_jp/pal-shopify-price-availability-anomaly-desk"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/JEZu5JhYm9m6NeTqz/builds/xxTQg4u0IX9qqm6Vf/openapi.json
