# E-commerce Returns Loss Analyzer (`afkdigital/ecommerce-returns-loss-analyzer`) Actor

Prioritize return-heavy SKUs and variants using your own anonymous CSV/JSON data, with source evidence and cost-aware estimates. No Shopify access.

- **URL**: https://apify.com/afkdigital/ecommerce-returns-loss-analyzer.md
- **Developed by:** [AFK Digital](https://apify.com/afkdigital) (community)
- **Categories:** E-commerce
- **Stats:** 2 total users, 1 monthly users, 15.4% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $3.00 / 1,000 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

## E-commerce Returns Loss Analyzer (API16)

Offline SKU/variant return analytics for authorized CSV/JSON store exports. Not affiliated with Shopify. No Shopify credentials, scraping, review analysis, API10 catalog audit, LLM or third-party API.

### Input

Select exactly one of returnsFile, returnsData (JSON array), returnsCsv (UTF-8 text). Optional salesFile/salesData/salesCsv and costsFile/costsData/costsCsv. Maximum 8 MiB and 100,000 rows per source. File uploads must be direct HTTPS api.apify.com key-value-store record URLs, with no redirect or external host. rightsConfirmed=true required; optional dateFrom/dateTo inclusive YYYY-MM-DD, currency 3-letter ISO code (default USD, no FX), resultLimit 1–500 SKUs (default 100).

Required returns columns: sku, positive integer quantity. Optional: row_id, variant, returned_at, return_reason_handle OR reason_code OR reason (only one). Sales: sku, quantity; optional row_id, variant, sold_at. Costs: sku and at least one component; optional row_id, variant, currency, nonrecoverable_unit_cost, return_shipping_per_unit, handling_per_unit, recovery_credit_per_unit. Every unexpected column is rejected.

### Privacy and provenance

Remove customer names, IDs, addresses, emails, phones, customer notes, order notes and free-text before uploading. Unexpected columns fail validation; no original source row content appears in the Dataset. The Actor cannot undo personal data uploaded before validation. Only safe opaque row_id values are permitted; known emails rejected but no automatic method detects all sensitive content. Use retention/access controls in your Apify account.

Older Shopify ReturnReason codes, e.g. DEFECTIVE and SIZE_TOO_SMALL, are supported. The current Shopify GraphQL ReturnLineItem.returnReason is deprecated; use ReturnLineItem.returnReasonDefinition.handle (definition also exposes name and id). Names and free-text notes are not used. Shopify API scopes are not required. Sources: https://shopify.dev/docs/api/admin-graphql/latest/objects/ReturnLineItem ; https://shopify.dev/docs/api/admin-graphql/latest/objects/ReturnReasonDefinition ; https://shopify.dev/docs/api/admin-graphql/latest/enums/ReturnReason

### Interpretation

Returned units: sum quantity on return dates. Period return percentage: 100 \* returns / sales for same SKU and date interval, only if positive sales denominator exists. This is NOT an order-cohort rate; units may exceed contemporaneous sales, and percentages may be over 100%. Dates missing when filtering cause excluded rows and warnings.
Reason distribution is returned UNIT counts for input reason handles/codes (no text inference). Known net cost uses unit quantity times supplied nonrecoverable inventory write-off + paid return shipping + processing/handling - actually recovered credit, only if each returned variant has at least some cost fields. EstimatedDirectLoss is shown ONLY when ALL FOUR components are explicitly given (zeros allowed) for every returned variant. This is a limited DIRECT cost estimate, NOT a calculation of lost revenue or lost profits. Enter inventory write-off only if truly unrecoverable. No unlisted operational costs or FX effects are inferred.

Priority ranking uses estimatedDirectLoss descending only when cost coverage is complete for every returned SKU; otherwise it uses returnedUnits descending, then SKU as tie-break. Each Dataset row includes SKU, reason and variant breakdown, sold and returned units, nullable period rate and loss, individual cost totals, up to 100 evidence row IDs per SKU and variant, cost-row IDs, warnings, priorityRank and priorityBasis. Full summary in default key-value store record SUMMARY. Evidence cap warning applies; item counts remain complete.

### Examples and checks

examples/returns.csv, examples/returns.json, examples/sales.csv, examples/costs.csv, examples/input.json contain fictional nonpersonal data. For local checks:

```
python3 -m unittest discover -s tests -v
python3 -m src.local examples/input.json
```

Runtime uses Dockerfile and Python Apify SDK 4.1.0. Source is entirely separate from API01–API15.

### Billing

Proposed event is sku-analyzed at $0.003 per *delivered* SKU. Synthetic platform apify-actor-start at $0.00005/run. No per-raw-row charge; default Dataset charging event must be disabled. Cloud run enforces event limits by SDK and validates paid SKU event before delivering data. A failed validation produces no billable SKU event. Platform may still bill a one-time startup event. See PRICING.md and reports/ for measured cost and status. No sales guarantee.

### Delivery limits and summary scopes

Dataset contains only the billed/delivered SKU rows. SUMMARY distinguishes skuCount (all qualifying SKUs), selectedSkuCount (after resultLimit), deliveredSkuCount/outputSkuCount (actually saved), and omittedSkuCount (not saved due to limit or run budget). Summary's whole-period return units and total direct loss, when available, cover all qualifying SKUs, **not only delivered Dataset rows**; see totalEstimatedDirectLossScope. Evidence IDs generated when no row_id exists refer to the anonymous input source position (such as returns:1); they are not Shopify-issued identifiers. Keep source files to re-check them.

Any budget limit can yield a truncated ranking. Start a separate higher-budget run to receive additional rows, rather than assuming truncated output is exhaustive.

# Actor input Schema

## `rightsConfirmed` (type: `boolean`):

Remove customer names, addresses, email addresses and free-text notes before uploading. Only authorized anonymous exports. The prefilled confirmation applies only to the included demonstration input. If you replace the sample, check your own rights and confirm deliberately.

## `returnsFile` (type: `string`):

Direct Apify key-value-store UTF-8 CSV/JSON file. Choose one mode only.

## `returnsData` (type: `array`):

Anonymous array of records; not for customer details.

## `returnsCsv` (type: `string`):

returns pasted CSV. Supply only anonymous permitted fields.

## `salesFile` (type: `string`):

Direct Apify key-value-store UTF-8 CSV/JSON file. Choose one mode only.

## `salesData` (type: `array`):

Anonymous array of records; not for customer details.

## `salesCsv` (type: `string`):

sales pasted CSV. Supply only anonymous permitted fields.

## `costsFile` (type: `string`):

Direct Apify key-value-store UTF-8 CSV/JSON file. Choose one mode only.

## `costsData` (type: `array`):

Anonymous array of records; not for customer details.

## `costsCsv` (type: `string`):

costs pasted CSV. Supply only anonymous permitted fields.

## `dateFrom` (type: `string`):

Inclusive start date. Supply only anonymous permitted fields.

## `dateTo` (type: `string`):

Inclusive end date. Supply only anonymous permitted fields.

## `currency` (type: `string`):

No FX conversion.

## `resultLimit` (type: `integer`):

Maximum SKU results. Supply only anonymous permitted fields.

## Actor input object example

```json
{
  "rightsConfirmed": true,
  "returnsData": [
    {
      "row_id": "RT-001",
      "sku": "TSHIRT-01",
      "variant": "Blue / M",
      "quantity": "2",
      "returned_at": "2026-09-18",
      "return_reason_handle": "too-tight"
    },
    {
      "row_id": "RT-002",
      "sku": "TSHIRT-01",
      "variant": "Blue / M",
      "quantity": "1",
      "returned_at": "2026-09-19",
      "return_reason_handle": "quality"
    },
    {
      "row_id": "RT-003",
      "sku": "MUG-02",
      "variant": "White",
      "quantity": "3",
      "returned_at": "2026-09-23",
      "return_reason_handle": "DEFECTIVE"
    }
  ],
  "currency": "USD",
  "resultLimit": 5
}
```

# Actor output Schema

## `dataset` (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 = {
    "rightsConfirmed": true,
    "returnsData": [
        {
            "row_id": "RT-001",
            "sku": "TSHIRT-01",
            "variant": "Blue / M",
            "quantity": "2",
            "returned_at": "2026-09-18",
            "return_reason_handle": "too-tight"
        },
        {
            "row_id": "RT-002",
            "sku": "TSHIRT-01",
            "variant": "Blue / M",
            "quantity": "1",
            "returned_at": "2026-09-19",
            "return_reason_handle": "quality"
        },
        {
            "row_id": "RT-003",
            "sku": "MUG-02",
            "variant": "White",
            "quantity": "3",
            "returned_at": "2026-09-23",
            "return_reason_handle": "DEFECTIVE"
        }
    ],
    "resultLimit": 5
};

