# Promotion Stacking Simulator (`afkdigital/newapi90-promotion-stacking-simulator`) Actor

Simulate coupon stacking on CSV/JSON carts. Compare discounts, shipping and supplied-cost contribution margins with an auditable trace. Platform-neutral; no store writes. $1 per 1,000 completed cart-rule scenarios.

- **URL**: https://apify.com/afkdigital/newapi90-promotion-stacking-simulator.md
- **Developed by:** [AFK Digital](https://apify.com/afkdigital) (community)
- **Categories:** E-commerce
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$1.00 / 1,000 completed cart-rule scenarios

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

## Promotion Stacking Simulator

AFK Digital — NEWAPI90 — release 0.1

Simulate customer-supplied promotions against carts before creating a campaign. This is a platform-neutral calculator, not a Shopify or other platform replica. It never creates coupons, contacts stores, or places orders. No tax, currency conversion, returns, checkout, or customer identity logic is inferred.

### Input

See demo.json. cartsFile and productCostsFile accept an encoded file object: {"format":"json","content":"\[...rows...]"} or {"format":"csv","content":"header\nrow..."}. JSON row arrays also work in the engine. No external URLs or local file paths are fetched.
Cart JSON: cart_id, currency, items containing sku, quantity, unit_price.
Cart CSV columns: cart_id,currency,sku,quantity,unit_price (one line per item).
Cost rows/CSV: sku,currency,unit_cost. Duplicate cost keys and mixed currency within a CSV cart fail validation.
Currency labels must agree for cost matching; no conversion is performed.

promotionRules: unique id; type percent, fixed, or free_shipping; scope product or cart (default cart); value; optional minimum; minimumBasis pre or post; includedSkus, excludedSkus; usageLimit and usageCount; stackable (default true).
rulePriority must contain all rules exactly once when more than one exists.
scenarios is an array of coupon ID arrays, each defining a selected subset. The priority always controls execution order. Repeated IDs apply once and subsequent occurrences are rejected.
allCombinations generates all subsets including the empty baseline, not permutations. It fails before expansion if the total exceeds maxScenarios. Changing order requires a separate run.

### Calculation contract

Prices are line totals rounded from quantity × unit price. Each discount step is rounded. Percentages apply to remaining eligible balances. Product fixed discounts are per unit; cart fixed discounts apply once and are proportionally allocated to eligible lines. Largest remainder allocation breaks ties by input line index.
minimum is inclusive and uses the whole merchandise subtotal, excluding shipping, including excluded products: pre uses original rounded subtotal; post uses the remaining subtotal immediately before this rule. SKU filters constrain discounts, not the minimum subtotal.
Free shipping removes remaining shipping revenue only; shipping expense remains. SKU filters have no effect on free_shipping.
Usage counters are supplied snapshots and evaluated independently per scenario/cart; no global consumption or live redemption enforcement is simulated.
A nonstackable promotion is rejected when another has already applied; an applied nonstackable promotion blocks later rules.
Discounts never make line or shipping balances negative.
roundingPolicy: decimals 0..4, mode HALF_UP (default), HALF_EVEN, or DOWN. Monetary output is decimal strings.

net_sales = discounted merchandise + remaining shipping revenue (tax excluded).
gross_margin = discounted merchandise − supplied product costs (amount, not percent).
contribution_margin = gross_margin + shipping revenue − shipping cost − other variable costs.
shippingInputs is keyed by cart_id with revenue, cost and variable_cost in the cart currency. Omitted revenue means no shipping revenue. Missing cost or variable_cost remains unknown: explicitly supply 0 only if known to be zero.
Missing product costs never become zero: gross/contribution margin and applicable threshold result are null. Missing shipping/variable expenses make contribution unknown. The calculator is not a claim of actual accounting profit.
marginThreshold: {type:amount|percent,value:number}. Percent uses contribution / net sales × 100; zero revenue produces an unknown percent. Breach means strictly below the threshold, not equal. Summary counts breaches and unknown margins without summing mixed currencies.

### Output and billing

Dataset rows include scenario_id, cart_id, currency, applied_promotions, rejected_promotions, rejection_reasons, discount_breakdown, net_sales, supplied_costs, gross_margin, contribution_margin, contribution_margin_percent, threshold_breach and calculation_trace.
Export the Dataset as JSON or CSV from Apify Console/API. Nested breakdown/trace objects remain JSON in local CSV. SUMMARY is a key-value record; local samples are sample_output.json, sample_output.csv and sample_summary.json.
One completed cart-rule scenario = one completed-scenario event. Price: USD 1.00 per 1,000 events (USD 0.001 each), platform usage included. 100 carts × 8 subsets = 800 events = USD 0.80, even though only 100 carts were supplied. A no-discount or rejected-promotion result is still a completed simulation and counts once. Validation failures are not charged. No additional startup charge is proposed.
Each result uses the Apify SDK completed-scenario charging event. Retries should be new runs only when intended; do not assume free replay.

### Limits

4 MB per encoded file, 8 MB total serialized input; 1,000 carts; 200 items/cart; 20,000 cost rows; 16 rules; 32 coupon references per explicit scenario; maxScenarios 1..10,000, default 1,000; engine 120 seconds; Actor process 240 seconds. Set platform timeout to 300 seconds and memory to 256 MB for the demo.
CSV must contain headers and decimal values using a dot. JSON monetary values should be strings to preserve exact representation.

### Run

python -m unittest discover -s tests -v
python main.py --local
docker build -t newapi90:0.1.0 .
docker run --rm newapi90:0.1.0

### Data and release

Input/output use the customer's Apify run storage and account permissions/retention settings. Do not submit sensitive personal data. No third-party API is called by the simulator. Delete run storage according to your account policy.
Actor ID: LvAArMz7gA8UzMqlS. Review platform storage retention/access before production use.

# Actor input Schema

## `cartsFile` (type: `object`):

Encoded file object: format json or csv; content contains file text.

## `productCostsFile` (type: `object`):

Encoded file object: format json or csv; content contains file text.

## `promotionRules` (type: `array`):

See README for promotionRules format and calculation rules.

## `rulePriority` (type: `array`):

See README for rulePriority format and calculation rules.

## `scenarios` (type: `array`):

See README for scenarios format and calculation rules.

## `shippingInputs` (type: `object`):

See README for shippingInputs format and calculation rules.

## `roundingPolicy` (type: `object`):

See README for roundingPolicy format and calculation rules.

## `marginThreshold` (type: `object`):

See README for marginThreshold format and calculation rules.

## `maxScenarios` (type: `integer`):

See README for maxScenarios format and calculation rules.

## `allCombinations` (type: `boolean`):

See README for allCombinations format and calculation rules.

## Actor input object example

```json
{
  "cartsFile": {
    "format": "json",
    "content": "[{\"cart_id\": \"DEMO-1\", \"currency\": \"USD\", \"items\": [{\"sku\": \"A\", \"quantity\": 1, \"unit_price\": \"100.00\"}]}]"
  },
  "productCostsFile": {
    "format": "json",
    "content": "[{\"sku\": \"A\", \"currency\": \"USD\", \"unit_cost\": \"60.00\"}]"
  },
  "promotionRules": [
    {
      "id": "TENPCT",
      "type": "percent",
      "scope": "cart",
      "value": "10"
    },
    {
      "id": "TENUSD",
      "type": "fixed",
      "scope": "cart",
      "value": "10"
    },
    {
      "id": "SHIP",
      "type": "free_shipping"
    }
  ],
  "rulePriority": [
    "TENPCT",
    "TENUSD",
    "SHIP"
  ],
  "scenarios": [
    [
      "TENPCT",
      "TENUSD"
    ],
    [
      "TENPCT",
      "TENUSD",
      "SHIP"
    ]
  ],
  "shippingInputs": {
    "DEMO-1": {
      "revenue": "10",
      "cost": "7",
      "variable_cost": "3"
    }
  },
  "roundingPolicy": {
    "mode": "HALF_UP",
    "decimals": 2
  },
  "marginThreshold": {
    "type": "amount",
    "value": "25"
  },
  "maxScenarios": 100,
  "allCombinations": false
}
```

# Actor output Schema

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

No description

## `csv` (type: `string`):

No description

## `summary` (type: `string`):

No description

# 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 = {
    "cartsFile": {
        "format": "json",
        "content": "[{\"cart_id\": \"DEMO-1\", \"currency\": \"USD\", \"items\": [{\"sku\": \"A\", \"quantity\": 1, \"unit_price\": \"100.00\"}]}]"
    },
    "productCostsFile": {
        "format": "json",
        "content": "[{\"sku\": \"A\", \"currency\": \"USD\", \"unit_cost\": \"60.00\"}]"
    },
    "promotionRules": [
        {
            "id": "TENPCT",
            "type": "percent",
            "scope": "cart",
            "value": "10"
        },
        {
            "id": "TENUSD",
            "type": "fixed",
            "scope": "cart",
            "value": "10"
        },
        {
            "id": "SHIP",
            "type": "free_shipping"
        }
    ],
    "rulePriority": [
        "TENPCT",
        "TENUSD",
        "SHIP"
    ],
    "scenarios": [
        [
            "TENPCT",
            "TENUSD"
        ],
        [
            "TENPCT",
            "TENUSD",
            "SHIP"
        ]
    ],
    "shippingInputs": {
        "DEMO-1": {
            "revenue": "10",
            "cost": "7",
            "variable_cost": "3"
        }
    },
    "roundingPolicy": {
        "mode": "HALF_UP",
        "decimals": 2
    },
    "marginThreshold": {
        "type": "amount",
        "value": "25"
    },
    "maxScenarios": 100
};

