# API reference

**PULPO WMS API Documentation**
Complete API documentation for integrating with PULPO WMS as a 3PL fulfiller.

**Overview**

This API enables third-party logistics (3PL) providers to integrate with PULPO WMS for managing:
- **Incoming processes**: Purchase orders, goods receipt, stock replenishment
- **Outgoing processes**: Sales orders, picking, packing, shipping
- **Inventory management**: Products, stock levels, kitting
- **Master data**: Merchants, channels, third parties, warehouses

**Key Concepts**

**Multi-tenant Architecture**
- **Tenant**: Your PULPO WMS account
- **Merchant**: Your customers (in 3PL scenarios)
- **Channel**: Sales channels for each merchant (e.g., Shopify, Amazon)
- **Warehouse**: Physical warehouse locations

**Authentication**
- OAuth 2.0 password grant flow
- Tokens expire after 60 minutes
- Store and reuse tokens to avoid rate limits

**Rate Limits**
- Default: 60-300 calls per minute (tenant-based)
- Handle 429 responses with exponential backoff
- Use bulk endpoints when possible

**Pagination**
- Offset-based pagination
- Use `limit` (1-2000, default 10) and `offset` (default 0)
- Use `capped_limit=0` for better performance (no total count)
- Use `sort_by=id:asc` to avoid duplicate results

**Webhooks**
- Subscribe to events for real-time updates
- Webhook payloads include full event data
- Configure retry logic for failed deliveries

**Getting Started**

1. Authenticate using `/auth` endpoint
2. Get your tenant and warehouse info from `/iam/users/me` and `/warehouses`
3. Create master data: Products, Third Parties
4. Subscribe to webhooks for order events
5. Create Purchase Orders (incoming) or Sales Orders (outgoing)

**Common Workflows**

**Incoming Process (Purchase Order)**
```
1. POST /inventory/bulk/products (create products)
2. POST /iam/bulk/third_parties (create suppliers)
3. POST /reception/bulk/purchase_orders (create PO)
4. Warehouse receives goods (via Android app)
5. Webhook: purchase_order_finished (GR - Goods Receipt)
6. Webhook: replenishment_order_finished (stock available)
```

**Outgoing Process (Sales Order)**
```
1. POST /iam/bulk/third_parties (create customers)
2. POST /sales/bulk/orders (create sales order)
3. Warehouse picks items (via Android app)
4. Webhook: packing_order_finished (PIC - Picking Complete)
5. Warehouse packs items (via Android app)
6. Webhook: sales_order_finished (PGI - Post Goods Issue)
```

**Support**
- Integration Guide: Version 4.4.0 (July 2024)
- API Documentation: https://eu.pulpo.co/api/v1/swagger/index.html

## Authentication

OAuth 2.0 authentication endpoints

### POST /auth — Authenticate or refresh an access token

operationId: `authenticate`

OAuth 2.0 endpoint supporting two grant types:

- `password` — exchange username + password for an access token.
- `refresh_token` — exchange a previously issued `refresh_token` for a fresh
  access token without re-prompting for credentials.

**Important:**
- Tokens expire after 60 minutes
- Store the token and reuse it until expiry
- Do NOT request a new token for every API call
- Create a dedicated API user with access to all warehouses
- If the auth response includes a `refresh_token`, use the `refresh_token` grant
  to silently renew the access token instead of re-submitting credentials.

Request body (object | object):
- (no documented fields)

Responses:
- 200: Successfully authenticated
- 401: Unauthorized - invalid or missing token
- 429: Rate limit exceeded - too many requests

### POST /auth/revoke — Revoke an access or refresh token

operationId: `revokeToken`

Best-effort logout — revokes the supplied token so it can no longer be used.

Send the current `Authorization: Bearer <token>` header AND the token to revoke
in the body. Servers may accept revoking a `refresh_token` here as well.

Returning 200 indicates the token is no longer valid; clients should also clear
their local copy regardless of the response.

Request body (object):
- `token` (string, required) — Access or refresh token to revoke

Responses:
- 200: Token revoked
- 401: Unauthorized - invalid or missing token

## User & Tenant

User and tenant information, and the tenant's **tags**.

**Tags = product_categories**

What the PULPO apps (mobile and browser) call **tags** is called
**`product_categories`** in the API. They are the same thing — only the name
differs. Despite the name, they are not limited to products: a tag can be assigned
to **products**, **users** and **warehouse locations**.

Create a tag once per tenant, then assign it by its **ID**:

| Record | How to assign tags |
|--------|--------------------|
| Product | `product_categories: [ids]` in `POST` / `PUT /inventory/bulk/products` |
| User | `product_categories: [ids]` in `POST /iam/users`, later `POST /iam/users/{id}/categories` |
| Location | `product_categories: [ids]` in `POST /warehouses/locations` or `PUT /warehouses/locations/{id}` |

In every case the list **replaces** the record's tags and `[]` removes them all.
Send tag IDs only — codes, objects, or a field called `tags` don't work.

Products and locations can be searched by tag with `product_categories=<id>`.

**Locations — watch out:**
- `PUT /warehouses/locations/{id}` **without** `product_categories` removes all of
  the location's tags. Always resend them.
- `POST /warehouses/locations/categories/assign`
  (`{"locations": [ids], "product_categories": [ids]}`) **adds** tags instead of
  replacing them, creates duplicates when repeated, and its result doesn't show
  in `GET /warehouses/locations/{id}` (only in the location search). Prefer
  `PUT /warehouses/locations/{id}`.

### GET /iam/users/me — Get current user information

operationId: `getCurrentUser`

Returns detailed information about the authenticated user, including:
- Tenant ID and details
- Accessible warehouses (allowlist — users only see data for these warehouses)
- Accessible merchants (allowlist)
- User profiles and permissions

Use this endpoint to obtain your `tenant_id` and `warehouse_id` values.

The returned `warehouses[]` and `merchants[]` define the user's effective
authorization scope. There is no explicit role/permission field — visibility
is implied by these allowlists, and clients should filter server responses
against the same sets.

Responses:
- 200: User information retrieved successfully
- 401: Unauthorized - invalid or missing token

### GET /iam/users/{id}/merchants — List merchants accessible to a user

operationId: `getUserMerchants`

Returns the merchants the given user has access to. Equivalent to
`me.merchants[]`, but addressable by ID.

If this endpoint is not available for your tenant, fall back to
`GET /merchants/` and intersect with the user's `merchants` allowlist.

Parameters:
- `id` (path, integer, required)

Responses:
- 200: Merchants for the user
- 401: Unauthorized - invalid or missing token

### GET /iam/merchants/{id}/channels — List sales channels for a merchant

operationId: `getMerchantChannels`

Returns the merchant_channels configured for a given merchant. Use the
returned `id` as `merchant_channel_id` on order/product creation.

Parameters:
- `id` (path, integer, required) — Merchant ID

Responses:
- 200: Channels retrieved
- 401: Unauthorized - invalid or missing token

### GET /iam/users/{id}/tasks — List active tasks owned by a user

operationId: `getUserTasks`

Returns the set of in-flight warehouse tasks currently assigned to a user.

Useful for the "one task at a time per user" rule applied in picking/packing —
before opening a new flow, check whether the user already owns an active task.

**Note:** Paused (`locked`) packing orders are **not** included here. Query
`GET /packing/orders?state=locked` to find them.

Parameters:
- `id` (path, integer, required) — User ID

Responses:
- 200: Active tasks for the user
- 401: Unauthorized - invalid or missing token

### GET /inventory/products/categories — Search tags (product_categories)

operationId: `searchTags`

Lists the tenant's tags. Tags are called `product_categories` in the API.

**Filters:** `id`, `code` and `name` are exact, case-sensitive matches (`code=Cold`
does not find `cold`). `id` and `code` also accept `to_list:` for several values.

`total_results` is `null` when `offset` is greater than 0.

Parameters:
- `id` (query, string) — Tag ID, or `to_list:id1,id2`
- `code` (query, string) — Exact code, or `to_list:code1,code2`
- `name` (query, string) — Exact name
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip
- `sort_by` (query, string) — Sort field and direction (field:asc or field:desc)

Responses:
- 200: Tags retrieved
- 401: Unauthorized - invalid or missing token

### GET /inventory/products/categories/{id} — Get a tag by ID

operationId: `getTag`

Parameters:
- `id` (path, integer, required)

Responses:
- 200: Tag retrieved
- 401: Unauthorized - invalid or missing token
- 422: Unknown ID

### POST /inventory/products/categories — Create a tag (product_category)

operationId: `createTag`

Creates a tag for the tenant. Send a plain object (not wrapped).

- `code`, `name` and `tenant_id` are required. `tenant_id` must be your own tenant
  (see `GET /iam/users/me`).
- `code` must be unique within the tenant. It is case-sensitive, so `cold` and
  `Cold` count as different codes.
- `name` does not need to be unique.

Use the returned `id` to assign the tag to products, users or locations.

Request body (object):
- `code` (string, required)
- `name` (string, required)
- `tenant_id` (integer, required)

Responses:
- 201: Tag created
- 400: Missing field, duplicate code, or a tenant the user doesn't belong to.
- 401: Unauthorized - invalid or missing token

### POST /iam/users/{id}/categories — Set a user's tags

operationId: `setUserTags`

Sets the user's **tags** (`product_categories`). The body is a plain JSON array of
tag IDs.

The list **replaces** the user's tags; `[]` removes all of them. If any ID is
unknown, the whole call fails and nothing changes. Tag codes are rejected.

This is the only way to change a user's tags after creation:
`PUT /iam/users/{id}` silently ignores `product_categories`. When creating a user
with `POST /iam/users`, tags can be sent directly as `product_categories: [ids]`.

Returns the full user, including the new `product_categories`.

Parameters:
- `id` (path, integer, required) — User ID

Request body (array of integer):
- (no documented fields)

Responses:
- 200: Tags set. The body is the full user.
- 400: Body is not a JSON array.
- 401: Unauthorized - invalid or missing token
- 422: Unknown tag ID or tag code sent, or unknown user. Nothing changed.

### PUT /inventory/products/categories/{id} — Update a tag

operationId: `updateTag`

Changes a tag's `code` and/or `name`. Only the fields you send change. The same
rules as on create apply: `code` must stay unique, neither may be empty.

Products, users and locations keep the tag — they reference it by ID, so a new
code or name shows up everywhere.

Parameters:
- `id` (path, integer, required)

Request body (object):
- `code` (string)
- `name` (string)

Responses:
- 200: Tag updated
- 401: Unauthorized - invalid or missing token
- 422: Unknown ID, duplicate code, or empty value.

### DELETE /inventory/products/categories/{id} — Delete a tag

operationId: `deleteTag`

Deletes a tag and returns it.

**Careful:** a tag that is in use can be deleted too. There is no warning — the
tag is silently removed from the products that had it (tested for products;
users and locations presumably behave the same).

Parameters:
- `id` (path, integer, required)

Responses:
- 200: Tag deleted. The body is the deleted tag.
- 401: Unauthorized - invalid or missing token
- 422: Unknown ID

## Warehouses

Warehouse management

### GET /warehouses/ — List all warehouses

operationId: `listWarehouses`

Returns detailed information about all warehouses accessible to the current user.

Use this to get warehouse IDs required for order creation.

Parameters:
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip

Responses:
- 200: Warehouses retrieved successfully
- 401: Unauthorized - invalid or missing token

### GET /warehouses/locations — Get warehouse locations

operationId: `getWarehouseLocations`

Returns physical locations within a warehouse.

**Use cases:**
- Find kitting locations for kitting tasks
- Map warehouse layout
- Track stock by specific bin/shelf

Parameters:
- `location_type_id` (query, integer) — Filter by location type (e.g., kitting, storage, return)
- `warehouse_id` (query, integer)
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip

Responses:
- 200: Locations retrieved

## Products

Product master data

### GET /inventory/products — Search products

operationId: `searchProducts`

Search and filter products with pagination.

**Useful filters:**
- `id`, `sku`, `article_number`, `barcode` — exact match, or `sku`/`name`
  accept a `contains:term` prefix for a substring search
- `name`, `description` — exact match, or `contains:term` on `name`
- `management_type` — `none`, `lot`, `serial`
- `third_party_id` — default supplier
- `merchant_id` (also `to_list:`), `active`, `has_stock`
- `product_categories` — tag ID, or `to_list:id1,id2` for products with any of
  them. Tag codes return an error.
- `holds_stock_on_warehouse_id` / `holds_blocked_stock_on_warehouse_id` —
  single ID or `to_list:id1,id2`
- `related_orders_state`, `related_orders_delivery_date` — exact match only,
  `YYYY-MM-DD HH:MM:SS`. A bare date or a `gte:`/`between:`/etc. prefix
  returns a 500 error.
- `view_attributes=id,sku,name` (return only specific fields)

`__or_search` and `show_deleted` are accepted but don't do anything on this
endpoint — deleted products never appear in search results regardless.

Parameters:
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip
- `sort_by` (query, string) — Sort field and direction (field:asc or field:desc)
- `capped_limit` (query, integer) — Set to 0 to exclude total_results and improve performance by ~20%. Pagination continues until returned items < limit. Allowed: `0`, `20`, `100`, `2000`.
- `id` (query, integer)
- `sku` (query, string) — Exact match or `contains:term` substring search
- `article_number` (query, string) — Exact match.
- `barcode` (query, string) — Exact match against any of the product's `barcodes`.
- `name` (query, string) — Exact match or `contains:term`
- `description` (query, string) — Exact match.
- `management_type` (query, string) Allowed: `none`, `lot`, `serial`.
- `third_party_id` (query, integer) — Default supplier ID.
- `merchant_id` (query, string) — Merchant ID. Use `to_list:1,2,3` for multiple.
- `active` (query, boolean)
- `has_stock` (query, boolean) — Whether the product has at least one stock record.
- `holds_stock_on_warehouse_id` (query, string) — Restricts `has_stock` to the given warehouse(s). Single ID or `to_list:id1,id2`.
- `holds_blocked_stock_on_warehouse_id` (query, string) — Product holds stock on a blocked position (unavailable state) in the given warehouse(s). Single ID or `to_list:id1,id2`.
- `related_orders_state` (query, string) — State of orders that reference this product.
- `related_orders_delivery_date` (query, string) — Delivery date of orders that reference this product. Exact match only, `YYYY-MM-DD HH:MM:SS` — a bare date or a `gte:`/`between:`/etc. prefix returns a 500 error.
- `view_attributes` (query, string) — Comma-separated list of fields to return

Responses:
- 200: Products found
- 401: Unauthorized - invalid or missing token

### POST /inventory/bulk/products — Create products in bulk

