# Bundle Sellable Stock Calculator (`afkdigital/bundle-sellable-stock-calculator`) Actor

Calculate bundle stock from CSV/XLSX/JSON. Separate standalone capacity from explicit priority allocation, with warehouse-isolated stock ledgers and row evidence.

- **URL**: https://apify.com/afkdigital/bundle-sellable-stock-calculator.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 unique bundle sku analyzeds

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

## Bundle Sellable Stock Calculator

Calculate how many complete product bundles can be sold from component stock. Upload CSV, XLSX or JSON files; no store or warehouse account connection is needed.

**Standalone capacity and jointly allocated stock are different.** Two bundles can each have standalone capacity 10 while competing for the same 10 components. Never add those standalone numbers together. This Actor optionally allocates the stock once using your explicit priority order.

### Quick start

Run with the default input to use a synthetic three-bundle, two-warehouse demo. No customer data or external integration is required. The demo has no bundle analysis charge.

For your own files, upload the files as records in private Apify key-value stores. Select each source store in the corresponding input picker. The Actor requests READ access only to those selected stores and retains limited permissions. API callers provide store ID strings:

```json
{
  "bundleComponentsFile": "YOUR_17_CHAR_ID_01",
  "inventoryFile": "YOUR_17_CHAR_ID_02",
  "reservationsFile": "YOUR_17_CHAR_ID_03",
  "warehouseScope": ["W1","W2"],
  "allocationMode": "priority",
  "bundlePriority": ["KIT-B","KIT-A"],
  "maxBundles": 10000
}
```

Replace placeholder store IDs with actual 17-character IDs. Record keys must be BUNDLE_COMPONENTS.csv/.xlsx/.json, INVENTORY.csv/.xlsx/.json and RESERVATIONS.csv/.xlsx/.json respectively (case-sensitive, one format per input). You may put all three records in the same selected store. Select stores with at most 1,000 record keys. Files stay in Apify storage; this Actor does not accept arbitrary web URLs or local server paths. Both component and inventory selections are required for customer runs. Omit reservations only when you intend to assume zero reserved stock.

### File columns

| File | Required columns | Meaning |
|---|---|---|
| bundleComponentsFile | bundle_sku, component_sku, quantity, unit | Positive component quantity required for one complete bundle |
| inventoryFile | component_sku, warehouse, on_hand, unit | Gross stock, including any reserved quantities |
| reservationsFile | component_sku, warehouse, quantity, unit | Nonnegative component quantities already reserved |

CSV must be UTF-8 with a comma delimiter and unique unpadded headers. XLSX must have exactly one worksheet, header row 1, and values only; formulas and error cells are rejected. Format SKU and warehouse columns as text to preserve leading zeroes. Excel numeric cells have spreadsheet precision limits: use text cells for high-precision quantities (especially more than 15 significant digits). JSON decimals and CSV/text quantities are parsed without binary float rounding. JSON must be an array of flat row objects, with unique keys. Do not upload credentials or unrelated customer fields.

Inventory permits exactly one row per component SKU and warehouse: consolidate duplicate rows first. Repeated BOM component rows are summed. Reservation rows are summed; upload each reservation once. Reservation records represent **components**, not bundle orders; explode reserved bundle orders into component quantities before upload. Do not subtract reservations from already-net inventory a second time.

### Calculation rules

Available component stock = max(0, gross on_hand minus reserved component quantity). Negative gross stock and excess reservations are flagged in calculation_basis.stock_warnings. Negative reservations and zero/negative BOM requirements are rejected. Quantities use decimal arithmetic, with at most six decimal places and magnitude at most 1e12; no binary floating-point allocation is used.

Standalone quantity = floor of the minimum available/required component ratio in that warehouse. Missing inventory is unknown and returns null quantity plus needs_review and missing_components. An inventory row explicitly recording zero stock returns 0. A missing row remains unknown even if another known component has zero.

Supported conversions: each/pcs/piece; kg/g/mg; l/ml; m/cm/mm. Case is normalized. All observations of one SKU must have compatible dimensions. Base units in the stock ledger are each, g, ml, cm. Packs, boxes and component-specific conversions are unsupported; normalize those before upload. Count quantities may be fractional if your own data explicitly supplies them, but output bundles are always whole numbers.

Warehouses are independent. No inter-warehouse transfer or pooled stock is assumed. Omitted warehouseScope selects warehouses present in inventory or reservations. An explicitly selected warehouse with no inventory yields unknown capacities.

- **standalone** (default): allocated_sellable_qty is null. There is no inferred joint allocation.
- **priority**: bundlePriority must list every bundle SKU exactly once, highest priority first. For each warehouse the Actor allocates as many complete bundles as possible to the first SKU, consumes its components, then processes the next SKU. This is a greedy rule, not an optimal product mix. Unknown-capacity bundles receive null allocation and consume no stock.
- Nested bundles, self references and BOM cycles are rejected. Flatten nested recipes before uploading.