// Run the Actor and wait for it to finish
const run = await client.actor("afkdigital/newapi90-promotion-stacking-simulator").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 = {
    "cartsFile": {
        "format": "json",
        "content": "[{\"cart_id\": \"DEMO-1\", \"currency\": \"USD\", \"items\": [{\"sku\": \"A\", \"quantity\": 1, \"unit_price\": \"100.00\"}]}]",
    },
    "productCostsFile": {
        "format": "json",
        "content": "[{\"sku\": \"A\", \"currency\": \"USD\", \"unit_cost\": \"60.00\"}]",
    },
    "promotionRules": [
        {
            "id": "TENPCT",
            "type": "percent",
            "scope": "cart",
            "value": "10",
        },
        {
            "id": "TENUSD",
            "type": "fixed",
            "scope": "cart",
            "value": "10",
        },
        {
            "id": "SHIP",
            "type": "free_shipping",
        },
    ],
    "rulePriority": [
        "TENPCT",
        "TENUSD",
        "SHIP",
    ],
    "scenarios": [
        [
            "TENPCT",
            "TENUSD",
        ],
        [
            "TENPCT",
            "TENUSD",
            "SHIP",
        ],
    ],
    "shippingInputs": { "DEMO-1": {
            "revenue": "10",
            "cost": "7",
            "variable_cost": "3",
        } },
    "roundingPolicy": {
        "mode": "HALF_UP",
        "decimals": 2,
    },
    "marginThreshold": {
        "type": "amount",
        "value": "25",
    },
    "maxScenarios": 100,
}

