# Shopify Merchandising Executive Brief (`practical_ai_lab_jp/pal-shopify-merchandising-executive-brief`) Actor

Turns daily snapshots of public Shopify storefronts into a severity-ranked executive brief: launches, price moves, availability and merchandising regressions with next actions.

- **URL**: https://apify.com/practical_ai_lab_jp/pal-shopify-merchandising-executive-brief.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 $0.10 / 1,000 store briefs

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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 Merchandising Executive Brief

Give this Actor several public Shopify storefront URLs and run it on a schedule. It stores a compact snapshot of each store's public product feed, compares today's snapshot with an earlier one, and produces **one joined, severity-ranked brief** for a commerce decision-maker:

| Buyer outcome | What it answers |
|---|---|
| **Assortment and launches** | Which products appeared or disappeared, which product types gained depth, was there a range reset? |
| **Reliable price comparisons** | Which products changed price (same variants only), which markdowns started or ended, is a store repricing as a whole? |
| **Availability signals** | What sold out, what came back, which products lost most of their variants, is there a stock-out wave? |
| **Merchandising regressions** | Which listings lost images, descriptions, tags or variants, which launches went live incomplete? |

The four outcomes are not separate reports. They are joined into ranked findings, compound risks (for example a launch that is both new and missing images) and a short list of **evidence-linked next actions** with priority and owner hints, plus an executive headline and a Markdown version of the brief.

### How it works

1. **Validate** every URL: HTTPS only, no credentials, no custom ports, no IP addresses, no internal host names, public DNS results only.
2. **Read robots.txt** for each store (with wildcard and `Allow`/`Disallow` precedence rules). If robots.txt cannot be read reliably or disallows the feed, the store is skipped.
3. **Read the public `/products.json` feed** in bounded pages (max 250 products per request, configurable cap per store, pause between requests, no proxies, no logins, no HTML scraping).
4. **Save a snapshot** per store and day in a named key-value store, and prune snapshots older than the retention window.
5. **Compare** with the newest snapshot that is old enough (default: at least 1 day old), run the four outcome analyses, join and rank them.

The first run for a store only saves a baseline. A comparison brief appears on the next qualifying run.

### Sample input

```json
{
  "storeUrls": ["https://www.allbirds.com", "https://kith.com"],
  "maxProductsPerStore": 500,
  "priceChangeThresholdPercent": 5,
  "baselineMinAgeDays": 1,
  "stateStoreName": "pal-shopify-merchandising-snapshots"
}
```

The URLs are examples of public Shopify storefronts, not endorsements. Only monitor stores whose terms allow reading their public feed. Schedule the Actor daily (or weekly with `baselineMinAgeDays: 7`) and keep the same `stateStoreName` on every run.

#### Input fields

| Field | Default | Meaning |
|---|---|---|
| `storeUrls` | required | 1-10 distinct public storefront URLs. Only the host is used. |
| `maxProductsPerStore` | 500 | 20-2000. Larger catalogs are marked truncated. |
| `priceChangeThresholdPercent` | 5 | Minimum price move and compare-at markdown depth that counts. |
| `baselineMinAgeDays` | 1 | Compare with the newest snapshot at least this old. |
| `maxBaselineAgeDays` | 35 | Older baselines are not used; a fresh baseline is saved. |
| `snapshotRetentionDays` | 30 | Older snapshots are deleted. |
| `stateStoreName` | `pal-shopify-merchandising-snapshots` | Named key-value store holding snapshots. |
| `requestDelayMs` | 1000 | Pause between requests; a larger robots.txt `Crawl-delay` (capped at 10 s) wins. |
| `assumeSameCurrency` | false | Turns on cross-store SKU price gaps. Only enable if all stores price in one currency. |
| `maxFindings` | 300 | Cap on ranked findings in the dataset. |
| `minSeverity` | low | Drops findings below this severity. |

### Output

The dataset holds records distinguished by `recordType`:

- `executive_brief` (one): headline, overall risk, counts by severity and outcome, top actions, store highlights and caveats.
- `action`: ranked next actions with `priority` (P1-P3), `ownerHint`, `recommendedAction`, `evidenceUrls` and `findingIds` that point to findings in the same dataset.
- `finding`: ranked evidence records with `severity`, `score`, `reliability` (`reliable` or `indicative`), product URL, before/after values and the snapshot keys used (`evidence.baselineSnapshot`, `evidence.currentSnapshot`).
- `store_summary`: per store status (`compared`, `baseline_only`, `error`, `skipped`), counts, metrics, notes and error code.

The default key-value store also holds `OUTPUT` (brief, top actions, store summaries) and `EXECUTIVE_BRIEF.md` (readable brief).

Ten finding types per store and type are kept at most (the rest is counted in `suppressedFindings`), so one big sale does not bury everything else.

### Pricing event (not configured here)

The code defines one pay-per-event name, `store-brief`, in `src/billing.py`. It is intended to be charged once per store for which a real cross-run comparison was produced. It is never charged for failed stores, skipped stores or first-run baseline-only stores. No payable plan is configured in this project, and the price is a decision for the publisher after real cloud unit costs are known.

### Limitations and sample-size caveats