### Outputs and evidence

The Dataset contains one row per unique bundle SKU per selected warehouse:
bundle_sku, warehouse, standalone_sellable_qty, allocated_sellable_qty, limiting_components, shared_stock_conflicts, calculation_basis, evidence_rows.

limiting_components describes standalone constraints, not constraints newly created by prior allocation. Shared-stock findings name the component, other_bundle_count, a sorted preview of up to 20 competing bundle SKUs, whether summed known standalone demand exceeds available stock, and whether any capacities remain unknown. Unknown demand is never presented as a precise total.

evidence_rows contains source-file labels and row numbers only: header is row 1, first data row is 2 (JSON uses the same virtual header convention). It includes up to 100 references, total_references and preview_truncated. Blank CSV/XLSX rows are unsupported for reliable row numbering; keep your tables contiguous.

Key-value records:

- RESULTS.json: full result rows.
- RESULTS.csv: formula-safe CSV; nested fields are JSON strings; potentially executable spreadsheet text is apostrophe-prefixed.
- ALLOCATION_SUMMARY: counts, assumptions, priority and component stock ledger with gross, reserved, available, allocated and remaining quantities. No cross-warehouse total is presented as transferable stock.

### Limits

10 MiB per file; 50,000 data rows per file; 32 columns; 256 characters per cell; 128-character identifiers; 10,000 unique bundle SKUs; 100 unique components per bundle; 20 warehouses; 20,000 output rows; 100,000 BOM-row × warehouse combinations; 40 MiB result JSON. XLSX archive expansion is limited to 50 MiB and 200 entries. maxBundles can lower the SKU limit. Exceeding a limit fails the analysis without silent truncation. Default runtime timeout is 240 seconds and memory 512 MiB.

### Pricing unit

Pricing: **USD 1.00 per 1,000 unique bundle SKU analyses** ($0.001 per SKU). The Store pricing tab is authoritative.

One successfully analyzed unique bundle SKU is counted once per run, including all its selected warehouse rows, recipe component rows, reservations and exports within the limits. A SKU with needs_review is still analyzed and counts once. Repeated BOM rows, multiple warehouses, shared components and multiple export formats do not create additional billable units. Re-running an analysis bills again. There is no separate component, warehouse or start fee. Demo and input validation failures have zero bundle analysis events. Budget is checked before writing results; insufficient budget fails rather than returning a partly allocated mix.

### Data handling

The Actor does not log file contents, component IDs, warehouse names or source rows. Expected failures use generic messages without customer values. Run input, uploaded source files, result Dataset and key-value records persist under Apify's storage and access settings; this is not zero-retention processing. The run token must be able to read the selected stores. Keep source and output stores private, restrict collaborator access and delete data when no longer needed. The Actor does not delete uploaded customer files automatically and sends no notifications or orders.

This tool computes from your uploaded snapshots and rules. It does not confirm real-time stock availability, alter inventory, or reserve stock in a warehouse.

### Development

Python 3.12+; install requirements.txt. Run:

```sh
python -m unittest discover -s tests -v
```

Version 1.0.0. AFK Digital.

# Actor input Schema

## `bundleComponentsFile` (type: `string`):

Select private store containing exactly one BUNDLE_COMPONENTS.csv, BUNDLE_COMPONENTS.xlsx or BUNDLE_COMPONENTS.json record. Only read access to the selected store is requested.

## `inventoryFile` (type: `string`):

Select private store containing exactly one INVENTORY.csv, INVENTORY.xlsx or INVENTORY.json record. Only read access to the selected store is requested.

## `reservationsFile` (type: `string`):

Select private store containing exactly one RESERVATIONS.csv, RESERVATIONS.xlsx or RESERVATIONS.json record. Only read access to the selected store is requested.

## `warehouseScope` (type: `array`):

Exact warehouse names; omitted selects warehouses in inventory and reservations. No stock pooling.

## `allocationMode` (type: `string`):

Standalone leaves allocated quantity null. Priority requires a complete ordered bundlePriority list.

## `bundlePriority` (type: `array`):

Highest priority first. Every unique bundle SKU exactly once; required only for priority mode.

## `maxBundles` (type: `integer`):

Reject larger inputs; never silently truncate.

## Actor input object example

```json
{
  "allocationMode": "standalone",
  "maxBundles": 10000
}
```

# Actor output Schema

## `json` (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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("afkdigital/bundle-sellable-stock-calculator").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 = {}

# Run the Actor and wait for it to finish
run = client.actor("afkdigital/bundle-sellable-stock-calculator").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 '{}' |
apify call afkdigital/bundle-sellable-stock-calculator --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,afkdigital/bundle-sellable-stock-calculator"
        }
    }
}
```

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/1RvwpTUv7x4IscmB4/builds/Gu4RwfxClT0Nm72cN/openapi.json