operationId: `bulkCreateProducts`

Creates multiple products at once. Products are the master data for all items in your warehouse.

To update existing products instead, use `PUT /inventory/bulk/products`.

**Important fields:**
- `sku`: Unique identifier per product (your external reference)
- `name`: Unique product name
- `merchant_id`: Owner of the product
- `barcodes`: Required for scanning in warehouse (Android app)
- `management_type`: none, lot, or serial (for batch tracking)

**Recommended batch size:** up to 50 items per request.

Request body (array of object):
- `id` (integer) — PULPO WMS product ID. Only used to identify the product on `PUT /inventory/bulk/products` (alternative to `sku`) — ignored on create.
- `active` (boolean, required) — Product is active. Set to `false` to deactivate without deleting — see `DELETE /inventory/bulk/products` to remove a product entirely.
- `name` (string, required) — Unique product name per tenant
- `sku` (string, required) — Unique SKU per product and tenant (your reference)
- `description` (string)
- `management_type` (string, required) — Inventory tracking method Allowed: `none`, `lot`, `serial`.
- `batch_control` (boolean, required) — Enable batch/expiry date tracking (use with lot/serial)
- `tenant_id` (integer, required) — Your PULPO WMS account ID
- `merchant_id` (integer, required) — Product owner (merchant)
- `merchant_channel_id` (integer) — Specific channel (null = all channels)
- `third_party_id` (integer) — Default supplier ID
- `cost_price` (number, required) — Product cost (use 1 if not relevant)
- `minimum_purchase_unit` (integer, required) — Minimum purchase quantity
- `minimum_sales_unit` (integer, required) — Minimum sales quantity
- `units_per_purchase_package` (integer, required) — Units per package (usually 1)
- `units_per_sales_package` (integer, required) — Units per sales package (usually 1)
- `purchase_measure_units` (string, required) — Unit of measure for purchasing
- `sales_measure_units` (string, required) — Unit of measure for sales
- `weight` (number, required) — Weight in kg
- `length` (number) — Length in cm
- `width` (number) — Width in cm
- `height` (number) — Height in cm
- `volume` (number) — Volume in cubic meters
- `stackable` (boolean) — Can be stacked
- `barcodes` (array of string, required) — Product barcodes (required for warehouse scanning)
- `product_categories` (array of integer) — **Tags** for the product, as a list of tag IDs (from `GET /inventory/products/categories`). Tags are called `product_categories` in the API. Codes or objects are rejected, and an unknown ID rejects the product. On update the list **replaces** the product's tags: `[]` removes all, leaving the field out (or `null`) keeps them. A field named `tags` is ignored.
- `hs_code` (string) — Harmonized System code for customs
- `origin_country` (string) — Country of origin (ISO 2-letter code)
- `supplier_product_id` (string) — Supplier's product code
- `article_number` (string) — Internal article number (optional). Some integrations match incoming product feeds against this field as a fallback when SKU is absent.
- `units_per_pallet` (integer) — Units per shipping pallet (optional)
- `lead_time` (integer) — Supplier lead time in days. **Note:** sent by some clients but server persistence may be partial — verify with your tenant before relying on it for ordering decisions.
- `moq` (integer) — Minimum order quantity. **Note:** sent by some clients but server persistence may be partial — verify before relying on it.
- `attributes` (object) — Custom attributes (flexible JSON). Some keys are read by the dashboard: `image_url` (or aliases `imageUrl`, `image`, `picture_url`, `pictureUrl`) renders the product thumbnail. On update, the whole object is replaced, not merged — resend every key you want to keep.

Responses:
- 201: Products processed. Check `created` for the products that succeeded and `errors` for the ones that didn't — a partial failure still returns 201 if at least the request itself was well-formed.
- 400: All items failed validation — none were created.
- 401: Unauthorized - invalid or missing token
- 429: Rate limit exceeded - too many requests

### PUT /inventory/bulk/products — Update products in bulk

operationId: `bulkUpdateProducts`

Updates existing products. Works as bulk — if any product update fails, the
remaining products continue processing.

**Identify the product to update:**
- `sku`: Product SKU (looked up together with your tenant)
- `id`: PULPO product ID also works, if you already store it

**Updatable fields:**
Send only the fields you want to change, plus the identifier — this is a
partial update, **except for `barcodes`**: it must always be included and
non-empty (resend the existing barcodes if you're not changing them, or the
request fails). Any other field accepted by product creation can be updated
— `name`, `active`, `cost_price`, `attributes`, etc.

**`attributes` is replaced, not merged:** whatever you send becomes the
product's complete `attributes` object, and any key you leave out is deleted
(including `image_url`, which drives the dashboard thumbnail). To change one
attribute, send all existing keys along with it.

To deactivate a product instead of updating it, send `active: false`.

**Recommended batch size:** up to 50 items per request.

Request body (array of object):
- `id` (integer) — PULPO WMS product ID. Only used to identify the product on `PUT /inventory/bulk/products` (alternative to `sku`) — ignored on create.
- `active` (boolean, required) — Product is active. Set to `false` to deactivate without deleting — see `DELETE /inventory/bulk/products` to remove a product entirely.
- `name` (string, required) — Unique product name per tenant
- `sku` (string, required) — Unique SKU per product and tenant (your reference)
- `description` (string)
- `management_type` (string, required) — Inventory tracking method Allowed: `none`, `lot`, `serial`.
- `batch_control` (boolean, required) — Enable batch/expiry date tracking (use with lot/serial)
- `tenant_id` (integer, required) — Your PULPO WMS account ID
- `merchant_id` (integer, required) — Product owner (merchant)
- `merchant_channel_id` (integer) — Specific channel (null = all channels)
- `third_party_id` (integer) — Default supplier ID
- `cost_price` (number, required) — Product cost (use 1 if not relevant)
- `minimum_purchase_unit` (integer, required) — Minimum purchase quantity
- `minimum_sales_unit` (integer, required) — Minimum sales quantity
- `units_per_purchase_package` (integer, required) — Units per package (usually 1)
- `units_per_sales_package` (integer, required) — Units per sales package (usually 1)
- `purchase_measure_units` (string, required) — Unit of measure for purchasing
- `sales_measure_units` (string, required) — Unit of measure for sales
- `weight` (number, required) — Weight in kg
- `length` (number) — Length in cm
- `width` (number) — Width in cm
- `height` (number) — Height in cm
- `volume` (number) — Volume in cubic meters
- `stackable` (boolean) — Can be stacked
- `barcodes` (array of string, required) — Product barcodes (required for warehouse scanning)
- `product_categories` (array of integer) — **Tags** for the product, as a list of tag IDs (from `GET /inventory/products/categories`). Tags are called `product_categories` in the API. Codes or objects are rejected, and an unknown ID rejects the product. On update the list **replaces** the product's tags: `[]` removes all, leaving the field out (or `null`) keeps them. A field named `tags` is ignored.
- `hs_code` (string) — Harmonized System code for customs
- `origin_country` (string) — Country of origin (ISO 2-letter code)
- `supplier_product_id` (string) — Supplier's product code
- `article_number` (string) — Internal article number (optional). Some integrations match incoming product feeds against this field as a fallback when SKU is absent.
- `units_per_pallet` (integer) — Units per shipping pallet (optional)
- `lead_time` (integer) — Supplier lead time in days. **Note:** sent by some clients but server persistence may be partial — verify with your tenant before relying on it for ordering decisions.
- `moq` (integer) — Minimum order quantity. **Note:** sent by some clients but server persistence may be partial — verify before relying on it.
- `attributes` (object) — Custom attributes (flexible JSON). Some keys are read by the dashboard: `image_url` (or aliases `imageUrl`, `image`, `picture_url`, `pictureUrl`) renders the product thumbnail. On update, the whole object is replaced, not merged — resend every key you want to keep.

Responses:
- 200: Products processed. Check `updated` for the products that succeeded and `errors` for the ones that didn't.
- 401: Unauthorized - invalid or missing token
- 422: All items failed validation — none were updated.

### DELETE /inventory/bulk/products — Delete products in bulk

operationId: `bulkDeleteProducts`

Permanently removes products. Deleted products no longer appear in
`GET /inventory/products` or other product searches.

Works as bulk — if any product fails to delete, the remaining products are
still processed.

**Recommended batch size:** up to 50 items per request.

Request body (array of object | array of string | array of integer):
- (no documented fields)

Responses:
- 200: Products processed. Check `deleted` for the products that succeeded and `errors` for the ones that didn't.
- 401: Unauthorized - invalid or missing token
- 422: All items failed — none were deleted (e.g. unknown sku/id).

## Third Parties

Suppliers and customers

### POST /iam/bulk/third_parties — Create third parties in bulk

operationId: `bulkCreateThirdParties`

Creates suppliers (type=S) or customers (type=C) in bulk.

To update existing third parties instead, use `PUT /iam/bulk/third_parties`.

**Suppliers (type=S):**
- Used in purchase orders
- `merchant_channel_id` can be NULL

**Customers (type=C):**
- Used in sales orders
- `merchant_channel_id` is REQUIRED

**Important:**
- Store the returned `id` for use in orders
- `identifier_number` + `third_type` must be unique — creating a duplicate is
  rejected, it does not update the existing record

**Recommended batch size:** up to 50 items per request.

Request body (array of object):
- `active` (boolean, required) — Third party is active
- `name` (string, required) — Company/person name
- `identifier_number` (string, required) — External reference (unique with third_type)
- `identifier_type` (string, required) — Type of identifier (ID, VAT, TAX, etc)
- `third_type` (string, required) — S=Supplier, C=Customer Allowed: `S`, `C`.
- `email` (string)
- `tenant_id` (integer, required)
- `merchant_id` (integer, required) — Associated merchant
- `merchant_channel_id` (integer) — Required for customers (C), optional for suppliers (S)
- `erp_id` (string) — External ERP ID
- `erp_code` (string) — External ERP code
- `attributes` (object) — Custom attributes including addresses
  - `addresses` (array of object)
    - `name` (string)
    - `company_name` (string)
    - `phone_number` (string)
    - `address` (object)

Responses:
- 201: Third parties processed. Check `created` for the ones that succeeded and `errors` for the ones that didn't.
- 400: All items failed validation — none were created.
- 401: Unauthorized - invalid or missing token

### PUT /iam/bulk/third_parties — Update third parties in bulk

operationId: `bulkUpdateThirdParties`

Updates existing suppliers or customers. Works as bulk — if any item fails,
the remaining ones continue processing. This is a partial update — send only
the fields you want to change, plus an identifier.

**Identify the third party to update:**
- `identifier_number` (with `third_type`)
- `id`: PULPO third party ID also works

**Recommended batch size:** up to 50 items per request.

Request body (array of object):
- `active` (boolean, required) — Third party is active
- `name` (string, required) — Company/person name
- `identifier_number` (string, required) — External reference (unique with third_type)
- `identifier_type` (string, required) — Type of identifier (ID, VAT, TAX, etc)
- `third_type` (string, required) — S=Supplier, C=Customer Allowed: `S`, `C`.
- `email` (string)
- `tenant_id` (integer, required)
- `merchant_id` (integer, required) — Associated merchant
- `merchant_channel_id` (integer) — Required for customers (C), optional for suppliers (S)
- `erp_id` (string) — External ERP ID
- `erp_code` (string) — External ERP code
- `attributes` (object) — Custom attributes including addresses
  - `addresses` (array of object)
    - `name` (string)
    - `company_name` (string)
    - `phone_number` (string)
    - `address` (object)

Responses:
- 200: Third parties processed. Check `updated` for the ones that succeeded and `errors` for the ones that didn't.
- 401: Unauthorized - invalid or missing token
- 422: All items failed — none were updated (e.g. unknown identifier_number/id).

### DELETE /iam/third_parties/{id} — Delete a third party

operationId: `deleteThirdParty`

Deletes a single supplier or customer by its PULPO ID. This is a soft
delete — the record is deactivated (`active: false`, `deleted_at`,
`deleted_by` set) and no longer appears in third party searches.

Third parties referenced by existing orders (purchase orders or sales
orders) cannot be deleted — deactivate them instead with
`PUT /iam/bulk/third_parties` (`active: false`).

Parameters:
- `id` (path, integer, required)

Responses:
- 200: Third party deleted (soft-deleted).
- 401: Unauthorized - invalid or missing token
- 422: Invalid ID, or the third party has order history and cannot be deleted.

## Purchase Orders

Incoming goods and purchase orders

### GET /reception/purchase_orders — List purchase orders

operationId: `listPurchaseOrders`

Lists purchase orders (incoming, returns, warehouse movements) with filters and pagination.

**Useful filters**

- `id`, `order_num` — exact match
- `warehouse_id`, `state`, `merchant_id` (also `to_list:`)
- `product_sku`, `product_name` — exact match, not a substring search
- `delivery_date` — exact match only, `YYYY-MM-DD HH:MM:SS`. `between:`/`gte:`/`lte:`
  prefixes are **not** supported and return a 500 error.
- `view_attributes` — comma-separated field list to return

`type`, `third_party_id`, `updated_at`, and a plain `inserted_at` filter are
accepted but don't actually filter anything on this endpoint — the response is
unaffected either way, so don't rely on them.

**Performance**

Pass `cap_limit=0` (or `capped_limit=0`) to skip the total-results count for
~20% lower latency. Stop paginating when the returned page is shorter than
the requested `limit`.

Parameters:
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip
- `sort_by` (query, string) — Sort field and direction (field:asc or field:desc)
- `capped_limit` (query, integer) — Set to 0 to exclude total_results and improve performance by ~20%. Pagination continues until returned items < limit. Allowed: `0`, `20`, `100`, `2000`.
- `id` (query, integer)
- `order_num` (query, string)
- `warehouse_id` (query, integer)
- `state` (query, string) Allowed: `queue`, `checking`, `finished_partially`, `closed`, `cancelled`.
- `merchant_id` (query, string) — Merchant ID. Use `to_list:1,2,3` for multiple.
- `product_sku` (query, string) — Exact SKU match.
- `product_name` (query, string) — Exact product name match (not a substring search).
- `delivery_date` (query, string) — Exact match only, `YYYY-MM-DD HH:MM:SS`. Range prefixes (`between:`/`gte:`/`lte:`) are not supported and return a 500 error.
- `view_attributes` (query, string) — Comma-separated list of fields to return

Responses:
- 200: Purchase orders retrieved
- 401: Unauthorized - invalid or missing token

### GET /reception/incoming_goods/{id} — Get an incoming-goods record by ID

operationId: `getIncomingGood`

Returns the full incoming-goods record, including per-item states, batch
details, destination locations, inspection photos (`attachments[]`), and
the operator who recorded the receipt (`owner`).