- **No currency in the feed.** Prices are compared as numbers per store. A market, currency or tax-display change can look like a price move. Very large moves (over 3x) are flagged `indicative`, and a store-wide move is reported as one summary finding.
- **Availability is a flag, not inventory.** It reflects the public `available` field. Overselling, hidden inventory and preorders are invisible.
- **Only published products are visible.** Draft, unpublished, password-protected, B2B or region-specific catalogs cannot be observed.
- **Snapshot cadence limits what you see.** A price raised and reverted between two runs is invisible. The comparison gap equals your schedule.
- **Product caps.** When a store has more products than `maxProductsPerStore`, removal findings are suppressed and new-product findings are marked `indicative`.
- **Small catalogs.** Share-based signals (churn, price waves, availability waves) need at least 30 comparable products; below that they are not raised and a note says so. Results from a handful of products are indicative.
- **Launch date.** `published_at` from the feed is used when it falls after the baseline; otherwise the product is reported as first seen in the feed.
- **Severity scores are heuristics** (type, size of change, premium price tier, recent launch). They are not revenue or margin estimates. Sales, traffic and conversion are not observable.
- **Cross-store SKU gaps** depend on SKUs being equal and titles similar; unrelated SKUs that collide are filtered by title similarity but can still be wrong. They are marked `indicative` when similarity is below 0.85.
- **Some stores disable or block `/products.json`.** Those stores are reported with an error code and nothing is charged.
- Findings are public-feed observations, not statements of fact about intent. Verify on the live storefront before reacting.

### Safety

- HTTPS only; hosts are validated, resolved, and connected by pinned public IP address (private, loopback, link-local and reserved ranges are refused).
- Redirects are followed manually, at most three times, and every target is re-validated and checked against that host's robots.txt.
- Response sizes are capped (8 MB for the feed, 512 KB for robots.txt); no compression is requested.
- No logins, cookies, contact harvesting, proxies, browser automation or paid APIs. No personal data is stored: snapshots hold product titles, handles, prices, availability flags and counts.
- Errors never trigger a charge.

### Project layout

```
src/main.py            Actor entry point (input, state store, output, charging)
src/pipeline.py        per-store collection, snapshot saving, comparison
src/collector.py       robots-aware bounded feed collection
src/fetcher.py         HTTPS GET with DNS pinning
src/urlsafety.py       URL validation, SSRF checks, robots evaluator
src/parsing.py         feed record to compact snapshot product
src/state.py           snapshot persistence and baseline selection
src/assortment.py      outcome 1
src/pricing.py         outcome 2 (+ optional cross-store gaps)
src/availability.py    outcome 3
src/merchandising.py   outcome 4
src/brief.py           joining, ranking, actions, executive brief
tests/                 offline unittest suite
```

### Local tests

The tests are fully offline (fake feed, in-memory state store):

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

# Actor input Schema

## `storeUrls` (type: `array`):

Public HTTPS storefront addresses (1-10 distinct stores). Only the host is used; the public /products.json feed is read after robots.txt allows it. Only monitor stores you are permitted to read under their terms.

## `maxProductsPerStore` (type: `integer`):

Upper bound on products read per store. If a store has more, the snapshot is marked truncated and removal findings are suppressed.

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

Minimum price change, and minimum compare-at discount depth, that counts as a finding.

## `baselineMinAgeDays` (type: `integer`):

The comparison uses the newest stored snapshot that is at least this many days older than today. Use 1 for daily runs, 7 for weekly comparisons.

## `maxBaselineAgeDays` (type: `integer`):

Snapshots older than this are treated as stale: no comparison is made and a fresh baseline is saved.

## `snapshotRetentionDays` (type: `integer`):

Daily snapshots older than this are deleted from the state store.

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

Named key-value store that persists snapshots between runs. Use the same name on every scheduled run. Lowercase letters, digits and hyphens only.

## `requestDelayMs` (type: `integer`):

Pause between requests to the same store. A larger Crawl-delay in robots.txt (capped at 10 s) takes precedence.

## `assumeSameCurrency` (type: `boolean`):

Enable cross-store price gaps for products sharing the same SKU. The public feed does not expose currency, so this is off unless you confirm all stores price in one currency.

## `maxFindings` (type: `integer`):

Cap on ranked findings written to the dataset (highest score first).

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

Findings below this severity are left out of the dataset.

## Actor input object example

```json
{
  "storeUrls": [
    "https://www.allbirds.com",
    "https://kith.com"
  ],
  "maxProductsPerStore": 500,
  "priceChangeThresholdPercent": 5,
  "baselineMinAgeDays": 1,
  "maxBaselineAgeDays": 35,
  "snapshotRetentionDays": 30,
  "stateStoreName": "pal-shopify-merchandising-snapshots",
  "requestDelayMs": 1000,
  "assumeSameCurrency": false,
  "maxFindings": 300,
  "minSeverity": "low"
}
```

# 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 = {
    "storeUrls": [
        "https://www.allbirds.com",
        "https://kith.com"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("practical_ai_lab_jp/pal-shopify-merchandising-executive-brief").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 = { "storeUrls": [
        "https://www.allbirds.com",
        "https://kith.com",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("practical_ai_lab_jp/pal-shopify-merchandising-executive-brief").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 '{
  "storeUrls": [
    "https://www.allbirds.com",
    "https://kith.com"
  ]
}' |
apify call practical_ai_lab_jp/pal-shopify-merchandising-executive-brief --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-merchandising-executive-brief"
        }
    }
}
```

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/N1cbgu3AKDsTBXWM2/builds/PrzadkPKPETXcddm6/openapi.json
