# InvoiceFoundry (`krffl-llc/invoice-generator`) Actor

InvoiceFoundry turns your client, line item, and branding details into polished PDF invoices in seconds. It automates taxes and currencies, embeds QR codes for instant payment, and streams structured data to your CRM or BI tools so every invoice stays consistent and audit ready.

- **URL**: https://apify.com/krffl-llc/invoice-generator.md
- **Developed by:** [Krffl LLC](https://apify.com/krffl-llc) (community)
- **Categories:** Other, Integrations
- **Stats:** 3 total users, 0 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$50.00 / 1,000 results

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?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## Invoice Generator Actor

Create polished invoices in bulk without touching a spreadsheet. This Actor turns structured input (JSON, spreadsheet exports, API payloads) into production-ready documents in minutes. It handles numbering, due dates, tax calculations, branding, and exports the output in multiple formats so you can plug the result straight into your workflow.

### Why use this Actor?

- **Batch-friendly**: Generate a single invoice or thousands in one run.
- **Consistent branding**: Configure colours, fonts, logos, layouts, watermarks, and optional QR codes.
- **Streamlined layout**: Two-column header (seller + logo), invoice details table with highlighted amount due, banded item grid, side-by-side totals & notes, and a footer QR/payment call-to-action.
- **US Letter ready**: Optimised for 8.5"×11" output so invoices print cleanly without tweaking margins.
- **Accurate calculations**: Supports percentage/fixed discounts, multiple tax rates, auto-numbering schemes, and due-date rules.
- **Multi-format output**: Produce PDF, HTML, and JSON representations, plus an aggregated ZIP archive for batch downloads.
- **Actionable analytics**: Receive a summary report with totals, averages, currency breakdowns, and failure counts.
- **Status tracking timeline**: Capture lifecycle updates (draft → paid) and persist them in the dataset for downstream automation or reporting.

### How it works

1. Provide an array of invoices in the input JSON (supports copy-paste from CSV/Excel after conversion).
2. Optionally customise numbering, templates, QR code behaviour, and output formats.
3. The Actor validates each invoice, calculates totals, and generates the formats you enabled.
4. Results are stored in the default key-value store and metadata is written to the dataset for downstream automation.

### Input

The full input schema lives in `.actor/input_schema.json`. Key fields are:

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `action` | String | ✅ | `GENERATE` (default) renders invoices. `UPDATE_STATUS` applies lifecycle updates you provide. `PROCESS_PASTDUE` auto-marks unpaid invoices past their due date as `overdue`. `UPSERT_DEFAULTS` stores shared seller/template defaults for future runs. |
| `invoices` | Array | Conditional | One or more invoice objects (seller, buyer, items, optional discounts, notes, terms, lifecycle `status`, customFields). Required when `action = GENERATE`. |
| `statusUpdates` | Array | Conditional | Batch of `{ invoiceNumber, status, amountPaid?, note?, paymentReference?, updatedAt? }` entries. `amountPaid` accepts a numeric value or numeric string. Required when `action` is `UPDATE_STATUS`. |
| `numberingScheme` | String | ❌ | Pattern for automatic invoice numbering (`INV-{YYYY}-{MM}-{####}`, `{CLIENT}-{DATE}-{SEQ}`, etc.). |
| `allowDuplicates` | Boolean | ❌ | Skip duplicate-number check when `true` (default `false`). |
| `output` | Object | ❌ | Toggles for generated formats (`pdf`, `html`, `json`). Defaults to PDF only. |
| `template` | Object | ❌ | Branding options: layout, colours, font family, logo URL placeholder, and QR code configuration (content, caption, payment link). |

Each invoice entry supports:

- `invoiceNumber`, `issueDate`, `dueDate`, `currency`
- `seller`/`buyer` objects with address & contact info
- `items`: array of `{ description, quantity, unitPrice, taxRate }`
- `discount`: `{ type: 'percentage' | 'fixed', value }`
- `notes`, `terms`, `status` (`draft`, `sent`, `viewed`, `partial_payment`, `paid`, `overdue`, `cancelled`)
- `customFields`: key/value pairs rendered in the PDF & HTML outputs

**Logo sizing tip:** the header positions the brand mark inside a 240×60 pt area (≈3.3″ × 0.8″). Supply a transparent PNG or SVG that’s no wider than ~600 px and ~200 px tall so it stays sharp when centered and scaled down.

#### Persisting defaults

Use `action: "UPSERT_DEFAULTS"` once to store company details, template colours, and other reusable settings:

```json
{
  "action": "UPSERT_DEFAULTS",
  "defaults": {
    "seller": {
      "name": "Acme Agency",
      "address": "100 Main St",
      "city": "Metropolis"
    },
    "template": {
      "primaryColor": "#123456",
      "logoUrl": "https://example.com/logo.png"
    }
  }
}
```

The actor saves these values in its default key-value store and merges them into every subsequent run. After seeding defaults you can omit the repeated fields—just provide the invoice payload (or status updates).

#### Example input

```json
{
  "invoices": [
    {
      "invoiceNumber": "INV-2025-001",
      "issueDate": "2025-01-15",
      "terms": "Net 30",
      "currency": "USD",
      "seller": {
        "name": "Example Agency",
        "address": "123 Business St",
        "city": "New York",
        "state": "NY",
        "zipCode": "10001",
        "country": "USA",
        "email": "billing@example.com"
      },
      "buyer": {
        "name": "Client Company",
        "address": "456 Client Ave",
        "city": "Los Angeles",
        "state": "CA",
        "zipCode": "90001",
        "country": "USA"
      },
      "items": [
        { "description": "Web Development", "quantity": 40, "unitPrice": 150, "taxRate": 0.1 },
        { "description": "Consulting", "quantity": 10, "unitPrice": 200, "taxRate": 0.1 }
      ],
      "discount": { "type": "percentage", "value": 5 },
      "notes": "Thank you for partnering with us this quarter. Please reference the PO on remittance.",
      "status": "SENT",
      "customFields": {
        "PO Number": "PO-12345",
        "Project Code": "PROJ-001"
      }
    }
  ],
  "numberingScheme": "INV-{YYYY}-{MM}-{####}",
  "output": {
    "pdf": true,
    "html": true,
    "json": true
  },
  "template": {
    "primaryColor": "#2563eb",
    "secondaryColor": "#64748b",
    "fontFamily": "Helvetica",
    "qrCode": {
      "enabled": true,
      "content": "invoiceUrl",
      "caption": "Scan to view this invoice online",
      "paymentLink": "https://pay.example.com/invoice/INV-2025-001"
    }
  }
}
```

#### Status update workflow

- Switch `action` to `UPDATE_STATUS` to skip rendering and apply lifecycle changes only.
- Provide one or more entries in `statusUpdates`. Each event is persisted in the default key-value store and appended to the dataset timeline so downstream automations can react.
- The dataset exposes a `statusTimeline` view that unwinds history so finance teams can filter by `paid`, `overdue`, reminder count, or the timestamp of the most recent status change.

Example payload:

```json
{
  "action": "UPDATE_STATUS",
  "statusUpdates": [
    {
      "invoiceNumber": "INV-2025-001",
      "status": "paid",
      "amountPaid": 1875.50,
      "paymentReference": "txn-872345",
      "note": "Paid via ACH",
      "updatedAt": "2025-02-12T14:05:00.000Z"
    }
  ]
}
```

#### Integrating with other actors

- Every run writes invoice metadata and lifecycle events to the default dataset (`RUN.defaultDatasetId`). Each item contains the current `status`, `lifecycleStatus`, payment balances, and full `statusHistory`.
- Create a dedicated notification actor (for Slack, email, accounting systems, etc.) that reads the dataset items for a run via the Apify API. You can trigger it with an Actor webhook on `RUN.SUCCEEDED`, schedule, or manual `apify.call`.
- Store any hand-off state (for example, the last processed dataset item ID) in the notification actor’s key-value store so it can retry failed deliveries without re-running invoice generation.
- This separation keeps the invoice generator deterministic while giving integrators freedom to shape payloads per destination.

#### Local testing helpers

- Sample payloads live in `test_configs/`:
  - `GENERATE.json` – seeds invoices and documents.
  - `UPDATE_STATUS.json` – applies two lifecycle updates to existing invoices.
  - `PROCESS_PASTDUE.json` – runs the overdue marker logic.
  - `UPSERT_DEFAULTS.json` – stores reusable seller/template defaults.
  - `STATUS_INDEX_SEED.json` – seed data for `invoice-status-index` when you need state without re-running `GENERATE`.
- Copy a file into `storage/key_value_stores/default/INPUT.json` (or point `APIFY_INPUT_FILE` at it) before `apify run`.
- To keep prior dataset/key-value store state between runs, add `--no-purge` (or export `APIFY_PURGE_LOCAL_STORAGE=0`) when running locally.
- When testing `PROCESS_PASTDUE`, copy `STATUS_INDEX_SEED.json` to `storage/key_value_stores/default/invoice-status-index.json` before executing so the action has invoices to evaluate.

### Output

| Location | Contents |
| --- | --- |
| Default dataset (`RUN.defaultDatasetId`) | One record per invoice/event. Success rows include amounts, URLs for each generated format, lifecycle status, payment balances, reminder metadata, and full status history. Failures store the error message. |
| Default key-value store (`RUN.defaultKeyValueStoreId`) | Generated files: `invoice-<number>.pdf`, `.html`, `.json` (depending on formats), `invoices-batch.zip`, `invoice-summary.json`, `invoice-summary.txt`. |
| Output schema shortcuts | `overview` (dataset view), `statusTimeline` (flattened lifecycle view), `invoices` (key prefix listing), `zipArchive`, and `summary` links surfaced in Apify Console. |

#### Summary analytics

`invoice-summary.json` contains totals, averages, per-currency breakdown, and failure counts. `invoice-summary.txt` provides a human-readable report.

### Typical use cases

- Freelancers and agencies automating recurring invoicing
- Marketplaces generating payout statements for vendors
- Back-office teams producing PDF invoices from ERP/CRM exports
- AI agents that need reliable document output from structured data

### Running on Apify

1. Open the Actor in Apify Console and review the input JSON form (auto-generated from `input_schema.json`).
2. Paste or upload your invoice data; tweak optional parameters.
3. Click **Run**. Monitor progress via the log and dataset preview.
4. Download generated documents from the **Key-value stores** tab or use the direct links exposed in the Output tab.
5. Optionally schedule recurring runs or trigger the Actor via API/Webhook. A ZIP archive (`invoices-batch.zip`) and analytics summaries (`invoice-summary.json`, `.txt`) are stored automatically when you generate PDF output for multiple invoices.

#### Scheduling recurring runs

1. In Apify Console, create a task for this actor (Actors → Tasks → **Create task**). The form exposes structured sections for defaults so you can fill them without editing raw JSON.
2. Go to Actors → Schedules → **Create schedule**, select the task, choose the cadence (cron expression, hourly, daily, weekly, etc.), and limit concurrent runs if needed.
3. Seed or update shared settings by running the task once with `action: "UPSERT_DEFAULTS"`; reuse the same task with `action: "GENERATE"` or status workflows afterwards.

Example hourly payment sync (set schedule cron to `0 * * * *`):

```json
{
  "action": "UPDATE_STATUS",
  "statusUpdates": [
    {
      "invoiceNumber": "INV-2025-001",
      "status": "paid",
      "amountPaid": 1250.0,
      "paymentReference": "txn-5678"
    }
  ]
}
```

Example daily past-due sweep (set schedule cron to `0 7 * * *` for 7:00 every morning):

```json
{
  "action": "PROCESS_PASTDUE",
}
```

### Development & deployment

```bash
npm install        # install dependencies
apify run          # run locally with INPUT.json
apify login        # authenticate with Apify
apify push         # deploy new version to the platform
npm test           # run unit/integration tests
```

For detailed architecture notes and full field descriptions see:

- [`SPECIFICATION.md`](./SPECIFICATION.md)
- [`ACTOR_DEVELOPMENT_GUIDE.md`](./ACTOR_DEVELOPMENT_GUIDE.md)
- [`AGENTS.md`](./AGENTS.md)
- [`CHANGELOG.md`](./CHANGELOG.md)
  Refer to `storage/key_value_stores/default/INPUT.json` for an annotated example that demonstrates colour theming, logo embedding, QR codes, and output format toggles.

### Support & feedback

- Bug reports / feature requests: open an issue in this repository or contact via Apify support.
- Contributions: feel free to submit pull requests for new templates, integrations, or localisation improvements.

### License

ISC

# Actor input Schema

## `action` (type: `string`):

Controls what the Actor does. Use GENERATE to create invoices or UPDATE\_STATUS to update existing invoices.

## `statusUpdates` (type: `array`):

Provide status transitions when action is UPDATE\_STATUS.

## `invoices` (type: `array`):

Array of invoice objects to generate. Can contain one or multiple invoices for batch processing.

## `numberingScheme` (type: `string`):

Pattern for auto-generating invoice numbers. Use placeholders: {YYYY}, {MM}, {DD}, {####}, {SEQ}, {CLIENT}, {PREFIX}. Example: 'INV-{YYYY}-{MM}-{####}'

## `allowDuplicates` (type: `boolean`):

If false, will error on duplicate invoice numbers

## `output` (type: `object`):

Select which formats to generate for each invoice.

## `template` (type: `object`):

Customization options for invoice appearance

## `defaults` (type: `object`):

Optional defaults to upsert when action is UPSERT\_DEFAULTS. These values will be merged with future runs.

## Actor input object example

```json
{
  "action": "GENERATE",
  "statusUpdates": [],
  "invoices": [
    {
      "invoiceNumber": "INV-2025-001",
      "issueDate": "2025-01-15",
      "dueDate": "2025-02-15",
      "currency": "USD",
      "seller": {
        "name": "Your Company Name",
        "address": "123 Business St",
        "city": "New York",
        "state": "NY",
        "zipCode": "10001",
        "country": "USA",
        "email": "billing@company.com",
        "phone": "+1-555-0123"
      },
      "buyer": {
        "name": "Client Company",
        "address": "456 Client Ave",
        "city": "Los Angeles",
        "state": "CA",
        "zipCode": "90001",
        "country": "USA"
      },
      "items": [
        {
          "description": "Web Development Services",
          "quantity": 40,
          "unitPrice": 150,
          "taxRate": 0.1
        }
      ],
      "notes": "Payment due within 30 days. Thank you for your business!",
      "terms": "Net 30",
      "status": "SENT",
      "customFields": {
        "PO Number": "PO-12345",
        "Project Code": "PROJ-001"
      }
    }
  ],
  "numberingScheme": "INV-{YYYY}-{MM}-{####}",
  "allowDuplicates": false,
  "output": {
    "pdf": true,
    "html": false,
    "json": false
  },
  "template": {
    "layout": "standard",
    "primaryColor": "#2563eb",
    "secondaryColor": "#64748b",
    "fontFamily": "Helvetica"
  },
  "defaults": {
    "seller": {
      "name": "Your Company Name",
      "address": "123 Business St",
      "city": "New York",
      "state": "NY",
      "zipCode": "10001",
      "country": "USA",
      "email": "billing@company.com",
      "phone": "+1-555-0123"
    },
    "template": {
      "layout": "standard",
      "primaryColor": "#2563eb",
      "secondaryColor": "#64748b",
      "logoUrl": "",
      "fontFamily": "Helvetica"
    }
  }
}
```

# Actor output Schema

## `overview` (type: `string`):

No description

## `statusTimeline` (type: `string`):

No description

## `invoices` (type: `string`):

No description

## `zipArchive` (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("krffl-llc/invoice-generator").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("krffl-llc/invoice-generator").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 krffl-llc/invoice-generator --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,krffl-llc/invoice-generator"
        }
    }
}

```

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/DmcVP8asbZgzHcvTa/builds/a1UeQub6EadHdQnGZ/openapi.json