Parameters:
- `id` (path, integer, required)

Responses:
- 200: Incoming-goods record retrieved
- 401: Unauthorized - invalid or missing token
- 404: Resource not found

### GET /reception/incoming_goods — List incoming-goods (receiving) records

operationId: `listIncomingGoods`

Lists incoming-goods records — individual receiving events against purchase
orders. A purchase order may have multiple incoming_goods (partial receipts).

For returns, query with `document_type=return` to see inspection history,
including per-item accepted/rejected outcomes and attached photos.

**Filters**

- `warehouse_id`, `purchase_order_id`, `merchant_id` (`to_list:` supported),
  `owner_id`, `sequence_number` — exact match
- `document_type` — `purchase_order`, `return`, `warehouse_movement`, `none`
  (`none` = unplanned receiving without a PO)
- `start_date` / `end_date` — filter by `inserted_at`. **Must be a full
  date-time** (`YYYY-MM-DDTHH:MM:SS`) — a bare `YYYY-MM-DD` date returns a
  500 error.

`sales_order_id` and a plain `inserted_at` filter are not supported by this
endpoint — both are silently ignored or error; use `start_date`/`end_date`
instead.

Parameters:
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip
- `sort_by` (query, string) — Sort field and direction (field:asc or field:desc)
- `capped_limit` (query, integer) — Set to 0 to exclude total_results and improve performance by ~20%. Pagination continues until returned items < limit. Allowed: `0`, `20`, `100`, `2000`.
- `warehouse_id` (query, integer)
- `purchase_order_id` (query, integer)
- `document_type` (query, string) Allowed: `purchase_order`, `return`, `warehouse_movement`, `none`.
- `merchant_id` (query, string) — Merchant ID. Use `to_list:1,2,3` for multiple.
- `owner_id` (query, integer) — User ID that received/owns the incoming-goods record.
- `sequence_number` (query, string) — Exact match, e.g. `IG-0000017`.
- `start_date` (query, string) — Filters by `inserted_at`, on/after this timestamp. Must be a full `YYYY-MM-DDTHH:MM:SS` date-time — a bare `YYYY-MM-DD` date returns a 500 error.
- `end_date` (query, string) — Filters by `inserted_at`, on/before this timestamp. Same format requirement as `start_date`.

Responses:
- 200: Incoming-goods records retrieved
- 401: Unauthorized - invalid or missing token

### POST /reception/bulk/purchase_orders — Create purchase orders in bulk

operationId: `bulkCreatePurchaseOrders`

Creates multiple purchase orders for incoming goods.

**Order Types:**
- `purchase_order`: Standard incoming goods (default)
- `return`: Customer returns (see Returns section for full workflow)
- `warehouse_movement`: Stock transfer from another warehouse

**Workflow:**
1. Create purchase order via API
2. Warehouse receives goods (Android app)
3. Webhook `purchase_order_finished` fires (Goods Receipt)
4. Webhook `replenishment_order_finished` fires (stock available)

**Important:**
- Products and suppliers must exist before creating PO
- Use `product_sku` OR `product_id` in items
- `delivery_date` should be in format YYYY-MM-DDTHH:MM:SS

**For Returns:**
- Set `type: return`
- Include `sales_order_id` referencing the original order
- Use the **customer** (type=C) as `third_party_id` (the customer becomes the "supplier" of returned goods)
- For batch-controlled products, include batch/lot numbers in `items[].batches` array
- Use the shipment tracking code as `order_num` for traceability

**Recommended batch size:** up to 50 orders per request.

Request body (array of object):
- `type` (string, required) — Order type Allowed: `purchase_order`, `warehouse_movement`, `return`.
- `order_num` (string, required) — Your external order number
- `delivery_date` (string, required) — Expected delivery date (YYYY-MM-DDTHH:MM:SS)
- `warehouse_id` (integer, required) — Receiving warehouse
- `merchant_id` (integer, required) — Merchant receiving goods
- `merchant_channel_id` (integer) — Optional channel
- `third_party_id` (integer, required) — Supplier ID (type=S) for purchase orders. For **returns**: use the customer ID (type=C) — the customer becomes the "supplier" of returned goods.
- `sales_order_id` (integer) — Required when `type=return`. The ID of the original sales order being returned. Retrieve this from `GET /sales/orders/{id}` or from the original order creation response.
- `notes` (string) — Order notes
- `criterium` (string) — Custom sorting/routing criteria
- `attributes` (object) — Custom attributes
- `items` (array of object, required)
  - `product_id` (integer) — PULPO product ID (use this OR product_sku)
  - `product_sku` (string) — Product SKU (use this OR product_id)
  - `requested_quantity` (integer, required) — Quantity to receive
  - `line_item_number` (string) — Line number in source system
  - `batches` (array of object) — Batch info for lot/serial managed products
    - `batch_number` (string)
    - `expiration_date` (string)
    - `quantity` (integer)
- `packagings` (array of object) — Optional physical loading units (pallets, boxes, bags, bins, mixed containers) describing how the order physically arrives. See the [Loading units](/guide/loading-units) guide page for the full model, nesting rules, and worked examples.
  - `line_item_number` (string, required) — Must match a `line_item_number` in `items`. Ties this unit to one order line (SKU).
  - `barcode` (string, required) — Identifier of the physical unit. Unique per unit — except a `mix_container`, which repeats the same barcode once per SKU it holds.
  - `barcode_agency` (string) — Source of the barcode, e.g. `custom` for your own barcodes.
  - `packaging_type` (string, required) Allowed: `bag`, `bin`, `box`, `pallet`, `mix_container`.
  - `packaging_level` (integer, required) — Nesting depth. `0` is the outermost unit, sitting directly at a warehouse location. Levels must be contiguous from `0` for a given `line_item_number` — a level-2 unit requires levels 0 and 1 to exist too, chained via `location_level_barcode`.
  - `location_level_barcode` (string) — `barcode` of the parent unit one level up (same SKU). `null` at level `0`.
  - `quantity_in_package` (integer, required) — Units of this line's SKU contained in the unit. A parent's quantity equals the sum of its children.
  - `dimensions_width` (number) — Width of the unit.
  - `dimensions_height` (number) — Height of the unit.
  - `dimensions_length` (number) — Length of the unit.
  - `dimensions_weight` (number) — Weight of the unit (named with the `dimensions_` prefix).

Responses:
- 201: Purchase orders processed. Check `created` for the ones that succeeded and `errors` for the ones that didn't.
- 400: All items failed validation — none were created.
- 401: Unauthorized - invalid or missing token

### POST /reception/incoming_goods — Record a receiving event

operationId: `createIncomingGood`

Records goods received — normally against a purchase order (or return PO), but
also usable for unplanned receiving with `document_type: none` and no
`purchase_order_id`. Multiple `incoming_goods` records can be created per PO for
partial receipts; the `purchase_order_finished` webhook fires once cumulative
quantities equal the requested quantities.

There is no endpoint to delete or cancel an incoming-goods record once created.

**Per-item outcomes**

Each item carries a `state` — `accepted` or `rejected` — and a
`destination_location_id` that routes the physical units accordingly (storage
vs return locations). Rejected items should carry `reason_codes`.

Request body (object):
- `warehouse_id` (integer, required)
- `third_party_id` (integer) — Supplier (PO) or customer (return)
- `purchase_order_id` (integer) — Required when receiving against a PO/return
- `document_type` (string, required) — `none` = unplanned receiving without a PO Allowed: `purchase_order`, `return`, `warehouse_movement`, `none`.
- `merchant_id` (integer)
- `merchant_channel_id` (integer)
- `owner_id` (integer) — User performing the receipt. Required for the `owner` field to be populated on the returned record.
- `start_date` (string, required) — When receiving began (YYYY-MM-DDTHH:MM:SS)
- `end_date` (string, required) — When receiving completed
- `notes` (string)
- `reason_codes` (array of object) — Order-level reason codes. Rejected items more commonly carry their own.
  - `reason_code` (string)
- `items` (array of object, required)
  - `product_id` (integer) — Use this OR `product_sku`
  - `product_sku` (string)
  - `quantity` (integer, required)
  - `state` (string, required) — Inspection outcome for this line Allowed: `accepted`, `rejected`.
  - `destination_location_id` (integer, required) — Storage/reception location for accepted units, return/rejection location for rejected units.
  - `batch_id` (integer) — Required for batch-controlled products
  - `reason_codes` (array of object) — Reason(s) for a rejected item.
    - `reason_code` (string)
  - `temp_id` (string) — Optional client-generated identifier (e.g. a UUID) to correlate this item across your own request/response handling. Not persisted or echoed back.
  - `notes` (string)

Responses:
- 201: Receiving event recorded
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

### DELETE /reception/purchase_orders/{id} — Cancel/delete a purchase order

operationId: `deletePurchaseOrder`

Cancels a purchase order that hasn't been received yet. This **is** available
via the API — despite older guidance suggesting cancellation was warehouse-only,
`DELETE` on a `queue`-state order removes it and it no longer appears in
`GET /reception/purchase_orders` searches.

Orders that have already started receiving are not expected to be
cancellable this way — this hasn't been verified against every state.

Parameters:
- `id` (path, integer, required)

Responses:
- 200: Purchase order deleted/cancelled.
- 401: Unauthorized - invalid or missing token
- 422: Invalid ID, or the order's state doesn't allow cancellation.

## Sales Orders

**Outgoing Orders and Fulfillment**

Sales orders represent outgoing goods from the warehouse. They go through a defined
state machine from creation to completion.

**Sales Order vs Fulfillment Order**

A **sales order** is the customer-facing order. A **fulfillment order** is the
execution unit inside the warehouse — typically there is one fulfillment order per
sales order, but a sales order may be split into multiple fulfillment orders
(e.g., partial fulfillment, multi-warehouse).

Picking tasks operate on **fulfillment_order IDs**, not sales order IDs.

The `paused` state lives on the **fulfillment order** (`fulfillment_orders[0].state`).
The parent sales order remains in `state: queue` while a fulfillment order is paused.
Clients should derive the effective UI state as
`fulfillment_orders[0].state || sales_order.state`.

**Order State Flow**

```
queue ──→ picking ──→ packing ──→ shipping ──→ ended
  │                                              ✗ (cannot cancel)
  ├──→ paused (on FO) ──→ queue (resume)
  │
  ├──→ cancelled (from queue)
  │
picking ──→ cancelled (if packing locations available)
  │
packing ──→ cancelled
```

**State Descriptions**

| State | Description |
|-------|-------------|
| `queue` | Order created, waiting to be picked |
| `picking` | Items are being picked in the warehouse |
| `packing` | Items are being packed into boxes |
| `shipping` | Packed and ready for shipment |
| `ended` | Order fully fulfilled (Post Goods Issue / PGI) |
| `paused` | Temporarily held — applied to the **fulfillment order**, not the sales order |
| `cancelled` | Order cancelled — cannot cancel from `ended` |

**Priority Levels**

| Value | Level |
|-------|-------|
| 1 | Low |
| 2 | Normal |
| 3 | High |
| 4 | Top |

**Common Filter Operators**

Sales order list endpoints accept these operator-prefixed filter values:

| Operator | Example | Meaning |
|----------|---------|---------|
| `between:` | `delivery_date=between:2024-03-01 00:00:00,2024-03-31 23:59:59` | Date range (inclusive) |
| `gte:` / `lte:` | `inserted_at=gte:2024-03-01 00:00:00` | Greater/less than or equal |
| `gt:` / `lt:` | `order_items_count=gt:5` | Strictly greater/less |
| `to_list:` | `merchant_id=to_list:69,70,71` | Match any of the listed values |
| `includes:` | `product_id=includes:123,456` | Order contains any of these products |
| `contains:` | `order_num=contains:SO-2024` | Substring match |

The `to_list:` operator works on `merchant_id`, `priority`, `criterium`, and most
ID-style filters, not just `priority`.

### GET /sales/orders — Search sales orders

operationId: `searchSalesOrders`

Searches and filters sales orders with pagination. Supports a wide range of filters
for querying orders by state, date, customer, product, and more.

**Possible states** (fixed, managed by PULPO): `queue`, `picking`, `packing`,
`shipping`, `ended`, `cancelled`. A paused order is not a sales order state — it
shows as `paused` on `fulfillment_orders[].state` while the sales order stays in
`queue`.

**Date filters** support range queries:
- `between:2024-01-01 00:00:00,2024-03-31 23:59:59`
- `gte:2024-01-01 00:00:00` (greater than or equal)
- `lte:2024-03-31 23:59:59` (less than or equal)

**Numeric filters** (order_items_count, volume, weight):
- `gte:value`, `gt:value`, `lte:value`, `lt:value`

**Product filters:**
- `product_id=123` — orders containing this product
- `product_id=includes:123,456` — orders containing any of these products
- `not_product_id=123` — orders NOT containing this product

**Priority filters:**
- `priority=2` — single priority
- `priority=to_list:1,2,3` — multiple priorities

**Performance tip:** Use `view_attributes=id,order_num,state` to return only specific fields.

Parameters:
- `state` (query, string) — Filter by order state Allowed: `queue`, `picking`, `packing`, `shipping`, `ended`, `cancelled`.
- `order_num` (query, string) — Filter by external order number
- `warehouse_id` (query, integer) — Filter by warehouse ID
- `merchant_id` (query, string) — Filter by merchant ID. Use `to_list:1,2,3` for multiple.
- `third_party_id` (query, integer) — Filter by customer/third party ID
- `client_id` (query, string) — Filter by customer client ID
- `product_id` (query, string) — Orders containing this product. Use `includes:id1,id2` for multiple.
- `not_product_id` (query, string) — Orders NOT containing this product
- `priority` (query, string) — Filter by priority. Use `to_list:1,2` for multiple.
- `channel` (query, string) — Filter by sales channel
- `inserted_at` (query, string) — Creation date filter (format: YYYY-MM-DD hh:mm:ss). Supports `between:`, `gte:`, `lte:`
- `updated_at` (query, string) — Last update filter (format: YYYY-MM-DD hh:mm:ss). Supports `between:`, `gte:`, `lte:`
- `delivery_date` (query, string) — Delivery date filter. Supports `between:`, `gte:`, `lte:`
- `order_items_count` (query, string) — Filter by number of line items. Supports `gte:`, `gt:`, `lte:`, `lt:`
- `estimated_total_weight` (query, string) — Filter by total weight. Supports `gte:`, `gt:`, `lte:`, `lt:`
- `estimated_total_volume` (query, string) — Filter by total volume. Supports `gte:`, `gt:`, `lte:`, `lt:`
- `order_products_qty` (query, string) — Filter by total product quantity. Supports `gte:`, `gt:`, `lte:`, `lt:`
- `criterium` (query, string) — Filter by criterium. Use `to_list:` for multiple.
- `return_label` (query, string) — Filter by return label code
- `product_category_id` (query, string) — Orders with products matching category ID
- `view_attributes` (query, string) — Comma-separated list of fields to return (e.g. `id,order_num,state`). No associations supported.
- `id` (query, string) — Filter by sales order ID
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip
- `sort_by` (query, string) — Sort field and direction (field:asc or field:desc)
- `capped_limit` (query, integer) — Set to 0 to exclude total_results and improve performance by ~20%. Pagination continues until returned items < limit. Allowed: `0`, `20`, `100`, `2000`.

