# Shopify Price & Promotion Diagnostics (`practical_ai_lab_jp/pal-shopify-price-promotion-diagnostics-suite`) Actor

Audit one public Shopify storefront for compare-at claims, variant price consistency and repeat-run promotion changes, with ranked fixes.

- **URL**: https://apify.com/practical_ai_lab_jp/pal-shopify-price-promotion-diagnostics-suite.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 $1.00 / 1,000 audit completeds

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 Price & Promotion Diagnostics

Audit one public Shopify storefront for the prices it actually publishes, the compare-at ("was") prices it shows, how consistent variant pricing is, and how promotions change between runs. The result is one severity-ranked fix list with concrete product URLs, evidence and caveats, plus JSON and CSV you can reproduce.

It is built for ecommerce pricing and merchandising teams who need to answer: *Which products should we fix first, and which discount claims deserve a second look?*

### Start with one URL

The only required input is `storeUrl`.

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

The URL above is only a format example. Replace it with a store you are allowed to analyse. The Actor reads only the store's public `/products.json` feed and respects `robots.txt`; if the site disallows the feed, the run stops and reports `ROBOTS_DENIED`.

**First run.** The Actor stores a compact snapshot for the domain and emits an explicit `baseline_created` record with status `BASELINE_CREATED`. You still get the full single-snapshot audit (compare-at integrity, variant consistency, ranked fixes). Cross-run promotion changes need a second run, and the output says so.

**Repeat runs.** The Actor loads the stored snapshot, emits `promotion_change_tracking` records for what changed, and reports status `DELTA_REPORT`. An unchanged catalogue says so explicitly instead of returning an empty result.

### Scheduling later runs

Nothing in this Actor runs by itself and it sends no alerts or notifications. To get repeat-run comparisons:

1. Save your input as an Apify **Task**.
2. Create a **Schedule** for that Task (for example weekly) in Apify Console.
3. Read the dataset or the `FIX_PRIORITY.csv` record after each scheduled run, or connect the Task to your own integration.

The snapshot is stored in a **named** key-value store (default `pal-shopify-price-promotion-state`), one record per domain, because a run's default store is new for every run and could not keep a baseline. Keep the name unchanged for the history to continue. Avoid running two jobs for the same domain at the same time.

### What you get: four buyer outcomes in one workflow

All rows share one dataset with a `recordType` column, a `severity`, and the product URL, so they join on `productUrl`/`productId`.

| Outcome | `recordType` | Needs a repeat run | Example codes |
| --- | --- | --- | --- |
| 1. Published price and compare-at audit | `price_compare_at_audit` | No | `PRICE_MISSING_OR_ZERO`, `COMPARE_AT_BELOW_PRICE`, `COMPARE_AT_EQUALS_PRICE`, `DEEP_DISCOUNT_CLAIM`, `EXTREME_DISCOUNT_CLAIM` |
| 2. Variant pricing consistency | `variant_pricing_consistency` | No | `MIXED_COMPARE_AT_ACROSS_VARIANTS`, `INCONSISTENT_DISCOUNT_DEPTH`, `VARIANT_PRICE_SPREAD`, `SKU_PRICE_CONFLICT` |
| 3. Repeat-run promotion changes | `promotion_change_tracking` | Yes | `PRICE_DROP`, `PRICE_INCREASE`, `PROMOTION_STARTED`, `PROMOTION_ENDED`, `COMPARE_AT_RAISED_WITHOUT_PRICE_DROP`, `PERSISTENT_DISCOUNT_CLAIM`, `NEW_PRODUCT`, `REMOVED_PRODUCT` |
| 4. Prioritised merchandising fixes | `fix_priority` | No | One row per product, joining signals from outcomes 1-3 |

Plus `baseline_created` (first run only), `run_summary` (every successful run) and `run_error` (failed runs, never charged).

#### Severity and ranking

Severities are `critical`, `high`, `medium`, `low` and `info`, worth 50, 25, 10, 3 and 0 points. A product's `priorityScore` is the sum of its signals, halved when every variant is unavailable. `fix_priority` rows are ranked by score and carry `rank`; the detail rows for each ranked product carry the same `rank`. Only the top `topProducts` products get rows; the summary reports how many were suppressed.

#### Other outputs

- `OUTPUT` (key-value store): run summary with counts, thresholds, request counts, robots status, caveats, state info and a small sample of top fixes and first changes.
- `FIX_PRIORITY.csv` and `PROMOTION_AND_PRICE_DETAILS.csv` (key-value store): CSV exports. Store-controlled text that starts with a spreadsheet formula character is prefixed with an apostrophe.
- The dataset itself can be exported as JSON or CSV from Apify Console or the API.

#### Illustrative record shape

This is a shape example with placeholder values, not output from a real run.

```json
{
    "recordType": "fix_priority",
    "rank": 1,
    "priorityScore": 35,
    "severity": "high",
    "code": "COMPARE_AT_BELOW_PRICE",
    "codes": ["COMPARE_AT_BELOW_PRICE", "MIXED_COMPARE_AT_ACROSS_VARIANTS"],
    "productUrl": "https://shop.example.com/products/example-item",
    "productTitle": "Example Item",
    "recommendedFix": "Clear or correct the compare-at price ... | Apply the promotion consistently ...",
    "affectedVariants": 2,
    "allVariantsUnavailable": false
}
```

### Input