# Run the Actor and wait for it to finish
run = client.actor("afkdigital/newapi90-promotion-stacking-simulator").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 '{
  "cartsFile": {
    "format": "json",
    "content": "[{\\"cart_id\\": \\"DEMO-1\\", \\"currency\\": \\"USD\\", \\"items\\": [{\\"sku\\": \\"A\\", \\"quantity\\": 1, \\"unit_price\\": \\"100.00\\"}]}]"
  },
  "productCostsFile": {
    "format": "json",
    "content": "[{\\"sku\\": \\"A\\", \\"currency\\": \\"USD\\", \\"unit_cost\\": \\"60.00\\"}]"
  },
  "promotionRules": [
    {
      "id": "TENPCT",
      "type": "percent",
      "scope": "cart",
      "value": "10"
    },
    {
      "id": "TENUSD",
      "type": "fixed",
      "scope": "cart",
      "value": "10"
    },
    {
      "id": "SHIP",
      "type": "free_shipping"
    }
  ],
  "rulePriority": [
    "TENPCT",
    "TENUSD",
    "SHIP"
  ],
  "scenarios": [
    [
      "TENPCT",
      "TENUSD"
    ],
    [
      "TENPCT",
      "TENUSD",
      "SHIP"
    ]
  ],
  "shippingInputs": {
    "DEMO-1": {
      "revenue": "10",
      "cost": "7",
      "variable_cost": "3"
    }
  },
  "roundingPolicy": {
    "mode": "HALF_UP",
    "decimals": 2
  },
  "marginThreshold": {
    "type": "amount",
    "value": "25"
  },
  "maxScenarios": 100
}' |
apify call afkdigital/newapi90-promotion-stacking-simulator --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,afkdigital/newapi90-promotion-stacking-simulator"
        }
    }
}
```

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/LvAArMz7gA8UzMqlS/builds/p0Ah9xuLU12IrQpa1/openapi.json