Responses:
- 200: Sales orders retrieved
- 401: Unauthorized - invalid or missing token

### GET /sales/orders/{id} — Get sales order by ID

operationId: `getSalesOrder`

Retrieves detailed information about a specific sales order by its PULPO ID.

**Use cases:**
- Get order details for creating a return purchase order
- Check current order state and fulfillment status
- Retrieve product list, quantities, and batch information
- Get the `third_party_id` (customer) needed for return orders

**Response includes:**
- Order metadata (state, dates, merchant info)
- Items with product IDs, SKUs, and quantities
- Ship-to address and customer details
- Shipment instructions and tracking info
- Batch/lot information for batch-controlled products

**Possible states** (fixed, managed by PULPO): `queue`, `picking`, `packing`,
`shipping`, `ended`, `cancelled`. A paused order shows as `paused` on
`fulfillment_orders[].state`, not on the sales order.

Parameters:
- `id` (path, integer, required) — Sales order ID

Responses:
- 200: Sales order retrieved successfully
- 401: Unauthorized - invalid or missing token
- 404: Resource not found

### GET /sales/orders/fulfillments — Search fulfillment orders

operationId: `searchFulfillmentOrders`

Lists fulfillment orders. Use it to read the `fulfillment_orders[].id` values
for picking, and to poll `process_information` after an asynchronous turbo
label picking request.

**Polling turbo label picking:**
`GET /sales/orders/fulfillments?view_attributes=id,order_num,sequence_number,process_information&id=to_list:14619148,14619149`
— repeat until every `process_information.status` is `turbo_label_created` or
`error_creating_picking`.

Only trust a status whose `attributes.request_id` equals the `x-request-id`
response header of your turbo call. `process_information` keeps the result of the
previous run — including after its picklist was deleted — until a new run starts.

`total_results` is `null` when `offset` is greater than 0.

Parameters:
- `id` (query, string) — One ID, or several with `to_list:` (e.g. `to_list:14619148,14619149`)
- `sales_order_id` (query, integer)
- `order_num` (query, string)
- `state` (query, string)
- `view_attributes` (query, string) — Comma-separated list of fields to return
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip

Responses:
- 200: Fulfillment orders retrieved
- 401: Unauthorized - invalid or missing token

### GET /sales/orders/{id}/returns — Get returns for a sales order

operationId: `getSalesOrderReturns`

Returns the return data associated with a specific sales order.

**Use cases:**
- Check if a sales order has any associated return purchase orders
- Get details of returned products and quantities
- Verify return status before creating a new return

This is useful to avoid creating duplicate returns and to track
the return history of an order.

Parameters:
- `id` (path, integer, required) — Sales order ID

Responses:
- 200: Return data retrieved successfully
- 401: Unauthorized - invalid or missing token
- 404: Resource not found

### GET /shipping/shipping_methods — Search shipping methods

operationId: `searchShippingMethods`

Lists the shipping methods the user can access. Use it to find the `id` you send
as `shipping_method_id` when creating sales orders.

**Filters** (`name`, `carrier`, `merchant_id`, `merchant_channel_id`) are exact
and case-sensitive matches: `name=FedEx` finds "FedEx", `name=fedex` and
`name=Fed` find nothing. Filters combine with AND. There is no `service` filter.

`total_results` is `null` when `offset` is greater than 0.

Parameters:
- `name` (query, string) — Exact shipping method name (case-sensitive)
- `carrier` (query, string) — Exact carrier (case-sensitive)
- `merchant_id` (query, integer) — Only methods of this merchant
- `merchant_channel_id` (query, integer) — Only methods of this merchant channel
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip
- `sort_by` (query, string) — Sort field and direction (field:asc or field:desc)

Responses:
- 200: Shipping methods retrieved
- 401: Unauthorized - invalid or missing token

### GET /shipping/shipping_methods/{id} — Get shipping method by ID

operationId: `getShippingMethod`

Returns one shipping method by its PULPO ID.

Parameters:
- `id` (path, integer, required) — Shipping method ID

Responses:
- 200: Shipping method retrieved
- 401: Unauthorized - invalid or missing token
- 422: Unknown ID, or the shipping method belongs to a merchant the user cannot access.

### POST /sales/bulk/orders — Create sales orders in bulk

operationId: `bulkCreateSalesOrders`

Creates multiple sales orders for outgoing fulfillment.

**Order Types:**
- `sales_order`: Standard outgoing order (default)
- `warehouse_movement`: Transfer to another warehouse
- `return`: Return to supplier
- `POS_external`: Direct stock reduction (no picking/packing)

**Workflow:**
1. Create sales order via API
2. Warehouse picks items (Android app)
3. Webhook `packing_order_finished` fires (Picking Complete)
4. Warehouse packs items (Android app)
5. Webhook `sales_order_finished` fires (Post Goods Issue)

**Customer:** `third_party_id` is required — create the customer first via
`POST /iam/bulk/third_parties` (type=C), then pass its `id` here.

**Priorities:** required. 1=low, 2=normal, 3=high, 4=top — send `1` if you
don't have a use case for it.

**Recommended batch size:** up to 50 orders per request.

Request body (array of object):
- `type` (string, required) — Order type Allowed: `sales_order`, `warehouse_movement`, `return`, `POS_external`.
- `order_num` (string, required) — Your external order number (must be unique)
- `delivery_date` (string, required) — Required delivery date (YYYY-MM-DDTHH:MM:SS)
- `warehouse_id` (integer, required) — Fulfilling warehouse
- `merchant_id` (integer, required) — Merchant fulfilling order
- `merchant_channel_id` (integer, required) — Sales channel (required)
- `third_party_id` (integer, required) — Customer ID (type=C third party). Create the customer first via `POST /iam/bulk/third_parties`, then pass its `id` here.
- `identifier_number` (string) — Customer external ID reference
- `identifier_type` (string) — ID type (defaults to CUSTOMER_ID if omitted)
- `priority` (integer, required) — 1=low, 2=normal, 3=high, 4=top. If you don't have a use case for order priority, send `1`.
- `shipping_method_id` (integer) — PULPO ID of the shipping method. The shipping method must already exist — create it with `POST /shipping/shipping_methods` and look it up with `GET /shipping/shipping_methods`. An unknown ID makes the whole request fail with `500 Internal Server Error`.
- `destination_warehouse_id` (integer) — Required if type=warehouse_movement
- `notes` (string) — Order notes
- `criterium` (string) — Custom routing criteria
- `is_cart` (boolean) — Shopping cart mode
- `ship_to` (object, required)
  - `name` (string, required) — Recipient name
  - `company_name` (string) — Company name
  - `phone_number` (string) — Phone number with country code
  - `address` (object, required)
    - `street` (string)
    - `house_nr` (string)
    - `city` (string)
    - `state` (string)
    - `zip` (string)
    - `country` (string) — ISO 2-letter country code
    - `country_code` (string) — ISO numeric country code
    - `email` (string)
    - `additional_info` (string)
- `items` (array of object, required)
  - `product_id` (integer) — PULPO product ID (use this OR product_sku)
  - `product_sku` (string) — Product SKU (use this OR product_id)
  - `quantity` (integer, required) — Quantity to fulfill
  - `line_order_id` (string) — Line number in source system
  - `required_date` (string) — Item-specific required date
  - `attributes` (object) — Custom line item attributes
- `attributes` (object) — Custom attributes

Responses:
- 201: Sales orders processed. Check `created` for the orders that succeeded and `errors` for the ones that didn't.
- 400: All items failed validation — none were created.
- 401: Unauthorized - invalid or missing token

### POST /sales/bulk/orders/quick — Create POS orders (instant stock reduction)

operationId: `bulkCreateQuickOrders`

Creates sales orders of type `POS_external` that immediately reduce stock without
going through picking/packing processes.

**Use cases:**
- Point of sale transactions
- Direct sales from warehouse
- Stock adjustments via sales

**Behavior:**
- Order status immediately changes to "finished"
- Stock is reduced instantly
- No picking or packing tasks created
- Webhook `sales_order_finished` fires immediately

Despite the instant-fulfillment behavior, `delivery_date` is still required
by the schema — send the current time if you don't have a real one.

**Recommended batch size:** up to 50 orders per request.

Request body (array of object):
- `type` (string, required) — Order type Allowed: `sales_order`, `warehouse_movement`, `return`, `POS_external`.
- `order_num` (string, required) — Your external order number (must be unique)
- `delivery_date` (string, required) — Required delivery date (YYYY-MM-DDTHH:MM:SS)
- `warehouse_id` (integer, required) — Fulfilling warehouse
- `merchant_id` (integer, required) — Merchant fulfilling order
- `merchant_channel_id` (integer, required) — Sales channel (required)
- `third_party_id` (integer, required) — Customer ID (type=C third party). Create the customer first via `POST /iam/bulk/third_parties`, then pass its `id` here.
- `identifier_number` (string) — Customer external ID reference
- `identifier_type` (string) — ID type (defaults to CUSTOMER_ID if omitted)
- `priority` (integer, required) — 1=low, 2=normal, 3=high, 4=top. If you don't have a use case for order priority, send `1`.
- `shipping_method_id` (integer) — PULPO ID of the shipping method. The shipping method must already exist — create it with `POST /shipping/shipping_methods` and look it up with `GET /shipping/shipping_methods`. An unknown ID makes the whole request fail with `500 Internal Server Error`.
- `destination_warehouse_id` (integer) — Required if type=warehouse_movement
- `notes` (string) — Order notes
- `criterium` (string) — Custom routing criteria
- `is_cart` (boolean) — Shopping cart mode
- `ship_to` (object, required)
  - `name` (string, required) — Recipient name
  - `company_name` (string) — Company name
  - `phone_number` (string) — Phone number with country code
  - `address` (object, required)
    - `street` (string)
    - `house_nr` (string)
    - `city` (string)
    - `state` (string)
    - `zip` (string)
    - `country` (string) — ISO 2-letter country code
    - `country_code` (string) — ISO numeric country code
    - `email` (string)
    - `additional_info` (string)
- `items` (array of object, required)
  - `product_id` (integer) — PULPO product ID (use this OR product_sku)
  - `product_sku` (string) — Product SKU (use this OR product_id)
  - `quantity` (integer, required) — Quantity to fulfill
  - `line_order_id` (string) — Line number in source system
  - `required_date` (string) — Item-specific required date
  - `attributes` (object) — Custom line item attributes
- `attributes` (object) — Custom attributes

Responses:
- 201: Quick orders processed and fulfilled. Check `created` for the orders that succeeded and `errors` for the ones that didn't.
- 400: All items failed (validation error or insufficient stock).

### POST /sales/orders/{id}/cancel — Cancel a single sales order

operationId: `cancelSalesOrder`

Cancels a specific sales order by ID.

**Cancellation rules:**
- Orders in state `ended` **cannot** be cancelled
- Orders in state `picking` cannot be cancelled when no packing locations are available
- The result depends on current state:
  - `queue` → cancelled immediately
  - `picking` → picking cancelled, items returned to stock
  - `packing` → packing cancelled, items returned to stock

Parameters:
- `id` (path, integer, required) — Sales order ID

Responses:
- 200: Sales order cancelled
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

### POST /sales/bulk/orders/cancel — Cancel sales orders in bulk

operationId: `bulkCancelSalesOrders`

Cancels multiple sales orders. Supports multiple payload formats for flexibility.

**Payload formats:**
- Array of objects with `order_num`: `[{"order_num": "SO-001"}, ...]`
- Array of order numbers: `["SO-001", "SO-002", ...]`
- Array of objects with `id`: `[{"id": 123}, ...]`
- Array of IDs: `[123, 456, ...]`

**Cancellation rules:**
- Orders in state `ended` **cannot** be cancelled
- Orders in state `picking` cannot be cancelled when there are no available packing locations
- The cancellation action depends on the current order state:
  - `queue` → cancelled immediately
  - `picking` → picking task cancelled, items returned
  - `packing` → packing task cancelled, items returned

**Recommended batch size:** up to 50 orders per request.

Request body (array of object | array of string | array of integer):
- (no documented fields)