| Field | Default | Purpose |
| --- | --- | --- |
| `storeUrl` (required) | none | One public HTTPS storefront URL. Only the host is used. |
| `maxPages` | 4 | Feed pages of up to 250 products each (1-10). Also bounds the request budget. |
| `maxProducts` | 1000 | Product cap (50-2500). |
| `topProducts` | 100 | Ranked products to report (10-500). |
| `deepDiscountPercent` | 60 | Review threshold for implied discount. 80% or more is always `EXTREME_DISCOUNT_CLAIM`. |
| `variantSpreadRatio` | 3 | Flag products whose top variant price is this many times the lowest. |
| `persistentDiscountDays` | 30 | Days of observed discount before `PERSISTENT_DISCOUNT_CLAIM`. |
| `requestDelaySeconds` | 1 | Pause between requests (0.5-10). |
| `stateStoreName` | `pal-shopify-price-promotion-state` | Named store holding the per-domain snapshot. |

### Safety and politeness

- HTTPS only, default port only, no credentials in URLs, no IP literals, no `localhost`/`.local`/`.internal`-style hosts.
- Every hostname is resolved and **all** answers must be public addresses; the connection is then made to the validated address while TLS is verified for the hostname.
- `robots.txt` is fetched first and checked before **every** storefront request, including each page and redirect. A `403`/`401` robots file, a server error, or a timeout means access rules are unknown and the run refuses to continue. A missing robots file (`404`/`410`) is treated as no restrictions.
- Redirects are followed only within the same host over HTTPS; a redirect elsewhere is refused with a hint to use the canonical URL.
- Hard limits: request budget (`maxPages` + 4), 8 MB per feed page, 20 s timeout, bounded state size. No proxies, no login, no cookies, no contact or personal data collection.
- Only public product price fields are read.

### Limitations and sample-size caveats

- **A compare-at price is a merchant-entered value.** The feed cannot show whether it was ever charged. Findings are review prompts, not proof of a false discount or any legal conclusion; rules differ by market.
- **Currency is not in the public feed.** Prices are reported as published and never converted.
- **Small catalogues give weak evidence.** The summary warns when fewer than 30 products were analysed or fewer than 10 discounted products were observed.
- **Truncated catalogues are partial.** If `maxPages` or `maxProducts` cuts the catalogue short, results cover a prefix of the feed and new/removed product detection is disabled until a complete run is stored. Complete coverage is assumed when a page returns fewer than 250 products.
- **Two observations only.** Changes that happen and reverse between runs are invisible.
- **"Observed since" is a lower bound.** `PERSISTENT_DISCOUNT_CLAIM` uses the first run that saw the discount and assumes it continued between runs. It can only fire once your stored history spans the threshold.
- Stores that disable or password-protect `/products.json`, or that disallow it in `robots.txt`, cannot be analysed and fail with a clear error. No data is guessed.
- Products with more than 100 variants are analysed on the first 100.
- Availability weighting uses the feed's `available` flag only.

### Pricing

The code defines one billing event, `audit-completed`, and submits it once only after a run has fetched products, pushed all results and saved state. Failed runs (robots denial, unsafe host, no product data, fetch errors) never reach that step and are not charged. **This package does not configure any payable plan**; the pricing for that event must be set up separately by the Actor owner, and the platform decides whether a charge applies.

### Development

The unit tests use only the Python standard library and fake transports; they make no network calls and do not need the Apify platform. From the project folder:

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

Core logic lives in `src/` (`safety`, `robots`, `http_client`, `parsing`, `analysis`, `state`, `diff`, `reporting`, `pipeline`); `src/main.py` and `src/storage.py` are the only modules that touch the Apify SDK.

# Actor input Schema

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

One public HTTPS storefront URL, for example https://your-store.example.com. Only the host is used; paths and queries are ignored. Use a store you are permitted to analyse; robots.txt is always honoured.

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

Each page holds up to 250 products. Hard request limit for the run.

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

Stop after this many products. Truncated catalogues disable new/removed product detection.

## `topProducts` (type: `integer`):

How many highest-priority products receive fix rows and detail rows.

## `deepDiscountPercent` (type: `number`):

Compare-at claims implying at least this discount are flagged for review. Claims of 80% or more are always flagged as extreme.

## `variantSpreadRatio` (type: `number`):

Flag products whose highest variant price is at least this multiple of the lowest.

## `persistentDiscountDays` (type: `integer`):

Flag products observed with a compare-at discount for at least this many days across stored runs.

## `requestDelaySeconds` (type: `number`):

Polite pause between storefront requests.

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

Named key-value store that keeps the per-domain comparison snapshot between runs. Keep the default unless you need separate histories.

## Actor input object example

```json
{
  "storeUrl": "https://www.allbirds.com",
  "maxPages": 4,
  "maxProducts": 1000,
  "topProducts": 100,
  "deepDiscountPercent": 60,
  "variantSpreadRatio": 3,
  "persistentDiscountDays": 30,
  "requestDelaySeconds": 1,
  "stateStoreName": "pal-shopify-price-promotion-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",
    "stateStoreName": "pal-shopify-price-promotion-state"
};

// Run the Actor and wait for it to finish
const run = await client.actor("practical_ai_lab_jp/pal-shopify-price-promotion-diagnostics-suite").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",
    "stateStoreName": "pal-shopify-price-promotion-state",
}

# Run the Actor and wait for it to finish
run = client.actor("practical_ai_lab_jp/pal-shopify-price-promotion-diagnostics-suite").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",
  "stateStoreName": "pal-shopify-price-promotion-state"
}' |
apify call practical_ai_lab_jp/pal-shopify-price-promotion-diagnostics-suite --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-promotion-diagnostics-suite"
        }
    }
}
```

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/9JXGcsyJylPzpkRhD/builds/kEdMX8YygWz9oSD2E/openapi.json