// Run the Actor and wait for it to finish
const run = await client.actor("afkdigital/ecommerce-returns-loss-analyzer").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 = {
    "rightsConfirmed": True,
    "returnsData": [
        {
            "row_id": "RT-001",
            "sku": "TSHIRT-01",
            "variant": "Blue / M",
            "quantity": "2",
            "returned_at": "2026-09-18",
            "return_reason_handle": "too-tight",
        },
        {
            "row_id": "RT-002",
            "sku": "TSHIRT-01",
            "variant": "Blue / M",
            "quantity": "1",
            "returned_at": "2026-09-19",
            "return_reason_handle": "quality",
        },
        {
            "row_id": "RT-003",
            "sku": "MUG-02",
            "variant": "White",
            "quantity": "3",
            "returned_at": "2026-09-23",
            "return_reason_handle": "DEFECTIVE",
        },
    ],
    "resultLimit": 5,
}

# Run the Actor and wait for it to finish
run = client.actor("afkdigital/ecommerce-returns-loss-analyzer").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 '{
  "rightsConfirmed": true,
  "returnsData": [
    {
      "row_id": "RT-001",
      "sku": "TSHIRT-01",
      "variant": "Blue / M",
      "quantity": "2",
      "returned_at": "2026-09-18",
      "return_reason_handle": "too-tight"
    },
    {
      "row_id": "RT-002",
      "sku": "TSHIRT-01",
      "variant": "Blue / M",
      "quantity": "1",
      "returned_at": "2026-09-19",
      "return_reason_handle": "quality"
    },
    {
      "row_id": "RT-003",
      "sku": "MUG-02",
      "variant": "White",
      "quantity": "3",
      "returned_at": "2026-09-23",
      "return_reason_handle": "DEFECTIVE"
    }
  ],
  "resultLimit": 5
}' |
apify call afkdigital/ecommerce-returns-loss-analyzer --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,afkdigital/ecommerce-returns-loss-analyzer"
        }
    }
}
```

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/m0eNSiz7kie1Y3dyU/builds/R0znfvsx3RIkhohEI/openapi.json