Responses:
- 200: Sales orders processed. Check `updated` for the orders that were cancelled and `errors` for the ones that weren't.
- 401: Unauthorized - invalid or missing token
- 422: All items failed (e.g. unknown order, or state doesn't allow cancellation).

### POST /sales/orders/{id}/pause — Pause a single sales order

operationId: `pauseSalesOrder`

Pauses a sales order. Only orders in state `queue` can be paused.
Paused orders are not available for picking.

Parameters:
- `id` (path, integer, required) — Sales order ID

Responses:
- 200: Sales order paused
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

### POST /sales/bulk/orders/pause — Pause sales orders in bulk

operationId: `bulkPauseSalesOrders`

Pauses multiple sales orders. Only orders in state `queue` can be paused.

**Payload formats** (same as cancel):
- `[{"order_num": "SO-001"}, ...]`
- `["SO-001", ...]`
- `[{"id": 123}, ...]`
- `[123, ...]`

Paused orders will not be picked until resumed.

**Recommended batch size:** up to 50 orders per request.

Request body (array of object | array of string | array of integer):
- (no documented fields)

Responses:
- 200: Sales orders processed. Check `updated` for the orders that were paused and `errors` for the ones that weren't.
- 401: Unauthorized - invalid or missing token

### POST /sales/orders/{id}/resume — Resume a paused sales order

operationId: `resumeSalesOrder`

Resumes a paused sales order. Only orders in state `paused` can be resumed.
The order returns to `queue` state and becomes available for picking.

Parameters:
- `id` (path, integer, required) — Sales order ID

Responses:
- 200: Sales order resumed
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

### POST /sales/bulk/orders/resume — Resume sales orders in bulk

operationId: `bulkResumeSalesOrders`

Resumes previously paused sales orders. Only orders in state `paused` can be resumed.
Resumed orders return to `queue` state and become available for picking.

**Payload formats** (same as cancel/pause):
- `[{"order_num": "SO-001"}, ...]`
- `["SO-001", ...]`
- `[{"id": 123}, ...]`
- `[123, ...]`

**Recommended batch size:** up to 50 orders per request.

Request body (array of object | array of string | array of integer):
- (no documented fields)

Responses:
- 200: Sales orders processed. Check `updated` for the orders that were resumed and `errors` for the ones that weren't.
- 401: Unauthorized - invalid or missing token

### POST /sales/orders/{id}/attach — Attach a file to a sales order

operationId: `attachFileToSalesOrder`

Uploads one file (for example a delivery note) and attaches it to the sales order.
Send it as `multipart/form-data`. Each call adds a new attachment — uploading the
same file twice creates two attachments.

**`type`** — one of `document`, `label`, `photo` or `undefined`. Left out or empty,
it is stored as `undefined`. Any other value is rejected.

**`document_type`** — only allowed with `type=document`. It is free text and stored
exactly as sent (no fixed list, case is kept), for example `delivery_note` or
`invoice`. Sending it with any other `type` is rejected.

**Files:** PDF and images (PNG tested) are accepted, plain text files are rejected.

Attachments can be added in any order state, including `ended`. They are returned
in `attachments[]` when you fetch or search the sales order.

Parameters:
- `id` (path, integer, required) — Sales order ID

Request body (object):
- `attachment` (string, required) — The file to upload (PDF or image).
- `type` (string) Allowed: `document`, `label`, `photo`, `undefined`.
- `document_type` (string) — Free text, only with `type=document`. Example `delivery_note`.
- `filename` (string) — Name to store instead of the uploaded file's name.

Responses:
- 201: File attached. The body is the full sales order (same shape as `GET /sales/orders/{id}`) including the new entry in `attachments[]`.
- 400: Invalid `type`, `document_type` without `type=document`, or a missing or unsupported file.
- 401: Unauthorized - invalid or missing token
- 422: Unknown sales order ID.

### POST /shipping/shipping_methods — Create a shipping method

operationId: `createShippingMethod`

Creates one shipping method. Only `name` is required, and it must be unique within
the merchant.

If `merchant_id` and `merchant_channel_id` are left out, the method is created for
the user's own merchant and channel.

Request body (object):
- `name` (string, required) — Must be unique within the merchant.
- `carrier` (string)
- `service` (string)
- `fetch_label` (boolean)
- `merchant_id` (integer)
- `merchant_channel_id` (integer)

Responses:
- 201: Shipping method created
- 400: Validation failed — missing or duplicate name.
- 401: Unauthorized - invalid or missing token

### PUT /sales/orders/{id} — Update a single sales order

operationId: `updateSalesOrder`

Updates an individual sales order by ID. Use this when editing one order
with a partial payload — for batch updates, use `PUT /sales/bulk/orders`.

**Editable fields**

- `notes`
- `priority` (1=low, 2=normal, 3=high, 4=top)
- `delivery_date`
- `items` — replaces the full line-item list; each item may include `id`
  (to match an existing line), `product_id`, and `quantity`
- `ship_to` — when only the address changes for an in-flight order, prefer
  `PATCH /fulfillment_orders/{id}/ship_to` (the address actually used by
  shipping)

**Edit window**

Updates are rejected when the order is in `picking`, `in_picking`, `packing`,
`in_packing`, `packed`, `ended`, or `cancelled` states. Clients should
gate the edit UI on these states.

Parameters:
- `id` (path, integer, required)

Request body (object):
- `notes` (string)
- `priority` (integer)
- `delivery_date` (string)
- `items` (array of object)
  - `id` (integer) — Existing line ID (omit to add a new line)
  - `product_id` (integer)
  - `quantity` (integer)
- `ship_to` (object)
  - `name` (string, required) — Recipient name
  - `company_name` (string) — Company name
  - `phone_number` (string) — Phone number with country code
  - `address` (object, required)
    - `street` (string)
    - `house_nr` (string)
    - `city` (string)
    - `state` (string)
    - `zip` (string)
    - `country` (string) — ISO 2-letter country code
    - `country_code` (string) — ISO numeric country code
    - `email` (string)
    - `additional_info` (string)

Responses:
- 200: Sales order updated
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token
- 404: Resource not found

### PUT /sales/bulk/orders — Update sales orders in bulk

operationId: `bulkUpdateSalesOrders`

Updates multiple existing sales orders. Works as bulk — if any update fails,
the remaining orders continue processing. This is a partial update — send
only the fields you want to change, plus an identifier.

**Updatable fields:**
- `order_num`: External order number
- `delivery_date`: Delivery date
- `priority`: Order priority (1=low, 2=normal, 3=high, 4=top)
- `ship_to`: Shipping address
- `notes`: Order notes
- `items`: Order line items (replaces existing items)
- `shipping_method_id`: Shipping method
- `attributes`: Custom attributes

**Important:**
- Orders must be identified by `order_num` or `id`
- Orders in state `ended` or `cancelled` cannot be updated
- Updating items replaces the full item list
- Updating `attributes` replaces the whole object — keys you leave out are
  deleted, so resend every key you want to keep

**Recommended batch size:** up to 50 orders per request.

Request body (array of object):
- `type` (string, required) — Order type Allowed: `sales_order`, `warehouse_movement`, `return`, `POS_external`.
- `order_num` (string, required) — Your external order number (must be unique)
- `delivery_date` (string, required) — Required delivery date (YYYY-MM-DDTHH:MM:SS)
- `warehouse_id` (integer, required) — Fulfilling warehouse
- `merchant_id` (integer, required) — Merchant fulfilling order
- `merchant_channel_id` (integer, required) — Sales channel (required)
- `third_party_id` (integer, required) — Customer ID (type=C third party). Create the customer first via `POST /iam/bulk/third_parties`, then pass its `id` here.
- `identifier_number` (string) — Customer external ID reference
- `identifier_type` (string) — ID type (defaults to CUSTOMER_ID if omitted)
- `priority` (integer, required) — 1=low, 2=normal, 3=high, 4=top. If you don't have a use case for order priority, send `1`.
- `shipping_method_id` (integer) — PULPO ID of the shipping method. The shipping method must already exist — create it with `POST /shipping/shipping_methods` and look it up with `GET /shipping/shipping_methods`. An unknown ID makes the whole request fail with `500 Internal Server Error`.
- `destination_warehouse_id` (integer) — Required if type=warehouse_movement
- `notes` (string) — Order notes
- `criterium` (string) — Custom routing criteria
- `is_cart` (boolean) — Shopping cart mode
- `ship_to` (object, required)
  - `name` (string, required) — Recipient name
  - `company_name` (string) — Company name
  - `phone_number` (string) — Phone number with country code
  - `address` (object, required)
    - `street` (string)
    - `house_nr` (string)
    - `city` (string)
    - `state` (string)
    - `zip` (string)
    - `country` (string) — ISO 2-letter country code
    - `country_code` (string) — ISO numeric country code
    - `email` (string)
    - `additional_info` (string)
- `items` (array of object, required)
  - `product_id` (integer) — PULPO product ID (use this OR product_sku)
  - `product_sku` (string) — Product SKU (use this OR product_id)
  - `quantity` (integer, required) — Quantity to fulfill
  - `line_order_id` (string) — Line number in source system
  - `required_date` (string) — Item-specific required date
  - `attributes` (object) — Custom line item attributes
- `attributes` (object) — Custom attributes

Responses:
- 200: Sales orders processed. Check `updated` for the orders that succeeded and `errors` for the ones that didn't.
- 401: Unauthorized - invalid or missing token
- 422: All items failed (e.g. unknown order, or state doesn't allow updates).

### PUT /shipping/bulk/shipping_methods — Bulk create or update shipping methods

operationId: `bulkUpsertShippingMethods`

Creates or updates several shipping methods in one call. The body is a plain JSON
array (not wrapped in an object).

**Matching:** each entry is matched to an existing method by `name` within the
merchant. A match is updated, otherwise a new method is created. `id` in the body is
ignored, so a method cannot be renamed through this endpoint.

**Always send `merchant_id` and `merchant_channel_id`.** Unlike the single create,
a new method created here without them gets no merchant. It then doesn't appear
in searches, can't be fetched or deleted by the user, and later calls with the same
name create further duplicates.

Partial success: valid entries are saved even when others fail. If any entry fails
the status is `422`, so always read both `created`/`updated` and `errors`.

Request body (array of object):
- `name` (string, required) — Must be unique within the merchant.
- `carrier` (string)
- `service` (string)
- `fetch_label` (boolean)
- `merchant_id` (integer)
- `merchant_channel_id` (integer)

Responses:
- 200: All entries saved.
- 400: Body is not a non-empty JSON array.
- 401: Unauthorized - invalid or missing token
- 422: At least one entry failed. Entries listed in `created`/`updated` were still saved.

### PATCH /fulfillment_orders/{id}/ship_to — Update the ship-to address on a fulfillment order

operationId: `updateFulfillmentOrderShipTo`

Updates the delivery address used during packing/shipping. This is the
endpoint to call when a label generation failure was caused by a bad
address — fix the address here, then retry label generation by calling
`PUT /packing/orders/{id}/boxes/{box_id}/shipment_tracking/{tracking_id}`
with `{ "retry": true }`.

Address changes via this endpoint do not propagate back to the parent
sales order's `ship_to`; use `PUT /sales/orders/{id}` or
`PUT /sales/bulk/orders` to persist the change there too.

Parameters:
- `id` (path, integer, required) — Fulfillment order ID

Request body (object):
- `name` (string, required) — Recipient name
- `company_name` (string) — Company name
- `phone_number` (string) — Phone number with country code
- `address` (object, required)
  - `street` (string)
  - `house_nr` (string)
  - `city` (string)
  - `state` (string)
  - `zip` (string)
  - `country` (string) — ISO 2-letter country code
  - `country_code` (string) — ISO numeric country code
  - `email` (string)
  - `additional_info` (string)

Responses:
- 200: Address updated
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token
- 404: Resource not found

### DELETE /sales/orders/{id}/attachments/{attachment_id} — Delete a sales order attachment

operationId: `deleteSalesOrderAttachment`

Removes one attachment from the sales order. Returns the full sales order without
the removed entry.

Parameters:
- `id` (path, integer, required) — Sales order ID
- `attachment_id` (path, string, required) — Attachment ID (UUID) from `attachments[].id`

Responses:
- 200: Attachment removed. The body is the full sales order.
- 401: Unauthorized - invalid or missing token
- 422: Unknown or already deleted attachment ID.

### DELETE /shipping/shipping_methods/{id} — Delete a shipping method

operationId: `deleteShippingMethod`

Permanently deletes a shipping method and returns the deleted record.

A shipping method that has ever been assigned to an order cannot be deleted —
this also applies when those orders are cancelled. The API then answers `422`
with a technical database message mentioning
`fulfillment_orders_shipping_method_id_fkey`.

Parameters:
- `id` (path, integer, required) — Shipping method ID

Responses:
- 200: Shipping method deleted. The body is the deleted record.
- 401: Unauthorized - invalid or missing token
- 422: Unknown ID, no access, or the method is used by orders.

## Picking

**Picking Tasks**

A picking task corresponds to one warehouse picker walking the floor with a
device. There are three picking strategies, all selectable when the task is
created:

| Strategy | Endpoint | Semantics |
|----------|----------|-----------|
| `single` | `POST /picking/bulk/orders` | One picking task **per** fulfillment_order |
| `batch` | `POST /picking/orders` (`cart: false`) | One picking task grouping multiple fulfillment_orders |
| `cart` | `POST /picking/orders` (`cart: true`) | Batch pick where each FO is placed in a separate cart slot |

Picking task creation always operates on **fulfillment_order IDs**, not sales
order IDs (see Sales Orders tag). Flatten `sales_order.fulfillment_orders[].id`
before posting.

**Picking Order States**

| State | Description |
|-------|-------------|
| `queue` | Created, awaiting a picker |
| `taken` | Claimed by a picker |
| `ended` | All items picked |
| `mixed` | Partially picked — some lines remain |
| `cancelled` | Cancelled, items returned to stock |

**Insufficient Stock Errors**

Both creation endpoints return a structured 400 (`/picking/bulk/orders`) or
422 (`/picking/orders`) when a fulfillment_order has insufficient stock for one
or more lines. See `PickingCreateError` schema. The `items[].insufficient_stock`
string identifies the failing product. The bulk endpoint additionally returns a
top-level `created[]` array with the picklists that were created.

The turbo label endpoints (`/picking/orders/turbo`, `/picking/bulk/orders/turbo`)
are asynchronous: errors appear in the fulfillment order's `process_information`.

### GET /picking/orders — List picking orders

operationId: `listPickingOrders`

Retrieves picking orders with filtering and pagination.

**Possible states** (fixed, managed by PULPO):
- `queue`: Waiting to be picked
- `taken`: Being picked
- `locked`: Remainder of a picking that was finished early with items missing
  (usually out of stock). The system creates it locked so it isn't picked again
  and again while stock is still missing — it must be unlocked manually before
  a picker can take it.
- `mixed`: Partially picked
- `ended`: Picking completed
- `cancelled`: Cancelled

**Useful filters:**
- `warehouse_id=140`
- `state=ended`
- `merchant_id=69`
- `sales_order_id=13283307` — picking history for a specific sales order
- `updated_at=between:2024-03-01 00:00:00,2024-03-31 23:59:59`

`sort_by` is not supported here — any value returns `500 Internal Server Error`.

Parameters:
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip
- `capped_limit` (query, integer) — Set to 0 to exclude total_results and improve performance by ~20%. Pagination continues until returned items < limit. Allowed: `0`, `20`, `100`, `2000`.
- `warehouse_id` (query, integer)
- `state` (query, string) Allowed: `queue`, `taken`, `locked`, `mixed`, `ended`, `cancelled`.
- `merchant_id` (query, integer)
- `sales_order_id` (query, integer) — Picking orders related to a specific sales order

Responses:
- 200: Picking orders retrieved

### POST /picking/orders — Create a batch or cart picklist

operationId: `createPickingOrder`

Creates **one** picklist that groups all given fulfillment orders. Use it for
**batch** picking (`cart: false`) and **cart** picking (`cart: true`). For one
picklist per order (standard picking), use `POST /picking/bulk/orders`.

| Request | Resulting picklist `type` |
|---------|---------------------------|
| several FOs, `cart: false` | `consolidated` |
| several FOs, `cart: true` | `cart_picking` |
| one FO, `cart: false` | `normal` |

**`orders_count`** splits the given fulfillment orders evenly over that many
picklists. Example: 4 FOs with `orders_count: 2` give 2 picklists with 2 FOs each.
These picklists get `type: normal`.

**`pickers`:** the first user ID becomes the picklist `owner`. Further IDs are
ignored. The picklist stays in `queue` until the picker starts it.

**All or nothing:** if any fulfillment order can't be picked (for example missing
stock or already on a picklist), no picklist is created and the call returns `422`.

**`delete_missing_stock_sales_items: true`** reduces lines without enough stock to
the available quantity, so the picklist can still be created. The sales order
keeps its original quantities.

`cart: true` does not change `is_cart` on the sales orders.

**Turbo label:** with `turbo_label: true` the picklist is created as a turbo label
picklist and the labels are generated **within this request** (synchronous, about
5 seconds per order on staging). For larger volumes use the asynchronous
`POST /picking/orders/turbo` instead.

Request body (object):
- `fulfillment_orders` (array of integer, required) — Fulfillment order IDs (`fulfillment_orders[].id` on the sales order)
- `cart` (boolean) — `true` = cart picking, `false` = batch picking
- `orders_count` (integer) — Split the fulfillment orders over this many picklists.
- `notes` (string) — Note shown on the picklist
- `pickers` (array of integer) — User ID to assign the picklist to. Only the first ID is used.
- `delete_missing_stock_sales_items` (boolean) — When `true`, lines without enough stock are reduced to the available quantity instead of failing the request.
- `turbo_label` (boolean) — Generate labels synchronously (see description).

Responses:
- 201: Picklist(s) created
- 400: `fulfillment_orders` missing or empty.
- 401: Unauthorized - invalid or missing token
- 422: Nothing was created. Unknown IDs, a fulfillment order that already has a picklist, or missing stock.

### POST /picking/orders/turbo — Create a turbo label batch picklist (asynchronous)

operationId: `createTurboPickingOrder`

Turbo label version of `POST /picking/orders`: **one** picklist for all given
fulfillment orders (`type: consolidated_turbo_label`, or `turbo_label` for a
single FO). Before picking starts, PULPO creates a draft packing order per sales
order and fetches the shipping labels.

**Asynchronous.** The call returns `204 No Content` immediately. The work runs in
the background and can take from seconds to minutes, because labels come from
external carrier systems. Track the result per fulfillment order with
`GET /sales/orders/fulfillments` and its `process_information`:

| `process_information.status` | Meaning |
|------------------------------|---------|
| `queue` | Waiting to be processed |
| `started` | Picklist created, labels being fetched. `value` = picklist number |
| `turbo_label_created` | Done. `value` = picklist number (e.g. `PI-0000095`) |
| `error_creating_picking` | Failed. See `errors`. The fulfillment order stays in `queue` and can be submitted again |

**Labels:** one packing box and label **per unit** in a draft packing order of
type `turbo_label`, one packing order per sales order.

**Not supported here:** `cart: true` and `turbo_label_per_order: true` both end in
`error_creating_picking`.

Unknown fulfillment order IDs are rejected synchronously with `422`. All other
errors (missing stock, already on a picklist) only show up in
`process_information`.

**Matching the status to your request:** the `x-request-id` header of the `204`
response equals `process_information.attributes.request_id` of the run it
started. Ignore statuses with a different `request_id` — they are left over from
an earlier run.

Request body (object):
- `fulfillment_orders` (array of integer, required)
- `cart` (boolean) — Must be `false`. Cart picking is not supported in turbo mode.
- `notes` (string)
- `pickers` (array of integer) — User ID to assign the picklist to. Only the first ID is used.
- `delete_missing_stock_sales_items` (boolean)
- `turbo_label` (boolean) — Ignored — this call always works in turbo mode.

Responses:
- 204: Accepted. Processing runs in the background — poll `process_information`.
- 400: `fulfillment_orders` missing or empty.
- 401: Unauthorized - invalid or missing token
- 422: Unknown fulfillment order ID. Nothing was started.

### POST /picking/bulk/orders/turbo — Create turbo label standard picklists (asynchronous)

operationId: `bulkCreateTurboPickingOrders`

Turbo label version of `POST /picking/bulk/orders`: **one** picklist per
fulfillment order (`type: turbo_label`). Before picking starts, PULPO creates a
draft packing order per sales order and fetches the shipping labels.

**Asynchronous.** The call returns `204 No Content` immediately. The work runs in
the background and can take from seconds to minutes, because labels come from
external carrier systems. Track the result per fulfillment order with
`GET /sales/orders/fulfillments` and its `process_information`:

| `process_information.status` | Meaning |
|------------------------------|---------|
| `queue` | Waiting to be processed |
| `started` | Picklist created, labels being fetched. `value` = picklist number |
| `turbo_label_created` | Done. `value` = picklist number (e.g. `PI-0000092`) |
| `error_creating_picking` | Failed. See `errors`. The fulfillment order stays in `queue` and can be submitted again |

Each fulfillment order is processed on its own — one can fail while the others
succeed.

**Labels:**
- Default: one packing box and label **per unit**.
- `turbo_label_per_order: true` with a `shipment_box_template_id`: **one** box and
  label for the whole order. Without a template ID this fails with
  `shipment_box_template_id_required_for_order_per_box_strategy`.

**Errors only show up in `process_information`** — the call itself always
returns `204` once the body is valid. Unknown fulfillment order IDs are silently
ignored.

**Matching the status to your request:** the `x-request-id` header of the `204`
response equals `process_information.attributes.request_id` of the run it
started. Ignore statuses with a different `request_id` — they are left over from
an earlier run.

Request body (object):
- `fulfillment_orders` (array of integer, required)
- `orders_count` (integer) — Accepted but has no effect on this call.
- `pickers` (array of integer)
- `notes` (string)
- `delete_missing_stock_sales_items` (boolean)
- `turbo_label` (boolean) — Ignored — this call always works in turbo mode.
- `turbo_label_per_order` (boolean) — One box and label per order instead of per unit. Requires `shipment_box_template_id`.
- `shipment_box_template_id` (integer) — Box template for `turbo_label_per_order` (from `GET /packing/boxes`).

Responses:
- 204: Accepted. Processing runs in the background — poll `process_information`.
- 400: `fulfillment_orders` missing or empty.
- 401: Unauthorized - invalid or missing token

### POST /picking/bulk/orders — Create standard picklists (one per order)

operationId: `bulkCreatePickingOrders`

Creates **one picklist per fulfillment order** (`type: normal`). Use this for
standard picking. For one picklist covering several orders, use
`POST /picking/orders`.

`orders_count` has no effect here — there is always one picklist per order.

**`pickers`:** the picklists are assigned to the given users in turn (first
picklist → first picker, second → second picker, …). Each becomes the picklist
`owner`; the picklist stays in `queue`.

**Partial success:** each fulfillment order is handled on its own. Those that
work are listed in `created`, the others in `errors`. If at least one fails, the
status is `400` — always read both lists. An unknown fulfillment order ID fails
the whole call with `422` and creates nothing.

**`delete_missing_stock_sales_items: true`** reduces lines without enough stock to
the available quantity, so the picklist can still be created. The sales order
keeps its original quantities.

**Turbo label:** with `turbo_label: true` the picklists are created as turbo label
picklists and the labels are generated **within this request** (synchronous,
about 5 seconds per order on staging). For larger volumes use the asynchronous
`POST /picking/bulk/orders/turbo` instead.

Request body (object):
- `fulfillment_orders` (array of integer, required)
- `orders_count` (integer) — Accepted but has no effect on this call.
- `pickers` (array of integer) — User IDs, assigned to the picklists in turn.
- `turbo_label` (boolean) — Generate labels synchronously (see description).
- `notes` (string) — Note shown on every created picklist
- `delete_missing_stock_sales_items` (boolean)

Responses:
- 201: All picklists created.
- 400: At least one fulfillment order failed. Entries in `created` were still created. Also returned when `fulfillment_orders` is missing or empty.
- 401: Unauthorized - invalid or missing token
- 422: An unknown fulfillment order ID was sent. Nothing was created.

### DELETE /picking/bulk/orders — Delete picklists in bulk

operationId: `bulkDeletePickingOrders`

Deletes several picklists in one call. The body is a plain JSON array of
picklist IDs (`picking_orders[].id`), not wrapped in an object.

**What happens to the orders:** the fulfillment orders and sales orders go back
to `queue` and can be put on a new picklist. Nothing is cancelled. For turbo label
picklists, the draft packing order and its labels are deleted too.

`process_information` on the fulfillment order is **not** reset — it still shows
the deleted picklist's number until a new turbo run starts.

**Partial success:** each ID is handled on its own. If at least one fails, the
status is `422` — read both `deleted` and `errors`.

Tested on picklists in `queue` only.

Request body (array of integer):
- (no documented fields)

Responses:
- 200: All picklists deleted.
- 400: Body is not a non-empty array of IDs.
- 401: Unauthorized - invalid or missing token
- 422: At least one ID failed (unknown or already deleted). Entries in `deleted` were still deleted.

### DELETE /picking/orders/{id} — Delete a picklist

operationId: `deletePickingOrder`

Deletes one picklist. Same effect as `DELETE /picking/bulk/orders` with a single
ID: the orders go back to `queue`, and turbo label packing orders are removed.
Returns the deleted picklist.

Parameters:
- `id` (path, integer, required) — Picklist ID

Responses:
- 200: Picklist deleted.
- 401: Unauthorized - invalid or missing token
- 422: Unknown or already deleted ID.

## Packing

**Packing Tasks**

A packing task is created by the system after picking completes. One packer
claims a task and works through its packing boxes until the order is ready to
ship.

**Packing Order State Machine**

```
queue ─accept─→ taken ─lock─→ locked
                 │ ↑           │
                 │ └─unlock────┘ (owner: → taken; non-owner: → queue)
                 │
                 └─finish─→ ended ─close─→ closed
```

| State | Description |
|-------|-------------|
| `queue` | Awaiting a packer |
| `taken` | Owned by a packer (see `owner.id`) |
| `locked` | Paused — kept by owner but not actively worked |
| `ended` | All boxes closed and `/finish` was called |
| `closed` | Final state — `/close` released the owner lock and assigned a shipping location |
| `cancelled` | Cancelled (terminal) |

**Ownership and "one task at a time"**

The authoritative ownership signal is `owner.id` on the packing order. A user
may only own one active (`taken` or `locked`) packing order at a time — call
`GET /iam/users/{id}/tasks` to discover the current owned task before opening
a new one. Paused (`locked`) tasks are NOT included in that endpoint's
response — they are queryable via `GET /packing/orders?state=locked`.

If a non-owner calls `POST /unlock` on a `locked` task, the task transitions
back to `queue` (not `taken`) — they must then call `POST /accept` to claim it.

**Polling After Box Close**

After triggering label generation, clients should poll `GET /packing/orders/{id}`
every ~5 seconds until each closed box has an `attachments[]` entry (the label PDF
URL) or `shipment_tracking.error_message` is set. The PULPO app gives up after
~2 minutes; client integrations should use the same budget (24 attempts).

The label readiness signal is the presence of `attachments[0].url` on the packing
box — **not** solely `shipment_tracking.status`.

### GET /packing/orders — List packing orders

operationId: `listPackingOrders`

Retrieves packing orders with filtering and pagination.

**Possible states** (fixed, managed by PULPO): `draft`, `queue`, `taken`,
`locked` (paused), `ended`, `closed`, `cancelled`.

Pass `state=locked` to retrieve paused packing orders — `locked` tasks are NOT
included in `GET /iam/users/{id}/tasks`, only in this list.

**Useful filters:**
- `warehouse_id`
- `state`
- `sales_order_id` — packing orders related to a specific sales order
- `view_attributes` — comma-separated field list (controls which nested
  attributes are returned; useful to keep payloads small for queue views)

**Performance:** pass `capped_limit=0` to skip the total-results count for
~20% lower latency.

Parameters:
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip
- `sort_by` (query, string) — Sort field and direction (field:asc or field:desc)
- `capped_limit` (query, integer) — Set to 0 to exclude total_results and improve performance by ~20%. Pagination continues until returned items < limit. Allowed: `0`, `20`, `100`, `2000`.
- `warehouse_id` (query, integer)
- `state` (query, string) Allowed: `draft`, `queue`, `taken`, `locked`, `ended`, `closed`, `cancelled`.
- `sales_order_id` (query, integer)
- `view_attributes` (query, string) — Comma-separated list of fields to return. Example: `id,sequence_number,state,inserted_at,fulfillment_order_id,sales_order_id,origin_location,items,sales_order,fulfillment_order`.

Responses:
- 200: Packing orders retrieved

### GET /packing/orders/{id} — Get a packing order by ID

operationId: `getPackingOrder`

Returns the full packing order, including `owner`, `origin_location`,
`packing_boxes[]` with attached labels (`attachments[]`), and the items to
pack.

Clients implementing the packing flow should call this endpoint to poll for
label readiness after a box is closed (~5s interval, ~24 attempts).

**Possible states** (fixed, managed by PULPO): `draft`, `queue`, `taken`,
`locked` (paused), `ended`, `closed`, `cancelled`.

Parameters:
- `id` (path, integer, required)
- `view_attributes` (query, string) — Comma-separated list of fields to return

Responses:
- 200: Packing order retrieved
- 401: Unauthorized - invalid or missing token
- 404: Resource not found

### POST /packing/orders/{id}/accept — Claim (accept) a packing order

operationId: `acceptPackingOrder`

Transitions `queue → taken` and sets `owner` to the calling user.

A user may only own one active packing order at a time. Use
`GET /iam/users/{id}/tasks` first to ensure no other task is owned.

If the order is in `locked` state and the caller is the original owner, use
`/unlock` instead. If the caller is not the original owner of a `locked`
order, call `/unlock` (returns the order to `queue`) and then `/accept`.

Parameters:
- `id` (path, integer, required)

Responses:
- 200: Packing order claimed
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

### POST /packing/orders/{id}/lock — Pause (lock) a packing order

operationId: `lockPackingOrder`

Pauses an in-flight packing order. Transitions `taken → locked` while keeping
the current owner. The task disappears from `GET /iam/users/{id}/tasks` but
remains visible via `GET /packing/orders?state=locked`.

Resume with `/unlock` (owner) or by `/unlock` + `/accept` (different user).

Parameters:
- `id` (path, integer, required)

Responses:
- 200: Packing order locked
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

### POST /packing/orders/{id}/unlock — Resume (unlock) a packing order

operationId: `unlockPackingOrder`

Unlocks a paused packing order. Behavior depends on the caller:

| Caller | Transition |
|--------|------------|
| Original owner | `locked → taken` (resumes work) |
| Any other user | `locked → queue` (owner is cleared; the task can then be `/accept`-ed by anyone) |

Parameters:
- `id` (path, integer, required)

Responses:
- 200: Packing order unlocked
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

### POST /packing/orders/{id}/boxes — Close one or more packing boxes (replace boxes array)

operationId: `closePackingBoxes`

Commits the set of closed packing boxes for the packing order.

**Important — replace semantics:** the request body is a complete list of
boxes that should exist for this order. The server **replaces** (not appends)
the existing boxes. Callers MUST resend every previously-closed box in this
list or those records will be wiped.

Each box must include `box_number` (1-indexed across the full list) and
`packing_order_id` (matching the path parameter).

Parameters:
- `id` (path, integer, required)

Request body (array of object):
- `packing_order_id` (integer, required) — Must match the path parameter
- `box_number` (integer, required) — 1-indexed across the full list
- `weight` (number)
- `length` (number)
- `width` (number)
- `height` (number)
- `packing_box_items` (array of object)
  - `line_order_id` (string) — External line order reference
  - `quantity` (integer) — Quantity of this product in the box
  - `product_id` (integer) — Unique product ID in PULPO WMS
  - `product` (object)
    - `tenant_id` (integer)
    - `sku` (string) — Product SKU (unique per tenant and merchant)

Responses:
- 200: Boxes committed
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token
- 422: Invalid state transition (e.g., order state went back to `queue` after a non-owner unlock)

### POST /packing/orders/{packing_order_id}/boxes/{box_id}/attach — Attach label file to packing box

operationId: `attachLabelToBox`

Uploads a shipping label PDF file to a packing box.

**File Requirements:**
- Format: PDF
- Type: `label`
- Max size: Check with PULPO support

**Workflow:**
1. Update shipment tracking to "started"
2. Generate label PDF in your system
3. POST label file to this endpoint
4. Update shipment tracking to "generated" with tracking codes

Parameters:
- `packing_order_id` (path, integer, required)
- `box_id` (path, integer, required)

Request body (object):
- `attachment` (string, required) — PDF file of shipping label
- `type` (string, required) Allowed: `label`.

Responses:
- 200: Label attached successfully
- 400: Bad request - invalid parameters
- 404: Resource not found

### POST /packing/orders/{id}/finish — Finish a packing order

operationId: `finishPackingOrder`

Transitions `taken → ended`. All items must be packed and each closed box
must have a label attachment (or `pulpowms_label_not_required` status).

After `/finish`, call `/close` with a `shipping_location_id` to release the
owner lock and move the order to `closed`.

Parameters:
- `id` (path, integer, required)

Responses:
- 200: Packing order finished
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

### POST /packing/orders/{id}/close — Close a packing order

operationId: `closePackingOrder`

Final step of the packing flow. Transitions `ended → closed`, sets
`end_date`, and releases the owner's "one active task" slot so they can
claim a new packing order.

Requires a `shipping_location_id` — the warehouse location where the
packed boxes are physically dropped off for the carrier. Look it up via
`GET /warehouses/locations?location_type_id={shipping_area}` (the shipping
area location type for the warehouse).

Parameters:
- `id` (path, integer, required)

Request body (object):
- `shipping_location_id` (integer, required) — Warehouse location where the boxes are dropped off

Responses:
- 200: Packing order closed
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

### PUT /packing/orders/{packing_order_id}/boxes/{box_id}/shipment_tracking/{tracking_id} — Update shipment tracking information

operationId: `updateShipmentTracking`

Updates shipment tracking for a specific packing box.

**Label Generation Workflow:**
1. Subscribe to `packing_box_closed` webhook
2. Receive webhook when box is closed
3. PUT with status `pulpowms_label_generation_started`
4. Generate label in your system
5. POST label file to attach endpoint
6. PUT with status `pulpowms_label_generated` + tracking info

**Status Values:**
- `null`: Initial state
- `pulpowms_label_generation_started`: Label generation in progress
- `pulpowms_label_generated`: Label successfully created
- `pulpowms_label_generation_failed`: Label creation failed
- `pulpowms_label_not_required`: Skip label (no waiting)

**Retrying a failed label:** PUT this endpoint with body `{ "retry": true }`
to re-trigger label generation for the same tracking record. Combine with
`PATCH /fulfillment_orders/{id}/ship_to` first if the failure was an
address issue.

**Polling:** after triggering label generation, poll
`GET /packing/orders/{id}` every ~5 seconds for up to ~2 minutes (24 attempts).
Treat the presence of `packing_boxes[].attachments[0].url` as the readiness
signal — not `shipment_tracking.status` alone. PULPO's own app gives up at
the 2-minute mark.

Parameters:
- `packing_order_id` (path, integer, required)
- `box_id` (path, integer, required)
- `tracking_id` (path, integer, required)

Request body (object):
- `status` (string) — Label generation status Allowed: `pulpowms_label_generation_started`, `pulpowms_label_generated`, `pulpowms_label_generation_failed`, `pulpowms_label_not_required`.
- `retry` (boolean) — Set `true` to re-trigger label generation for the same tracking record (e.g., after fixing the ship-to address via `PATCH /fulfillment_orders/{id}/ship_to`).
- `tracking_code` (string) — Carrier tracking number (required for success)
- `tracking_url` (string) — Carrier tracking URL
- `carrier_code` (string) — Carrier code (required for success)
- `error_message` (string) — Error message (required for failed status)
- `service_point_id` (integer) — Pickup point ID
- `attributes` (object) — Custom attributes

Responses:
- 200: Shipment tracking updated successfully
- 404: Resource not found

## Batch Management

**Batch & Expiration Date Management**

Products with `batch_control: true` and `management_type: lot` or `serial` support batch tracking
with expiration dates. This is essential for perishable goods, pharmaceuticals, or any product
requiring lot traceability.

**Prerequisites**

To use batch management, the product must be created with:
- `management_type`: `lot` (for lot-based tracking) or `serial` (for serial number tracking)
- `batch_control`: `true` (enables expiration date tracking)

**Batch Lifecycle**

```
1. Create product with batch_control=true, management_type=lot
2. POST /inventory/products/{product_id}/batches → Create batch with expiration_date
3. Reference batch in purchase orders (items[].batches array)
4. GET /inventory/products/{product_id}/batches → List batches for a product
5. GET /inventory/stocks/expiring → Monitor expiring stock across warehouse
6. PUT /inventory/products/batches/{batch_id} → Update batch expiration date
```

**Batch Fields**

| Field | Description | Format |
|-------|-------------|--------|
| `number` | Alphanumerical batch/lot number | String |
| `type` | Batch type: `lot`, `serial`, or `none` | String |
| `expiration_date` | Expiration date of the batch | `YYYY-MM-DD` |
| `client_id` | Client identifier associated to batch | String |
| `third_party_id` | Supplier ID for the batch | Integer |

**Using Batches in Orders**

When creating purchase orders or sales orders for batch-controlled products,
include the `batches` array in the order items:

```json
{
  "items": [
    {
      "product_id": 7646303,
      "requested_quantity": 100,
      "batches": ["LOT-2025-001"]
    }
  ]
}
```

### GET /inventory/products/batches — Search all batches

operationId: `searchBatches`

Searches batches across all products with optional filters.

**Filters:**
- `product_id`: Filter by specific product
- `number`: Filter by batch/lot number
- `type`: Filter by batch type
- `expiration_date`: Filter by expiration date
- `existing_stock`: Only show batches with existing stock
- `show_unavailable_stock`: Include batches with unavailable stock

Parameters:
- `product_id` (query, integer) — Filter by product ID
- `number` (query, string) — Alphanumerical batch/lot number
- `type` (query, string) — Type of batch Allowed: `lot`, `serial`, `none`.
- `expiration_date` (query, string) — Expiration date filter (format: YYYY-MM-DD)
- `client_id` (query, string) — Client identifier associated to batch
- `existing_stock` (query, boolean) — Only show batches with existing stock
- `show_unavailable_stock` (query, boolean) — Include batches with unavailable stock
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip

Responses:
- 200: Batches retrieved successfully
- 401: Unauthorized - invalid or missing token

### GET /inventory/products/{id}/batches — List batches for a product

operationId: `listProductBatches`

Returns all batches associated with a specific product.
Only applicable for products with `batch_control: true` and `management_type: lot` or `serial`.

**Filters:**
- `number`: Filter by batch/lot number
- `type`: Filter by batch type (`lot`, `serial`, `none`)
- `expiration_date`: Filter by expiration date (format: `YYYY-MM-DD`)
- `client_id`: Filter by client identifier

Parameters:
- `id` (path, integer, required) — Product ID
- `number` (query, string) — Alphanumerical batch/lot number
- `type` (query, string) — Type of batch Allowed: `lot`, `serial`, `none`.
- `expiration_date` (query, string) — Expiration date filter (format: YYYY-MM-DD)
- `client_id` (query, string) — Client identifier associated to batch
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip

Responses:
- 200: Batches retrieved successfully
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

### GET /inventory/products/batches/{id} — Get batch by ID

operationId: `getBatch`

Returns detailed information about a specific batch by its ID.

Parameters:
- `id` (path, integer, required) — Batch ID

Responses:
- 200: Batch retrieved successfully
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

### POST /inventory/products/{id}/batches — Create a batch for a product

operationId: `createBatch`

Creates a new batch/lot for a product that has `batch_control: true`.

**Required setup:**
- Product must have `management_type` set to `lot` or `serial`
- Product must have `batch_control` set to `true`

**Use cases:**
- Pre-create batches before receiving goods
- Register lot numbers with expiration dates for perishable products
- Track serial numbers for individual items

Parameters:
- `id` (path, integer, required) — Product ID

Request body (object):
- `number` (string, required) — Alphanumerical batch/lot number
- `type` (string, required) — Type of batch: `lot`, `serial`, or `none` Allowed: `lot`, `serial`, `none`.
- `expiration_date` (string) — Expiration date (format: YYYY-MM-DD)
- `client_id` (string) — Client identifier associated to batch
- `third_party_id` (string) — Supplier ID for the batch

Responses:
- 201: Batch created successfully
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

### PUT /inventory/products/batches/{id} — Update a batch

operationId: `updateBatch`

Updates fields of a batch, such as the expiration date, lot number, or supplier.

**Common use cases:**
- Correct an expiration date
- Update the supplier (third_party_id) associated with a batch
- Change the client identifier

Parameters:
- `id` (path, integer, required) — Batch ID

Request body (object):
- `number` (string) — Alphanumerical batch/lot number
- `expiration_date` (string) — Expiration date (format: YYYY-MM-DD)
- `type` (string) — Type of batch Allowed: `lot`, `serial`, `none`.
- `client_id` (string) — Client identifier associated to batch
- `third_party_id` (string) — Supplier ID for the batch

Responses:
- 201: Batch updated successfully
- 400: Bad request - invalid parameters
- 401: Unauthorized - invalid or missing token

## Stock

Inventory and stock management — all endpoints for checking product availability and stock levels.

**Checking Product Availability**

PULPO WMS provides several ways to query stock depending on your use case:

| Endpoint | Purpose | Best For |
|----------|---------|----------|
| `GET /inventory/stocks/summary` | Aggregated stock totals (total, available, unavailable, rejected) | Quick availability checks, dashboard displays |
| `POST /inventory/stocks/products/locations` | Stock breakdown by warehouse location | Warehouse operations, location-level inventory |
| `GET /inventory/stocks/expiring` | Stock sorted by expiration date | Perishable goods monitoring, expiry compliance |
| `GET /inventory/stocks/availability/products/{id}/batches` | Per-batch/serial available quantities | Batch-specific fulfillment, serial number tracking |

**Available vs Total Stock**

The **summary** endpoint distinguishes between:
- **Total**: Stock physically in storage, user, cross-docking, and packing locations
- **Available**: Total minus open orders — this is what you can actually fulfill
- **Unavailable**: Stock reserved by open orders + in reception + in return
- **Rejected**: Stock in return locations pending inspection

**Filtering**

All stock endpoints support filtering by `product_id` and `warehouse_id`. The summary endpoint also supports `merchant_id` for multi-tenant queries.

### GET /inventory/stocks — List stock records

operationId: `listStocks`

Lists raw stock records, optionally scoped to a product, location, batch, or
warehouse. Each row represents a stock quantity at a specific
(product, location, batch) tuple.

**When to use this vs the other stock endpoints:**

| Use case | Endpoint |
|----------|----------|
| Aggregate per-product totals | `GET /inventory/stocks/summary` |
| Per-location quantities | `POST /inventory/stocks/products/locations` |
| Soon-to-expire stock | This endpoint or `GET /inventory/stocks/batches` (the batch-grouped variant returns more complete batch metadata) |
| Count units at one location | This endpoint with `location_id` + `limit=1` |

Each row includes nested `batch: { id, number, expiration_date, type }` for
batch-managed products — use this rather than `/inventory/stocks/expiring`
when you need full batch metadata.

Parameters:
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip
- `sort_by` (query, string) — Sort field and direction (field:asc or field:desc)
- `capped_limit` (query, integer) — Set to 0 to exclude total_results and improve performance by ~20%. Pagination continues until returned items < limit. Allowed: `0`, `20`, `100`, `2000`.
- `warehouse_id` (query, integer)
- `product_id` (query, integer)
- `location_id` (query, integer)
- `batch_id` (query, integer)
- `merchant_id` (query, string) — Merchant ID. Use `to_list:1,2,3` for multiple.

Responses:
- 200: Stock records retrieved
- 401: Unauthorized - invalid or missing token

### GET /inventory/stocks/summary — Get stock summary

operationId: `getStockSummary`

Returns stock summary for products with detailed breakdown.

**Stock Types:**
- `total`: Stock in storage, user, cross-docking, packing locations
- `available`: Total minus open orders
- `unavailable`: Open orders + reception + return
- `rejected`: Stock in return locations

**Filters:**
- Filter by `product_id`, `warehouse_id`, `merchant_id`
- Repeat `product_id` to query multiple products in one call:
  `?product_id=1957711&product_id=1957712`
- `merchant_id` accepts `to_list:1,2,3` for multi-merchant queries
- Combine filters for precise queries

Parameters:
- `product_id` (query, integer | array of integer) — Product ID; repeat the parameter to query multiple products.
- `warehouse_id` (query, integer)
- `merchant_id` (query, string) — Merchant ID. Use `to_list:1,2,3` for multiple.
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip

Responses:
- 200: Stock summary retrieved

### GET /inventory/stocks/batches — List stock grouped by batch

operationId: `listStockBatches`

Returns stock aggregated by batch (one row per batch), with each row carrying
the total quantity across all locations holding that batch plus the per-location
breakdown.

This is the recommended endpoint for expiring-stock reporting when you need
full batch metadata — `GET /inventory/stocks/expiring` returns a truncated
subset of fields.

**Filters:**
- `batch_expiration_date` — supports `between:`, `gte:`, `lte:` (e.g.,
  `lte:2025-12-31` for soon-to-expire batches)
- `total_quantity` — supports `gte:`, `gt:` (e.g., `gt:0` to exclude empty
  batches)
- `product_management_type` — `lot` or `serial`
- `merchant_id=to_list:...` for multi-merchant queries

Parameters:
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip
- `sort_by` (query, string) — Sort field and direction (field:asc or field:desc)
- `capped_limit` (query, integer) — Set to 0 to exclude total_results and improve performance by ~20%. Pagination continues until returned items < limit. Allowed: `0`, `20`, `100`, `2000`.
- `warehouse_id` (query, integer)
- `merchant_id` (query, string) — Merchant ID. Use `to_list:` for multiple.
- `batch_expiration_date` (query, string) — Expiration filter. Supports `between:`, `gte:`, `lte:`.
- `total_quantity` (query, string) — Quantity filter. Supports `gte:`, `gt:`.
- `product_management_type` (query, string) Allowed: `lot`, `serial`.
- `zone_id` (query, integer)
- `location_type_id` (query, integer)

Responses:
- 200: Batch-grouped stock retrieved
- 401: Unauthorized - invalid or missing token

### GET /inventory/stocks/expiring — Get expiring stock

operationId: `getExpiringStock`

Lists stock items sorted by expiration date (ascending), allowing you to identify
products that are expiring soon.

**Use cases:**
- Monitor perishable goods approaching expiry
- Plan promotions or markdowns for soon-to-expire stock
- Generate expiry reports for compliance

**Filters:**
- `product_id`: Filter by specific product
- `batch_id`: Filter by specific batch
- `zone_id`, `location_id`: Filter by warehouse zone/location
- `stock_state_id`: Filter by stock state

Parameters:
- `product_id` (query, integer) — Product ID to filter
- `batch_id` (query, integer) — Batch ID to filter
- `location_id` (query, integer) — Location ID to filter
- `zone_id` (query, integer) — Zone ID to filter
- `location_type_id` (query, integer) — Location Type ID to filter
- `stock_state_id` (query, integer) — Stock State ID to filter
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip

Responses:
- 200: Expiring stock retrieved (sorted by expiration date ascending)
- 401: Unauthorized - invalid or missing token

### GET /inventory/stocks/availability/products/{id}/batches — Get batch availability for a product

operationId: `getBatchAvailability`

Returns the available and reception quantities per batch for a given product.
Useful for checking which batches have stock available for fulfillment.

Parameters:
- `id` (path, integer, required) — Product ID

Responses:
- 200: Batch availability retrieved
- 401: Unauthorized - invalid or missing token

### POST /inventory/stocks/products/locations — Get stock by product and location

operationId: `getStockByLocation`

Returns detailed stock information per product and per physical location.

**New Feature:**
- `include_packed_goods_segmentation=true`: Shows if stock is packed or loose
- `packed_or_loose` values: `packed`, `loose`, `both`

**Use cases:**
- Detailed location-level stock reports
- Loading unit tracking
- Warehouse layout optimization

Parameters:
- `include_packed_goods_segmentation` (query, boolean) — Include packed/loose stock breakdown
- `warehouse_id` (query, integer)
- `product_id` (query, integer)
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip

Request body (object):
- `warehouse_id` (integer)
- `product_id` (integer)

Responses:
- 200: Stock locations retrieved

### POST /inventory/stocks/correct — Correct stock at a location

operationId: `correctStock`

Adds or removes stock for a product at a specific location. The path isn't
under `/bulk/`, but the request still accepts multiple `items` in one call.

**Direction:** `quantity` is signed — positive adds stock, negative removes
it. Removing more than what's available at that location returns a 422
(`not_enough_stock_to_remove_for_given_location_product_batch`).

**Batch-controlled products (`lot`/`serial`):** include `item_batches`, one
entry per batch/lot/serial affected. For `serial`-managed products, each
batch's `quantity` must be `1` — a serial is a single unique unit. For `lot`
it can be any amount. The batch-level quantities are what actually get
applied — keep the item's own `quantity` equal to their sum to avoid
confusion, even though it isn't strictly validated against it.

**Recommended batch size:** up to 50 corrections (`items` entries) per
request.

Request body (object):
- `warehouse_id` (integer, required) — Warehouse the correction applies to.
- `reason_codes` (array of object) — Optional reason code(s) for the correction, referenced by `id` — not by code string.
  - `id` (integer)
- `items` (array of object, required)
  - `location_id` (integer, required) — Location where the correction is applied.
  - `product_id` (integer, required)
  - `quantity` (integer, required) — Signed amount to add (positive) or remove (negative). For batch-controlled products, keep this equal to the sum of `item_batches[].quantity` — the batch-level values are what actually get applied.
  - `item_batches` (array of object) — Required for lot/serial-managed products; omit for `none`-managed products.
    - `batch_id` (integer, required) — Existing lot/serial batch ID. For a `serial`-managed product, `quantity` must be `1` on every entry (a serial is a single unique unit); for `lot` it can be any amount.
    - `quantity` (integer, required) — Signed amount to add (positive) or remove (negative) from this batch.
  - `notes` (string)

Responses:
- 200: Stock corrected
- 401: Unauthorized - invalid or missing token
- 422: Validation error — a required field is missing, or (for negative quantities) there isn't enough stock to remove.

## Kitting

Kit assembly and kitting tasks

### GET /warehouses/location_types — Get kitting location types

operationId: `getKittingLocationType`

Helper endpoint to find kitting location type IDs.

Use the returned ID with `/warehouses/locations` to find actual kitting locations.

Parameters:
- `name` (query, string, required)

Responses:
- 200: Location types found

### POST /inventory/kits — Create kit template

operationId: `createKit`

Creates a kit template that defines how to assemble a new product from component products.

**Workflow:**
1. Create kit product (the final assembled item)
2. Create kit template (this endpoint) defining components
3. Create kitting task to assemble kits
4. Webhook fires when kits are assembled

**Example:**
- Kit Product: "Coffee Gift Box"
- Components: 2x Coffee Beans, 1x Coffee Mug, 1x Gift Box

Request body (object):
- `name` (string, required) — Unique kit name
- `product_id` (integer, required) — Final product ID (the assembled kit)
- `items` (array of object, required) — Component products
  - `product_id` (integer, required) — Component product ID
  - `quantity` (integer, required) — Quantity needed per kit
- `warehouses` (array of integer, required) — Warehouse IDs where kit can be assembled

Responses:
- 200: Kit created successfully

### POST /kitting/tasks — Create kitting task

operationId: `createKittingTask`

Creates a task to assemble kits from component products.

**Workflow:**
1. Webhook `replenishment_order_created` (type=kit_move): Components moved to kitting area, stock reduced
2. Warehouse assembles kits (Android app)
3. Webhook `replenishment_order_finished` (type=kitting): Kits moved to storage, kit product stock increased

**Requirements:**
- Kit template must exist
- Sufficient component stock must be available
- `destination_location_id` must be a kitting location

Request body (object):
- `warehouse_id` (integer, required) — Warehouse for kitting
- `destination_location_id` (integer, required) — Kitting location ID
- `items` (array of object, required)
  - `kit_id` (integer, required) — Kit template ID
  - `quantity` (integer, required) — Number of kits to assemble

Responses:
- 200: Kitting task created successfully

## Webhooks

Event subscriptions and webhooks

### GET /webhook/ — List webhook subscriptions

operationId: `listWebhooks`

Returns your webhook subscriptions. Use it to check what is subscribed, or to find the
`id` you need to [delete a subscription](#tag/Webhooks/operation/deleteWebhook).

**Only enabled webhooks by default.** Without `enabled=false` in the query, disabled
subscriptions are left out, even when you filter by their `id` or `url`. To see
everything, call once with `enabled=true` and once with `enabled=false`.

**Filters** (all optional, combine as needed):
- `id`, `url`, `method`, `enabled`, `warehouse_id`, `merchant_id`,
  `merchant_channel_id` match exactly.
- `url` also accepts a partial match with `like:`, e.g. `url=like:%25my-domain%25`
  (`%25` is the URL-encoded `%` wildcard).
- Each filter takes one value. Lists such as `warehouse_id=1,2` or
  `warehouse_id=in:1,2` are not supported and return an error.
- Unknown query parameters are ignored.

**Paging:** `total_results` is only filled on the first page (`offset` 0 or not set).
On later pages it is `null`, so read it from the first call.

Parameters:
- `id` (query, string) — Webhook ID
- `url` (query, string) — Exact endpoint URL, or `like:%pattern%` for a partial match
- `method` (query, string) Allowed: `POST`.
- `enabled` (query, boolean) — `true` (the default) returns enabled webhooks, `false` returns disabled ones. Any other value returns an error.
- `warehouse_id` (query, integer)
- `merchant_id` (query, integer)
- `merchant_channel_id` (query, integer)
- `limit` (query, integer) — Number of items to return (1-2000)
- `offset` (query, integer) — Number of items to skip
- `sort_by` (query, string) — Sort field and direction (field:asc or field:desc)

Responses:
- 200: Matching webhook subscriptions. An empty `webhooks` list (and `total_results: 0`) when nothing matches.

### GET /webhook/{id} — Get a webhook subscription

operationId: `getWebhook`

Returns one webhook subscription by its `id`. Unlike the list, this also returns
disabled webhooks. The webhook is returned directly, not inside a `webhooks` list.

Parameters:
- `id` (path, string, required) — Webhook ID (UUID)

Responses:
- 200: The webhook subscription
- 422: No webhook with this id exists

### POST /webhook/ — Subscribe to webhook events

operationId: `subscribeWebhook`

Subscribes your endpoint to receive real-time notifications for warehouse events.

**Available Events:**

**Purchase Orders / Incoming:**
- `purchase_order_updated` [📎](/guide/incoming#purchase_order_updated "Sample payload"): PO modified
- `purchase_order_deleted`: PO deleted
- `purchase_order_finished` [📎](/guide/incoming#purchase_order_finished "Sample payload"): Goods receipt completed (GR)
- `purchase_order_finished_early` [📎](/guide/incoming#purchase_order_finished_early "Sample payload"): PO closed with partial receipt
- `incoming_good_created` [📎](/guide/incoming#incoming_good_created "Sample payload"): Receiving task created
- `replenishment_order_created` [📎](/guide/incoming#replenishment_order_created "Sample payload"): Stock movement to storage started
- `replenishment_order_finished` [📎](/guide/incoming#replenishment_order_finished "Sample payload"): Stock available in warehouse

**Sales Orders / Outgoing:**
- `sales_order_created` [📎](/guide/outgoing#sales_order_created "Sample payload"): Order accepted
- `sales_order_updated` [📎](/guide/outgoing#sales_order_updated "Sample payload"): Order modified
- `sales_order_cancelled` [📎](/guide/outgoing#sales_order_cancelled "Sample payload"): Order cancelled
- `sales_order_finished` [📎](/guide/outgoing#sales_order_finished "Sample payload"): Order fully shipped (PGI)
- `fulfillment_order_finished` [📎](/guide/outgoing#fulfillment_order_finished "Sample payload"): Single fulfillment completed
- `picking_order_created` [📎](/guide/outgoing#picking_order_created "Sample payload"): Picking task created
- `picking_order_finished` [📎](/guide/outgoing#picking_order_finished "Sample payload"): Picking completed
- `packing_order_created` [📎](/guide/outgoing#packing_order_created "Sample payload"): Packing task created
- `packing_order_finished` [📎](/guide/outgoing#packing_order_finished "Sample payload"): Packing completed (PIC)
- `packing_order_closed` [📎](/guide/outgoing#packing_order_closed "Sample payload"): Packing task closed and left the packing station
- `packing_box_closed` [📎](/label-provider/webhooks#packing_box_closed "Sample payload"): Individual box sealed (for label generation)

**Stock & Inventory:**
- `stock_correction_finished` [📎](/guide/stock-changes#stock_correction_finished "Sample payload"): Manual stock adjustment
- `counting_task_created`: Inventory count started
- `counting_task_finished`: Inventory count completed
- `counting_task_closed` [📎](/guide/stock-changes#counting_task_closed "Sample payload"): Count finalized

**Shipping:**
- `shipment_tracking_updated` [📎](/label-provider/shipment-tracking#shipment_tracking_updated "Sample payload"): Tracking info changed
- `turbo_label_packing_created`: Quick label process

**Filters:**
- Filter by `warehouse_id`, `merchant_id`, `merchant_channel_id`
- `allowed_types`: Array of event types to receive

**Best Practices:**
- Implement idempotency (webhook may retry)
- Return 200 OK quickly (process async)
- Verify webhook signature if available
- Handle out-of-order delivery

Request body (object):
- `url` (string, required) — Your webhook endpoint URL (must be HTTPS)
- `method` (string, required) — HTTP method. Required, there is no default. Allowed: `POST`.
- `warehouse_id` (integer, required) — Warehouse whose events you receive. Required.
- `merchant_id` (integer) — Filter by merchant
- `merchant_channel_id` (integer) — Filter by channel
- `allowed_types` (array of string, required) — Event types to receive

Responses:
- 201: Webhook subscription created. The new subscription is returned inside a `webhooks` list. Keep `webhooks[0].id`: you need it to delete the subscription later.
- 400: Validation failed. `errors` names each invalid field, for example a missing `url`, `method` or `warehouse_id`, or an unknown event in `allowed_types`.

### DELETE /webhook/{id} — Delete a webhook subscription

operationId: `deleteWebhook`

Removes a webhook subscription, so PULPO no longer sends its events to that URL.

The `id` is the UUID returned when you subscribed (`webhooks[].id` in the
[Subscribe to webhook events](#tag/Webhooks/operation/subscribeWebhook) response). If
you don't have it any more, look it up with
[List webhook subscriptions](#tag/Webhooks/operation/listWebhooks). Disabled webhooks
can be deleted too.

**Responses:**
- `204 No Content` with an empty body when the webhook was deleted.
- `422` with `{"errors": {"id": "The given id is invalid"}}` when no webhook with this
  id exists, including one you already deleted. Treat this as "already gone" if you
  retry deletes.

Parameters:
- `id` (path, string, required) — Webhook ID (UUID)

Responses:
- 204: Webhook deleted. The response body is empty.
- 422: No webhook with this id exists (never existed or already deleted)

---

Website version: https://connect.pulpo.co/reference
Whole guide in one file: https://connect.pulpo.co/llms-full.txt
Index of all pages: https://connect.pulpo.co/llms.txt
